Local Agents8 min read

Build a Local AI Agent That Cites a File with Ollama and Python

Build a zero-dependency Python tool-calling agent with Ollama, inspect the two-turn JSON protocol, enforce safe file allow-lists, and test missing-fact refusal.

Ramon GoveiaEditor, PolarisonPublished Checked against official sources

Most “build an AI agent” tutorials pull in heavy orchestration frameworks, five third-party SDKs, and a paid cloud API key before you ever see what the model actually sent over the wire. Stripped of abstractions, an AI agent is remarkably simple: it is a loop where a language model can emit a structured tool call (JSON naming a function and its arguments), your Python code executes that function safely, and you feed the result back into the conversation so the model can ground its final answer in real facts.

In this lab, we build a zero-dependency, read-only local agent using Python’s standard library (urllib and json) and a local Qwen model running in Ollama. You will inspect every message in the two-turn tool-calling protocol, verify deterministic source citations, and run a deliberate missing-fact test to prove whether the model admits ignorance instead of hallucinating.

Why build an agent with zero frameworks first?

Frameworks like LangChain, LlamaIndex, and PydanticAI are valuable once you manage dozens of tools, retries, and structured state machines. When you are debugging why a local 4B or 7B model misfires a tool call, however, framework abstractions hide the exact JSON payload exchanged with Ollama. Writing the 60-line loop directly with the standard library teaches you three critical engineering habits:

  • Strict allow-listing: your code — never the model — decides which function names, arguments, and file paths are permitted to execute.
  • Programmatic citations: instead of trusting the LLM to type the right filename in prose, Python prints the verified tool name and source path directly from the runtime execution trace.
  • Negative-case testing: testing what happens when a fact is absent from the source document is far more revealing than testing easy lookups.

How Ollama’s two-turn tool-calling protocol works

Ollama implements an OpenAI-compatible tools array on /api/chat. Under the hood, Ollama injects your JSON Schema tool definitions into the model’s native chat template (for Qwen, special <tool_call> tokens) and parses the model’s output back into structured JSON. Every grounded answer takes exactly two model calls:

  1. Turn 1 — Discovery & tool request: Python sends the user’s question alongside the JSON Schema for read_release_note (a read-only function taking zero arguments).
  2. Model emits structured intent: Instead of answering from memory, Qwen responds with a tool_calls array requesting read_release_note.
  3. Defensive validation in Python: Your script verifies that the model returned exactly one tool call, that its name matches read_release_note, and that no unexpected arguments were injected. Only then does Python read release-note.md from a fixed, hardcoded path (preventing path-traversal attacks like ../../.env).
  4. Turn 2 — Grounded synthesis: Python appends the model’s tool-call message plus a role: "tool" message containing the raw Markdown text, and sends the updated history back to Ollama.
  5. Verified output: Qwen composes a concise answer strictly from the retrieved text, and Python prints the executed tool name and filename alongside it.

Step 1: Run the local notes agent

First complete our Windows Ollama + Qwen 3.5 setup so qwen3.5:4b is installed and listening on port 11434. Download agent.py and release-note.md into the same directory, then run two contrasting queries:

ollama list
python agent.py
python agent.py "Who owns rollback?"

The sample release-note.md explicitly names Mina as owner of a Thursday deployment at 14:30 UTC, while intentionally omitting any rollback owner. In our test, the default query retrieved the deployment time accurately, and the second query correctly reported that no rollback owner was present in the file — instead of fabricating a name.

Inside the tool schema and defensive loop

When you expand this pattern to your own notes, logs, or internal docs, keep the tool schema minimal and validate every field before executing local code:

TOOLS = [{
    "type": "function",
    "function": {
        "name": "read_release_note",
        "description": "Read the current release note markdown file for deployment facts.",
        "parameters": {"type": "object", "properties": {}, "required": []},
    },
}]

# Defensive check before executing any local I/O:
calls = msg.get("tool_calls") or []
if len(calls) != 1 or calls[0]["function"]["name"] != "read_release_note":
    raise RuntimeError(f"Unexpected tool call payload: {calls}")

Notice two crucial details. First, keep temperature: 0 on tool-calling turns — higher sampling temperatures dramatically increase malformed JSON and hallucinated argument names on smaller 4B–8B models. Second, never pass raw model-supplied file paths directly into open(); always map keys to an explicit allow-list of files or resolve paths inside a sandboxed directory.

Step 2: Mutate a fact to verify real grounding

A classic trap when testing LLMs is mistaking memorized or guessed answers for real tool use. Prove your agent is genuinely reading disk state by editing release-note.md: change the deployment time from 14:30 UTC to 16:15 UTC, save the file, and re-run python agent.py. The answer must immediately reflect 16:15 UTC. Then re-run the rollback-owner query to confirm the model still refuses to invent missing fields.

Scaling up: Local agent vs. Cloud API cost

Because tool calling requires two round-trips per user question (and agentic coding loops can easily chain 10 to 30 tool calls), token costs multiply quickly on flagship cloud models — especially when the entire conversation history is re-sent on every turn. Running your development and read-only lookup loops locally on Ollama costs $0, while production multi-tool agents on the cloud benefit massively from prompt caching and low-cost tiers ranked in our cheapest models for RAG guide.

Debugging tool-calling failures

  • Connection refused on 127.0.0.1:11434: verify Ollama is running (ollama ps or launch Ollama from the Start menu).
  • Model answers directly without calling the tool: confirm the installed tag supports native tool calling (Qwen 3.5, Qwen 2.5, Llama 3.1+, Mistral) and make the tool description explicit about what facts live inside the file.
  • Unexpected tool name or extra arguments: smaller models occasionally invent optional parameters when temperature > 0. Force temperature: 0 and tighten your system instruction.
  • Answer contradicts the cited file: inspect the raw role: "tool" string sent on Turn 2, check that num_ctx is large enough to hold the entire file without silent truncation, and shorten the user question.

To benchmark another local model fairly, keep the exact same release-note.md and two questions, and score three things separately: valid tool-call syntax, exact fact accuracy, and honest refusal on missing fields. See the official Ollama tool-calling docs for multi-tool and streaming examples.

Keep reading