Until now the model only produced text. An agent can also act: it decides to call a function, your code runs it, and the result goes back to the model, which decides what to do next. The pattern of interleaving reasoning with actions was popularised as ReAct (Yao and colleagues, 2022), and it underlies most agent systems.
This power comes with risk, so this stage puts the safety structure in from the first line: read-only tools, a step limit, a log of every action and errors that can’t crash the loop.
You need: the Stage 3 setup (rag.py and the docs/ folder) and a local model that supports tool calling. We tested with qwen3:8b and qwen3.5:9b:
ollama pull qwen3:8b
1. How tool calling works
You send the model a list of tool schemas: names, descriptions and JSON Schemas for the arguments. When the model wants a tool, its reply contains a tool_calls entry instead of (or as well as) text. Your code then:
- checks the requested tool exists;
- runs it with the given arguments;
- sends the result back as a
toolmessage; - calls the model again.
The loop ends when the model replies with no tool calls. That reply is the answer.
The most important idea: the model never executes anything. It can only ask. Your code decides which tools exist and what they are allowed to do.
2. The agent
Save this as agent.py, next to rag.py from Stage 3. It gives the model two tools: a calculator, and the document search you built in Stage 3.
import ast, json, operator, sys
import requests
from rag import build_index, search
OLLAMA = "http://localhost:11434/api/chat"
MAX_STEPS = 6
# --- Tools: small, read-only, and safe to call with any input ------------------------------------------
OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv,
ast.Pow: operator.pow, ast.USub: operator.neg}
def calculator(expression: str) -> str:
"""Evaluate arithmetic only (numbers and + - * / **). Never uses eval()."""
def ev(node):
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
return node.value
if isinstance(node, ast.BinOp) and type(node.op) in OPS:
return OPS[type(node.op)](ev(node.left), ev(node.right))
if isinstance(node, ast.UnaryOp) and type(node.op) in OPS:
return OPS[type(node.op)](ev(node.operand))
raise ValueError("only arithmetic is allowed")
return str(ev(ast.parse(expression, mode="eval").body))
CHUNKS = build_index("docs")
def search_docs(query: str) -> str:
"""Return the three most relevant passages, with ids to cite."""
return "\n\n".join(f"[{c['id']}] {c['text']}" for _, c in search(CHUNKS, query))
TOOLS = {"calculator": calculator, "search_docs": search_docs}
SCHEMAS = [
{"type": "function", "function": {"name": "calculator", "description": "Evaluate an arithmetic expression.",
"parameters": {"type": "object", "properties": {"expression": {"type": "string"}}, "required": ["expression"]}}},
{"type": "function", "function": {"name": "search_docs", "description": "Search the company policy documents.",
"parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}},
]
def run(model: str, task: str) -> str:
messages = [
{"role": "system", "content": "Use the tools to answer. Search the documents for facts and use the calculator "
"for arithmetic. Cite passage ids. If the documents don't say, say so."},
{"role": "user", "content": task},
]
for step in range(1, MAX_STEPS + 1):
r = requests.post(OLLAMA, json={"model": model, "messages": messages, "tools": SCHEMAS,
"stream": False, "options": {"temperature": 0}}, timeout=300)
r.raise_for_status()
msg = r.json()["message"]
messages.append(msg)
calls = msg.get("tool_calls") or []
if not calls:
return msg["content"] # the model answered: done
for call in calls:
name, args = call["function"]["name"], call["function"]["arguments"]
try:
result = TOOLS[name](**args) if name in TOOLS else f"error: unknown tool {name}"
except Exception as e: # a failing tool returns an error message, not a crash
result = f"error: {e}"
print(f"step {step}: {name}({json.dumps(args)}) -> {result[:80]!r}")
messages.append({"role": "tool", "tool_name": name, "content": result})
return f"Stopped after {MAX_STEPS} steps without a final answer."
if __name__ == "__main__":
print(run(sys.argv[1], sys.argv[2]))
What each safety piece does:
- The calculator never uses
eval(). It parses the expression and evaluates only numbers and arithmetic operators. A model asked to “calculate”__import__('os').system(...)gets an error, not a shell. - Both tools are read-only. Nothing the agent does can change data. Add write actions (sending email, editing records) only behind an explicit human approval step.
MAX_STEPSstops runaway loops. An agent that keeps calling tools without converging costs money and time.- Tool errors become messages, so the model can recover (for example, by rephrasing a calculation) instead of the program crashing.
- Every call is printed, so you can see exactly what the agent did. In production, write this to a log you keep.
Run it:
python agent.py qwen3:8b "An employee has 25 days of annual leave and has used 17. How many days are left, and how many can they carry into next year?"
3. What our test run showed
With qwen3:8b, the agent called both tools in its first step:
step 1: calculator({"expression": "25 - 17"}) -> '8'
step 1: search_docs({"query": "annual leave carryover policy"}) -> '[handbook.md#0] # Employee handbook Full-time ...'
It then answered correctly: 8 days remain, and up to 5 can be carried into the first quarter of the next year, citing handbook.md#0.
But it also added: “Requests for carryover must be submitted via the HR portal at least two weeks in advance.” The handbook says that about absences longer than three days, not about carryover. The agent retrieved the right passage and still attached a rule to the wrong thing. qwen3.5:9b answered the same question correctly without that error.
This is the most important lesson of the stage: tools make agents more capable, not more careful. Retrieval and calculation were correct, and the final answer still contained a misreading.
4. Evaluate agents like everything else
Reuse the Stage 2 habit. Write tasks with known answers and check three things for each:
| Check | How |
|---|---|
| Right tools called | Inspect the log: did it search before stating a policy? Did it calculate rather than guess? |
| Final answer correct | Compare with the expected answer, field by field where possible |
| No unsupported claims | Every policy statement should match its cited passage |
The third check is the hardest to automate. Start by reviewing it yourself on ten tasks. Later stages cover automating it with a separate checker model, which is how this site’s own editorial pipeline works.
Project checklist
-
agent.pyruns with both tools, logs every call, and stops atMAX_STEPS. - You tried to break the calculator with a non-arithmetic expression, and it refused.
- Ten evaluation tasks, scored on the three checks above, for two models.
- One improvement (a clearer system message, or better tool descriptions), measured before and after.
Prepared with AI assistance and reviewed by an editor before publication. Editorial & AI policy.