智能体课程文档

工具

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

Ask a Question Open In Colab

工具

正如我们在第一单元中探讨的,Agent 使用工具来执行各种操作。在 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, InferenceClientModel, 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=InferenceClientModel())

# 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, InferenceClientModel

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=InferenceClientModel())

# 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, InferenceClientModel

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

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

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, InferenceClientModel, Tool

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

model = InferenceClientModel("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, InferenceClientModel, 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,可以查看我们的免费 MCP 课程

安装 mcp 客户端

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

pip install "smolagents[mcp]"

MCP 服务器工具可以按如下方式加载到一个 ToolCollection 对象中:

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


model = InferenceClientModel("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.")

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

资源

  • 工具教程 - 探索此教程以学习如何有效地使用工具。
  • 工具文档 - 关于工具的全面参考文档。
  • 工具导览 - 一步一步的导览,帮助您高效地构建和利用工具。
  • 构建高效的 Agent - 关于开发可靠和高性能自定义功能 Agent 的最佳实践的详细指南。
< > 在 GitHub 上更新