这篇适合谁,读完能做到什么
如果你已经能让智能体跑起来,想把它接到自己的函数、第三方服务或 MCP 服务器上,这篇适合你。读完你应该能用两种方式定义一个工具,知道 smolagents 自带哪些工具,并会从 Hub、Hugging Face Space、LangChain 或 MCP 服务器导入现成的工具。
工具是什么
在 smolagents 里,工具就是大模型在智能体系统中可以调用的函数[1]。要让模型正确使用一个工具,它需要一份接口描述,包括四部分:名称、说明工具用途的描述、输入参数的类型和说明,以及输出类型[1]。
比如一个网页搜索工具可以叫 web_search,接收一个 query 字符串作为输入,返回包含搜索结果的字符串[1]。模型就是靠这份描述判断要不要调用它、怎么调用,所以描述要写清楚。接口描述里的四项(名称、描述、输入、输出)对应模型读取工具时需要的全部信息[1]。
两种定义方式
smolagents 提供两种定义工具的方式。@tool 装饰器包装普通的 Python 函数,适合简单的工具;继承 Tool 类则适合功能更复杂的工具[1]。
@tool 是定义简单工具的推荐方式。smolagents 会从 Python 函数中读取基本信息,所以函数名要清楚,文档字符串要写好,模型才用得顺手[1]。一个写得好的 @tool 函数,应该有描述性的函数名,输入和输出的类型注解,以及带 Args: 部分的详细说明,逐个解释参数[1]。
下面的例子定义了一个返回哥谭市评分最高的餐饮服务的工具。函数里的服务列表是写死的示例数据,并不是真正的搜索,所以这段代码展示的是结构,不是可直接上线的集成[1]:
@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要让它真正联网,需要你自己把 services 换成真实的数据来源,示例本身不会联网[1]。
把工具交给使用 InferenceClientModel 的 CodeAgent,再打印 agent.run() 的结果即可。示例中给出的输出是 Gotham Catering Co.[1]:
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.第二种方式是继承 Tool。子类会把函数包装在元数据之中,需要定义 name、description、inputs、output_type,以及包含逻辑的 forward 方法[1]。其中 description 会被用来填充智能体的系统提示词[1]。inputs 是一个字典,每个输入都要带 type 和 description 两个键[1]。下面的类定义了一个生成超级英雄主题派对创意的工具[1]:
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"forward 方法按类别查找主题,找不到时返回一句提示[1]:
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'.")使用时先实例化,再把实例传给智能体[1]:
# 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?"
)内置工具箱
smolagents 自带一批预置工具,可以直接放进智能体。它们是 PythonInterpreterTool、FinalAnswerTool、UserInputTool、DuckDuckGoSearchTool、GoogleSearchTool 和 VisitWebpageTool[1]。用法和自定义工具一样,加入 tools 列表即可。内置工具由库提供,自定义工具则要你自己定义名称、描述和参数说明[1]。工具的名称和描述是模型判断用哪个工具时依据的主要信息[1]。
分享工具和导入别人的工具
自定义工具可以用 push_to_hub() 上传到你的 Hugging Face 账号下[1]。示例中的用户名和令牌只是占位符,运行前要换成你自己的:
party_theme_tool.push_to_hub("{your_username}/party_theme_tool", token="<YOUR_HUGGINGFACEHUB_API_TOKEN>")反过来,load_tool() 可以导入别人分享到 Hub 上的工具[1]。发布之后,其他人同样可以按仓库名用 load_tool() 导入你的工具[1]。分享前,请确认工具的名称、描述和参数说明都写完整,别人导入后同样靠这些信息来使用它[1]。下面的例子加载了一个文生图工具,交给智能体使用:
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.")trust_remote_code=True 允许工具运行存放在其仓库中的代码,所以只加载你信任的作者分享的工具。
把 Hugging Face Space 变成工具
Tool.from_space() 可以把一个 Hugging Face Space 变成工具[1]。它通过 Space 的 Gradio 后端连接,依赖 gradio_client 包,如果没有安装,需要先用 pip 装上[1]。下面的例子使用一个图像生成 Space,让智能体先改写提示词,再生成图片[1]:
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 工具
Tool.from_langchain() 可以把 LangChain 工具加载进 smolagents 的工作流[1]。先安装 LangChain 的集成包[1]:
pip install -U langchain-communitySerpAPITool 这类搜索工具需要 SerpAPI 的密钥。示例通过环境变量 SERPAPI_API_KEY 设置它[1]:
os.environ['SERPAPI_API_KEY'] = '...'转换之后的 LangChain 工具与 smolagents 自带的工具用法相同,放进 tools 列表即可。下面的代码加载一个 SerpAPI 工具并交给 CodeAgent。代码中的 model 是一个需要事先创建好的模型对象[1]:
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 也能从 MCP 服务器导入工具。可用的 MCP 服务器列在 glama.ai 和 smithery.ai 上,两个站点合起来有数百个[1]。先安装 MCP 集成[1]:
pip install "smolagents[mcp]"下面的例子把一个 MCP 服务器的工具装进 ToolCollection,然后在 with 代码块中运行智能体。服务器通过 uvx 启动,使用的是 pubmedmcp 包[1]:
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.")限制和常见问题
- 描述决定模型的用法。工具的名称和描述会进入提示词,描述含糊,模型就容易选错工具或填错参数。
- 搜索类工具要先配置密钥,LangChain 的 SerpAPI 工具就需要
SERPAPI_API_KEY[1]。 - 导入第三方工具时,
trust_remote_code=True会让远端代码运行,务必先看清来源。 - 使用 Space 工具要先安装
gradio_client,使用 MCP 工具要先安装smolagents[mcp][1]。 - 示例用
with语句包住ToolCollection,把 MCP 连接的使用范围限定在代码块之内[1]。 - 工具要尽量只做一件事。一个工具只负责一个明确的动作,模型更容易判断什么时候该用它。同一个智能体可以同时挂载内置、自定义和导入的工具,但工具越多,模型每一步要比较的选项也越多[1]。
下一步
smolagents 官方的工具页面里有更多写法[2]。想深入了解 MCP,可以从那门免费的 MCP 课程开始[1]。
本文改编自 Hugging Face 开源智能体课程第二单元 smolagents 部分中的工具一节[1],原文以 Apache-2.0 许可证发布。
来源
- 1ToolsHugging Face agents-course (Apache-2.0)
- 2Tools TutorialHugging Face
引用本页: smolagents 自定义工具. TellWorld, https://www.tellworld.net/zh/practice/practice-smolagents-tools. 更新于 2026-11-14