# 工具

<Tip warning={true}>

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

</Tip>

要了解更多关于智能体和工具的信息，请务必阅读[入门指南](../index)。本页面包含底层类的 API 文档。

## 工具

### load_tool[[smolagents.load_tool]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>smolagents.load_tool</name><anchor>smolagents.load_tool</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/tools.py#L840</source><parameters>[{"name": "repo_id", "val": ""}, {"name": "model_repo_id", "val": ": str | None = None"}, {"name": "token", "val": ": str | None = None"}, {"name": "trust_remote_code", "val": ": bool = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **repo_id** (`str`) --
  Space repo ID of a tool on the Hub.
- **model_repo_id** (`str`, *optional*) --
  Use this argument to use a different model than the default one for the tool you selected.
- **token** (`str`, *optional*) --
  The token to identify you on hf.co. If unset, will use the token generated when running `huggingface-cli
  login` (stored in `~/.huggingface`).
- **trust_remote_code** (`bool`, *optional*, defaults to False) --
  This needs to be accepted in order to load a tool from Hub.
- **kwargs** (additional keyword arguments, *optional*) --
  Additional keyword arguments that will be split in two: all arguments relevant to the Hub (such as
  `cache_dir`, `revision`, `subfolder`) will be used when downloading the files for your tool, and the others
  will be passed along to its init.</paramsdesc><paramgroups>0</paramgroups></docstring>

Main function to quickly load a tool from the Hub.

<Tip warning={true}>

Loading a tool means that you'll download the tool and execute it locally.
ALWAYS inspect the tool you're downloading before loading it within your runtime, as you would do when
installing a package using pip/npm/apt.

</Tip>




</div>

### tool[[smolagents.tool]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>smolagents.tool</name><anchor>smolagents.tool</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/tools.py#L1061</source><parameters>[{"name": "tool_function", "val": ": Callable"}]</parameters><paramsdesc>- **tool_function** (`Callable`) -- Function to convert into a Tool subclass.
  Should have type hints for each input and a type hint for the output.
  Should also have a docstring including the description of the function
  and an 'Args:' part where each argument is described.</paramsdesc><paramgroups>0</paramgroups></docstring>

Convert a function into an instance of a dynamically created Tool subclass.




</div>

### Tool[[smolagents.Tool]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.Tool</name><anchor>smolagents.Tool</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/tools.py#L106</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters></docstring>

A base class for the functions used by the agent. Subclass this and implement the `forward` method as well as the
following class attributes:

- **description** (`str`) -- A short description of what your tool does, the inputs it expects and the output(s) it
  will return. For instance 'This is a tool that downloads a file from a `url`. It takes the `url` as input, and
  returns the text contained in the file'.
- **name** (`str`) -- A performative name that will be used for your tool in the prompt to the agent. For instance
  `"text-classifier"` or `"image_generator"`.
- **inputs** (`Dict[str, Dict[str, Union[str, type, bool]]]`) -- The dict of modalities expected for the inputs.
  It has one `type`key and a `description`key.
  This is used by `launch_gradio_demo` or to make a nice space from your tool, and also can be used in the generated
  description for your tool.
- **output_type** (`type`) -- The type of the tool output. This is used by `launch_gradio_demo`
  or to make a nice space from your tool, and also can be used in the generated description for your tool.
- **output_schema** (`Dict[str, Any]`, *optional*) -- The JSON schema defining the expected structure of the tool output.
  This can be included in system prompts to help agents understand the expected output format. Note: This is currently
  used for informational purposes only and does not perform actual output validation.

You can also override the method [setup()](/docs/smolagents/main/zh/reference/tools#smolagents.Tool.setup) if your tool has an expensive operation to perform before being
usable (such as loading a model). [setup()](/docs/smolagents/main/zh/reference/tools#smolagents.Tool.setup) will be called the first time you use your tool, but not at
instantiation.



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_dict</name><anchor>smolagents.Tool.from_dict</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/tools.py#L367</source><parameters>[{"name": "tool_dict", "val": ": dict[str, Any]"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **tool_dict** (`dict[str, Any]`) -- Dictionary representation of the tool.
- ****kwargs** -- Additional keyword arguments to pass to the tool's constructor.</paramsdesc><paramgroups>0</paramgroups><rettype>`Tool`</rettype><retdesc>Tool object.</retdesc></docstring>

Create tool from a dictionary representation.








</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_gradio</name><anchor>smolagents.Tool.from_gradio</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/tools.py#L741</source><parameters>[{"name": "gradio_tool", "val": ""}]</parameters></docstring>

Creates a [Tool](/docs/smolagents/main/zh/reference/tools#smolagents.Tool) from a gradio tool.


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_hub</name><anchor>smolagents.Tool.from_hub</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/tools.py#L516</source><parameters>[{"name": "repo_id", "val": ": str"}, {"name": "token", "val": ": str | None = None"}, {"name": "trust_remote_code", "val": ": bool = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **repo_id** (`str`) --
  The name of the Space repo on the Hub where your tool is defined.
- **token** (`str`, *optional*) --
  The token to identify you on hf.co. If unset, will use the token generated when running
  `huggingface-cli login` (stored in `~/.huggingface`).
- **trust_remote_code(`str`,** *optional*, defaults to False) --
  This flags marks that you understand the risk of running remote code and that you trust this tool.
  If not setting this to True, loading the tool from Hub will fail.
- **kwargs** (additional keyword arguments, *optional*) --
  Additional keyword arguments that will be split in two: all arguments relevant to the Hub (such as
  `cache_dir`, `revision`, `subfolder`) will be used when downloading the files for your tool, and the
  others will be passed along to its init.</paramsdesc><paramgroups>0</paramgroups></docstring>

Loads a tool defined on the Hub.

<Tip warning={true}>

Loading a tool from the Hub means that you'll download the tool and execute it locally.
ALWAYS inspect the tool you're downloading before loading it within your runtime, as you would do when
installing a package using pip/npm/apt.

</Tip>




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_langchain</name><anchor>smolagents.Tool.from_langchain</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/tools.py#L762</source><parameters>[{"name": "langchain_tool", "val": ""}]</parameters></docstring>

Creates a [Tool](/docs/smolagents/main/zh/reference/tools#smolagents.Tool) from a langchain tool.


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_space</name><anchor>smolagents.Tool.from_space</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/tools.py#L599</source><parameters>[{"name": "space_id", "val": ": str"}, {"name": "name", "val": ": str"}, {"name": "description", "val": ": str"}, {"name": "api_name", "val": ": str | None = None"}, {"name": "token", "val": ": str | None = None"}]</parameters><paramsdesc>- **space_id** (`str`) --
  The id of the Space on the Hub.
- **name** (`str`) --
  The name of the tool.
- **description** (`str`) --
  The description of the tool.
- **api_name** (`str`, *optional*) --
  The specific api_name to use, if the space has several tabs. If not precised, will default to the first available api.
- **token** (`str`, *optional*) --
  Add your token to access private spaces or increase your GPU quotas.</paramsdesc><paramgroups>0</paramgroups><rettype>[Tool](/docs/smolagents/main/zh/reference/tools#smolagents.Tool)</rettype><retdesc>The Space, as a tool.</retdesc></docstring>

Creates a [Tool](/docs/smolagents/main/zh/reference/tools#smolagents.Tool) from a Space given its id on the Hub.







<ExampleCodeBlock anchor="smolagents.Tool.from_space.example">

Examples:
```py
>>> 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")
```

</ExampleCodeBlock>
<ExampleCodeBlock anchor="smolagents.Tool.from_space.example-2">

```py
>>> 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')
```

</ExampleCodeBlock>


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>push_to_hub</name><anchor>smolagents.Tool.push_to_hub</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/tools.py#L421</source><parameters>[{"name": "repo_id", "val": ": str"}, {"name": "commit_message", "val": ": str = 'Upload tool'"}, {"name": "private", "val": ": bool | None = None"}, {"name": "token", "val": ": bool | str | None = None"}, {"name": "create_pr", "val": ": bool = False"}]</parameters><paramsdesc>- **repo_id** (`str`) --
  The name of the repository you want to push your tool to. It should contain your organization name when
  pushing to a given organization.
- **commit_message** (`str`, *optional*, defaults to `"Upload tool"`) --
  Message to commit while pushing.
- **private** (`bool`, *optional*) --
  Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
- **token** (`bool` or `str`, *optional*) --
  The token to use as HTTP bearer authorization for remote files. If unset, will use the token generated
  when running `huggingface-cli login` (stored in `~/.huggingface`).
- **create_pr** (`bool`, *optional*, defaults to `False`) --
  Whether to create a PR with the uploaded files or directly commit.</paramsdesc><paramgroups>0</paramgroups></docstring>

Upload the tool to the Hub.




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>save</name><anchor>smolagents.Tool.save</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/tools.py#L390</source><parameters>[{"name": "output_dir", "val": ": str | Path"}, {"name": "tool_file_name", "val": ": str = 'tool'"}, {"name": "make_gradio_app", "val": ": bool = True"}]</parameters><paramsdesc>- **output_dir** (`str` or `Path`) -- The folder in which you want to save your tool.
- **tool_file_name** (`str`, *optional*) -- The file name in which you want to save your tool.
- **make_gradio_app** (`bool`, *optional*, defaults to True) -- Whether to also export a `requirements.txt` file and Gradio UI.</paramsdesc><paramgroups>0</paramgroups></docstring>

Saves the relevant code files for your tool so it can be pushed to the Hub. This will copy the code of your
tool in `output_dir` as well as autogenerate:

- a `{tool_file_name}.py` file containing the logic for your tool.
If you pass `make_gradio_app=True`, this will also write:
- an `app.py` file providing a UI for your tool when it is exported to a Space with `tool.push_to_hub()`
- a `requirements.txt` containing the names of the modules used by your tool (as detected when inspecting its
  code)




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>setup</name><anchor>smolagents.Tool.setup</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/tools.py#L251</source><parameters>[]</parameters></docstring>

Overwrite this method here for any operation that is expensive and needs to be executed before you start using
your tool. Such as loading a big model.


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>to_dict</name><anchor>smolagents.Tool.to_dict</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/tools.py#L292</source><parameters>[]</parameters></docstring>
Returns a dictionary representing the tool

</div></div>

### launch_gradio_demo[[smolagents.launch_gradio_demo]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>smolagents.launch_gradio_demo</name><anchor>smolagents.launch_gradio_demo</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/tools.py#L794</source><parameters>[{"name": "tool", "val": ": Tool"}]</parameters><paramsdesc>- **tool** (`Tool`) -- The tool for which to launch the demo.</paramsdesc><paramgroups>0</paramgroups></docstring>

Launches a gradio demo for a tool. The corresponding tool class needs to properly implement the class attributes
`inputs` and `output_type`.




</div>

## 默认工具

### PythonInterpreterTool[[smolagents.PythonInterpreterTool]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.PythonInterpreterTool</name><anchor>smolagents.PythonInterpreterTool</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/default_tools.py#L38</source><parameters>[{"name": "*args", "val": ""}, {"name": "authorized_imports", "val": " = None"}, {"name": "**kwargs", "val": ""}]</parameters></docstring>


</div>

### FinalAnswerTool[[smolagents.FinalAnswerTool]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.FinalAnswerTool</name><anchor>smolagents.FinalAnswerTool</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/default_tools.py#L80</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters></docstring>


</div>

### UserInputTool[[smolagents.UserInputTool]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.UserInputTool</name><anchor>smolagents.UserInputTool</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/default_tools.py#L90</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters></docstring>


</div>

### DuckDuckGoSearchTool[[smolagents.DuckDuckGoSearchTool]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.DuckDuckGoSearchTool</name><anchor>smolagents.DuckDuckGoSearchTool</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/default_tools.py#L101</source><parameters>[{"name": "max_results", "val": ": int = 10"}, {"name": "rate_limit", "val": ": float | None = 1.0"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **max_results** (`int`, default `10`) -- Maximum number of search results to return.
- **rate_limit** (`float`, default `1.0`) -- Maximum queries per second. Set to `None` to disable rate limiting.
- ****kwargs** -- Additional keyword arguments for the `DDGS` client.</paramsdesc><paramgroups>0</paramgroups></docstring>
Web search tool that performs searches using the DuckDuckGo search engine.



<ExampleCodeBlock anchor="smolagents.DuckDuckGoSearchTool.example">

Examples:
```python
>>> from smolagents import DuckDuckGoSearchTool
>>> web_search_tool = DuckDuckGoSearchTool(max_results=5, rate_limit=2.0)
>>> results = web_search_tool("Hugging Face")
>>> print(results)
```

</ExampleCodeBlock>


</div>

### GoogleSearchTool[[smolagents.GoogleSearchTool]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.GoogleSearchTool</name><anchor>smolagents.GoogleSearchTool</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/default_tools.py#L159</source><parameters>[{"name": "provider", "val": ": str = 'serpapi'"}]</parameters></docstring>


</div>

### VisitWebpageTool[[smolagents.VisitWebpageTool]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.VisitWebpageTool</name><anchor>smolagents.VisitWebpageTool</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/default_tools.py#L451</source><parameters>[{"name": "max_output_length", "val": ": int = 40000"}]</parameters></docstring>


</div>

### SpeechToTextTool[[smolagents.SpeechToTextTool]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.SpeechToTextTool</name><anchor>smolagents.SpeechToTextTool</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/default_tools.py#L606</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters></docstring>


</div>

## 工具集合[[smolagents.ToolCollection]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.ToolCollection</name><anchor>smolagents.ToolCollection</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/tools.py#L895</source><parameters>[{"name": "tools", "val": ": list[Tool]"}]</parameters></docstring>

Tool collections enable loading a collection of tools in the agent's toolbox.

Collections can be loaded from a collection in the Hub or from an MCP server, see:
- [ToolCollection.from_hub()](/docs/smolagents/main/zh/reference/tools#smolagents.ToolCollection.from_hub)
- [ToolCollection.from_mcp()](/docs/smolagents/main/zh/reference/tools#smolagents.ToolCollection.from_mcp)

For example and usage, see: [ToolCollection.from_hub()](/docs/smolagents/main/zh/reference/tools#smolagents.ToolCollection.from_hub) and [ToolCollection.from_mcp()](/docs/smolagents/main/zh/reference/tools#smolagents.ToolCollection.from_mcp)



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_hub</name><anchor>smolagents.ToolCollection.from_hub</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/tools.py#L909</source><parameters>[{"name": "collection_slug", "val": ": str"}, {"name": "token", "val": ": str | None = None"}, {"name": "trust_remote_code", "val": ": bool = False"}]</parameters><paramsdesc>- **collection_slug** (str) -- The collection slug referencing the collection.
- **token** (str, *optional*) -- The authentication token if the collection is private.
- **trust_remote_code** (bool, *optional*, defaults to False) -- Whether to trust the remote code.</paramsdesc><paramgroups>0</paramgroups><rettype>ToolCollection</rettype><retdesc>A tool collection instance loaded with the tools.</retdesc></docstring>
Loads a tool collection from the Hub.

it adds a collection of tools from all Spaces in the collection to the agent's toolbox

> [!NOTE]
> Only Spaces will be fetched, so you can feel free to add models and datasets to your collection if you'd
> like for this collection to showcase them.







<ExampleCodeBlock anchor="smolagents.ToolCollection.from_hub.example">

Example:
```py
>>> 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.")
```

</ExampleCodeBlock>


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_mcp</name><anchor>smolagents.ToolCollection.from_mcp</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/tools.py#L949</source><parameters>[{"name": "server_parameters", "val": ": 'mcp.StdioServerParameters' | dict"}, {"name": "trust_remote_code", "val": ": bool = False"}, {"name": "structured_output", "val": ": bool | None = None"}]</parameters><paramsdesc>- **server_parameters** (`mcp.StdioServerParameters` or `dict`) --
  Configuration parameters to connect to the MCP server. This can be:

  - An instance of `mcp.StdioServerParameters` for connecting a Stdio MCP server via standard input/output using a subprocess.

  - A `dict` with at least:
    - "url": URL of the server.
    - "transport": Transport protocol to use, one of:
      - "streamable-http": Streamable HTTP transport (default).
      - "sse": Legacy HTTP+SSE transport (deprecated).
- **trust_remote_code** (`bool`, *optional*, defaults to `False`) --
  Whether to trust the execution of code from tools defined on the MCP server.
  This option should only be set to `True` if you trust the MCP server,
  and undertand the risks associated with running remote code on your local machine.
  If set to `False`, loading tools from MCP will fail.
- **structured_output** (`bool`, *optional*, defaults to `False`) --
  Whether to enable structured output features for MCP tools. If True, enables:
  - Support for outputSchema in MCP tools
  - Structured content handling (structuredContent from MCP responses)
  - JSON parsing fallback for structured data
  If False, uses the original simple text-only behavior for backwards compatibility.</paramsdesc><paramgroups>0</paramgroups><rettype>ToolCollection</rettype><retdesc>A tool collection instance.</retdesc></docstring>
Automatically load a tool collection from an MCP server.

This method supports Stdio, Streamable HTTP, and legacy HTTP+SSE MCP servers. Look at the `server_parameters`
argument for more details on how to connect to each MCP server.

Note: a separate thread will be spawned to run an asyncio event loop handling
the MCP server.







<ExampleCodeBlock anchor="smolagents.ToolCollection.from_mcp.example">

Example with a Stdio MCP server:
```py
>>> import os
>>> from smolagents import ToolCollection, CodeAgent, InferenceClientModel
>>> from mcp import StdioServerParameters

>>> model = InferenceClientModel()

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

</ExampleCodeBlock>

<ExampleCodeBlock anchor="smolagents.ToolCollection.from_mcp.example-2">

Example with structured output enabled:
```py
>>> with ToolCollection.from_mcp(server_parameters, trust_remote_code=True, structured_output=True) as tool_collection:
>>>     agent = CodeAgent(tools=[*tool_collection.tools], add_base_tools=True, model=model)
>>>     agent.run("Please find a remedy for hangover.")
```

</ExampleCodeBlock>

<ExampleCodeBlock anchor="smolagents.ToolCollection.from_mcp.example-3">

Example with a Streamable HTTP MCP server:
```py
>>> with ToolCollection.from_mcp({"url": "http://127.0.0.1:8000/mcp", "transport": "streamable-http"}, trust_remote_code=True) as tool_collection:
>>>     agent = CodeAgent(tools=[*tool_collection.tools], add_base_tools=True, model=model)
>>>     agent.run("Please find a remedy for hangover.")
```

</ExampleCodeBlock>


</div></div>

## 智能体类型

智能体可以处理工具之间的任何类型的对象；工具是完全多模态的，可以接受和返回文本、图像、音频、视频以及其他类型的对象。为了增加工具之间的兼容性，以及正确呈现在 ipython（jupyter、colab、ipython notebooks 等）中的返回结果，我们为这些类型实现了包装类。

被包装的对象应该继续保持其初始行为；例如，一个文本对象应继续表现为字符串，一个图像对象应继续表现为 `PIL.Image`。

这些类型有三个特定的用途：

- 调用 `to_raw` 方法时，应返回底层对象
- 调用 `to_string` 方法时，应将对象转换为字符串：对于 `AgentText` 类型，可以直接返回字符串；对于其他实例，则返回对象序列化版本的路径
- 在 ipython 内核中显示时，应正确显示对象

### AgentText[[smolagents.AgentText]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.AgentText</name><anchor>smolagents.AgentText</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agent_types.py#L62</source><parameters>[{"name": "value", "val": ""}]</parameters></docstring>

Text type returned by the agent. Behaves as a string.


</div>

### AgentImage[[smolagents.AgentImage]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.AgentImage</name><anchor>smolagents.AgentImage</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agent_types.py#L74</source><parameters>[{"name": "value", "val": ""}]</parameters></docstring>

Image type returned by the agent. Behaves as a PIL.Image.Image.



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>save</name><anchor>smolagents.AgentImage.save</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agent_types.py#L164</source><parameters>[{"name": "output_bytes", "val": ""}, {"name": "format", "val": ": str = None"}, {"name": "**params", "val": ""}]</parameters><paramsdesc>- **output_bytes** (bytes) -- The output bytes to save the image to.
- **format** (str) -- The format to use for the output image. The format is the same as in PIL.Image.save.
- ****params** -- Additional parameters to pass to PIL.Image.save.</paramsdesc><paramgroups>0</paramgroups></docstring>

Saves the image to a file.



</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>to_raw</name><anchor>smolagents.AgentImage.to_raw</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agent_types.py#L119</source><parameters>[]</parameters></docstring>

Returns the "raw" version of that object. In the case of an AgentImage, it is a PIL.Image.Image.


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>to_string</name><anchor>smolagents.AgentImage.to_string</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agent_types.py#L136</source><parameters>[]</parameters></docstring>

Returns the stringified version of that object. In the case of an AgentImage, it is a path to the serialized
version of the image.


</div></div>

### AgentAudio[[smolagents.AgentAudio]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.AgentAudio</name><anchor>smolagents.AgentAudio</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agent_types.py#L176</source><parameters>[{"name": "value", "val": ""}, {"name": "samplerate", "val": " = 16000"}]</parameters></docstring>

Audio type returned by the agent.



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>to_raw</name><anchor>smolagents.AgentAudio.to_raw</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agent_types.py#L216</source><parameters>[]</parameters></docstring>

Returns the "raw" version of that object. It is a `torch.Tensor` object.


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>to_string</name><anchor>smolagents.AgentAudio.to_string</anchor><source>https://github.com/huggingface/smolagents/blob/main/src/smolagents/agent_types.py#L237</source><parameters>[]</parameters></docstring>

Returns the stringified version of that object. In the case of an AgentAudio, it is a path to the serialized
version of the audio.


</div></div>

<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/zh/reference/tools.md" />