smolagents
БесплатноБез исполняемых скриптовНе проверенsmolagents is Hugging Face's small Python library for building AI agents that solve a task by writing and running Python code that calls your tools. Use when…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
smolagents — Hugging Face Lightweight Agent Framework
Overview
smolagents runs a ReAct loop around any LLM. Its main agent, CodeAgent, has the model write a Python snippet at every step; the snippet calls your tools as plain functions and ends by calling final_answer(...). ToolCallingAgent does the same job with JSON tool calls. Tools are decorated functions, MCP servers, or Hub repositories; agents can manage other agents; generated code runs in a restricted local interpreter or in a remote sandbox. This skill follows smolagents 1.26.
Instructions
Install
The core package has no model client. Add the extras for the model and tools you use:
python -m venv .venv && source .venv/bin/activate
pip install "smolagents[toolkit]" # core + web search and webpage tools
pip install "smolagents[openai]" # OpenAIModel, AzureOpenAIModel
pip install "smolagents[litellm]" # LiteLLMModel: Anthropic, Ollama, 100+ providers
pip install "smolagents[mcp]" "mcp<2" # MCPClient; with mcp 2.x it fails on import (mcpadapt 0.1.20)
pip install "smolagents[docker]" # executor_type="docker" (also: e2b, modal, blaxel)
Pick a model
import os
from smolagents import InferenceClientModel, OpenAIModel, LiteLLMModel
# Hugging Face Inference Providers; reads HF_TOKEN from the environment
model = InferenceClientModel(model_id="deepseek-ai/DeepSeek-R1", provider="together")
# OpenAI, or any OpenAI-compatible server through api_base
model = OpenAIModel(model_id="gpt-5", api_key=os.environ["OPENAI_API_KEY"])
# Anthropic through LiteLLM (provider prefix + the provider's model id)
model = LiteLLMModel(model_id="anthropic/claude-sonnet-5-5", api_key=os.environ["ANTHROPIC_API_KEY"])
# Local Ollama; raise num_ctx, the Ollama default context is too small for agents
model = LiteLLMModel(model_id="ollama_chat/llama3.2", api_base="http://localhost:11434", num_ctx=8192)
HfApiModel was renamed to InferenceClientModel and no longer imports. OpenAIServerModel still works as an alias of OpenAIModel. There is no AnthropicServerModel; use LiteLLMModel.
Write tools and run a CodeAgent
A tool is a typed function with a docstring. The description and the Args: section are placed in the system prompt, so they are the manual the model reads.
from smolagents import CodeAgent, tool
ORDERS = {"ORD-20481": 129.50, "ORD-20482": 80.00}
@tool
def get_order_total(order_id: str) -> float:
"""Return the total amount in USD of one order.
Args:
order_id: Order identifier, for example "ORD-20481".
"""
return ORDERS[order_id]
agent = CodeAgent(
tools=[get_order_total],
model=model,
max_steps=6, # default is 20
additional_authorized_imports=["statistics"], # imports the generated code may use
instructions="Answer with a number rounded to two decimals.",
)
total = agent.run("What is the combined total of orders ORD-20481 and ORD-20482?")
print(total) # 209.5
agent.run() returns whatever the generated code passed to final_answer. Useful options: add_base_tools=True (adds web_search and visit_webpage; needs the toolkit extra), planning_interval=3 (a planning step every three steps), final_answer_checks=[fn] (reject an answer and keep going), stream_outputs=True, and return_full_result=True (a RunResult with output, state and token_usage). After a run, agent.memory.steps holds every step and agent.replay() prints them.
For models that are better at JSON tool calls than at writing code, swap the class and keep everything else:
from smolagents import ToolCallingAgent
agent = ToolCallingAgent(tools=[get_order_total], model=model)
Managed agents
ManagedAgent was removed. Give any agent a name and a description and pass it in managed_agents; the manager calls it like a tool.
from smolagents import CodeAgent, ToolCallingAgent, WebSearchTool, VisitWebpageTool
web_agent = ToolCallingAgent(
tools=[WebSearchTool(), VisitWebpageTool()],
model=model,
max_steps=10,
name="web_search_agent",
description="Runs web searches and reads pages. Give it a full question.",
)
manager = CodeAgent(tools=[], model=model, managed_agents=[web_agent],
additional_authorized_imports=["pandas", "numpy"])
Tools from MCP servers and the Hub
import os
from mcp import StdioServerParameters
from smolagents import CodeAgent, MCPClient, load_tool
server = StdioServerParameters(command="uvx", args=["--quiet", "[email protected]"],
env={"UV_PYTHON": "3.12", **os.environ})
with MCPClient(server, structured_output=True) as tools:
agent = CodeAgent(tools=tools, model=model)
agent.run("Find two recent reviews on statin intolerance and list their PMIDs.")
# Streamable HTTP server
with MCPClient({"url": "http://127.0.0.1:8000/mcp", "
Установить smolagents в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл smolagents?
smolagents is Hugging Face's small Python library for building AI agents that solve a task by writing and running Python code that calls your tools. Use when a user asks to build an agent with smolagents, create a CodeAgent or ToolCallingAgent, write a tool with the @tool decorator, connect an agent to an MCP server or a Hub tool, set up a manager agent with sub-agents, switch the model behind an agent (Hugging Face Inference Providers, OpenAI, Anthropic, Ollama), or run agent-generated code in a Docker or E2B sandbox.
Как установить скилл smolagents?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл smolagents запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic