smolagents 文档

工具

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

工具

Smolagents 是一个实验性 API,随时可能更改。由于 API 或底层模型容易发生变化,智能体返回的结果可能会有所不同。

要了解有关智能体和工具的更多信息,请务必阅读入门指南。此页面包含底层类的 API 文档。

工具

load_tool

smolagents.load_tool

< >

( repo_id model_repo_id: typing.Optional[str] = None token: typing.Optional[str] = None trust_remote_code: bool = False **kwargs )

参数

  • repo_id (str) — Hub 上工具的 Repo ID。
  • model_repo_id (str, optional) — 使用此参数可以为所选工具使用与默认模型不同的模型。
  • token (str, optional) — 用于在 hf.co 上识别您的令牌。如果未设置,将使用运行 huggingface-cli login 时生成的令牌(存储在 ~/.huggingface 中)。
  • trust_remote_code (bool, optional, defaults to False) — 需要接受此项才能从 Hub 加载工具。
  • kwargs (附加关键字参数, optional) — 将拆分为两部分的附加关键字参数:所有与 Hub 相关的参数(例如 cache_dirrevisionsubfolder)将在下载工具文件时使用,其他参数将传递给其 init。

从 Hub 快速加载工具的主函数。

加载工具意味着您将下载该工具并在本地执行它。在运行时加载工具之前,请务必检查您要下载的工具,就像使用 pip/npm/apt 安装软件包时一样。

tool

smolagents.tool

< >

( tool_function: typing.Callable )

参数

  • tool_function (Callable) — 转换为 Tool 子类的函数。应为每个输入提供类型提示,并为输出提供类型提示。还应包含一个文档字符串,其中包含函数描述和一个“Args:”部分,其中描述了每个参数。

将函数转换为动态创建的 Tool 子类的实例。

Tool

class smolagents.Tool

< >

( *args **kwargs )

代理使用的函数基类。继承此类并实现 forward 方法以及以下类属性

  • description (str) — 简要描述您的工具的功能、期望的输入和将返回的输出。例如“这是一个从 url 下载文件的工具。它以 url 作为输入,并返回文件中包含的文本”。
  • name (str) — 将在代理提示中用于您的工具的执行性名称。例如 "text-classifier""image_generator"
  • inputs (Dict[str, Dict[str, Union[str, type, bool]]]) — 输入期望的模态字典。它有一个 typekey 和一个 descriptionkey。launch_gradio_demo 使用它或从您的工具创建一个漂亮的 space,也可以在为您工具生成的描述中使用。
  • output_type (type) — 工具输出的类型。launch_gradio_demo 使用它或从您的工具创建一个漂亮的 space,也可以在为您工具生成的描述中使用。

如果您的工具在可用之前需要执行昂贵的操作(例如加载模型),您还可以覆盖方法 setup()setup() 将在您第一次使用工具时调用,而不是在实例化时调用。

from_gradio

< >

( gradio_tool )

从 gradio 工具创建 Tool。

from_hub

< >

( repo_id: str token: typing.Optional[str] = None trust_remote_code: bool = False **kwargs )

参数

  • repo_id (str) — Hub 上定义您的工具的仓库名称。
  • token (str, optional) — 用于在 hf.co 上识别您的令牌。如果未设置,将使用运行 huggingface-cli login 时生成的令牌(存储在 ~/.huggingface 中)。
  • trust_remote_code(str, optional, defaults to False) — 此标志表明您了解运行远程代码的风险,并且您信任此工具。如果不将其设置为 True,则从 Hub 加载工具将失败。
  • kwargs (附加关键字参数, optional) — 将拆分为两部分的附加关键字参数:所有与 Hub 相关的参数(例如 cache_dirrevisionsubfolder)将在下载工具文件时使用,其他参数将传递给其 init。

加载 Hub 上定义的工具。

从 Hub 加载工具意味着您将下载该工具并在本地执行它。在运行时加载工具之前,请务必检查您要下载的工具,就像使用 pip/npm/apt 安装软件包时一样。

from_langchain

< >

( langchain_tool )

从 langchain 工具创建一个 Tool

from_space

< >

( space_id: str name: str description: str api_name: typing.Optional[str] = None token: typing.Optional[str] = None ) Tool

参数

  • space_id (str) — Hub 上的 Space 的 ID。
  • name (str) — 工具的名称。
  • description (str) — 工具的描述。
  • api_name (str, 可选) — 要使用的特定 api_name,如果 space 有多个标签页。 如果未指定,则默认为第一个可用的 api。
  • token (str, 可选) — 添加您的令牌以访问私有 space 或增加您的 GPU 配额。

返回

Tool

Space,作为一个工具。

从 Hub 上给定 ID 的 Space 创建一个 Tool

示例

>>> image_generator = Tool.from_space(
...     space_id="black-forest-labs/FLUX.1-schnell",
...     name="image-generator",
...     description="Generate an image from a prompt"
... )
>>> image = image_generator("Generate an image of a cool surfer in Tahiti")
>>> face_swapper = Tool.from_space(
...     "tuan2308/face-swap",
...     "face_swapper",
...     "Tool that puts the face shown on the first image on the second image. You can give it paths to images.",
... )
>>> image = face_swapper('./aymeric.jpeg', './ruth.jpg')

push_to_hub

< >

( repo_id: str commit_message: str = 'Upload tool' private: typing.Optional[bool] = None token: typing.Union[bool, str, NoneType] = None create_pr: bool = False )

参数

  • repo_id (str) — 您想要将工具推送到的仓库名称。 当推送到给定的组织时,它应该包含您的组织名称。
  • commit_message (str, 可选, 默认为 "Upload tool") — 推送时提交的消息。
  • private (bool, 可选) — 是否将仓库设为私有。 如果为 None(默认),则仓库将是公开的,除非组织的默认设置为私有。 如果仓库已存在,则此值将被忽略。
  • token (boolstr, 可选) — 用作远程文件的 HTTP Bearer 授权的令牌。 如果未设置,将使用运行 huggingface-cli login 时生成的令牌(存储在 ~/.huggingface 中)。
  • create_pr (bool, 可选, 默认为 False) — 是否使用上传的文件创建 PR 或直接提交。

将工具上传到 Hub。

save

< >

( output_dir: str | pathlib.Path tool_file_name: str = 'tool' make_gradio_app: bool = True )

参数

  • output_dir (strPath) — 您要将工具保存在其中的文件夹。
  • tool_file_name (str, 可选) — 您要将工具保存在其中的文件名。
  • make_gradio_app (bool, 可选, 默认为 True) — 是否同时导出 requirements.txt 文件和 Gradio UI。

保存工具的相关代码文件,以便可以将其推送到 Hub。 这会将工具的代码复制到 output_dir 中,并自动生成

  • 一个 {tool_file_name}.py 文件,其中包含工具的逻辑。 如果您传递 make_gradio_app=True,这将还会写入
  • 一个 app.py 文件,当使用 tool.push_to_hub() 导出到 Space 时,为您的工具提供 UI
  • 一个 requirements.txt,其中包含工具使用的模块的名称(在检查其代码时检测到)

setup

< >

( )

在此处覆盖此方法,以进行任何昂贵的操作,并且需要在开始使用工具之前执行。 例如加载大型模型。

to_dict

< >

( )

返回表示工具的字典

launch_gradio_demo

smolagents.launch_gradio_demo

< >

( tool: Tool )

参数

  • tool (Tool) — 要为其启动演示的工具。

为工具启动一个 gradio 演示。 相应的工具类需要正确实现类属性 inputsoutput_type

默认工具

PythonInterpreterTool

class smolagents.PythonInterpreterTool

< >

( *args authorized_imports = None **kwargs )

FinalAnswerTool

class smolagents.FinalAnswerTool

< >

( *args **kwargs )

UserInputTool

class smolagents.UserInputTool

< >

( *args **kwargs )

DuckDuckGoSearchTool

class smolagents.DuckDuckGoSearchTool

< >

( max_results = 10 **kwargs )

GoogleSearchTool

class smolagents.GoogleSearchTool

< >

( provider: str = 'serpapi' )

VisitWebpageTool

class smolagents.VisitWebpageTool

< >

( max_output_length: int = 40000 )

SpeechToTextTool

class smolagents.SpeechToTextTool

< >

( *args **kwargs )

ToolCollection

class smolagents.ToolCollection

< >

( tools: typing.List[smolagents.tools.Tool] )

工具集合允许在代理的工具箱中加载工具集合。

集合可以从 Hub 中的集合或 MCP 服务器加载,请参阅

有关示例和用法,请参阅: ToolCollection.from_hub()ToolCollection.from_mcp()

from_hub

< >

( collection_slug: str token: typing.Optional[str] = None trust_remote_code: bool = False ) ToolCollection

参数

  • collection_slug (str) — 引用集合的集合slug。
  • token (str, 可选) — 如果集合是私有的,则为身份验证令牌。
  • trust_remote_code (bool, 可选, 默认为 False) — 是否信任远程代码。

返回

ToolCollection

使用工具加载的工具集合实例。

从 Hub 加载工具集合。

它将集合中所有 Spaces 的工具集合添加到代理的工具箱中

[!NOTE] 只会获取 Spaces,因此您可以随意将模型和数据集添加到您的集合中,如果您希望此集合展示它们。

示例

>>> from smolagents import ToolCollection, CodeAgent

>>> image_tool_collection = ToolCollection.from_hub("huggingface-tools/diffusion-tools-6630bb19a942c2306a2cdb6f")
>>> agent = CodeAgent(tools=[*image_tool_collection.tools], add_base_tools=True)

>>> agent.run("Please draw me a picture of rivers and lakes.")

from_mcp

< >

( server_parameters: typing.Union[ForwardRef('mcp.StdioServerParameters'), dict] trust_remote_code: bool = False ) ToolCollection

参数

  • server_parameters (mcp.StdioServerParametersdict) — 用于连接到 MCP 服务器的服务器参数。如果提供了 dict,则假定它是 mcp.client.sse.sse_client 的参数。
  • trust_remote_code (bool, 可选, 默认为 False) — 是否信任执行来自 MCP 服务器上定义的工具的代码。 仅当您信任 MCP 服务器,并了解在本地计算机上运行远程代码相关的风险时,才应将此选项设置为 True。 如果设置为 False,则从 MCP 加载工具将失败。

返回

ToolCollection

工具集合实例。

自动从 MCP 服务器加载工具集合。

此方法同时支持 SSE 和 Stdio MCP 服务器。 请查看 sever_parameters 参数,了解有关如何连接到 SSE 或 Stdio MCP 服务器的更多详细信息。

注意:将生成一个单独的线程来运行处理 MCP 服务器的 asyncio 事件循环。

使用 Stdio MCP 服务器的示例

>>> from smolagents import ToolCollection, CodeAgent
>>> from mcp import StdioServerParameters

>>> server_parameters = StdioServerParameters(
>>>     command="uv",
>>>     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], add_base_tools=True)
>>>     agent.run("Please find a remedy for hangover.")

使用 SSE MCP 服务器的示例

>>> 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.")

代理类型

代理可以处理工具之间的任何类型的对象;工具是完全多模态的,可以接受和返回文本、图像、音频、视频以及其他类型。 为了提高工具之间的兼容性,以及在 ipython (jupyter, colab, ipython notebooks, …) 中正确呈现这些返回,我们围绕这些类型实现了包装类。

包装的对象应继续像最初一样运行;文本对象应仍像字符串一样运行,图像对象应仍像 PIL.Image 一样运行。

这些类型有三个特定用途

  • 在类型上调用 to_raw 应返回底层对象
  • 在类型上调用 to_string 应将对象作为字符串返回:对于 AgentText 而言,这可以是字符串,但在其他实例中,这将是对象序列化版本的路径
  • 在 ipython 内核中显示它应正确显示对象

AgentText

class smolagents.AgentText

< >

( value )

代理返回的文本类型。 行为类似于字符串。

AgentImage

class smolagents.AgentImage

< >

( value )

代理返回的图像类型。 行为类似于 PIL.Image.Image。

save

< >

( output_bytes format: str = None **params )

参数

  • output_bytes (bytes) — 用于保存图像的输出字节。
  • format (str) — 输出图像的格式。此格式与 PIL.Image.save 中的格式相同。
  • **params — 传递给 PIL.Image.save 的额外参数。

将图像保存到文件。

to_raw

< >

( )

返回该对象的“原始”版本。对于 AgentImage,它是一个 PIL.Image.Image。

to_string

< >

( )

返回该对象的字符串化版本。对于 AgentImage,它是图像序列化版本的路径。

AgentAudio

smolagents.AgentAudio

< >

( value samplerate = 16000 )

代理返回的音频类型。

to_raw

< >

( )

返回该对象的“原始”版本。它是一个 torch.Tensor 对象。

to_string

< >

( )

返回该对象的字符串化版本。对于 AgentAudio,它是音频序列化版本的路径。

< > GitHub 上更新