smolagents 文件

工具

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

工具

在這裡,我們將看到高階工具的使用方法。

如果您是構建代理的新手,請務必先閱讀代理簡介smolagents 入門指南

什麼是工具,如何構建它?

工具主要是LLM在代理系統中可以使用的一個函式。

但要使用它,LLM需要被賦予一個API:名稱、工具描述、輸入型別和描述、輸出型別。

所以它不能僅僅是一個函式。它應該是一個類。

因此,核心的工具是一個類,它用元資料封裝了一個函式,這些元資料有助於LLM理解如何使用它。

它看起來像這樣:

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(filter=task, sort="downloads", direction=-1)))
        return model.id

model_downloads_tool = HFModelDownloadsTool()

自定義工具繼承自Tool,以繼承有用的方法。子類還定義了

  • 一個屬性 `name`,對應於工具本身的名稱。名稱通常描述工具的功能。由於程式碼返回任務下載量最多的模型,我們將其命名為 `model_download_counter`。
  • 一個 `description` 屬性,用於填充代理的系統提示。
  • 一個 `inputs` 屬性,它是一個字典,包含鍵 `“type”` 和 `“description”`。它包含有助於 Python 直譯器對輸入做出明智選擇的資訊。
  • 一個 `output_type` 屬性,指定輸出型別。`inputs` 和 `output_type` 的型別都應該是 Pydantic 格式,它們可以是以下任意一種:`~AUTHORIZED_TYPES()`。
  • 一個 `forward` 方法,其中包含要執行的推理程式碼。

這就是在代理中使用它所需要的一切!

還有另一種構建工具的方法。在入門指南中,我們使用`@tool`裝飾器實現了一個工具。建議使用tool()裝飾器來定義簡單的工具,但有時您需要更多:在一個類中使用多個方法以提高畫質晰度,或者使用額外的類屬性。

在這種情況下,您可以透過如上所述繼承 Tool 來構建您的工具。

將您的工具分享到 Hub

您可以透過在工具上呼叫 push_to_hub() 將自定義工具作為空間倉庫分享到 Hub。請確保您已在 Hub 上為其建立了一個倉庫,並且正在使用具有讀取許可權的令牌。

model_downloads_tool.push_to_hub("{your_username}/hf-model-downloads", token="<YOUR_HUGGINGFACEHUB_API_TOKEN>")

為了將工具成功推送到 Hub,您的工具需要遵守一些規則:

  • 所有方法都是自包含的,例如使用來自其引數的變數。
  • 根據上述觀點,**所有匯入都應直接在工具函式內定義**,否則在嘗試使用您的自定義工具呼叫 save()push_to_hub() 時會出錯。
  • 如果繼承`__init__`方法,則除了`self`之外不能給出其他引數。這是因為在特定工具例項初始化期間設定的引數難以跟蹤,這會阻礙它們正確地共享到hub。無論如何,建立特定類的目的是可以為任何需要硬編碼的內容設定類屬性(只需在`class YourTool(Tool):`行下直接設定`your_variable=(...)`)。當然,仍然可以透過將內容分配給`self.your_variable`在程式碼中的任何位置建立類屬性。

工具推送到 Hub 後,即可對其進行視覺化。這裡是我推送的 `model_downloads_tool`。它具有漂亮的 Gradio 介面。

深入檢視工具檔案,您會發現所有工具邏輯都在 tool.py 中。您可以在那裡檢查他人共享的工具。

然後,您可以使用 load_tool() 載入工具或使用 from_hub() 建立工具,並將其傳遞給代理中的 `tools` 引數。由於執行工具意味著執行自定義程式碼,因此您需要確保信任該倉庫,因此我們要求傳遞 `trust_remote_code=True` 才能從 Hub 載入工具。

from smolagents import load_tool, CodeAgent

model_download_tool = load_tool(
    "{your_username}/hf-model-downloads",
    trust_remote_code=True
)

從 MCP 伺服器使用工具

我們的 `MCPClient` 允許您從 MCP 伺服器載入工具,併為您提供對連線和工具管理的完全控制

對於基於 stdio 的 MCP 伺服器

from smolagents import MCPClient, CodeAgent
from mcp import StdioServerParameters
import os

server_parameters = StdioServerParameters(
    command="uvx",  # Using uvx ensures dependencies are available
    args=["--quiet", "pubmedmcp@0.1.3"],
    env={"UV_PYTHON": "3.12", **os.environ},
)

with MCPClient(server_parameters) as tools:
    agent = CodeAgent(tools=tools, model=model, add_base_tools=True)
    agent.run("Please find the latest research on COVID-19 treatment.")

對於基於可流式 HTTP 的 MCP 伺服器

from smolagents import MCPClient, CodeAgent

with MCPClient({"url": "http://127.0.0.1:8000/mcp", "transport": "streamable-http"}) as tools:
    agent = CodeAgent(tools=tools, model=model, add_base_tools=True)
    agent.run("Please find a remedy for hangover.")

您還可以使用try…finally模式手動管理連線生命週期

from smolagents import MCPClient, CodeAgent
from mcp import StdioServerParameters
import os

# Initialize server parameters
server_parameters = StdioServerParameters(
    command="uvx",
    args=["--quiet", "pubmedmcp@0.1.3"],
    env={"UV_PYTHON": "3.12", **os.environ},
)

# Manually manage the connection
try:
    mcp_client = MCPClient(server_parameters)
    tools = mcp_client.get_tools()

    # Use the tools with your agent
    agent = CodeAgent(tools=tools, model=model, add_base_tools=True)
    result = agent.run("What are the recent therapeutic approaches for Alzheimer's disease?")

    # Process the result as needed
    print(f"Agent response: {result}")
finally:
    # Always ensure the connection is properly closed
    mcp_client.disconnect()

您還可以透過傳遞伺服器引數列表同時連線到多個 MCP 伺服器

from smolagents import MCPClient, CodeAgent
from mcp import StdioServerParameters
import os

server_params1 = StdioServerParameters(
    command="uvx",
    args=["--quiet", "pubmedmcp@0.1.3"],
    env={"UV_PYTHON": "3.12", **os.environ},
)

server_params2 = {"url": "http://127.0.0.1:8000/sse"}

with MCPClient([server_params1, server_params2]) as tools:
    agent = CodeAgent(tools=tools, model=model, add_base_tools=True)
    agent.run("Please analyze the latest research and suggest remedies for headaches.")

安全警告:在連線到任何 MCP 伺服器之前,務必驗證其來源和完整性,尤其是在生產環境中。使用 MCP 伺服器存在安全風險。

  • 信任至關重要:只使用來自受信任來源的 MCP 伺服器。惡意伺服器可以在您的機器上執行有害程式碼。
  • 基於 StdIO 的 MCP 伺服器將始終在您的機器上執行程式碼(這是它們的預期功能)。
  • 可流式 HTTP MCP 伺服器:雖然遠端 MCP 伺服器不會在您的機器上執行程式碼,但仍需謹慎操作。

將空間匯入為工具

您可以使用 Tool.from_space() 方法直接從 Hub 匯入 Gradio Space 作為工具!

您只需提供 Hub 上 Space 的 ID、其名稱以及一段描述,這將幫助您的代理理解該工具的功能。在底層,這將使用 `gradio-client` 庫來呼叫 Space。

例如,我們從 Hub 匯入 FLUX.1-dev 空間,並使用它來生成影像。

image_generation_tool = Tool.from_space(
    "black-forest-labs/FLUX.1-schnell",
    name="image_generator",
    description="Generate an image from a prompt"
)

image_generation_tool("A sunny beach")

瞧,這是您的圖片!🏖️

然後,您可以像使用任何其他工具一樣使用此工具。例如,我們來改進提示“穿著宇航服的兔子”,並生成它的影像。此示例還展示瞭如何將附加引數傳遞給代理。

from smolagents import CodeAgent, InferenceClientModel

model = InferenceClientModel(model_id="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 rabbit wearing a space suit'}
)
=== 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(prompt="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")
final_answer(image)

這有多酷?🤩

使用 LangChain 工具

我們熱愛 Langchain,並認為它擁有一套非常引人注目的工具。要從 LangChain 匯入工具,請使用 `from_langchain()` 方法。

以下是使用 LangChain 網頁搜尋工具重新建立介紹搜尋結果的方法。此工具需要 `pip install langchain google-search-results -q` 才能正常工作。

from langchain.agents import load_tools

search_tool = Tool.from_langchain(load_tools(["serpapi"])[0])

agent = CodeAgent(tools=[search_tool], model=model)

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

管理您的代理工具箱

您可以透過在屬性 `agent.tools` 中新增或替換工具來管理代理的工具箱,因為它是一個標準字典。

讓我們將 `model_download_tool` 新增到已使用預設工具箱初始化的現有代理中。

from smolagents import InferenceClientModel

model = InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct")

agent = CodeAgent(tools=[], model=model, add_base_tools=True)
agent.tools[model_download_tool.name] = model_download_tool

現在我們可以利用新工具了

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

注意不要給代理新增太多工具:這可能會讓較弱的LLM引擎不堪重負。

使用工具集

您可以使用 ToolCollection 來利用工具集合。它支援從 Hub 或 MCP 伺服器載入工具集合。

來自任何 MCP 伺服器的工具集

利用來自 glama.aismithery.ai 上數百個 MCP 伺服器的工具。

MCP 伺服器工具可以使用 ToolCollection.from_mcp() 載入。

安全警告:在連線到任何 MCP 伺服器之前,務必驗證其來源和完整性,尤其是在生產環境中。使用 MCP 伺服器存在安全風險。

  • 信任至關重要:只使用來自受信任來源的 MCP 伺服器。惡意伺服器可以在您的機器上執行有害程式碼。
  • 基於 StdIO 的 MCP 伺服器將始終在您的機器上執行程式碼(這是它們的預期功能)。
  • 可流式 HTTP MCP 伺服器:雖然遠端 MCP 伺服器不會在您的機器上執行程式碼,但仍需謹慎操作。

對於基於 stdio 的 MCP 伺服器,將伺服器引數作為 `mcp.StdioServerParameters` 的例項傳遞

from smolagents import ToolCollection, CodeAgent
from mcp import StdioServerParameters

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

對於基於可流式 HTTP 的 MCP 伺服器,只需將帶有引數的字典傳遞給 `mcp.client.streamable_http.streamablehttp_client`,並新增鍵 `transport`,其值為 `"streamable-http"`

from smolagents import ToolCollection, CodeAgent

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)
    agent.run("Please find a remedy for hangover.")

來自 Hub 中集合的工具集

您可以使用所需集合的 slug 來利用它。然後將它們作為列表傳遞以初始化您的代理,並開始使用它們!

from smolagents import ToolCollection, CodeAgent

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

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

為了加快啟動速度,工具僅在代理呼叫時載入。

< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.