What You Will Learn
An AI agent is a program in which a language model decides which of your tools to use next, your code runs them, and the results go back to the model until the task is finished or a limit stops it. This lesson explains that loop before you install anything. You will:
- describe what a model call does and what it cannot do;
- name the parts of an agent loop and what stops it;
- read a recorded run and point to every model call, tool call and the final answer;
- find where a second recorded run went wrong.
Before you start, you need nothing installed. There are no model calls in this lesson. Allow about 30 minutes.
What a Model Call Does
A language model turns text into more text. You send it a request containing a conversation, and it predicts a reply. Everything an agent does is built from requests like this, so a few words are worth fixing now:
- Token. Models read and write text in pieces called tokens: a short word, part of a longer word, a number or a punctuation mark. Lengths, limits and speeds are counted in tokens, not characters or words.
- Context window. The number of tokens a single request can hold, counting the conversation you send and the reply. Anything beyond it is cut off. Ollama, the program that runs the course's model, uses 4,096 tokens on a typical laptop unless you ask for more; this course asks for 8,192.
- Messages and roles. The conversation is a list of messages. A
systemmessage holds standing instructions ("You help staff at an equipment-rental desk..."),usermessages are the requests, andassistantmessages are the model's replies. Agents add a fourth role,tool, explained below. - Stop reason. Each reply says why the model stopped writing: usually because it finished, sometimes because it reached a length limit you set.
- Thinking output. Some models write out intermediate reasoning, returned separately from the answer. The course model has no thinking mode; a later lesson shows what thinking output looks like in models that produce it.
Three limits follow from this, and the rest of the course depends on them:
- A model call only produces text. The model cannot run code, open a file, read your database or reach the internet. If a reply says "I checked the bookings", nothing was checked unless your program did it.
- A model does not remember between requests. Each request must carry the whole conversation again. What looks like memory in a chat app is the app resending earlier messages.
- A reply is a prediction, not a fact. The model writes what is likely to come next, given its training and the conversation. It can be fluent and wrong. The model card for the course model says plainly that it may produce inaccurate responses and should be tested for each use.
Tools, the Loop and Stop Conditions
A tool is a function in your program that you describe to the model: its
name, what it does, and the arguments it takes, written as a JSON Schema. The
model never runs a tool. It can only reply with a request, "call
check_availability with these arguments", and your code decides whether
and how to run it. The loop below is what turns a model that writes text into
an agent that gets work done.

One agent loop. Blue arrows are the normal path; the two boxes on the right are the ways the loop ends.
Follow the numbered arrows:
- Your program sends the messages and the tool definitions. The first time, that is the system message and the user's question. Before sending, it checks its budget, for example "at most six model calls", and stops if the budget is used up.
- The model replies. The reply is either an ordinary answer or a request to call one or more tools, with arguments it has filled in.
- If the reply asks for tools, your program runs them. It checks that
each tool exists and that the arguments are valid, runs the function, and
adds a
toolmessage carrying the result. - Back to the top. The conversation is now longer: it holds the model's request and the results. Your program sends all of it again, so the model can use the results or ask for another tool.
The loop has two normal ways to end, shown on the right. A reply with no tool requests is the final answer. A budget that runs out stops a run that is not converging. Later lessons add a time budget, a limit on repeated calls and more stop reasons, such as a model server that stays unavailable. An agent without a budget can loop until you stop it by hand.
A Recorded Run, Step by Step
Here is a real run of the course model, granite4.1:3b, recorded on
2026-10-21 while the course was choosing its model. The program offered three
tools: search_items (find items by name), check_availability (count free
units for a date range) and create_booking. It ran at temperature 0 with a
budget of six model calls. The tools and the small test database were an
early version of the ones you build later, so field names differ slightly;
the shape of the run is what matters here.
Each line is one message. asks for shows a tool request in the model's
reply, with the arguments it chose:
[system] You help staff at an equipment-rental desk answer questions about the catalogue and bookings. Use the tools to look up facts; never guess item ids, stock or availability. Dates are written YYYY-MM-DD. Today is 2026-11-01.
[user] How many 45 litre backpacks are free from 2026-11-10 to 2026-11-12?
[assistant] asks for search_items({"query": "45 litre backpack"})
[tool] [{"item_id": "pack-45l", "name": "45 litre backpack", "stock": 6}]
[assistant] asks for check_availability({"item_id": "pack-45l", "start": "2026-11-10", "end": "2026-11-12"})
[tool] {"item_id": "pack-45l", "start": "2026-11-10", "end": "2026-11-12", "free_units": 6}
[assistant] There are **6 free 45‑litre backpacks** available from 2026‑11‑10 through 2026‑11‑12.
The program recorded three model calls, 12.5 seconds in total on the author's computer, and the answer matched the database: six backpacks were free. Read it against the diagram:
- Pass 1. The program sent the system and user messages with the three
tool definitions. The model did not know the item's id, and the system
message told it never to guess ids, so it asked for
search_itemswith the words from the question. The program ran the search and added thetoolmessage: one matching item,pack-45l. - Pass 2. The program sent the conversation again, now five messages
long. The model used the id from the search result and asked for
check_availabilitywith the two dates copied from the question. The program ran it and added the result: six free units. - Pass 3. The program sent all seven messages. The model's reply asked for no tool, so it was the final answer, and the loop stopped there.
Notice who did what. The model chose the tools and filled in their arguments;
the program did every lookup, wrote every tool message and decided when the
run was over. One detail is invisible on screen: the model wrote the dates
and "45-litre" with non-breaking hyphens and put narrow no-break spaces before
the dates. They look like ordinary hyphens and spaces, but a program that
checks answers by comparing text has to allow for them, and the course's
checks do.
Agents, Single Calls and Workflows
An agent is not always the right design. The same model can be used in three ways:
| Design | Who decides the steps | Suits |
|---|---|---|
| A single call | Nobody: one request, one reply | Writing, summarising or extracting from text you supply |
| A fixed workflow | Your code: a sequence of model calls and checks you wrote | Tasks whose steps you know in advance, such as extract, check, then reply |
| An agent | The model, one step at a time, within your limits | Tasks whose steps depend on what the tools return |
Agents are flexible, but each step costs another model call, the path can differ between runs, and mistakes can compound. Published guidance on building agents recommends starting with the simplest design that works and adding agent behaviour only when it is needed. This course teaches all three, and a later module compares a workflow and an agent on the same task with measurements rather than opinion.
The Course's Local Setup
Every core exercise in this course runs on your own computer:
- Ollama is a free program that runs language models locally. It listens
only on your own computer, at the address
127.0.0.1:11434, and the course's prompts stay on your computer. The next lesson installs it. - Granite 4.1 3B (
granite4.1:3b) is a small open-weight model from IBM, a 2.1 GB download under the Apache 2.0 licence, built to call tools. It runs without a graphics card (GPU), uses one if you have a supported one, and makes mistakes a larger model might not. The course uses those mistakes as material: you will see them, measure them and design around them. - Python with four libraries: httpx to send requests, Pydantic to describe and check data, the MCP SDK for the Model Context Protocol, and pytest for tests.
- A scripted stand-in model, written in a later lesson, returns fixed replies so you can test every branch of your agent quickly and repeatably. It is always labelled as a stand-in: it tests your code, not a model.
No account, API key, payment or cloud service is needed after installation, and no lesson depends on one.
What This Course Covers
This course builds one agent from the protocol upwards: model calls, structured output, tool calling, the agent loop, tool design, workflows, context and memory, safety, reliability, traces, tests, evaluation, the Model Context Protocol (MCP) and a second API format, ending with a final challenge. Some neighbouring topics are deliberately left to other VectaCourses courses:
| Left out here | Covered by |
|---|---|
| Several agents working together, orchestration frameworks such as LangGraph, durable execution across processes | Multi-Agent Systems and Workflow Orchestration |
| The Model Context Protocol and its Python SDK in depth (this course builds one local server and client) | Model Context Protocol (MCP) for Developers |
| Embeddings, vector databases and retrieval evaluation (this course uses a keyword search tool) | Retrieval-Augmented Generation (RAG) and Vector Databases |
Exercise: Read a Recorded Run
Nothing to run: this exercise is reading and writing. Copy the recorded run above into a text file or onto paper, and label every line with:
- Who produced it: your program or the model.
- What it is: the system message, the user's request, a model call's reply (and whether it requests a tool or gives the final answer), or a tool result.
- The pass it belongs to (1, 2 or 3).
Then answer: which line shows the loop's stop reason, and what is that reason?
Success means every line has all three labels, you can say for each tool request why the model needed it, and you have named the stop reason. Compare with the answer below when you have finished.
Your Turn: Find Where a Run Went Wrong
The same program ran a second question in the same recording. The desk has never rented kayaks, so the right answer is "we have no kayaks". The system message was the same as above:
[user] How many kayaks are free from 2026-11-10 to 2026-11-11?
[assistant] asks for search_items({"max_results": 5, "query": "kayak"})
[tool] []
[assistant] asks for search_items({"max_results": 10, "query": "kayak"})
[tool] []
[assistant] asks for search_items({"max_results": 20, "query": "kayak"})
[tool] error: invalid arguments for search_items: max_results: Input should be less than or equal to 10
[assistant] asks for search_items({"max_results": 10, "query": "kayak"})
[tool] []
[assistant] asks for check_availability({"item_id": "KAYAK001", "start": "2026-11-10", "end": "2026-11-11"})
[tool] error: invalid arguments for check_availability: item_id: String should match pattern '^[a-z0-9]+(-[a-z0-9]+)*#x27;
[assistant] asks for check_availability({"end": "2026-11-11", "item_id": "Kayak", "start": "2026-11-10"})
[tool] error: invalid arguments for check_availability: item_id: String should match pattern '^[a-z0-9]+(-[a-z0-9]+)*#x27;
The program recorded six model calls and no final answer. Find:
- the first model call at which the run started repeating itself, and why the repetition could not help;
- the point where the model broke an instruction in the system message;
- what stopped the run, and what would have happened without it.
If you get stuck: count the model calls (each asks for line is one), and
compare each request with the result just before it.
Check Your Understanding
- Put these six steps of one agent run in order:
(a) the model replies with a final answer;
(b) the program adds a
toolmessage with the result; (c) the program sends the system message, the question and the tool definitions; (d) the program runscheck_availabilityagainst the database; (e) the model replies asking forcheck_availability; (f) the program sends the conversation again. - Suppose the program ran the tool but forgot to add the
toolmessage before calling the model again. What would the model see, and what might it do?
Answer and Reasoning
Exercise
| Line | Who produced it | What it is | Pass |
|---|---|---|---|
[system] | Your program | Standing instructions, sent with every request | 1 to 3 |
[user] | Your program, passing on the user's question | The request | 1 to 3 |
[assistant] asks for search_items | The model | Reply to model call 1: a tool request; the id is unknown and the instructions forbid guessing | 1 |
[tool] [{"item_id": "pack-45l", ...}] | Your program | Tool result from the database | 1 |
[assistant] asks for check_availability | The model | Reply to model call 2: a tool request using the id it was just given | 2 |
[tool] {"item_id": "pack-45l", ... "free_units": 6} | Your program | Tool result | 2 |
[assistant] There are **6 free ... | The model | Reply to model call 3: no tool request, so the final answer | 3 |
The last line shows the stop reason: a final answer, a reply with no tool requests. The budget of six model calls was never reached. The system and user messages belong to every pass because the whole conversation is resent each time.
Your turn
- Repetition starts at model call 2. The first search for "kayak"
returned an empty list, and the model searched for the same word again,
only asking for more results. An empty result means nothing matched;
raising
max_resultscannot make a match appear. Call 3 asked for 20, which the tool's schema forbids (at most 10), and call 4 went back to the same search a third time. - Calls 5 and 6 broke the instruction "never guess item ids". With no
search result to use, the model invented
KAYAK001and thenKayak. The program's argument check rejected both, because neither matches the id pattern, so no wrong data was looked up. Validation in your code, not the model's good behaviour, is what kept the run safe. - The budget stopped it after six model calls. The sixth tool result was added but never read, because the loop ended before another call. Without a budget the run would have continued, costing time on every pass, with no sign of converging. A better run would have answered "the desk has no kayaks" after the first empty search. Later lessons make that more likely with clearer tool results, and catch repetition when it happens.
Check your understanding
- c, e, d, b, f, a. The program sends the request (c); the model asks for a tool (e); the program runs it (d) and records the result (b); the program sends the longer conversation (f); the model answers (a).
- The model would see its own tool request with nothing after it, as if the
tool had never run. It cannot know the result, because results reach it
only through
toolmessages. It might ask for the same tool again, so the run repeats until the budget stops it, or it might answer without the data, which means a guess presented as an answer. Either way the program has the result and the model does not.
References
- Ollama: Tool calling: tools described by name, description and JSON Schema; the loop repeats until a reply has no tool calls.
- Ollama API: Generate a chat message: message roles and the fields of a reply.
- Ollama FAQ: the 4,096-token default context and that Ollama runs locally on 127.0.0.1.
- Ollama: Context length: what the context window holds and how it is set.
- Ollama library: granite4.1 and the Granite 4.1 3B model card: size, licence, tool calling and the stated limitations.
- Anthropic: Building effective agents: workflows compared with agents, and starting with the simplest design.