使用提供的工具作为函数进行任务解决(异步函数调用)
AutoGen 提供了由LLM、工具或人类驱动的可对话代理,这些代理可以通过自动聊天共同执行任务。该框架允许通过多代理对话使用工具和人类参与。请参阅有关此功能的文档这里。
在本笔记本中,我们演示了如何使用 AssistantAgent
和
UserProxyAgent
来利用 OpenAI 模型的新功能(模型版本 0613)进行函数调用。必须将指定的提示和函数配置
传递给 AssistantAgent
以初始化代理。相应的函数必须传递给 UserProxyAgent
,它将
执行由 AssistantAgent
进行的任何函数调用。除了需要确保描述与函数匹配之外,我们建议
检查 AssistantAgent
中的系统消息,以确保指令与函数调用描述一致。
Requirements
import time
from typing_extensions import Annotated
import autogen
from autogen.cache import Cache
config_list = autogen.config_list_from_json(env_or_file="OAI_CONFIG_LIST", filter_dict={"tags": ["tool"]})
tip
了解更多关于为agent配置LLM的信息在这里.
进行异步和同步函数调用
在这个例子中,我们演示了使用AssistantAgent
和UserProxyAgent
执行函数调用。通过AssistantAgent
的默认系统提示,我们允许LLM助手使用代码执行任务,而UserProxyAgent
将从LLM响应中提取代码块并执行它们。通过新的“function_call”功能,我们在OpenAI配置中为AssistantAgent
定义了函数并指定了函数的描述。然后我们在UserProxyAgent
中注册这些函数。
llm_config = {
"config_list": config_list,
}
coder = autogen.AssistantAgent(
name="chatbot",
system_message="For coding tasks, only use the functions you have been provided with. You have a stopwatch and a timer, these tools can and should be used in parallel. Reply TERMINATE when the task is done.",
llm_config=llm_config,
)
# create a UserProxyAgent instance named "user_proxy"
user_proxy = autogen.UserProxyAgent(
name="user_proxy",
system_message="A proxy for the user for executing code.",
is_termination_msg=lambda x: x.get("content", "") and x.get("content", "").rstrip().endswith("TERMINATE"),
human_input_mode="NEVER",
max_consecutive_auto_reply=10,
code_execution_config={"work_dir": "coding"},
)
# define functions according to the function description
# An example async function registered using register_for_llm and register_for_execution decorators
@user_proxy.register_for_execution()
@coder.register_for_llm(description="create a timer for N seconds")
async def timer(num_seconds: Annotated[str, "Number of seconds in the timer."]) -> str:
for i in range(int(num_seconds)):
time.sleep(1)
# should print to stdout
return "Timer is done!"
# An example sync function registered using register_function
def stopwatch(num_seconds: Annotated[str, "Number of seconds in the stopwatch."]) -> str:
for i in range(int(num_seconds)):
time.sleep(1)
return "Stopwatch is done!"
autogen.agentchat.register_function(
stopwatch,
caller=coder,
executor=user_proxy,
description="create a stopwatch for N seconds",
)
开始对话。await
用于暂停和恢复代码执行,以便进行异步IO操作。如果没有 await
,异步函数会返回一个协程对象,但不会执行该函数。使用 await
时,异步函数会被执行,当前函数会暂停,直到等待的函数返回结果。
with Cache.disk() as cache:
await user_proxy.a_initiate_chat( # noqa: F704
coder,
message="Create a timer for 5 seconds and then a stopwatch for 5 seconds.",
cache=cache,
)
Create a timer for 5 seconds and then a stopwatch for 5 seconds.
--------------------------------------------------------------------------------
***** Suggested tool Call (call_h6324df0CdGPDNjPO8GrnAQJ): timer *****
Arguments:
{"num_seconds":"5"}
**********************************************************************
--------------------------------------------------------------------------------
>>>>>>>> EXECUTING ASYNC FUNCTION timer...
***** Response from calling tool "call_h6324df0CdGPDNjPO8GrnAQJ" *****
Timer is done!
**********************************************************************
--------------------------------------------------------------------------------
***** Suggested tool Call (call_7SzbQxI8Nsl6dPQtScoSGPAu): stopwatch *****
Arguments:
{"num_seconds":"5"}
**************************************************************************
--------------------------------------------------------------------------------
>>>>>>>> EXECUTING ASYNC FUNCTION stopwatch...
***** Response from calling tool "call_7SzbQxI8Nsl6dPQtScoSGPAu" *****
Stopwatch is done!
**********************************************************************
--------------------------------------------------------------------------------
TERMINATE
--------------------------------------------------------------------------------
异步函数调用与群聊
同步和异步可以在超过两个代理的拓扑结构中使用。下面,我们展示了群聊中的这一功能。
markdownagent = autogen.AssistantAgent(
name="Markdown_agent",
system_message="Respond in markdown only",
llm_config=llm_config,
)
# Add a function for robust group chat termination
@user_proxy.register_for_execution()
@markdownagent.register_for_llm()
@coder.register_for_llm(description="terminate the group chat")
def terminate_group_chat(message: Annotated[str, "Message to be sent to the group chat."]) -> str:
return f"[GROUPCHAT_TERMINATE] {message}"
groupchat = autogen.GroupChat(agents=[user_proxy, coder, markdownagent], messages=[], max_round=12)
llm_config_manager = llm_config.copy()
llm_config_manager.pop("functions", None)
llm_config_manager.pop("tools", None)
manager = autogen.GroupChatManager(
groupchat=groupchat,
llm_config=llm_config_manager,
is_termination_msg=lambda x: "GROUPCHAT_TERMINATE" in x.get("content", ""),
)
最后,我们初始化将使用上述定义函数的聊天:
message = """
1) Create a timer and a stopwatch for 5 seconds each in parallel.
2) Pretty print the result as md.
3) when 1 and 2 are done, terminate the group chat
"""
with Cache.disk() as cache:
await user_proxy.a_initiate_chat( # noqa: F704
manager,
message=message,
cache=cache,
)
1) Create a timer and a stopwatch for 5 seconds each in parallel.
2) Pretty print the result as md.
3) when 1 and 2 are done, terminate the group chat
--------------------------------------------------------------------------------
***** Suggested tool Call (call_qlS3QkcY1NkfgpKtCoR6oGo7): timer *****
Arguments:
{"num_seconds": "5"}
**********************************************************************
***** Suggested tool Call (call_TEHlvMgCp0S3RzBbVsVPXWeL): stopwatch *****
Arguments:
{"num_seconds": "5"}
**************************************************************************
--------------------------------------------------------------------------------
>>>>>>>> EXECUTING ASYNC FUNCTION timer...
>>>>>>>> EXECUTING ASYNC FUNCTION stopwatch...
***** Response from calling tool "call_qlS3QkcY1NkfgpKtCoR6oGo7" *****
Timer is done!
**********************************************************************
--------------------------------------------------------------------------------
***** Response from calling tool "call_TEHlvMgCp0S3RzBbVsVPXWeL" *****
Stopwatch is done!
**********************************************************************
--------------------------------------------------------------------------------
***** Suggested tool Call (call_JuQwvj4FigfvGyBeTMglY2ee): terminate_group_chat *****
Arguments:
{"message":"Both timer and stopwatch have completed their countdowns. The group chat is now being terminated."}
*************************************************************************************
--------------------------------------------------------------------------------
>>>>>>>> EXECUTING ASYNC FUNCTION terminate_group_chat...
***** Response from calling tool "call_JuQwvj4FigfvGyBeTMglY2ee" *****
[GROUPCHAT_TERMINATE] Both timer and stopwatch have completed their countdowns. The group chat is now being terminated.
**********************************************************************
--------------------------------------------------------------------------------