How to Build a Local AI Agent with smolagents and Ollama


Your next AI agent can run on your own machine

Most agent tutorials start with an API key: sign up, paste it into an environment variable, and every step costs money and sends your data to someone else's server. The quieter alternative is smolagents, Hugging Face's deliberately small agent library, pointed at a model running on your own hardware through Ollama.

smolagents is Apache 2.0 licensed, has over 30,000 GitHub stars, and its core logic fits in roughly 1,000 lines of Python — small enough to read. Ollama supplies the model. Together they give you an agent that plans, calls tools, and writes files without a cloud account, and this guide sets it all up in about 30 minutes.


Source: Hugging Face smolagents documentation


What makes smolagents different

Most agent frameworks make the model answer with JSON: a blob naming a tool and its arguments. smolagents takes another route — its CodeAgent writes its actions as short Python snippets, so the model can search three sites, filter the results, and add up numbers in one step, using loops and conditionals like ordinary code.

Hugging Face reports code actions take 30% fewer steps than JSON tool calling — fewer slow local generations, and more done per turn, since Python composes results in one step. The loop is simple: task 

in, code out, tools run, observation back, until the agent calls final_answer.



The CodeAgent loop: task, code, tools, answer. Illustration: NewsCarpenter

What you need

Step 1: Pull a model that can handle agent work

Agent work is harder than chat: the model must follow multi-step instructions, track tool outputs, and write valid code. Small or weakly-instructed models loop or forget the task halfway through. Qwen2.5-Coder 7B is a solid start — small enough for a laptop, and trained heavily on code, which is exactly what a CodeAgent asks it to write.

ollama pull qwen2.5-coder:7b
ollama list

Confirm Ollama is answering with curl http://localhost:11434/api/tags — it should list your model. If the connection is refused, run ollama serve in another terminal.

Step 2: Install smolagents with LiteLLM support

Create a project folder and a virtual environment, then install smolagents with its LiteLLM extra — the adapter that lets smolagents talk to Ollama. The base install does not include it.

mkdir smol-agent && cd smol-agent
python -m venv .venv
source .venv/bin/activate
pip install 'smolagents[litellm]'

On Windows, activate with .venv\Scripts\activate instead. If you want the built-in web search tool as well, pip install 'smolagents[toolkit]' adds the default toolset.

Step 3: Connect smolagents to Ollama

This is the step most people get wrong, and the failure is silent. Ollama's default context window is 4,096 tokens. A CodeAgent's system prompt, tool definitions, and a couple of observation steps blow past that fast, and Ollama truncates from the top — so the agent loops or forgets the task after two steps, with no error. Set a large context window up front:

from smolagents import CodeAgent, LiteLLMModel

model = LiteLLMModel(
    model_id="ollama_chat/qwen2.5-coder:7b",
    api_base="http://localhost:11434",
    num_ctx=32768,
)

The ollama_chat/ prefix routes the request to your local Ollama server, and num_ctx passes through to Ollama per request. 32,768 tokens suits a 7B model on 16 GB of RAM; if the model fails to load, drop it to 16,384.

Step 4: Run your first agent

Save this as agent.py — add_base_tools=True adds the built-in tools, including the final-answer tool:

from smolagents import CodeAgent, LiteLLMModel

model = LiteLLMModel(
    model_id="ollama_chat/qwen2.5-coder:7b",
    api_base="http://localhost:11434",
    num_ctx=32768,
)

agent = CodeAgent(tools=[], model=model, add_base_tools=True)
result = agent.run(
    "How many days are there between 2026-11-11 and 2027-03-01? "
    "Show the calculation."
)
print(result)

Run it with python agent.py and watch it work in steps: a snippet using Python's datetime, executed, then the answer. A date calculation is a deliberately boring first task — it proves the code-execution loop works before you hand the agent real tools.

Step 5: Give it web search

An agent that cannot look things up is a calculator. Add the built-in web search tool and ask something that needs current information:

from smolagents import CodeAgent, LiteLLMModel, WebSearchTool

model = LiteLLMModel(
    model_id="ollama_chat/qwen2.5-coder:7b",
    api_base="http://localhost:11434",
    num_ctx=32768,
)

agent = CodeAgent(
    tools=[WebSearchTool()],
    model=model,
    add_base_tools=True,
)
result = agent.run(
    "What is the latest release version of smolagents, "
    "and what changed in it? Summarize in three bullet points."
)
print(result)

The agent calls web_search() like an ordinary Python function, sometimes twice with different queries, then composes the answer from both result sets. That composition is where code agents pull ahead of JSON agents.

Step 6: Write your own tool

Custom tools are plain Python functions with a @tool decorator. The docstring is the tool's description, and type hints are required — smolagents builds the schema from them.

from smolagents import CodeAgent, LiteLLMModel, tool

@tool
def read_note(filename: str) -> str:
    """Read a text note from the notes folder.

    Args:
        filename: Name of the file, for example "ideas.txt".
    """
    with open(f"notes/{filename}") as f:
        return f.read()

model = LiteLLMModel(
    model_id="ollama_chat/qwen2.5-coder:7b",
    api_base="http://localhost:11434",
    num_ctx=32768,
)

agent = CodeAgent(
    tools=[read_note],
    model=model,
    add_base_tools=True,
)
agent.run("Read ideas.txt and list the three best ideas in it.")

Step 7: Two agents are better than one

Once one agent works, try a small team: a manager CodeAgent hands subtasks to managed agents. Here a research agent with web search feeds the manager, which writes the summary:

from smolagents import CodeAgent, LiteLLMModel, WebSearchTool

model = LiteLLMModel(
    model_id="ollama_chat/qwen2.5-coder:7b",
    api_base="http://localhost:11434",
    num_ctx=32768,
)

researcher = CodeAgent(
    tools=[WebSearchTool()],
    model=model,
    name="researcher",
    description="Searches the web and returns facts with sources.",
)
manager = CodeAgent(
    tools=[],
    model=model,
    managed_agents=[researcher],
    add_base_tools=True,
)
manager.run(
    "Research the latest smolagents release and write a short summary."
)

Our CrewAI and Ollama multi-agent crew guide builds the same idea with role-based crews, and our LangGraph tutorial covers graph-structured agents.

Do not skip the sandbox warning

A CodeAgent runs model-written Python on your machine. The built-in executor restricts imports and blocks some system access, but Hugging Face is explicit: LocalPythonExecutor is a best-effort mitigation, not a security boundary — it can be bypassed. Treat it that way.

Beyond your own trusted prompts, run the agent's code in a real sandbox — smolagents supports E2B, Blaxel, Modal, and Docker. Never point a CodeAgent at folders holding credentials or irreplaceable files, or let it run code from untrusted pages or prompts: as NCC Group showed, prompt injection can turn a helpful agent into a file-reading one.

Troubleshooting

  • The agent loops or repeats itself. Raise num_ctx (Step 3) — a 32k window needs the RAM to hold it.
  • The agent ignores your tool. A missing Args: section or vague docstring is the usual culprit.
  • Code fails with an import error. The local executor allows only a small import list by default. Pass extras through additional_authorized_imports — only modules you trust.
  • Answers are wrong but confident. Local 7B models are weaker at multi-step reasoning than frontier models. Use smaller steps and specific prompts, or move to Qwen2.5-Coder 14B or 32B.
  • LiteLLM cannot reach Ollama. Check curl http://localhost:11434/api/tags, and drop any trailing /v1 from api_base.

Where to go from here

You now have a local agent that can compute, search, use your own tools, and delegate to a teammate — all without an API key. Next steps: give it memory, connect your files through an MCP server, and move code execution into a Docker sandbox before it touches anything important. The library is small on purpose: when something behaves oddly, you can open agents.py and read the whole loop in an afternoon. That readability is what turns a demo into a tool you trust.

Comments

Popular posts from this blog

Open-Source AI Weekly: Bonsai, GigaChat 4 Lead

Claude Claims Proof of Riemann Hypothesis After 167 Years

How to Build an AI Agent with LangGraph in 30 Minutes