Agents that think in code!
smolagents 是一个库,使您能够在几行代码中运行强大的代理。它提供:
✨ 简洁:代理的逻辑大约需要1000行代码(参见 代理人.py).我们将抽象保持在原始代码之上的最小形状!
🤗 Hub集成:你可以 在Hub中共享/提取工具或代理 即时共享最高效的代理!
🌐 模型无关:烟雾剂支持任何LLM。它可以是本地的 transformers 或 ollama 模型,其中之一 Hub上的许多提供商,或通过我们的 轻量级LLM 整合。
👁️ 模态不可知:代理支持文本、视觉、视频甚至音频输入!查阅 本教程 视觉。
🛠️ 工具无关:您可以使用任何工具 MCP服务器,从 LangChain,你甚至可以使用 枢纽空间 作为一种工具。
可以找到完整的文档 这里.
\[!注意\] 查看我们的 发布博客文章 了解更多信息 smolagents!快速演示
首先使用默认工具集安装软件包:
pip install "smolagents[toolkit]"然后定义你的代理,给它提供所需的工具并运行它!
from smolagents import CodeAgent, WebSearchTool, InferenceClientModel
model = InferenceClientModel()
agent = CodeAgent(tools=[WebSearchTool()], model=model, stream_outputs=True)
agent.run("How many seconds would it take for a leopard at full speed to run through Pont des Arts?")https://github.com/user-attachments/assets/84b149b4-246c-40c9-a48d-ba013b08e600
您甚至可以将您的代理作为Space存储库共享到Hub:
agent.push_to_hub("m-ric/my_agent")
# agent.from_hub("m-ric/my_agent") to load an agent from Hub
[](https://ko-fi.com/N4N71WOHZ3)我们的库与LLM无关:您可以将上面的示例切换到任何推理提供程序。
InferenceClientModel, gateway for all inference providers supported on HF
from smolagents import InferenceClientModel
model = InferenceClientModel(
model_id="deepseek-ai/DeepSeek-R1",
provider="together",
)LiteLLM to access 100+ LLMs
from smolagents import LiteLLMModel
model = LiteLLMModel(
model_id="anthropic/claude-4-sonnet-latest",
temperature=0.2,
api_key=os.environ["ANTHROPIC_API_KEY"]
)OpenAI-compatible servers: Together AI
import os
from smolagents import OpenAIModel
model = OpenAIModel(
model_id="deepseek-ai/DeepSeek-R1",
api_base="https://api.together.xyz/v1/", # Leave this blank to query OpenAI servers.
api_key=os.environ["TOGETHER_API_KEY"], # Switch to the API key for the server you're targeting.
)OpenAI-compatible servers: OpenRouter
import os
from smolagents import OpenAIModel
model = OpenAIModel(
model_id="openai/gpt-4o",
api_base="https://openrouter.ai/api/v1", # Leave this blank to query OpenAI servers.
api_key=os.environ["OPENROUTER_API_KEY"], # Switch to the API key for the server you're targeting.
)Local transformers model
from smolagents import TransformersModel
model = TransformersModel(
model_id="Qwen/Qwen3-Next-80B-A3B-Thinking",
max_new_tokens=4096,
device_map="auto"
)Azure models
import os
from smolagents import AzureOpenAIModel
model = AzureOpenAIModel(
model_id = os.environ.get("AZURE_OPENAI_MODEL"),
azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
api_key=os.environ.get("AZURE_OPENAI_API_KEY"),
api_version=os.environ.get("OPENAI_API_VERSION")
)Amazon Bedrock models
import os
from smolagents import AmazonBedrockModel
model = AmazonBedrockModel(
model_id = os.environ.get("AMAZON_BEDROCK_MODEL_ID")
)命令行界面
您可以使用两个命令从CLI运行代理: smolagent 和 webagent.
smolagent 是一个通用命令,用于运行多步 CodeAgent 它可以配备各种工具。
# Run with direct prompt and options
smolagent "Plan a trip to Tokyo, Kyoto and Osaka between Mar 28 and Apr 7." --model-type "InferenceClientModel" --model-id "Qwen/Qwen3-Next-80B-A3B-Thinking" --imports pandas numpy --tools web_search
# Run in interactive mode (launches setup wizard when no prompt provided)
smolagent交互模式将引导您完成以下操作:
- 代理类型选择(CodeAgent与ToolCallingAgent)
- 从可用工具箱中选择工具
- 模型配置(类型、ID、API设置)
- 高级选项,如额外导入
- 任务提示输入
例如:
webagent "go to xyz.com/men, get to sale section, click the first clothing item you see. Get the product details, and the price, return them. note that I'm shopping from France" --model-type "LiteLLMModel" --model-id "gpt-5"代码代理是如何工作的?
我们的 CodeAgent 其工作方式主要类似于经典的ReAct代理,但LLM引擎将其操作作为Python代码片段编写。
flowchart TB
Task[User Task]
Memory[agent.memory]
Generate[Generate from agent.model]
Execute[Execute Code action - Tool calls are written as functions]
Answer[Return the argument given to 'final_answer']
Task -->|Add task to agent.memory| Memory
subgraph ReAct[ReAct loop]
Memory -->|Memory as chat messages| Generate
Generate -->|Parse output to extract code action| Execute
Execute -->|No call to 'final_answer' tool => Store execution logs in memory and keep running| Memory
end
Execute -->|Call to 'final_answer' tool| Answer
%% Styling
classDef default fill:#d4b702,stroke:#8b7701,color:#ffffff
classDef io fill:#4a5568,stroke:#2d3748,color:#ffffff
class Task,Answer io动作现在是Python代码片段。因此,工具调用将作为Python函数调用执行。例如,以下是代理如何在一个操作中对多个网站进行网络搜索:
requests_to_search = ["gulf of mexico america", "greenland denmark", "tariffs"]
for request in requests_to_search:
print(f"Here are the search results for {request}:", web_search(request))将操作编写为代码片段被证明比当前的行业惯例更好,即让LLM输出它想要调用的工具字典: 减少30%的步骤 (因此LLM呼叫减少30%)以及 在困难的基准测试中达到更高的性能.前往 我们对代理商的高级介绍 了解更多信息。
特别是,由于代码执行可能是一个安全问题(任意代码执行!),我们在运行时提供了选项:
- 一个安全的python解释器,可以在您的环境中更安全地运行代码(比原始代码执行更安全,但仍然有风险)
与…一起 CodeAgent,我们还提供标准 ToolCallingAgent 它将动作写入JSON/文本blob。你可以选择最适合你用例的风格。
这个图书馆怎么样?
我们努力将抽象保持在最低限度: agents.py 有\<1000行代码。 尽管如此,我们还是实现了几种类型的代理: CodeAgent 将其操作编写为Python代码片段,以及更经典的 ToolCallingAgent 利用内置的工具调用方法。我们还有多代理层次结构、从工具集合导入、远程代码执行、视觉模型。..
顺便问一下,为什么要使用框架?好吧,因为这件事的很大一部分是不平凡的。例如,代码代理必须在整个系统提示、解析器和执行过程中保持代码的一致格式。因此,我们的框架可以为您处理这种复杂性。当然,我们仍然鼓励你破解源代码,只使用你需要的部分,排除其他所有内容!
代理工作流的开放模型有多强大?
我们创造了 CodeAgent 与一些领先的模型进行实例比较 这个基准 它收集了来自几个不同基准的问题,提出了各种各样的挑战。
在此处查找基准测试代码 有关所使用的代理设置的更多详细信息,请参阅LLM代码代理与vanilla代码代理的比较(剧透:代码代理效果更好)。
这种比较表明,开源模型现在可以采用最好的封闭模型!
安全
使用代码执行代理时,安全性是一个关键考虑因素。我们的图书馆提供:
- 安全运行代理代码的最佳实践
有关安全策略、漏洞报告和有关安全代理执行的更多信息,请参阅我们的 安全策略.
贡献
欢迎大家贡献,开始我们的 贡献指南.
Cite罩衫
如果你使用 smolagents 在您的出版物中,请使用以下BibTeX条目引用它。
@Misc{smolagents,
title = {`smolagents`: a smol library to build great agentic systems.},
author = {Aymeric Roucher and Albert Villanova del Moral and Thomas Wolf and Leandro von Werra and Erik Kaunismäki},
howpublished = {\url{https://github.com/huggingface/smolagents}},
year = {2025}
}