工具通过让代理能够与外部系统交互,如搜索网页、运行 SQL、发送电子邮件或调用 API,使代理具有“代理性”。

Agno 提供了 80 多个预构建的工具集,但在大多数情况下,您将自己编写工具。通用语法如下:

import random

from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools import tool


@tool(show_result=True, stop_after_tool_call=True)
def get_weather(city: str) -> str:
    """获取某个城市的天气。"""
    # 在实际实现中,这会调用天气 API
    weather_conditions = ["sunny", "cloudy", "rainy", "snowy", "windy"]
    random_weather = random.choice(weather_conditions)

    return f"The weather in {city} is {random_weather}."


agent = Agent(
    model=OpenAIChat(model="gpt-4o-mini"),
    tools=[get_weather],
    markdown=True,
)
agent.print_response("What is the weather in San Francisco?", stream=True)

在上面的示例中,get_weather 函数是一个工具。当调用它时,由于我们设置了 show_result=True,工具结果将显示在输出中。

然后,由于我们设置了 stop_after_tool_call=True,代理将在工具调用后停止。

使用 Toolkit 类

Toolkit 类提供了一种管理多个工具的方法,并对它们的执行进行额外控制。您可以指定哪些工具在执行后停止代理,以及哪些工具的结果应该显示。

from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.googlesearch import GoogleSearchTools

agent = Agent(
    model=OpenAIChat(id="gpt-4.5-preview"),
    tools=[
        GoogleSearchTools(
            stop_after_tool_call_tools=["google_search"],
            show_result_tools=["google_search"],
        )
    ],
    show_tool_calls=True,
)

agent.print_response("What's the latest about gpt 4.5?", markdown=True)

在此示例中,GoogleSearchTools 工具集被配置为在执行 google_search 函数后停止代理,并显示该函数的结果。

阅读更多关于: