Agents 课程文档

工具

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

Ask a Question Open In Colab

工具

正如我们在单元 1 中探讨的那样,agents 使用工具来执行各种操作。在 smolagents 中,工具被视为 LLM 可以在 agent 系统中调用的函数

为了与工具交互,LLM 需要一个包含以下关键组件的接口描述

  • 名称:工具的名称
  • 工具描述:工具的功能
  • 输入类型和描述:工具接受的参数
  • 输出类型:工具返回的内容

例如,在为韦恩庄园的派对做准备时,阿福需要各种工具来收集信息 - 从搜索餐饮服务到寻找派对主题创意。以下是一个简单的搜索工具接口的示例

  • 名称: web_search
  • 工具描述: 在网络上搜索特定查询
  • 输入: query (字符串) - 要查找的搜索词
  • 输出: 包含搜索结果的字符串

通过使用这些工具,阿福可以做出明智的决定并收集计划完美派对所需的所有信息。

在下面,您可以看到一个动画,演示了工具调用是如何管理的

Agentic pipeline from https://huggingface.co/docs/smolagents/conceptual_guides/react

工具创建方法

smolagents 中,工具可以通过两种方式定义

  1. 使用 @tool 装饰器 用于简单的基于函数的工具
  2. 创建 Tool 的子类 用于更复杂的功能

@tool 装饰器

@tool 装饰器是定义简单工具的推荐方法。在底层,smolagents 将从 Python 解析关于函数的基本信息。因此,如果您清晰地命名您的函数并编写良好的文档字符串,LLM 将更容易使用它。

使用这种方法,我们定义一个函数,其中包含

  • 清晰且描述性的函数名称,帮助 LLM 理解其用途。
  • 输入和输出的类型提示,以确保正确使用。
  • 详细的描述,包括 Args: 部分,其中明确描述每个参数。这些描述为 LLM 提供了有价值的上下文,因此仔细编写它们非常重要。

生成一个检索评分最高的餐饮服务的工具

Alfred Catering
您可以按照此 notebook 中的代码进行操作,您可以使用 Google Colab 运行它。

假设阿福已经决定了派对的菜单,但现在他需要帮助为如此多的客人准备食物。为此,他想聘请餐饮服务,并且需要确定可用的评分最高的选项。阿福可以利用工具搜索他所在地区最好的餐饮服务。

以下是阿福如何使用 @tool 装饰器来实现这一点的示例

from smolagents import CodeAgent, HfApiModel, tool

# Let's pretend we have a function that fetches the highest-rated catering services.
@tool
def catering_service_tool(query: str) -> str:
    """
    This tool returns the highest-rated catering service in Gotham City.

    Args:
        query: A search term for finding catering services.
    """
    # Example list of catering services and their ratings
    services = {
        "Gotham Catering Co.": 4.9,
        "Wayne Manor Catering": 4.8,
        "Gotham City Events": 4.7,
    }

    # Find the highest rated catering service (simulating search query filtering)
    best_service = max(services, key=services.get)

    return best_service


agent = CodeAgent(tools=[catering_service_tool], model=HfApiModel())

# Run the agent to find the best catering service
result = agent.run(
    "Can you give me the name of the highest-rated catering service in Gotham City?"
)

print(result)   # Output: Gotham Catering Co.

将工具定义为 Python 类

这种方法涉及创建 Tool 的子类。对于复杂的工具,我们可以实现一个类而不是 Python 函数。该类使用元数据包装函数,帮助 LLM 理解如何有效地使用它。在这个类中,我们定义了

  • name:工具的名称。
  • description:用于填充 agent 系统提示的描述。
  • inputs:一个字典,键为 typedescription,提供信息以帮助 Python 解释器处理输入。
  • output_type:指定预期的输出类型。
  • forward:包含要执行的推理逻辑的方法。

下面,我们可以看到一个使用 Tool 构建的工具示例,以及如何在 CodeAgent 中集成它。

生成一个关于超级英雄主题派对的创意的工具

阿福在庄园举办的派对是一个超级英雄主题活动,但他需要一些创意,使其真正特别。作为一位出色的主人,他想用独特的主题给客人带来惊喜。

为此,他可以使用一个 agent,根据给定的类别生成超级英雄主题派对创意。这样,阿福可以找到完美的派对主题来让客人惊叹。

from smolagents import Tool, CodeAgent, HfApiModel

class SuperheroPartyThemeTool(Tool):
    name = "superhero_party_theme_generator"
    description = """
    This tool suggests creative superhero-themed party ideas based on a category.
    It returns a unique party theme idea."""

    inputs = {
        "category": {
            "type": "string",
            "description": "The type of superhero party (e.g., 'classic heroes', 'villain masquerade', 'futuristic Gotham').",
        }
    }

    output_type = "string"

    def forward(self, category: str):
        themes = {
            "classic heroes": "Justice League Gala: Guests come dressed as their favorite DC heroes with themed cocktails like 'The Kryptonite Punch'.",
            "villain masquerade": "Gotham Rogues' Ball: A mysterious masquerade where guests dress as classic Batman villains.",
            "futuristic Gotham": "Neo-Gotham Night: A cyberpunk-style party inspired by Batman Beyond, with neon decorations and futuristic gadgets."
        }

        return themes.get(category.lower(), "Themed party idea not found. Try 'classic heroes', 'villain masquerade', or 'futuristic Gotham'.")

# Instantiate the tool
party_theme_tool = SuperheroPartyThemeTool()
agent = CodeAgent(tools=[party_theme_tool], model=HfApiModel())

# Run the agent to generate a party theme idea
result = agent.run(
    "What would be a good superhero party idea for a 'villain masquerade' theme?"
)

print(result)  # Output: "Gotham Rogues' Ball: A mysterious masquerade where guests dress as classic Batman villains."

有了这个工具,阿福将成为终极超级主人,用一场让客人难忘的超级英雄主题派对给他们留下深刻印象!🦸‍♂️🦸‍♀️

默认工具箱

smolagents 附带一组预构建的工具,可以直接注入到您的 agent 中。默认工具箱 包括

  • PythonInterpreterTool
  • FinalAnswerTool
  • UserInputTool
  • DuckDuckGoSearchTool
  • GoogleSearchTool
  • VisitWebpageTool

阿福可以使用各种工具来确保韦恩庄园的派对完美无瑕

  • 首先,他可以使用 DuckDuckGoSearchTool 找到有创意的超级英雄主题派对创意。

  • 对于餐饮,他将依靠 GoogleSearchTool 来查找哥谭市评分最高的餐饮服务。

  • 为了管理座位安排,阿福可以使用 PythonInterpreterTool 运行计算。

  • 收集完所有信息后,他将使用 FinalAnswerTool 编译计划。

有了这些工具,阿福保证派对既特别又无缝。 🦇💡

共享和导入工具

smolagents 最强大的功能之一是其在 Hub 上共享自定义工具并无缝集成社区创建的工具的能力。这包括与 HF SpacesLangChain 工具 连接,从而显著增强阿福在韦恩庄园策划难忘派对的能力。 🎭

通过这些集成,阿福可以利用先进的活动策划工具——无论是调整灯光以获得完美氛围、策划派对的理想播放列表,还是与哥谭市最好的餐饮服务商协调。

以下示例展示了这些功能如何提升派对体验

将工具共享到 Hub

与社区共享您的自定义工具非常容易!只需使用 push_to_hub() 方法将其上传到您的 Hugging Face 帐户即可。

例如,阿福可以共享他的 party_theme_tool,以帮助其他人找到哥谭市最好的餐饮服务。以下是具体操作方法

party_theme_tool.push_to_hub("{your_username}/party_theme_tool", token="<YOUR_HUGGINGFACEHUB_API_TOKEN>")

从 Hub 导入工具

您可以使用 load_tool() 函数轻松导入其他用户创建的工具。例如,阿福可能想要使用 AI 生成派对的宣传图片。他无需从头开始构建工具,而是可以利用社区中预定义的工具

from smolagents import load_tool, CodeAgent, HfApiModel

image_generation_tool = load_tool(
    "m-ric/text-to-image",
    trust_remote_code=True
)

agent = CodeAgent(
    tools=[image_generation_tool],
    model=HfApiModel()
)

agent.run("Generate an image of a luxurious superhero-themed party at Wayne Manor with made-up superheros.")

将 Hugging Face Space 导入为工具

您还可以使用 Tool.from_space() 将 HF Space 导入为工具。这为与社区中数千个 space 集成打开了可能性,用于从图像生成到数据分析的各种任务。

该工具将使用 gradio_client 连接到 space Gradio 后端,因此如果您尚未安装,请确保通过 pip 安装它。

对于派对,阿福可以使用现有的 HF Space 来生成 AI 生成的图像,用于公告(而不是我们之前提到的预构建工具)。让我们构建它!

from smolagents import CodeAgent, HfApiModel, Tool

image_generation_tool = Tool.from_space(
    "black-forest-labs/FLUX.1-schnell",
    name="image_generator",
    description="Generate an image from a prompt"
)

model = HfApiModel("Qwen/Qwen2.5-Coder-32B-Instruct")

agent = CodeAgent(tools=[image_generation_tool], model=model)

agent.run(
    "Improve this prompt, then generate an image of it.",
    additional_args={'user_prompt': 'A grand superhero-themed party at Wayne Manor, with Alfred overseeing a luxurious gala'}
)

导入 LangChain 工具

我们将在接下来的章节中讨论 LangChain 框架。现在,我们只需注意,我们可以在您的 smolagents 工作流程中重用 LangChain 工具!

您可以使用 Tool.from_langchain() 方法轻松加载 LangChain 工具。阿福是一位完美主义者,在韦恩一家外出时,他正在为韦恩庄园举办一场壮观的超级英雄之夜做准备。为了确保每个细节都超出预期,他利用 LangChain 工具来寻找顶级娱乐创意。

通过使用 Tool.from_langchain(),阿福可以轻松地将高级搜索功能添加到他的 smolagent 中,使他只需几个命令即可发现独家的派对创意和服务。

以下是他操作的方法

from langchain.agents import load_tools
from smolagents import CodeAgent, HfApiModel, Tool

search_tool = Tool.from_langchain(load_tools(["serpapi"])[0])

agent = CodeAgent(tools=[search_tool], model=model)

agent.run("Search for luxury entertainment ideas for a superhero-themed event, such as live performances and interactive experiences.")

从任何 MCP 服务器导入工具集合

smolagents 还允许从 glama.aismithery.ai 上提供的数百个 MCP 服务器导入工具。

安装 mcp 客户端

我们首先需要为 smolagents 安装 mcp 集成。

pip install "smolagents[mcp]"

MCP 服务器工具可以加载到 ToolCollection 对象中,如下所示

import os
from smolagents import ToolCollection, CodeAgent
from mcp import StdioServerParameters
from smolagents import HfApiModel


model = HfApiModel("Qwen/Qwen2.5-Coder-32B-Instruct")


server_parameters = StdioServerParameters(
    command="uvx",
    args=["--quiet", "pubmedmcp@0.1.3"],
    env={"UV_PYTHON": "3.12", **os.environ},
)

with ToolCollection.from_mcp(server_parameters, trust_remote_code=True) as tool_collection:
    agent = CodeAgent(tools=[*tool_collection.tools], model=model, add_base_tools=True)
    agent.run("Please find a remedy for hangover.")

通过这种设置,阿福可以快速发现豪华的娱乐选择,确保哥谭市的精英宾客拥有难忘的体验。此工具帮助他为韦恩庄园策划完美的超级英雄主题活动! 🎉

资源

  • 工具教程 - 探索本教程,学习如何有效地使用工具。
  • 工具文档 - 关于工具的综合参考文档。
  • 工具引导 - 帮助您高效构建和使用工具的分步引导。
  • 构建有效的 Agents - 关于开发可靠且高性能的自定义函数 agents 的最佳实践的详细指南。
< > 在 GitHub 上更新