Module 14 · How AI Agents Work · Lesson 29 of 34
The agent loop, step by step
Think, call a tool, observe, repeat. What really happens between your code and the model on every turn.
In this lesson · about 20 minutes
- Describe the agent loop and who does what in it
- Read an agent trace and explain each step
- Explain why context grows and what stops the loop
You have used agents throughout the course. Here is what happens inside. An agent is a short program around a model:
messages = [system_prompt, user_message]
for step in range(MAX_STEPS):
reply = model(messages, tools=TOOLS)
if reply.tool_calls:
for call in reply.tool_calls:
result = run_tool(call) # your code runs it
messages.append(call)
messages.append(result)
else:
return reply.text # the model is done
return hand_over("step limit reached")
- The model only ever produces text. Sometimes that text is a structured tool call: a name and arguments.
- Your code runs the tool, checks permissions, and appends the result to the messages.
- The model is called again with the whole growing history, and decides the next step.
- The loop ends when the model answers without calling a tool, or when your limits stop it.
Try it · simulator
Inside the agent loop: a live trace
Step through an agent handling a late-delivery complaint: what it thinks, which tools it calls, what comes back, and how its context grows. Try the scenario where a tool fails, and the one that loops.
- 1 · CustomerMy order 2231 still hasn't arrived! It was due yesterday.
Steps so far
1
Tool calls
0
Context now
1,217tokens
Status
Running
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Written by Noviq Academy in its own words. The simulators are small teaching models that keep the real idea and leave out the scale; their numbers (prices, speeds, scores) are illustrative. Model names, prices and features change quickly, so check your provider's current documentation before you build. Read-aloud uses your device's built-in voices.