Build a Local AI Agent with OpenAI Agents SDK and Ollama

OpenAI's Agents SDK is a small Python library for building agents: an agent is a model plus instructions and tools, and a runner handles the loop of model calls, tool execution, and follow-up replies. Out of the box it talks to OpenAI's cloud. But the SDK ships a Chat Completions adapter that accepts any OpenAI-compatible client, and Ollama exposes exactly that interface at http://localhost:11434/v1. Put the two together and the whole agent loop runs on your own machine: no API key, no per-token bill, and your files never leave the room.




A local agent stack: an open model served by Ollama, wired to tools and memory in Python. Source: Machine Learning Mastery, via LLMs Central.

This guide builds a working file-search agent in about 30 minutes: it reads notes from a folder, answers questions about them, and hands off to a specialist when needed. If you already run models with Ollama, the new part is short — one adapter, one client, and a decorator for tools.

What you need

  • Python 3.10 or newer, and a terminal.
  • Ollama installed and running. The 20-minute Ollama setup guide covers installation if you have not done it yet.
  • A model that can call tools reliably. gpt-oss:20b is the pick here: a 20-billion-parameter open-weight model with native tool calling, about a 13 GB download, and it needs roughly 16 GB of VRAM. On a smaller card, qwen3:8b (about 5 GB) is the lighter fallback.
  • About 30 minutes.

Step 1: Pull the model and check the endpoint

Download the model, then confirm Ollama answers on its OpenAI-compatible endpoint. The /v1/models call should list the tag you just pulled.

ollama pull gpt-oss:20b
ollama list
curl http://localhost:11434/v1/models

If the curl call fails with a connection error, Ollama is not running. Start it with ollama serve on Linux, or launch the Ollama app on macOS and Windows.

Step 2: Install the SDK

Create a virtual environment and install the package. The SDK changes between minor releases, so pin the version in a requirements.txt once you have a working setup.

python3 -m venv .venv
source .venv/bin/activate
pip install openai-agents

Step 3: Point the SDK at Ollama

Three lines do the connection. AsyncOpenAI points at Ollama's local endpoint with a placeholder API key, which Ollama ignores but the client library still requires. OpenAIChatCompletionsModel wraps that client so the SDK can use it as a model. Tracing is switched off because the SDK's built-in tracing posts to OpenAI's platform, and without an OpenAI key that call fails.

from agents import (
    Agent,
    AsyncOpenAI,
    OpenAIChatCompletionsModel,
    Runner,
    set_tracing_disabled,
)

set_tracing_disabled(disabled=True)

client = AsyncOpenAI(
    base_url="http://localhost:11434/v1",
    api_key="ollama",  # placeholder; Ollama ignores it
)
model = OpenAIChatCompletionsModel(
    model="gpt-oss:20b",
    openai_client=client,
)

agent = Agent(
    name="Assistant",
    instructions="You are a helpful assistant.",
    model=model,
)

result = Runner.run_sync(agent, "Write a haiku about recursion in programming.")
print(result.final_output)

Run it with python agent.py. A haiku in the output means the wiring works. The model name must match a pulled tag exactly, including the size suffix — gpt-oss:20b, not gpt-oss.



Ollama serves local models through an OpenAI-compatible API, so agent frameworks can talk to it like any cloud endpoint. Source: DEV Community.

Step 4: Give the agent tools

An agent that can only chat is a demo. The @function_tool decorator turns an ordinary Python function into a tool: the SDK builds the JSON schema from the type hints and uses the docstring as the model's description of what the tool does. The example below gives the agent two tools for a notes folder. Keep the scope tight on purpose — a tool that can read any path on disk is a tool that can read anything.

import os
from agents import function_tool

NOTES_DIR = os.path.expanduser("~/notes")

@function_tool
def list_notes() -> str:
    """List the files in the local notes folder."""
    return "\n".join(sorted(os.listdir(NOTES_DIR)))

@function_tool
def read_note(filename: str) -> str:
    """Read one note file by name."""
    path = os.path.join(NOTES_DIR, filename)
    with open(path, encoding="utf-8") as f:
        return f.read()

Attach the tools to the agent and ask a question that needs them. The runner calls the model, runs whatever tool it requests, feeds the result back, and repeats until the model answers.

agent = Agent(
    name="Notes assistant",
    instructions=(
        "You answer questions about the user's notes. "
        "Use list_notes to see what exists, then read_note to read a file. "
        "If a note does not exist, say so instead of guessing."
    ),
    model=model,
    tools=[list_notes, read_note],
)

result = Runner.run_sync(
    agent, "Which of my notes mention project deadlines?"
)
print(result.final_output)

Watch the first runs closely. A model that calls a tool with a made-up filename, or answers from memory instead of reading the file, is telling you the model is too weak for the job. That is the most common failure in local agent setups, and the fix is a stronger model, not more prompt text.

Step 5: Route work with handoffs

One agent doing everything gets messy fast. Handoffs let a triage agent pass a request to a specialist and return the specialist's answer. The pattern below adds a second agent that only handles scheduling notes, while the triage agent decides which one should answer.

scheduler = Agent(
    name="Scheduler",
    instructions="You only answer questions about dates, deadlines, and schedules in the notes.",
    model=model,
    tools=[list_notes, read_note],
)

triage = Agent(
    name="Triage",
    instructions="Hand off scheduling questions to the Scheduler. Answer everything else yourself.",
    model=model,
    tools=[list_notes, read_note],
    handoffs=[scheduler],
)

result = Runner.run_sync(triage, "When is the product launch?")
print(result.final_output)

Each specialist keeps its own instructions and tools, so adding a third one — a research agent with web search, for instance — is a small change. For how frameworks compare on this kind of orchestration, see the LangGraph vs CrewAI vs AutoGen comparison, and the LangGraph tutorial builds the same idea with a graph-based runtime.

Troubleshooting

  • "Model not found" or a 404 from Ollama: run ollama list and copy the tag verbatim. A missing :20b suffix is the usual cause.
  • The model ignores tools or invents arguments: switch to a model with stronger tool calling. gpt-oss:20b and qwen3:8b handle it; most 3B models do not, and no amount of prompt engineering fixes that.
  • Tracing errors or 401 responses: make sure set_tracing_disabled(disabled=True) runs before any agent call. Tracing is the one part of the SDK that still assumes an OpenAI account.
  • First answer is slow, later ones are fast: Ollama loads the model into VRAM on first use. Check ollama ps while a request is in flight to see what is loaded and whether it fits in GPU memory.
  • Features that only exist on the Responses API: deferred tool loading and hosted tool search are Responses-only. On the Chat Completions path they are rejected, so design around plain function tools and handoffs instead.

Where this setup fits

This combination is the shortest path from wanting an agent to having one running on your own machine. The SDK stays out of the way: three primitives, a small amount of code, and the same Agent object works unchanged if you later swap Ollama for a hosted endpoint. The trade is capability — a 20B local model will not match a frontier cloud model on hard reasoning, and tool calling is where that gap shows first. For personal assistants, file triage, and automation around your own data, that trade is usually worth it: free to run, private by default, and fast enough on a mid-range GPU. For persistent memory on top, the Mem0 and Ollama guide adds recall to a local agent without a cloud service.

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