代理使用工具来执行操作并与外部系统进行交互

工具是代理可以运行以完成任务的函数。例如:搜索网页、运行 SQL、发送电子邮件或调用 API。你可以使用任何 Python 函数作为工具,或者使用预构建的工具包。通用语法如下:

from agno.agent import Agent

agent = Agent(
    # 添加函数或工具包
    tools=[...],
    # 在代理响应中显示工具调用
    show_tool_calls=True
)

使用工具包

Agno 提供了许多预构建的工具包,你可以将它们添加到你的代理中。例如,让我们使用 DuckDuckGo 工具包来搜索网页。

你可以在工具包指南中找到更多工具包。
1

创建 Web 搜索代理

创建一个文件 web_search.py

web_search.py
from agno.agent import Agent
from agno.tools.duckduckgo import DuckDuckGoTools

agent = Agent(tools=[DuckDuckGoTools()], show_tool_calls=True, markdown=True)
agent.print_response("法国正在发生什么?", stream=True)
2

运行代理

安装库

pip install openai duckduckgo-search agno

运行代理

python web_search.py

编写自己的工具

为了获得更多控制权,你可以编写自己的 Python 函数并将它们作为工具添加到代理中。例如,这是如何将 get_top_hackernews_stories 工具添加到代理的方法。

hn_agent.py
import json
import httpx

from agno.agent import Agent

def get_top_hackernews_stories(num_stories: int = 10) -> str:
    """使用此函数获取 Hacker News 的热门故事。

    Args:
        num_stories (int): 要返回的故事数量。默认为 10。

    Returns:
        str: 热门故事的 JSON 字符串。
    """

    # 获取热门故事 ID
    response = httpx.get('https://hacker-news.firebaseio.com/v0/topstories.json')
    story_ids = response.json()

    # 获取故事详情
    stories = []
    for story_id in story_ids[:num_stories]:
        story_response = httpx.get(f'https://hacker-news.firebaseio.com/v0/item/{story_id}.json')
        story = story_response.json()
        if "text" in story:
            story.pop("text", None)
        stories.append(story)
    return json.dumps(stories)

agent = Agent(tools=[get_top_hackernews_stories], show_tool_calls=True, markdown=True)
agent.print_response("总结一下 hackernews 的前 5 个故事?", stream=True)

阅读更多关于:

属性

以下属性允许 Agent 使用工具

| 参数 | 类型 | 类型 | 默认值 | 描述 | |-----------|------|---------|-------------| | tools | List[Union[Tool, Toolkit, Callable, Dict, Function]] | List[Union[Tool, Toolkit, Callable, Dict, Function]] | - | 提供给模型的工具列表。工具是模型可能为其生成 JSON 输入的函数。 | | show_tool_calls | bool | bool | False | 在模型响应中打印工具调用的签名。 | | tool_call_limit | int | int | - | 单次运行允许的最大工具调用次数。 | | tool_choice | Union[str, Dict[str, Any]] | Union[str, Dict[str, Any]] | - | 控制模型调用的工具(如果有)。“none” 表示模型不会调用工具,而是生成消息。“auto” 表示模型可以在生成消息或调用工具之间进行选择。通过 {"type": "function", "function": {"name": "my_function"}} 指定特定函数会强制模型调用该工具。“none” 是在没有工具存在时的默认设置。“auto” 是存在工具时的默认设置。 | | read_chat_history | bool | bool | False | 添加一个允许模型读取聊天记录的工具。 | | search_knowledge | bool | bool | False | 添加一个允许模型搜索知识库(又名 Agentic RAG)的工具。 | | update_knowledge | bool | bool | False | 添加一个允许模型更新知识库的工具。 | | read_tool_call_history | bool | bool | False | 添加一个允许模型获取工具调用历史记录的工具。 |

开发者资源