Hugging Face 开源 smolagents:代码即行动的智能体框架
Hugging Face 发布轻量级智能体库 smolagents,核心创新在于让模型直接生成 Python 代码作为行动指令,而非传统的 JSON 工具调用。该框架通过简化架构显著提升了开源模型在复杂任务中的表现,基准测试显示其性能已可媲美顶级闭源模型。
报道正文
本文目录8 个章节
推出 smolagents:一个用于构建智能体的简单库
发布于 2024 年 12 月 31 日 在 GitHub 上更新 点赞 1209
Aymeric Roucher m-ric merve merve Thomas Wolf thomwolf
今天,我们正式推出 smolagents,这是一个非常简单的库,旨在解锁语言模型的智能体(agentic)能力。以下是其功能预览:
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=HfApiModel())
agent.run("How many seconds would it take for a leopard at full speed to run through Pont des Arts?")
目录
🤔 什么是智能体?
任何高效的 AI 系统都需要为 LLM 提供某种访问现实世界的方式:例如调用搜索工具获取外部信息,或操作特定程序以解决任务。换句话说,LLM 应该具备 能动性(agency)。智能体程序是 LLM 通往外部世界的门户。
AI 智能体是 由 LLM 输出控制工作流程的程序。
任何利用 LLM 的系统都会将 LLM 的输出集成到代码中。LLM 输入对代码工作流程的影响程度,决定了 LLM 在该系统中的能动性水平。
请注意,根据这一定义,“agent”(智能体)并非一个非黑即白、0 或 1 的二元概念;相反,“agency”(自主性/能动性)在一个连续谱系上演变,具体取决于你在工作流程中赋予 LLM 的权力大小。
下表展示了不同系统中自主性的变化:
| 自主性级别 | 描述 | 通常称呼 | 示例模式 |
|---|---|---|---|
| ☆☆☆ | LLM 输出对程序流程没有影响 | 简单处理器 | process_llm_output(llm_response) |
| ★☆☆ | LLM 输出决定基本控制流 | 路由器 (Router) | if llm_decision(): path_a() else: path_b() |
| ★★☆ | LLM 输出决定函数执行 | 工具调用 (Tool call) | run_function(llm_chosen_tool, llm_chosen_args) |
| ★★★ | LLM 输出控制迭代和程序继续 | 多步 Agent | while llm_should_continue(): execute_next_step() |
| ★★★ | 一个 agentic workflow 可以启动另一个 agentic workflow | Multi-Agent | if llm_trigger(): execute_agent() |
多步 Agent 具有如下代码结构:
memory = [user_defined_task]
while llm_should_continue(memory):
action = llm_get_next_action(memory)
observations = execute_action(action)
memory += [action, observations]因此,该系统以循环方式运行,在每一步执行一个新动作(该动作可能涉及调用一些预先确定的 tools,它们只是普通函数),直到其观察结果明显表明已达到解决给定任务所需的满意状态。以下是一个多步 Agent 如何解决简单数学问题的示例:

✅ 何时使用 agents / ⛔ 何时避免使用它们
当你需要 LLM 来决定应用程序的工作流程时,agents 非常有用。但它们往往是大材小用。关键问题在于:我是否真的需要在工作流程中具备灵活性,才能高效地解决当前任务?如果预设的工作流程经常无法满足需求,那就意味着你需要更多的灵活性。让我们举个例子:假设你正在开发一个处理冲浪旅行网站客户请求的应用程序。
你可以提前知道这些请求将属于两个类别之一(基于用户选择),并且为这两种情况分别定义了预设的工作流程。
- 想要了解旅行相关信息?⇒ 让他们访问搜索栏来搜索你的知识库
- 想要与销售沟通?⇒ 让他们填写联系表单
If that deterministic workflow fits all queries, by all means just code everything! This will give you a 100% reliable system with no risk of error introduced by letting unpredictable LLMs meddle in your workflow. For the sake of simplicity and robustness, it's advised to regularize towards not using any agentic behaviour.
But what if the workflow can't be determined that well in advance?
For instance, a user wants to ask : "I can come on Monday, but I forgot my passport so risk being delayed to Wednesday, is it possible to take me and my stuff to surf on Tuesday morning, with a cancellation insurance?" This question hinges on many factors, and probably none of the predetermined criteria above will suffice for this request.
If the pre-determined workflow falls short too often, that means you need more flexibility.
That is where an agentic setup helps.
In the above example, you could just make a multi-step agent that has access to a weather API for weather forecasts, Google Maps API to compute travel distance, an employee availability dashboard and a RAG system on your knowledge base.
Until recently, computer programs were restricted to pre-determined workflows, trying to handle complexity by piling up if/else switches. They focused on extremely narrow tasks, like "compute the sum of these numbers" or "find the shortest path in this graph". But actually, most real-life tasks, like our trip example above, do not fit in pre-determined workflows. Agentic systems open up the vast world of real-world tasks to programs!
Code agents
In a multi-step agent, at each step, the LLM can write an action, in the form of some calls to external tools. A common format (used by Anthropic, OpenAI, and many others) for writing these actions is generally different shades of "writing actions as a JSON of tools names and arguments to use, which you then parse to know which tool to execute and with which arguments".
Multiple research papers have shown that having the tool calling LLMs in code is much better.
The reason for this is simply that we crafted our code languages specifically to be the best possible way to express actions performed by a computer. If JSON snippets were a better expression, JSON would be the top programming language and programming would be hell on earth.
The figure below, taken from Executable Code Actions Elicit Better LLM Agents, illustrates some advantages of writing actions in code:

Writing actions in code rather than JSON-like snippets provides better:
- Composability: could you nest JSON actions within each other, or define a set of JSON actions to re-use later, the same way you could just define a python function?
- Object management: how do you store the output of an action like
generate_imagein JSON? - Generality: code is built to express simply anything you can have a computer do.
- Representation in LLM training data: plenty of quality code actions is already included in LLMs’ training data which means they’re already trained for this!
Introducing smolagents: making agents simple 🥳
We built smolagents with these objectives:
✨ Simplicity: the logic for agents fits in ~thousands lines of code (see this file). We kept abstractions to their minimal shape above raw code!
🧑💻 First-class support for Code Agents, i.e. agents that write their actions in code (as opposed to "agents being used to write code"). To make it secure, we support executing in sandboxed environments via E2B.
- On top of this
CodeAgentclass, we still support the standardToolCallingAgentthat writes actions as JSON/text blobs.
🤗 Hub integrations: you can share and load tools to/from the Hub, and more is to come!
🌐 Support for any LLM: it supports models hosted on the Hub loaded in their transformers version or through our inference API, but also supports models from OpenAI, Anthropic and many others via our LiteLLM integration.
smolagents is the successor to transformers.agents, and will be replacing it as transformers.agents gets deprecated in the future.
Building an agent
To build an agent, you need at least two elements:
[注:本文篇幅超长,以上为核心前篇精译,后续内容保留原文呈现]
For the model, you can use any LLM, either open models using our HfApiModel class, that leverages Hugging Face's free inference API (as shown in the leopard example above), or you can use LiteLLMModel to leverage litellm and pick from a list of 100+ different cloud LLMs.
For the tool, you can just make a function with type hints on inputs and outputs, and docstrings giving descriptions for inputs, and use the @tool decorator to make it a tool.
Here’s how to make a custom tool that gets travel times from Google Maps, and how to use it into a travel planner agent:
from typing import Optional
from smolagents import CodeAgent, HfApiModel, tool
@tool
def get_travel_duration(start_location: str, destination_location: str, transportation_mode: Optional[str] = None) -> str:
"""Gets the travel time between two places.
Args:
start_location: the place from which you start your ride
destination_location: the place of arrival
transportation_mode: The transportation mode, in 'driving', 'walking', 'bicycling', or 'transit'. Defaults to 'driving'.
"""
import os
import googlemaps
from datetime import datetime
gmaps = googlemaps.Client(os.getenv("GMAPS_API_KEY"))
if transportation_mode is None:
transportation_mode = "driving"
try:
directions_result = gmaps.directions(
start_location,
destination_location,
mode=transportation_mode,
departure_time=datetime(2025, 6, 6, 11, 0),
)
if len(directions_result) == 0:
return "No way found between these places with the required transportation mode."
return directions_result[0]["legs"][0]["duration"]["text"]
except Exception as e:
print(e)
return e
agent = CodeAgent(tools=[get_travel_duration], model=HfApiModel(), additional_authorized_imports=["datetime"])
agent.run("Can you give me a nice one-day trip around Paris with a few locations and the times? Could be in the city or outside, but should fit in one day. I'm travelling only with a rented bicycle.")After a few steps of gathering travel times and running calculations, the agent returns this final proposition:
One-day Paris bike trip itinerary:
1. Start at Eiffel Tower at 9:00 AM.
2. Sightseeing at Eiffel Tower until 10:30 AM.
3. Travel to Notre-Dame Cathedral at 10:46 AM.
4. Sightseeing at Notre-Dame Cathedral until 12:16 PM.
5. Travel to Montmartre at 12:41 PM.
6. Sightseeing at Montmartre until 2:11 PM.
7. Travel to Jardin du Luxembourg at 2:33 PM.
8. Sightseeing at Jardin du Luxembourg until 4:03 PM.
9. Travel to Louvre Museum at 4:12 PM.
10. Sightseeing at Louvre Museum until 5:42 PM.
11. Lunch break until 6:12 PM.
12. Planned end time: 6:12 PM.After building a tool, sharing it to the Hub is as simple as:
get_travel_duration.push_to_hub("{your_username}/get-travel-duration-tool")You can see the result under this space. You can check the logic for the tool under the file tool.py in the space. As you can see, the tool was actually exported to a class inheriting from class Tool, which is the underlying structure for all our tools.
How strong are open models for agentic workflows?
We've created CodeAgent instances with some leading models, and compared them on this benchmark that gathers questions from a few different benchmarks to propose a varied blend of challenges.
Find the benchmark here for more detail on the agentic setup used, and see a comparison of code agents versus tool calling agents (spoilers: code works better).

This comparison shows that open source models can now take on the best closed models!