Thank you for reading part ten of our AI basics course. Here you will build a local AI agent that can read a source, use a calculator and return to the model with what it found. You will also learn how to check whether it actually did the work.
This matters when an answer needs more than one action. An assistant that estimates a bill may need to find a price first, check its date, then calculate a total. To check whether those actions happened, you need a log that records each one.
If you are new to AI, read what AI and language models are for an introduction. Then use our tokens and embeddings guide to understand the pieces a model reads. You can try this example without knowing every training detail.
For the Python work, start with part six on RAG for searching your notes. Follow part seven on tool calling and part eight on the agent harness to see how the model requests tools. The download includes those earlier functions beside the new controller.
What multi-step AI does between your question and its answer
Ask a chatbot to explain a receipt and it may answer in one reply. Ask it to find a receipt in your files, read the total and compare it with an expense limit, and the task now has several steps. Finding the file can change what the assistant needs to do next.
In this tutorial, multi-step AI means a program that makes several model requests and carries useful results from one request into the next. The model can ask for an allowed tool. Python runs that tool, sends back its result and asks the model what to do with it.
When a model says "opening the receipt," that text alone does not open a file. The application needs a tool that can read the receipt.
A fixed workflow could always search, read and calculate in an order you wrote in Python. An agent gives the model some choice over the next action. The program still decides which tools exist, whether a request is allowed and when the task must stop.
This distinction follows the workflow and agent terminology in Anthropic's Building Effective Agents article. Product names use "agent" more loosely, so we will describe the control we actually give our model.
Our example sends repeated requests to one chat model. A separate embedding model handles searches of the notes.
Why a tool result can change the next step
Suppose a file search returns "No matching file." A fixed script might stop there. A model could try another permitted filename after seeing the error, then answer from the file it managed to read. That change depends on a result it did not have at the beginning.
The same idea helps when an answer needs fresh information. A model can request a lookup, inspect what comes back and decide whether another lookup is needed. More requests also create more opportunities to make mistakes, so adding a loop does not automatically improve the answer.
Inside each request, the language model still generates tokens from its input. It has not learned new weights because Python sent it a tool result. The result becomes part of the conversation that the next request can use.
The ReAct research paper studied models that alternate between reasoning and taking actions. Our example shares the practical idea of acting and using feedback, but it does not reproduce that paper's experiments or expose a model's hidden thoughts.
We turn thinking off for these runs. The logs show the requests, proposed tool calls and actual results, which are enough to check whether a file was read.
Choose a small task with a checkable answer
Our task uses the AI pricing article as its source. The saved text reports a rounded output rate of 24 tokens per second for an earlier Qwen3 8B test.
We ask the agent to read that source, then estimate the generation time for 120 output tokens. The arithmetic is 120 divided by 24, giving five seconds.
Those five seconds describe an estimate based on that earlier rounded rate. They exclude loading, processing the prompt, searching notes and the extra model requests in this tutorial. We are not claiming that today's complete agent task finishes in five seconds.
The task is deliberately easy to check. We know which file contains the measurement and which calculation should follow it. If the program cannot show those steps here, a detailed answer would still leave us unsure whether it did the work.
For this exact task, a fixed Python workflow would be simpler. Using an agent lets us observe which steps it chooses and where it fails.
Open the example before asking the model to work
You can download the example code and recorded runs to follow this lesson. Unzip it and open a terminal inside the extracted folder.
The Python files use the standard library. Our recorded environment was Python 3.14.8 and Ollama 0.40.15 on an Apple M2 Pro with 32 GiB of memory. Model digests and the saved API metadata are included, since a model tag alone does not identify every file behind a run.
Start with the saved trace. You can read it without downloading a model or starting Ollama.
python3 inspect_trace.py
python3 checks.py
The first command prints the model turn, prompt count, generated count and tools actually dispatched on that turn.
1 432 29 ['read_file']
2 3308 155 ['divide']
3 3454 109 []
The second command runs 17 offline checks of the controller. These use scripted replies to test failures such as an unknown tool or a missing source read. They are not 17 questions answered correctly by the model.
To make a fresh model run, use the Ollama setup from part six with qwen3:8b and nomic-embed-text already installed. The program connects to Ollama on your own computer.
python3 collect.py --case explicit-source
This loads the question and settings from recorded/explicit-source.json, runs them again and writes a new log to runs/explicit-source.json. It leaves the recorded example untouched. Your new output and counts can differ.
The notes folder contains a frozen snapshot of 35 public articles. We refreshed the text and rebuilt the search index for this lesson, producing 287 chunks with 768 numbers in each embedding.
Keep the bundled notes and index together while comparing the saved runs. If you replace the embedding model, rebuild the index using compatible document embeddings before judging search results.
How Python carries the conversation between steps
Open agent.py. The program begins with a system instruction and your question, then sends the conversation and tool descriptions to Ollama's chat endpoint.
Our tool menu contains search_notes, read_file and divide. Search returns relevant passages. Read returns a permitted note's full text. Divide performs checked arithmetic in Python.
The following excerpts come from the complete runnable file in the download. Follow them in that file, rather than assembling a second program from the excerpts.
request = {"model": model, "messages": messages, "tools": SCHEMAS,
"stream": False, "think": False,
"options": {"num_ctx": 32768, "num_predict": 350,
"temperature": 0, "seed": 0}}
num_ctx sets the context allocation used here. num_predict bounds generation in each request, while the outer loop limits how many requests the program can make. A fixed seed and temperature zero do not promise the same output across model builds or hardware.
The model can return an assistant message containing tool_calls. We append the full assistant message to the history, including those calls. Keeping only its text would lose the requests that explain the tool results.
Before running a tool, the controller checks how many tool attempts remain and how often the same call has appeared. It adds each allowed tool result as a message for the next model request.
name, result = execute(call)
args = fn.get("arguments") if isinstance(fn, dict) else None
record["results"].append({"name": name,
"arguments": args if isinstance(args, dict) else {},
"content": result})
messages.append({"role": "tool", "tool_name": name, "content": result})
The tool result becomes another message in messages. On the next turn, the model sees the earlier conversation plus that result and can request another tool or offer an answer.
In the saved direct-source run, the first request asked for read_file. The second saw that file and asked for divide. The third saw the calculator result and returned an answer.
Only the read and calculation are Python actions. The three model requests are separate inference calls, even though the application presents them as one task.
The model got five seconds and skipped a required step
Our first question asked the model to find the earlier rate in the notes, read the source and then calculate. The system instruction also told it to read a source before using a recorded measurement.
It searched the notes, found the rate in a passage, called divide and answered five seconds. The answer cited the right filename. There was no read_file call anywhere in the log.
The arithmetic was correct, but the requested full-file check never happened. The citation suggested that the model had checked more of the source than the log showed.
You can inspect this in recorded/unchecked.json. Its controller status is answer_returned, which means the model returned text without further tool calls and the enabled checks accepted it. That label is not a factual accuracy score.
We added a Python check that requires a successful source read before the controller accepts the answer.
Make source reading a condition for completion
The Python controller can accept a required filename and an expected division. When the model offers final text, evidence_gaps checks the recorded actions before accepting that text.
For a read to count, the result must contain the complete expected file text from a successful read_file call. Mentioning the filename or attempting a read that fails does not meet this requirement.
The division must happen in a later model turn than the read. If a model requests both actions together, it chose the calculation before receiving the file. Executing that batch in order would not show that the model used the reading.
gaps = evidence_gaps(trace, required_read, required_division, source_text)
record["evidence_gaps"] = gaps
if gaps:
if turn == max_turns:
trace["status"] = "evidence_limit"
break
messages.append({"role": "user", "content": "Host evidence check is incomplete. "
+ " ".join(gaps) + ". Do this before your final answer."})
continue
When something is missing, the controller adds a message describing the missing action and gives the model another turn, if the budget permits. The full implementation also checks whether generation was cut off, so a truncated reply cannot quietly pass as the final answer.
We supplied the expected filename and the numbers 120 and 24. This is a narrow check for a known exercise, not a program that can discover whether any answer on any topic is true.
It can establish that the program returned the file and later ran the expected division. It cannot establish that every sentence in the final explanation is accurate, or that the model understood the document.
For an unknown invoice, you would need a different check. You might verify the invoice ID, the currency and the amounts extracted from the actual document before allowing a total into your accounting system.
What happened when we changed the task and the limits
The table compares five recorded live runs on the local model. It shows the entire task, not just the last response.
| Run | Model requests | Tool attempts | Prompt tokens | Generated tokens | Observed result |
|---|---|---|---|---|---|
| Unchecked | 3 | 2 | 2,891 | 308 | Answered, skipped full read |
| Checked, six turns | 6 | 3 | 13,327 | 583 | Stopped at turn limit |
| Checked, seven turns | 7 | 4 | 17,990 | 799 | Answered after required actions |
| Explicit source | 3 | 2 | 7,194 | 293 | Read, divided, answered |
| Source-only question | 4 | 2 | 5,664 | 204 | Recovered from a wrong filename |
In the checked six-turn run, the model first searched and divided again without reading the file. The host rejected its candidate answer, and it then read the source.
Its next candidate still failed our order requirement because the calculation had happened before the read. On turn six it finally proposed the required division, but the controller stopped before executing it. There was no remaining model turn to receive the result.
We allowed seven turns in another run. That run completed the required sequence and returned an answer, using seven model requests and four tool attempts along the way.
These individual runs do not establish a success rate or tell us whether an extra turn would help another task. In the six-turn run, the budget stopped the model just as it requested the required division.
For the explicit-source version, we gave the exact filename and a clear instruction to read it before calculating. That run followed the short path in three requests.
Here the model needed no search or correction rounds. Because we already knew the file and the calculation, Python could also have carried out that sequence directly.
Count the whole conversation, not just its last reply
The direct-source run ended with 109 generated tokens. Looking only at that reply would hide the two earlier model requests, which generated 29 and 155 tokens.
The total was 293 generated tokens and 7,194 prompt tokens. You can reproduce those sums from the three rows printed by inspect_trace.py.
Our totals add Ollama's prompt_eval_count and eval_count across requests. They are API-reported counts for these runs. They are not the number of unique words in the conversation or a measurement of electricity.
The program sends the conversation again on each turn. That includes tool descriptions and earlier results, so a full file can appear in several requests. Caching can change the work required. These summed counts do not prove every repeated token was processed from scratch.
The checked seven-turn run used more reported prompt tokens than the unchecked run. The longer run included more context while the controller checked the required actions. The calculation itself was unchanged.
When you compare an agent with a single reply, count the extra requests and inspect what each one achieved. For these local runs, the token totals describe the requests. They do not calculate a cloud-service charge.
Set limits on model requests and tool attempts
A model may keep requesting a search even when another search adds nothing. It can also vary the query slightly, which makes a simple duplicate check less useful.
Our controller has separate limits for model turns and tool attempts. A turn is one request to the chat model. A tool attempt is a dispatch through the checked executor, including an attempt that returns a validation error.
max_turns defaults to six and max_tools to six. The last allowed model turn may return an answer, but cannot start another tool. A tool call needs a later model turn to receive its result, so the controller blocks tool calls on the last turn.
The exact-repeat guard allows the same tool name and arguments twice, then stops before a third dispatch. It ignores changing call IDs, since a new ID does not make the same search useful.
To check that behavior, the offline suite uses a scripted responder that always requests the same file read. The program dispatches twice, then stops with repeat_limit. No language model participates in that test.
For a separate turn-limit test, we allow more repeats than the turn budget can reach. The responder keeps requesting that file, and the four-turn budget stops it after three tool attempts. Changing arguments could also evade the exact-repeat check, so we keep the outer budget in either case.
These controlled tests check whether our code stops repeated tool requests. They use scripted replies and do not show a live model looping forever.
The HTTP helper has a 120-second timeout on its request. That is separate from an overall task deadline, which this teaching program does not implement. It also does not summarize a growing history or resume an interrupted task.
Ask about missing evidence without inventing a measurement
Another question asked whether the pricing article contained an actual battery wattmeter result. It did not. The article discusses assumptions and an adapter-based upper bound, which are different from a measured power reading.
In our saved run, the model first requested the wrong filename. The tool returned an error, and the model offered an answer anyway. The host's source requirement sent it back to read the correct file.
It then returned the supported core conclusion that the article did not contain that actual measurement. We still read the explanation ourselves, rather than assuming a passed source check made every phrase correct.
Notice the question's scope. It asks what that article reports. A search returning a few passages would not establish that no such measurement exists anywhere in all our notes, let alone on the internet.
When your assistant says "there is no evidence," check which files or passages it searched before accepting that claim.
Give the model only the tools the task needs
The model can request only the functions our dispatcher recognizes. A request for run_shell returns an unknown-tool error. We never execute generated Python text to make a tool appear.
read_file accepts permitted note filenames, rejects paths outside the notes folder and excludes symbolic links. Those checks belong in Python, even if the tool description already asks the model to behave.
The calculator checks argument keys and number types before dividing. It rejects booleans, non-finite numbers and inputs outside its chosen range, then also checks that the result is finite.
values = [args["numerator"], args["denominator"]]
if any(type(v) not in (int, float) or abs(v) > 1e6 or not math.isfinite(v) for v in values):
return name, "Expected finite numbers between -1000000 and 1000000."
if values[1] == 0:
return name, "Denominator must not be zero."
quotient = values[0] / values[1]
if not math.isfinite(quotient):
return name, "Result must be finite."
return name, json.dumps({"value": quotient}, allow_nan=False)
The order of these checks matters. Python integers can be much larger than a floating-point value can represent. We check the permitted size before asking math.isfinite to inspect a huge integer, which could otherwise raise an overflow error.
There is another edge case. A tiny nonzero denominator can produce a non-finite quotient even when the inputs passed the range check. The result check catches that separately.
Search and read do not edit the notes, and there is no shell or write tool in this menu. The command-line program does write JSON logs, however, and those logs contain complete messages and source text.
Our bundled corpus is public. If you replace it with work files, review what enters the logs before sharing them. Running a model locally does not make every saved file safe to distribute.
Finally, a document can contain instructions aimed at the assistant. We tell the model to treat notes as evidence, but that sentence is not a security boundary. Restricted tools reduce what the host can execute, while misleading text can still influence the answer.
Try the loop with a question you can check
Use the archived explicit-source run first and follow the three requests. Find the full-file result, then the division, then the final text. Compare that sequence with the unchecked run that skipped the read.
You can inspect these public JSON traces in our JSON visualizer if you prefer an expandable tree. The tool helps you see the structure, but it does not judge the answer's facts.
For your own exercise, choose a short document and a question with an answer you can verify. Decide what a successful tool result must contain before you ask the model to work, then check the final explanation against it.
Open recorded/unchecked.json and find the missing read before running a new task.