smolagents 文件

smolagents

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

smolagents

什麼是 smolagents?

smolagents 是一個開源的 Python 庫,旨在讓使用者能夠僅用幾行程式碼就極其輕鬆地構建和執行 Agent。

smolagents 的主要特性包括

簡潔性:Agent 的邏輯程式碼量在千行左右。我們力求將抽象保持在原始程式碼之上的最簡形式!

🧑‍💻 對程式碼 Agent 的一流支援CodeAgent 以程式碼形式編寫其動作(而非“使用 Agent 編寫程式碼”)來呼叫工具或執行計算,從而實現自然的組合性(函式巢狀、迴圈、條件判斷)。為確保安全性,我們支援透過 E2B 或 Docker 在沙盒環境中執行

📡 支援常見的工具呼叫 Agent:除了 CodeAgent,ToolCallingAgent 還支援常規的基於 JSON/文字的工具呼叫,適用於偏好該正規化的場景。

🤗 與 Hub 整合:以 Gradio Spaces 的形式,無縫地在 Hub 上共享和載入 Agent 和工具。

🌐 模型無關:輕鬆整合任何大型語言模型(LLM),無論它託管在 Hub 上並透過推理服務提供商提供服務,還是透過 OpenAI、Anthropic 等 API 訪問,或透過 LiteLLM 整合許多其他模型,抑或是使用 Transformers 或 Ollama 在本地執行。使用您偏好的 LLM 來驅動 Agent 既直接又靈活。

👁️ 模態無關:除了文字,Agent 還可以處理視覺、影片和音訊輸入,拓寬了可能應用的範圍。請檢視此教程瞭解視覺處理。

🛠️ 工具無關:您可以使用來自任何 MCP 伺服器的工具,來自 LangChain 的工具,甚至可以把 Hub Space 作為工具使用。

💻 命令列工具:附帶命令列實用程式(smolagent、webagent),可快速執行 Agent,無需編寫樣板程式碼。

快速入門

只需幾分鐘即可開始使用 smolagents!本指南將向您展示如何建立並執行您的第一個 Agent。

安裝

使用 pip 安裝 smolagents

pip install smolagents[toolkit]  # Includes default tools like web search

建立您的第一個 Agent

這是一個建立和執行 Agent 的最小示例

from smolagents import CodeAgent, InferenceClientModel

# Initialize a model (using Hugging Face Inference API)
model = InferenceClientModel()  # Uses a default model

# Create an agent with no tools
agent = CodeAgent(tools=[], model=model)

# Run the agent with a task
result = agent.run("Calculate the sum of numbers from 1 to 10")
print(result)

就是這樣!您的 Agent 將使用 Python 程式碼來解決任務並返回結果。

新增工具

讓我們透過新增一些工具來使我們的 Agent 更有能力

from smolagents import CodeAgent, InferenceClientModel, DuckDuckGoSearchTool

model = InferenceClientModel()
agent = CodeAgent(
    tools=[DuckDuckGoSearchTool()],
    model=model,
)

# Now the agent can search the web!
result = agent.run("What is the current weather in Paris?")
print(result)

使用不同的模型

您可以在您的 Agent 中使用各種模型

# Using a specific model from Hugging Face
model = InferenceClientModel(model_id="meta-llama/Llama-2-70b-chat-hf")

# Using OpenAI/Anthropic (requires smolagents[litellm])
from smolagents import LiteLLMModel
model = LiteLLMModel(model_id="gpt-4")

# Using local models (requires smolagents[transformers])
from smolagents import TransformersModel
model = TransformersModel(model_id="meta-llama/Llama-2-7b-chat-hf")

後續步驟

< > 在 GitHub 上更新

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