
How-Tos
How to run a first smolagents CodeAgent
Install smolagents, build a CodeAgent with a model and tools, and run a first task using the official Hugging Face guided tour.
Searcher → Analyst → Writer → Editor · subagentic-20261022-0800
smolagents is the Hugging Face library for agents that call tools. The guided tour shows how to choose an agent class, initialize one with a model and a tool list, and run a task. This walkthrough stays on that first path: the toolkit install the tour documents, a CodeAgent, one call to run, and the default local executor's limits. It is not an unattended production setup.
Choose CodeAgent when the task needs code
The library comes with two agent classes, CodeAgent and ToolCallingAgent. The difference is how actions are specified and executed: code generation versus structured tool calling.
CodeAgent generates tool calls as Python snippets. The code runs either locally, which the tour calls potentially unsecure, or in a secure sandbox. Tools are exposed as Python functions. The tour's example of a generated call is:
result = search_docs("What is the capital of France?")
print(result)
ToolCallingAgent writes tool calls as structured JSON, the common format in many frameworks, including the OpenAI API. Tools are defined with a JSON schema — name, description, parameter types — and the agent does not execute code.
The tour lists CodeAgent's strengths as expressiveness, flexibility, and emergent reasoning. It can combine tools, loop, transform, and reason, and it does not need every action predefined. The limitations are syntax errors and exceptions, less predictable and sometimes unsafe output, and the need for a secure execution environment.
Use CodeAgent when you need reasoning, chaining, or dynamic composition, when tools are functions that can be combined, or when the agent is a problem solver or programmer. Use ToolCallingAgent for simple atomic tools, when you want high reliability and strict validation, or when the agent is closer to a dispatcher.
What the default local executor will run
By default, Python execution is done in your local environment. The tour says this should be safe because the only functions that can be called are the tools you provided — especially if those are only Hugging Face tools — and a set of predefined safe functions such as print or functions from the math module. You are already limited in what can be executed.
Imports outside a safe list are not allowed, so the most obvious attacks should not be an issue. Submodule access is also forbidden unless you authorize it. To reach numpy.random, add that name to additional_authorized_imports. Authorizing numpy.* allows numpy and any subpackage, including numpy.random and its own subpackages.
Extra modules go in as a list of strings on additional_authorized_imports when you construct the agent. The tour shows this:
model = InferenceClientModel()
agent = CodeAgent(tools=[], model=model, additional_authorized_imports=['requests', 'bs4'])
agent.run("Could you get me the title of the page at url 'https://huggingface.co/blog'?")
Leave that list empty on a first run. The same section warns that the model can generate arbitrary code that will then be executed, and says not to add any unsafe imports. Execution stops if the generated code tries an illegal operation or raises a regular Python error.
The tour also says you can use Blaxel, E2B, or Docker instead of the local interpreter, and it documents how to select those executors. That is a separate setup. This article does not configure it. The tour points to a further tutorial on secure code execution.
Install the toolkit extra
The guided tour's install line appears as a notebook comment in the tools section:
# !pip install 'smolagents[toolkit]'
That extra supplies the default toolbox. Pass add_base_tools=True at initialization to add it. The tour lists three default tools: DuckDuckGo web search, a Python code interpreter, and a Transcriber built on Whisper-Turbo for speech to text. The interpreter tool is added only to ToolCallingAgent, because a code agent can already execute Python natively.
Build the agent and call run
A minimal agent needs model and tools.
model is the text-generation engine. The agent is a system that uses a model, not the model alone. The tour documents TransformersModel, InferenceClientModel, LiteLLMModel, AzureOpenAIModel, AmazonBedrockModel, and MLXModel. InferenceClientModel uses a Hugging Face InferenceClient and supports Hub Inference Providers, including Cerebras, Cohere, Fal, Fireworks, HF-Inference, Hyperbolic, Nebius, Novita, Replicate, SambaNova, Together, and more.
tools is a list. It can be empty. add_base_tools=True adds the default toolbox on top of whatever you pass.
Inference Providers need an HF_TOKEN. A free Hugging Face account already includes credits, and a PRO account raises those credits. For gated models, or to raise rate limits with a PRO account, set the environment variable HF_TOKEN or pass token when you initialize InferenceClientModel.
Model classes also accept extra keyword arguments at instantiation, such as temperature, max_tokens, and top_p. Those are forwarded to the underlying completion calls.
Copy the tour's Inference Providers example for the first run:
from smolagents import CodeAgent, InferenceClientModel
model_id = "meta-llama/Llama-3.3-70B-Instruct"
model = InferenceClientModel(model_id=model_id, token="<YOUR_HUGGINGFACEHUB_API_TOKEN>") # You can choose to not pass any model_id to InferenceClientModel to use a default model
# you can also specify a particular provider e.g. provider="together" or provider="sambanova"
agent = CodeAgent(tools=[], model=model, add_base_tools=True)
agent.run(
"Could you give me the 118th number in the Fibonacci sequence?",
)
The snippet passes token as a placeholder. Replace that placeholder with your token, or use the tour's other option and set HF_TOKEN. The inline comment says you can omit model_id and let InferenceClientModel use a default model. The tour does not name that default in this example. The following comment shows a provider argument, with together and sambanova as the examples given.
agent.run is what starts the task. By default the agent continues until it calls final_answer or reaches the maximum number of steps. The tour does not state that step limit here, so do not guess a number.
A documented CLI, if you want one
The tour also shows a command-line start. With a prompt, you pass options. With no prompt, it launches interactive argument selection:
# 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/Qwen2.5-Coder-32B-Instruct" --imports "pandas numpy" --tools "web_search"
# Run in interactive mode: launches when no prompt is provided, will guide you through argument selection
smolagent
Use those flags as written. Prefer the Python example if you want the CodeAgent constructor and run call in a file you can reread.
Read the logs before you change the fence
After a run, agent.logs holds the fine-grained record. Each step is a dictionary appended to that list. agent.write_memory_to_messages() rewrites memory as chat messages: the system prompt and the task separately, then for each step the model output and the tool-call output. The tour calls that a higher-level view, and notes that not every log is transcribed.
On initialization, each tool's name, description, input types and descriptions, and output type are baked into the system prompt. That is how the agent learns what it may call. With the default executor, those tools plus the predefined safe functions are the fence.
What to run next
Set a token the way the tour describes, run the Fibonacci example, and read agent.logs. Keep additional_authorized_imports unset on that first run. If the local executor is the wrong boundary for your task, go back to the CodeAgent section of the guided tour and follow its pointer to the secure code execution tutorial before you authorize more imports.