smolagents 文件
工具
並獲得增強的文件體驗
開始使用
工具
Smolagents 是一個實驗性 API,可能隨時更改。由於 API 或底層模型容易發生變化,智慧體返回的結果可能有所不同。
要了解更多關於智慧體和工具的資訊,請務必閱讀入門指南。本頁面包含底層類的 API 文件。
工具基類
load_tool
smolagents.load_tool
< source >( repo_id model_repo_id: str | None = None token: str | None = None trust_remote_code: bool = False **kwargs )
引數
- repo_id (
str
) — 工具在 Hub 上的 Space repo ID。 - model_repo_id (
str
, 可選) — 使用此引數可使用與所選工具的預設模型不同的模型。 - token (
str
, 可選) — 用於在 hf.co 上識別您的令牌。如果未設定,將使用執行huggingface-cli login
時生成的令牌(儲存在~/.huggingface
中)。 - trust_remote_code (
bool
, 可選, 預設為 False) — 需要接受此項才能從 Hub 載入工具。 - kwargs (附加關鍵字引數,可選) — 附加關鍵字引數將分為兩部分:與 Hub 相關的所有引數(例如
cache_dir
、revision
、subfolder
)將用於下載工具檔案,其餘引數將傳遞給其 init。
用於從 Hub 快速載入工具的主函式。
載入工具意味著您將下載工具並在本地執行它。在執行時載入工具之前,請務必檢查您下載的工具,就像您使用 pip/npm/apt 安裝包時一樣。
工具
smolagents.tool
< source >( tool_function: Callable )
將函式轉換為動態建立的工具子類的例項。
工具
智慧體所用函式的基本類。繼承此類並實現 forward
方法以及以下類屬性
- description (
str
) — 您的工具功能的簡短描述,它期望的輸入以及將返回的輸出。例如,“這是一個從url
下載檔案的工具。它以url
作為輸入,並返回檔案中包含的文字。” - name (
str
) — 將在提示智慧體時用於您的工具的指示性名稱。例如"text-classifier"
或"image_generator"
。 - inputs (
Dict[str, Dict[str, Union[str, type, bool]]]
) — 輸入期望的模態字典。它有一個type
鍵和一個description
鍵。這用於launch_gradio_demo
或從您的工具製作一個漂亮的 Space,也可以用於您工具生成的描述中。 - output_type (
type
) — 工具輸出的型別。這用於launch_gradio_demo
或從您的工具製作一個漂亮的 Space,也可以用於您工具生成的描述中。
如果您的工具在可用之前有昂貴的操作要執行(例如載入模型),您還可以覆蓋 setup() 方法。 setup() 將在您第一次使用工具時呼叫,而不是在例項化時呼叫。
from_dict
< source >( tool_dict: dict[str, Any] **kwargs ) → Tool
從字典表示建立工具。
從 Gradio 工具建立 Tool。
from_hub
< source >( repo_id: str token: str | None = None trust_remote_code: bool = False **kwargs )
引數
- repo_id (
str
) — 您要將工具推送到的儲存庫名稱。當推送到給定組織時,它應包含您的組織名稱。 - token (
str
, 可選) — 用於在 hf.co 上識別您的令牌。如果未設定,將使用執行huggingface-cli login
時生成的令牌(儲存在~/.huggingface
中)。 - trust_remote_code(
str
, 可選, 預設為 False) — 此標誌表示您瞭解執行遠端程式碼的風險,並且信任此工具。如果未將其設定為 True,則從 Hub 載入工具將失敗。 - kwargs (附加關鍵字引數,可選) — 附加關鍵字引數將分為兩部分:與 Hub 相關的所有引數(例如
cache_dir
、revision
、subfolder
)將用於下載工具檔案,其餘引數將傳遞給其 init。
載入 Hub 上定義的工具。
從 Hub 載入工具意味著您將下載工具並在本地執行它。在執行時載入工具之前,請務必檢查您下載的工具,就像您使用 pip/npm/apt 安裝包時一樣。
從 LangChain 工具建立 Tool。
from_space
< source >( space_id: str name: str description: str api_name: str | None = None token: str | None = None ) → Tool
根據其在 Hub 上的 ID 從 Space 建立 Tool。
push_to_hub
< source >( repo_id: str commit_message: str = 'Upload tool' private: bool | None = None token: bool | str | None = None create_pr: bool = False )
引數
- repo_id (
str
) — 您要將工具推送到的儲存庫名稱。它應包含您在推送到給定組織時的組織名稱。 - commit_message (
str
, 可選, 預設為"Upload tool"
) — 推送時提交的訊息。 - private (
bool
, 可選) — 是否將儲存庫設為私有。如果為None
(預設),則儲存庫將是公共的,除非組織的預設設定為私有。如果儲存庫已存在,此值將被忽略。 - token (
bool
或str
, 可選) — 用作遠端檔案 HTTP bearer 授權的令牌。如果未設定,將使用執行huggingface-cli login
時生成的令牌(儲存在~/.huggingface
中)。 - create_pr (
bool
, 可選, 預設為False
) — 是否建立包含已上傳檔案的 PR 或直接提交。
將工具上傳到 Hub。
儲存
< source >( output_dir: str | Path tool_file_name: str = 'tool' make_gradio_app: bool = True )
儲存工具的相關程式碼檔案,以便將其推送到 Hub。這將把工具程式碼複製到 output_dir
中,並自動生成
- 一個包含工具邏輯的
{tool_file_name}.py
檔案。如果您傳入make_gradio_app=True
,它還將寫入 - 一個
app.py
檔案,用於在工具匯出到 Space 並使用tool.push_to_hub()
時為工具提供 UI - 一個
requirements.txt
,其中包含工具使用的模組名稱(在檢查其程式碼時檢測到)
在此處覆蓋此方法以執行任何昂貴的操作,並且需要在開始使用工具之前執行。例如載入大型模型。
返回表示工具的字典
launch_gradio_demo
為工具啟動 Gradio 演示。相應的工具類需要正確實現類屬性 inputs
和 output_type
。
工具集
工具集允許在智慧體的工具箱中載入工具集合。
可以從 Hub 中的集合或從 MCP 伺服器載入集合,請參閱
有關示例和用法,請參閱:ToolCollection.from_hub() 和 ToolCollection.from_mcp()
from_hub
< source >( collection_slug: str token: str | None = None trust_remote_code: bool = False ) → ToolCollection
從 Hub 載入工具集合。
它將集合中所有 Space 的工具集合新增到代理的工具箱中
[!NOTE] 只會獲取 Space,因此您可以隨意將模型和資料集新增到您的集合中,如果您希望此集合展示它們。
示例
>>> 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: 'mcp.StdioServerParameters' | dict trust_remote_code: bool = False ) → ToolCollection
引數
- server_parameters (
mcp.StdioServerParameters
或dict
) — 連線到 MCP 伺服器的配置引數。這可以是:-
mcp.StdioServerParameters
的例項,用於透過子程序使用標準輸入/輸出連線 Stdio MCP 伺服器。 -
一個至少包含以下內容的
dict
:- “url”:伺服器的 URL。
- “transport”:要使用的傳輸協議,可以是:
- “streamable-http”:可流式 HTTP 傳輸(預設)。
- “sse”:舊版 HTTP+SSE 傳輸(已棄用)。
-
- trust_remote_code (
bool
, 可選, 預設為False
) — 是否信任執行 MCP 伺服器上定義的工具程式碼。僅當您信任 MCP 伺服器並理解在本地機器上執行遠端程式碼的風險時,才應將此選項設定為True
。如果設定為False
,從 MCP 載入工具將失敗。
返回
ToolCollection
一個工具集合例項。
自動從 MCP 伺服器載入工具集合。
此方法支援 Stdio、可流式 HTTP 和舊版 HTTP+SSE MCP 伺服器。有關如何連線到每個 MCP 伺服器的更多詳細資訊,請參閱 server_parameters
引數。
注意:將生成一個單獨的執行緒來執行處理 MCP 伺服器的 asyncio 事件迴圈。
Stdio MCP 伺服器示例
>>> 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.")
可流式 HTTP MCP 伺服器示例
>>> 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.")
MCP 客戶端
class smolagents.MCPClient
< 來源 >( server_parameters: 'StdioServerParameters' | dict[str, Any] | list['StdioServerParameters' | dict[str, Any]] adapter_kwargs: dict[str, Any] | None = None )
引數
- server_parameters (StdioServerParameters | dict[str, Any] | list[StdioServerParameters | dict[str, Any]]) — 連線到 MCP 伺服器的配置引數。如果您想同時連線多個 MCP,則可以是一個列表。
-
mcp.StdioServerParameters
的例項,用於透過子程序使用標準輸入/輸出連線 Stdio MCP 伺服器。 -
一個至少包含以下內容的
dict
:- “url”:伺服器的 URL。
- “transport”:要使用的傳輸協議,可以是:
- “streamable-http”:可流式 HTTP 傳輸(預設)。
- “sse”:舊版 HTTP+SSE 傳輸(已棄用)。
-
- adapter_kwargs (dict[str, Any], 可選) — 要直接傳遞給
MCPAdapt
的其他關鍵字引數。
管理與 MCP 伺服器的連線,並將其工具提供給 SmolAgents。
注意:只有在透過 connect()
方法啟動連線後才能訪問工具,該方法在初始化期間完成。如果您不使用上下文管理器,我們強烈建議使用“try … finally”來確保連線被清除。
示例
# fully managed context manager + stdio
with MCPClient(...) as tools:
# tools are now available
# context manager + Streamable HTTP transport:
with MCPClient({"url": "https://:8000/mcp", "transport": "streamable-http"}) as tools:
# tools are now available
# manually manage the connection via the mcp_client object:
try:
mcp_client = MCPClient(...)
tools = mcp_client.get_tools()
# use your tools here.
finally:
mcp_client.disconnect()
連線到 MCP 伺服器並初始化工具。
斷開連線
< 來源 >( exc_type: type[BaseException] | None = None exc_value: BaseException | None = None exc_traceback: TracebackType | None = None )
斷開與 MCP 伺服器的連線
獲取工具
< 來源 >( ) → list[Tool]
返回
list[Tool]
可從 MCP 伺服器獲得的 SmolAgents 工具。
丟擲
ValueError
ValueError
— 如果 MCP 伺服器工具為 None(通常假定伺服器未啟動)。
可從 MCP 伺服器獲得的 SmolAgents 工具。
注意:目前,這始終返回在會話建立時可用的工具,但在未來的版本中,它還將在呼叫時返回 MCP 伺服器上可用的任何新工具。
代理型別
代理可以在工具之間處理任何型別的物件;工具完全是多模態的,可以接受和返回文字、影像、音訊、影片以及其他型別。為了增加工具之間的相容性,並正確地在 ipython(jupyter、colab、ipython notebooks 等)中渲染這些返回,我們圍繞這些型別實現了包裝器類。
被包裝的物件應繼續保持其最初的行為;文字物件應仍表現為字串,影像物件應仍表現為 PIL.Image
。
這些型別有三個特定用途
- 對型別呼叫
to_raw
應該返回底層物件 - 對型別呼叫
to_string
應該將物件作為字串返回:對於AgentText
,可以是字串,但在其他例項中將是物件序列化版本的路徑 - 在 ipython 核心中顯示它應該正確顯示物件
AgentText
代理返回的文字型別。行為類似於字串。
AgentImage
代理返回的影像型別。行為類似於 PIL.Image.Image。
將影像儲存到檔案。
返回該物件的“原始”版本。對於 AgentImage,它是一個 PIL.Image.Image。
返回該物件的字串化版本。對於 AgentImage,它是影像序列化版本的路徑。
AgentAudio
代理返回的音訊型別。
返回該物件的“原始”版本。它是一個 torch.Tensor
物件。
返回該物件的字串化版本。對於 AgentAudio,它是音訊序列化版本的路徑。