smolagents 文档
工具
并获得增强的文档体验
开始使用
工具
在这里,我们将看到工具的高级用法。
如果您是 Agent 构建新手,请务必先阅读 Agent 介绍 和 smolagents 引导教程。
什么是工具,以及如何构建工具?
工具主要是 LLM 可以在 Agent 系统中使用的函数。
但是要使用它,需要给 LLM 提供一个 API:名称、工具描述、输入类型和描述、输出类型。
因此它不能仅仅是一个函数。它应该是一个类。
因此,工具的核心是一个类,它用元数据包装一个函数,以帮助 LLM 理解如何使用它。
以下是它的外观
from smolagents import Tool
class HFModelDownloadsTool(Tool):
name = "model_download_counter"
description = """
This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub.
It returns the name of the checkpoint."""
inputs = {
"task": {
"type": "string",
"description": "the task category (such as text-classification, depth-estimation, etc)",
}
}
output_type = "string"
def forward(self, task: str):
from huggingface_hub import list_models
model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
return model.id
model_downloads_tool = HFModelDownloadsTool()
自定义工具继承 Tool 以继承有用的方法。子类还定义了
- 一个属性
name
,它对应于工具本身的名称。该名称通常描述工具的作用。由于代码返回任务下载次数最多的模型,让我们将其命名为model_download_counter
。 - 属性
description
用于填充 Agent 的系统提示。 - 一个
inputs
属性,它是一个字典,键为"type"
和"description"
。它包含有助于 Python 解释器对输入做出明智选择的信息。 - 一个
output_type
属性,它指定输出类型。inputs
和output_type
的类型都应为 Pydantic 格式,它们可以是以下任何一种:~AUTHORIZED_TYPES()
。 - 一个
forward
方法,其中包含要执行的推理代码。
这就是在 Agent 中使用它所需的全部内容!
还有另一种构建工具的方法。在引导教程中,我们使用 @tool
装饰器实现了一个工具。tool() 装饰器是定义简单工具的推荐方法,但有时您需要更多:在一个类中使用多个方法以获得更高的清晰度,或使用其他类属性。
在这种情况下,您可以通过子类化 Tool 来构建您的工具,如上所述。
将您的工具分享到 Hub
您可以通过在工具上调用 push_to_hub() 将您的自定义工具分享到 Hub。确保您已在 Hub 上为其创建了一个仓库,并且正在使用具有读取权限的令牌。
model_downloads_tool.push_to_hub("{your_username}/hf-model-downloads", token="<YOUR_HUGGINGFACEHUB_API_TOKEN>")
为了使推送到 Hub 工作,您的工具需要遵守一些规则
- 所有方法都是自包含的,例如,使用来自其 args 的变量。
- 根据以上几点,所有导入都应直接在工具的函数中定义,否则在尝试使用您的自定义工具调用 save() 或 push_to_hub() 时,您将收到错误。
- 如果您子类化
__init__
方法,则可以使其仅包含self
参数。这是因为在特定工具实例的初始化期间设置的参数很难跟踪,这会阻止它们正确地共享到 hub。无论如何,创建特定类的想法是,您可以为您需要硬编码的任何内容设置类属性(只需在class YourTool(Tool):
行下直接设置your_variable=(...)
即可)。当然,您仍然可以通过将内容分配给self.your_variable
在代码中的任何位置创建类属性。
一旦您的工具被推送到 Hub,您就可以可视化它。这里 是我推送的 model_downloads_tool
。它具有漂亮的 Gradio 界面。
当深入研究工具文件时,您可以发现所有工具的逻辑都在 tool.py 下。您可以在那里检查其他人共享的工具。
然后,您可以使用 load_tool() 加载工具,或使用 from_hub() 创建工具,并将其传递给 Agent 中的 tools
参数。由于运行工具意味着运行自定义代码,因此您需要确保信任仓库,因此我们需要传递 trust_remote_code=True
才能从 Hub 加载工具。
from smolagents import load_tool, CodeAgent
model_download_tool = load_tool(
"{your_username}/hf-model-downloads",
trust_remote_code=True
)
将 Space 导入为工具
您可以使用 Tool.from_space() 方法直接从 Hub 导入 Space 作为工具!
您只需要提供 Hub 上 Space 的 ID、其名称以及描述,这将帮助您的 Agent 理解工具的作用。在幕后,这将使用 gradio-client
库来调用 Space。
例如,让我们从 Hub 导入 FLUX.1-dev Space,并使用它来生成图像。
image_generation_tool = Tool.from_space(
"black-forest-labs/FLUX.1-schnell",
name="image_generator",
description="Generate an image from a prompt"
)
image_generation_tool("A sunny beach")
瞧,这是您的图像!🏖️

然后您可以像使用任何其他工具一样使用此工具。例如,让我们改进提示 a rabbit wearing a space suit
并生成它的图像。此示例还展示了如何将其他参数传递给 Agent。
from smolagents import CodeAgent, HfApiModel
model = HfApiModel(model_id="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 rabbit wearing a space suit'}
)
=== Agent thoughts: improved_prompt could be "A bright blue space suit wearing rabbit, on the surface of the moon, under a bright orange sunset, with the Earth visible in the background" Now that I have improved the prompt, I can use the image generator tool to generate an image based on this prompt. >>> Agent is executing the code below: image = image_generator(prompt="A bright blue space suit wearing rabbit, on the surface of the moon, under a bright orange sunset, with the Earth visible in the background") final_answer(image)

这有多酷?🤩
使用 LangChain 工具
我们喜欢 Langchain,并认为它有一套非常引人注目的工具。要从 LangChain 导入工具,请使用 from_langchain()
方法。
以下是如何使用它来使用 LangChain 网络搜索工具重新创建介绍中的搜索结果。此工具需要 pip install langchain google-search-results -q
才能正常工作。
from langchain.agents import load_tools
search_tool = Tool.from_langchain(load_tools(["serpapi"])[0])
agent = CodeAgent(tools=[search_tool], model=model)
agent.run("How many more blocks (also denoted as layers) are in BERT base encoder compared to the encoder from the architecture proposed in Attention is All You Need?")
管理您的 Agent 的工具箱
您可以通过在属性 agent.tools
中添加或替换工具来管理 Agent 的工具箱,因为它是一个标准字典。
让我们将 model_download_tool
添加到仅使用默认工具箱初始化的现有 Agent。
from smolagents import HfApiModel
model = HfApiModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct")
agent = CodeAgent(tools=[], model=model, add_base_tools=True)
agent.tools[model_download_tool.name] = model_download_tool
现在我们可以利用新工具
agent.run(
"Can you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub but reverse the letters?"
)
注意不要向 Agent 添加太多工具:这可能会使较弱的 LLM 引擎不堪重负。
使用工具集合
您可以通过使用 ToolCollection 来利用工具集合。它支持从 Hub 或 MCP 服务器工具加载集合。
从 Hub 中的集合获取工具集合
您可以使用要使用的集合的 slug 来利用它。然后将它们作为列表传递以初始化您的 Agent,并开始使用它们!
from smolagents import ToolCollection, CodeAgent
image_tool_collection = ToolCollection.from_hub(
collection_slug="huggingface-tools/diffusion-tools-6630bb19a942c2306a2cdb6f",
token="<YOUR_HUGGINGFACEHUB_API_TOKEN>"
)
agent = CodeAgent(tools=[*image_tool_collection.tools], model=model, add_base_tools=True)
agent.run("Please draw me a picture of rivers and lakes.")
为了加快启动速度,工具仅在 Agent 调用时加载。
从任何 MCP 服务器获取工具集合
利用来自 glama.ai 或 smithery.ai 上提供的数百个 MCP 服务器的工具。
安全警告: 使用 MCP 服务器存在安全风险
- 信任至关重要: 仅使用来自可信来源的 MCP 服务器。恶意服务器可能会在您的机器上执行有害代码。
- 基于 Stdio 的 MCP 服务器 始终会在您的机器上执行代码(这是它们的预期功能)。
- 基于 SSE 的 MCP 服务器 在当前的实现中可能容易受到远程代码执行攻击。修复程序正在开发中,但仍建议谨慎。
在连接到任何 MCP 服务器之前,务必验证其来源和完整性,尤其是在生产环境中。
MCP 服务器工具可以使用 ToolCollection.from_mcp() 加载。
对于基于 stdio 的 MCP 服务器,请将服务器参数作为 mcp.StdioServerParameters
的实例传递
from smolagents import ToolCollection, CodeAgent
from mcp import StdioServerParameters
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.")
对于基于 SSE 的 MCP 服务器,只需将包含参数的 dict 传递给 mcp.client.sse.sse_client
from smolagents import ToolCollection, CodeAgent
with ToolCollection.from_mcp({"url": "http://127.0.0.1:8000/sse"}, trust_remote_code=True) as tool_collection:
agent = CodeAgent(tools=[*tool_collection.tools], add_base_tools=True)
agent.run("Please find a remedy for hangover.")