通过本节的学习,将学会如何使用AutoGen定义智能体并调用函数和工具。
在这个例子中,我们将赋予智能体一个工具的访问权限,该工具是一个函数,包含可用度假目的地的列表及其度假目的地的可用性。 可以认为这是一个旅行社的智能体可以访问旅行数据库的场景。
项目依赖
poetry add python-dotenv
poetry add autogen-agentchat
poetry add "autogen-ext[openai]"定义函数(Functions)
def vacation_destination(city: str) -> tuple[str, str]:
"""
Checks if a specific vacation destination is available
Args:
city (str): Name of the city to check
Returns:
tuple: Contains city name and availability status ('Available' or 'Unavailable')
"""
destinations = {
"Barcelona": "Available",
"Tokyo": "Unavailable",
"Cape Town": "Available",
"Vancouver": "Available",
"Dubai": "Unavailable",
}
if city in destinations:
return city, destinations[city]
else:
return city, "City not found"定义FunctionTool
要让智能体将vacation_destinations用作FunctionTool,我们需要将其定义为一个FunctionTool。我们还将提供该工具的描述,这有助于智能体识别该工具的用途,以便完成用户请求的任务。
from autogen_core.tools import FunctionTool
get_vacations = FunctionTool(
vacation_destination,
description="Search for vacation destinations and if they are availabe or not.",
)定义智能体
现在我们可以用下面的代码创建智能体。我们定义了system_message,以向智能体提供关于如何帮助用户查找度假目的地的指令。
我们还将reflect_on_tool_use参数设置为true。这允许我们使用LLM来获取工具调用的响应,并使用自然语言发送响应。
你可以将此参数设置为false来查看差异。
from autogen_agentchat.agents import AssistantAgent
agent = AssistantAgent(
name="assistant",
model_client=client,
tools=[get_vacations],
system_message="You are a travel agent that helps users find vacation destinations.",
reflect_on_tool_use=True,
)运行智能体
现在我们可以使用初始用户消息(要求去东京旅行)来运行智能体。你可以更改此城市目的地,以查看智能体如何响应城市的可用性。
完整代码:
import asyncio
from dotenv import load_dotenv
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_core.tools import FunctionTool
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.messages import TextMessage
from autogen_core import CancellationToken
load_dotenv()
client = OpenAIChatCompletionClient(model="gpt-4o")
def vacation_destination(city: str) -> tuple[str, str]:
"""
Checks if a specific vacation destination is available
Args:
city (str): Name of the city to check
Returns:
tuple: Contains city name and availability status ('Available' or 'Unavailable')
"""
destinations = {
"Barcelona": "Available",
"Tokyo": "Unavailable",
"Cape Town": "Available",
"Vancouver": "Available",
"Dubai": "Unavailable",
}
if city in destinations:
return city, destinations[city]
else:
return city, "City not found"
get_vacations = FunctionTool(
vacation_destination,
description="Search for vacation destinations and if they are availabe or not.",
)
agent = AssistantAgent(
name="assistant",
model_client=client,
tools=[get_vacations],
system_message="You are a travel agent that helps users find vacation destinations.",
reflect_on_tool_use=True,
)
async def main():
response = await agent.on_messages(
[TextMessage(content="I would like to take a trip to Tokyo", source="user")],
cancellation_token=CancellationToken(),
)
print(response.inner_messages)
print(response.chat_message)
asyncio.run(main())执行结果:
[ToolCallRequestEvent(source='assistant', models_usage=RequestUsage(prompt_tokens=78, completion_tokens=16), content=[FunctionCall(id='call_lpPgiefSjGHIF3BmduZzQcYh', arguments='{"city":"Tokyo"}', name='vacation_destination')], type='ToolCallRequestEvent'), ToolCallExecutionEvent(source='assistant', models_usage=None, content=[FunctionExecutionResult(content="('Tokyo', 'Unavailable')", call_id='call_lpPgiefSjGHIF3BmduZzQcYh', is_error=False)], type='ToolCallExecutionEvent')]
source='assistant' models_usage=RequestUsage(prompt_tokens=66, completion_tokens=62) content='It looks like detailed recommendations for Tokyo are currently unavailable. However, I’d be happy to share general advice! Tokyo is a vibrant city with a mix of ancient traditions and cutting-edge modernity. Is there something specific you’re looking for in your trip—like food, culture, shopping, or something else?' type='TextMessage'AssistantAgent reflect_on_tool_use
- 当
reflect_on_tool_use为False(默认值)时,工具调用结果将作为ToolCallSummaryMessage返回到chat_message中。可以使用tool_call_summary_format来自定义工具调用摘要。
[ToolCallRequestEvent(source='assistant', models_usage=RequestUsage(prompt_tokens=78, completion_tokens=16), content=[FunctionCall(id='call_0hxE8cgdy6rVIo3aIr5iXo7y', arguments='{"city":"Tokyo"}', name='vacation_destination')], type='ToolCallRequestEvent'), ToolCallExecutionEvent(source='assistant', models_usage=None, content=[FunctionExecutionResult(content="('Tokyo', 'Unavailable')", call_id='call_0hxE8cgdy6rVIo3aIr5iXo7y', is_error=False)], type='ToolCallExecutionEvent')]
source='assistant' models_usage=None content="('Tokyo', 'Unavailable')" type='ToolCallSummaryMessage'- 当
reflect_on_tool_use为True时,将使用工具调用和结果进行另一次模型推理,并将文本响应作为TextMessage返回到chat_message中。
[ToolCallRequestEvent(source='assistant', models_usage=RequestUsage(prompt_tokens=78, completion_tokens=16), content=[FunctionCall(id='call_pEfelVuaWOJK20iIgjzGQ7Us', arguments='{"city":"Tokyo"}', name='vacation_destination')], type='ToolCallRequestEvent'), ToolCallExecutionEvent(source='assistant', models_usage=None, content=[FunctionExecutionResult(content="('Tokyo', 'Unavailable')", call_id='call_pEfelVuaWOJK20iIgjzGQ7Us', is_error=False)], type='ToolCallExecutionEvent')]
source='assistant' models_usage=RequestUsage(prompt_tokens=66, completion_tokens=40) content='It seems like I don’t have detailed information for Tokyo at the moment. Do you have specific preferences or activities you’re interested in? I can help you explore similar destinations or guide you in planning!' type='TextMessage'总结
- 模型客户端
autogen_ext.models.openaiOpenAIChatCompletionClient - 工具定义
autogen_core.toolsFunctionTool - 智能体定义
autogen_agentchat.agentsAssistantAgent - 消息定义
autogen_agentchat.messagesTextMessage
FunctionTool
通过包装标准Python函数来创建自定义工具。
FunctionTool提供了一个接口,用于异步或同步执行Python函数。每个函数都必须包含其所有参数和返回类型的类型注解。这些注解使FunctionTool能够生成必要的schema,用于输入验证、序列化,以及告知LLM预期参数。当LLM准备函数调用时,它会利用此schema生成与函数规范对齐的参数。
注意:用户有责任验证工具的输出类型是否与预期类型匹配。