十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

smolagents 高级工具使用指南:从自定义 Tool 到 Hub 分享与工具箱管理

smolagents 高级工具使用指南:从自定义 Tool 到 Hub 分享与工具箱管理 smolagents 高级工具使用指南从自定义 Tool 到 Hub 分享与工具箱管理【免费下载链接】smolagents smolagents: a barebones library for agents that think in code.项目地址: https://gitcode.com/gh_mirrors/smo/smolagents本指南基于 docs/source/zh/tutorials/tools.md 编写聚焦 smolagents 中“工具Tool”的高级用法。你将学会如何通过继承Tool基类构建带完整元数据的自定义工具、如何将工具分享到 Hugging Face Hub 再加载复用、如何把 Gradio Space 与 LangChain 工具一键导入 agent、以及如何管理与组织 agent 的工具箱含ToolCollection集合。文中所有结论均以仓库源码如 src/smolagents/tools.py、tests/test_tools.py为事实依据。如果你刚接触 agent 构建建议先阅读 agent 介绍 和 smolagents 导览再回到本教程学习更高级的工具用法。什么是工具如何构建一个工具为什么工具不能只是一个函数工具本质上是 LLM 可以在 agent 系统中调用的函数。但要被 LLM 正确使用工具必须向模型暴露一个完整的“API”工具名称、工具描述、输入类型与描述、输出类型。因此它不能仅仅是一个函数而应当是一个类。从源码看smolagents 用Tool这个抽象基类定义于 src/smolagents/tools.py#L106-L129来承载这一设计工具是“一个包装了函数的类”并附带帮助 LLM 理解如何调用它的元数据。通过继承Tool构建自定义工具以下是官方教程中的完整示例——构建一个返回 Hugging Face Hub 上某任务下载量最高模型的工具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(filtertask, sortdownloads, direction-1))) return model.id model_downloads_tool HFModelDownloadsTool()自定义工具通过继承 [Tool] 来获得有用的方法。子类需要定义以下属性name工具本身的名称通常描述工具的功能。由于代码返回指定任务下载量最多的模型这里命名为model_download_counter。description一段描述文本会被填入 agent 的系统提示system prompt中帮助 LLM 判断何时使用该工具。inputs一个字典每个输入项包含type和description两个键为 agent 的 Python 解释器选择合适的输入提供依据。output_type指定输出类型。inputs和output_type的类型应采用 Pydantic 格式可取值包括[string, boolean, integer, number, image, audio, array, object, any, null]。forward包含要执行的推理代码的方法。定义好这五部分工具就可以直接交给 agent 使用了。源码级的补充说明在 src/smolagents/tools.py#L82-L93 中AUTHORIZED_TYPES常量完整定义了上述十种合法类型Tool.validate_arguments()src/smolagents/tools.py#L144-L226会在子类实例化时自动校验name必须是合法 Python 标识符、每个输入都必须包含type与description键、类型必须在授权清单内并且forward方法的参数必须与inputs的键严格一致否则会抛出异常。对应地tests/test_tools.py#L85-L120 中的TestTool测试用例专门覆盖了这些输入类型校验分支例如非法类型抛出ValueError、类型为列表时元素必须全为字符串等。这意味着你构建工具时写错元数据会在实例化阶段立刻得到明确报错而不是等到运行时。另外Tool.__call__src/smolagents/tools.py#L231-L249还内置了两个实用行为惰性初始化首次调用工具时才会触发setup()适合加载大模型等昂贵操作只需覆写setup方法即可dict 参数兼容当传入单个字典且其键与inputs匹配时会自动展开为关键字参数。两种构建方式的取舍tool装饰器 vs 继承Tool在 smolagents 导览 中已经介绍过使用tool装饰器把普通函数快速变成工具见 docs/source/zh/guided_tour.md#L246-L263。tool装饰器源码位于 src/smolagents/tools.py#L1061-L1168是定义简单工具的推荐方式它会从函数的类型注解与 docstring 中自动解析出name、description、inputs、output_type等元数据并动态创建一个SimpleTool子类。但有时你需要更多能力例如在类中使用多个方法让代码更清晰使用额外的类属性来硬编码配置需要精细控制输入 schema。这时就应像上面那样通过继承Tool来构建工具。两种方式在 agent 中的使用完全等价可以按需选择。将你的工具分享到 Hub一键推送push_to_hub调用 [~Tool.push_to_hub] 即可把自定义工具以 Space 仓库的形式分享到 Hugging Face Hub。前提是你已经在 Hub 上为该工具创建了仓库并且使用的 token 具有写权限model_downloads_tool.push_to_hub({your_username}/hf-model-downloads, tokenYOUR_HUGGINGFACEHUB_API_TOKEN)从源码看push_to_hub会依次完成创建或复用repo_typespace、space_sdkgradio的仓库并打上smolagents、tool标签见_initialize_hub_reposrc/smolagents/tools.py#L460-L472然后提交三个文件见_prepare_hub_filessrc/smolagents/tools.py#L474-L493tool.py工具的完整逻辑代码app.py由launch_gradio_demo自动生成的 Gradio 演示界面requirements.txt通过静态分析工具代码提取出的依赖列表。其他参数还包括commit_message默认Upload tool、private是否私有、create_pr是否以 PR 形式提交。推送前的三条硬性规则为了让工具能被正确序列化并推送到 Hub你的工具必须遵守以下规则否则调用 [~Tool.save] 或 [~Tool.push_to_hub] 时会报错所有方法自包含方法只使用来自自身参数的变量所有 import 必须写在工具函数内部不要在模块顶层导入第三方库否则序列化检查会失败。这正是上面示例中from huggingface_hub import list_models写在forward内部的原因如果覆写__init__除self外不允许任何其他参数因为工具实例初始化时设置的参数难以跟踪会阻碍正确分享到 Hub。需要硬编码的内容直接以类属性形式写在class YourTool(Tool):行下方即可当然你也可以在代码中任何位置通过self.your_variable ...动态创建实例属性。加载 Hub 上的工具工具推送成功后即成为带 Gradio 界面的 Space。在 src/smolagents/tools.py#L516-L569 的Tool.from_hub与顶层函数load_tool中加载逻辑是下载该 Space 中的tool.py文件动态执行源码找到其中的Tool子类并实例化。由于运行工具意味着执行自定义代码必须显式传入trust_remote_codeTrue表明你信任该仓库否则加载会直接失败from smolagents import load_tool, CodeAgent model_download_tool load_tool( {your_username}/hf-model-downloads, trust_remote_codeTrue )[!WARNING] 从 Hub 加载工具会在本地执行其代码。请像安装 pip/npm 包一样先检查工具的tool.py内容再运行。将 Space 导入为工具使用 [Tool.from_space]src/smolagents/tools.py#L599-L739可以直接把一个 Hugging Face 上的 Gradio Space 变成工具。你只需提供 Space 的 id、工具名称和一段帮助 agent 理解功能的描述。底层通过gradio-client库与 Space 交互。例如导入 FLUX.1-schnell 文生图 Spaceimage_generation_tool Tool.from_space( black-forest-labs/FLUX.1-schnell, nameimage_generator, descriptionGenerate an image from a prompt ) image_generation_tool(A sunny beach)源码细节from_space内部会实例化一个SpaceToolWrapper自动通过client.view_api()读取 Space 暴露的 API 签名来构建inputs与output_type输出组件为 Image 时映射为image为 Audio 时映射为audio否则为any。若 Space 有多个标签页可通过api_name参数指定具体 API不指定时默认取第一个可用 API 并给出警告。它还会把本地图片文件、PIL.Image对象或 HTTP URL 自动转换为 gradio 客户端可用的handle_file形式并处理返回的图片/音频路径。导入后即可像普通工具一样使用。例如让 agent 先改进提示词、再生成图片from smolagents import CodeAgent, InferenceClientModel model InferenceClientModel(model_idQwen/Qwen3-Next-80B-A3B-Thinking) agent CodeAgent(tools[image_generation_tool], modelmodel) agent.run( Improve this prompt, then generate an image of it., additional_args{user_prompt: A rabbit wearing a space suit} )运行时 agent 会先思考改进后的提示词再调用工具执行代码 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(promptA 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)这个示例还展示了如何通过additional_args{user_prompt: ...}向 agent 传递额外的用户上下文。使用 LangChain 工具smolagents 也支持直接复用 LangChain 生态中丰富的工具。使用from_langchain()方法即可导入from langchain.agents import load_tools search_tool Tool.from_langchain(load_tools([serpapi])[0]) agent CodeAgent(tools[search_tool], modelmodel) 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?)使用前需要安装依赖pip install langchain google-search-results -q源码细节Tool.from_langchainsrc/smolagents/tools.py#L762-L791会创建LangChainToolWrapper将 LangChain 工具的name转为小写、description、args复制到 smolagents 的Tool接口中output_type固定为string并在forward中调用原langchain_tool.run()。管理你的 agent 工具箱agent 的工具箱就是一个以工具名为键的标准字典agent.tools因此可以直接通过添加或替换字典项来管理。下面的例子把前面加载的model_download_tool添加到一个仅使用默认工具箱初始化的 agent 中from smolagents import InferenceClientModel model InferenceClientModel(model_idQwen/Qwen3-Next-80B-A3B-Thinking) agent CodeAgent(tools[], modelmodel, add_base_toolsTrue) agent.tools[model_download_tool.name] model_download_tool现在 agent 就多了一个新工具可以提出这样的任务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? )源码细节在 src/smolagents/agents.py#L389-L402 的_setup_tools中可以看到add_base_toolsTrue时会把 src/smolagents/default_tools.py#L678-L681 中TOOL_MAPPING定义的默认工具如PythonInterpreterTool、WebSearchTool等全部加入工具箱同时无论何时都会自动补上final_answer工具见 src/smolagents/default_tools.py#L83-L90它是 agent 收敛答案、结束任务的关键出口。每次运行任务时这些工具都会被发送给 Python 执行器send_tools而agent.tools就是你随时可以增删改的入口。[!TIP] 注意不要向 agent 添加太多工具这可能会让较弱的 LLM 引擎不堪重负反而降低任务完成质量。使用工具集合当工具数量较多时可以使用ToolCollection对象一次性加载一组工具再以列表形式传给 agent 初始化。从 Hub 集合加载工具使用你想使用的集合的 slugfrom smolagents import ToolCollection, CodeAgent image_tool_collection ToolCollection.from_hub( collection_slughuggingface-tools/diffusion-tools-6630bb19a942c2306a2cdb6f, tokenYOUR_HUGGINGFACEHUB_API_TOKEN ) agent CodeAgent(tools[*image_tool_collection.tools], modelmodel, add_base_toolsTrue) agent.run(Please draw me a picture of rivers and lakes.)源码细节ToolCollection.from_hub通过get_collection拉取集合只筛选其中类型为 Space 的项目然后对每个 Space 调用Tool.from_hub实例化工具私有集合需传token同样需要trust_remote_codeTrue。为了加快启动速度工具只有在 agent 实际调用时才会被加载。从 MCP 服务器加载工具集合ToolCollection.from_mcpsrc/smolagents/tools.py#L949-L1058可以从任意 MCP 服务器批量导入工具支持 Stdio 与 Streamable HTTP以及兼容sse两类传输协议。注意该 API 需要安装额外依赖pip install smolagents[mcp]并且加载 MCP 工具同样要求显式传入trust_remote_codeTrue。Stdio 服务器示例from smolagents import ToolCollection, CodeAgent from mcp import StdioServerParameters import os server_parameters StdioServerParameters( commanduvx, args[--quiet, pubmedmcp0.1.3], env{UV_PYTHON: 3.12, **os.environ}, ) with ToolCollection.from_mcp(server_parameters, trust_remote_codeTrue) as tool_collection: agent CodeAgent(tools[*tool_collection.tools], modelmodel, add_base_toolsTrue) agent.run(Please find a remedy for hangover.)Streamable HTTP 服务器只需传一个带transport键的字典from smolagents import ToolCollection, CodeAgent with ToolCollection.from_mcp({url: http://127.0.0.1:8000/mcp, transport: streamable-http}, trust_remote_codeTrue) as tool_collection: agent CodeAgent(tools[*tool_collection.tools], add_base_toolsTrue) agent.run(Please find a remedy for hangover.)如需启用结构化输出支持可追加structured_outputTrue参数。[!WARNING]安全警告使用 MCP 服务器前务必核实其来源与完整性尤其在生产环境中。Stdio 型 MCP 服务器必然会在你的机器上执行代码这正是其功能Streamable HTTP 型远程服务器虽不会直接在本机执行代码仍需保持警惕。结构化输出与输出 Schema 支持基于 2025-06-18 及之后的 MCP 规范MCP 工具可以携带outputSchema声明输出结构。smolagents 支持通过structured_outputTrue开启该能力让 agent 的 LLM 在调用工具前就能“看到”输出的数据结构从而更智能地处理 JSON 等复杂返回from smolagents import MCPClient, CodeAgent # 启用结构化输出支持 with MCPClient(server_parameters, structured_outputTrue) as tools: agent CodeAgent(toolstools, modelmodel, add_base_toolsTrue) agent.run(Get weather information for Paris)启用后主要带来三点增强输出 Schema 支持工具可为输出定义 JSON Schema、结构化内容处理兼容 MCP 响应中的structuredContent、JSON 解析自动从工具响应中解析结构化数据。同时CodeAgent的系统提示会相应增强把工具的 JSON Schema 信息注入其中相关实现见 src/smolagents/tools.py#L258-L287 的to_code_prompt。配合 pydantic 定义一个带结构化输出的 MCP 服务器demo/weather.pyfrom pydantic import BaseModel, Field from mcp.server.fastmcp import FastMCP mcp FastMCP(Weather Service) class WeatherInfo(BaseModel): location: str Field(descriptionThe location name) temperature: float Field(descriptionTemperature in Celsius) conditions: str Field(descriptionWeather conditions) humidity: int Field(descriptionHumidity percentage, ge0, le100) mcp.tool( nameget_weather_info, descriptionGet weather information for a location as structured data., # structured_outputTrue is enabled by default in FastMCP ) def get_weather_info(city: str) - WeatherInfo: Get weather information for a city. return WeatherInfo( locationcity, temperature22.5, conditionspartly cloudy, humidity65 )然后配合structured_outputTrue使用from smolagents import MCPClient, CodeAgent from mcp import StdioServerParameters server_parameters StdioServerParameters( commandpython, args[demo/weather.py] ) with MCPClient(server_parameters, structured_outputTrue) as tools: agent CodeAgent(toolstools, modelmodel) result agent.run(What is the temperature in Tokyo in Fahrenheit?) print(result)兼容性说明当前版本structured_output默认值为False以保持向后兼容现有代码无需改动即可继续获得纯文本输出。但官方计划在后续版本源码中的警告信息提示为 1.25将默认值改为True因此建议显式传入structured_outputTrue以提前获得更优的工具输出处理仅在确实需要维持纯文本行为时才显式传False。小结围绕工具这个核心概念本教程覆盖了 smolagents 的完整工具生态场景推荐方式关键入口简单工具tool装饰器smolagents.tool复杂工具继承Tool并覆写forwardsrc/smolagents/tools.py#L106-L129分享工具到 Hubtool.push_to_hub()src/smolagents/tools.py#L421-L458从 Hub 加载工具load_tool()/Tool.from_hub()src/smolagents/tools.py#L840-L879导入 Gradio SpaceTool.from_space()src/smolagents/tools.py#L599-L739导入 LangChain 工具Tool.from_langchain()src/smolagents/tools.py#L762-L791管理工具箱直接操作agent.tools字典src/smolagents/agents.py#L389-L402工具集合ToolCollection.from_hub/from_mcpsrc/smolagents/tools.py#L909-L1058掌握这些能力后你可以轻松扩展 agent 的感知与行动边界既能用几行代码定义专属工具并沉淀到 Hub 复用也能把 Hugging Face Space、LangChain 乃至 MCP 服务器上的现成能力批量接入 agent。相关源码与测试可进一步查阅 src/smolagents/tools.py、src/smolagents/default_tools.py、tests/test_tools.py 以及 工具 API 参考。【免费下载链接】smolagents smolagents: a barebones library for agents that think in code.项目地址: https://gitcode.com/gh_mirrors/smo/smolagents创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表