From one call to a loop
An agent is a model that calls tools in a loop and decides for itself what to do next, until the job is done. There is no special agent model and no hidden machinery: the harness from the last lesson simply keeps going. Call the model; if it asks for tools, run them, add the results and call it again; if it answers without asking for a tool, stop.
- GoalThe user’s request, the instructions and the list of tools
- ThinkThe model works out what it knows and what it needs next
- ActIt writes one or more tool calls, and the harness runs them
- LookThe results are added to the context as observations
- Done?A reply with no tool call ends the loop; so does a step, time or money limit
Anthropic’s guide to building agents (2024) draws a useful line. In a workflow, your code decides the order of model calls and tools. In an agent, the model decides them as it goes, based on what it has seen.
Workflow: you fix the steps
- Example: translate a description, check its terms against a glossary, then format it. Always in that order.
- Predictable, cheaper and easy to test.
- Best when you know the steps in advance.
Agent: the model picks each step
- Example: “find out why this program crashes and fix it”. Nobody knows in advance which files it will read.
- Handles tasks whose steps cannot be predicted.
- Costs more, is harder to test, and can wander off course.
A complete agent in plain Python
Here is a whole agent: two date tools, one loop and a brake. It speaks the OpenAI-style format, so changing base_url and model points it at Qwen, Kimi, a vLLM server or llama.cpp on your own computer (the APIs lesson).
import json, os
from datetime import date
from openai import OpenAI
client = OpenAI(base_url="https://api.deepseek.com",
api_key=os.environ["DEEPSEEK_API_KEY"])
def weekday(day):
return date.fromisoformat(day).strftime("%A")
def days_between(start, end):
return (date.fromisoformat(end) - date.fromisoformat(start)).days
TOOLS = {"weekday": weekday, "days_between": days_between}
SCHEMAS = [
{"type": "function", "function": {
"name": "weekday",
"description": "Day of the week for a date given as YYYY-MM-DD.",
"parameters": {"type": "object", "required": ["day"],
"properties": {"day": {"type": "string"}}}}},
{"type": "function", "function": {
"name": "days_between",
"description": "Whole days from start to end, both YYYY-MM-DD. "
"Negative if end is before start.",
"parameters": {"type": "object", "required": ["start", "end"],
"properties": {"start": {"type": "string"},
"end": {"type": "string"}}}}},
]
def run_agent(question, max_steps=10):
messages = [
{"role": "system", "content": "Use the tools for every date fact. "
"Never do date arithmetic in your head."},
{"role": "user", "content": question},
]
for step in range(max_steps):
reply = client.chat.completions.create(
model="deepseek-flash", messages=messages, tools=SCHEMAS)
msg = reply.choices[0].message
messages.append(msg) # keeps its reasoning and calls
if not msg.tool_calls:
return msg.content # no tool call: the agent is done
for call in msg.tool_calls:
try:
args = json.loads(call.function.arguments)
result = TOOLS[call.function.name](**args)
except Exception as e: # unknown tool, bad JSON, bad date
result = f"Error: {e}"
messages.append({"role": "tool", "tool_call_id": call.id,
"content": str(result)})
return "Stopped: the step limit was reached before an answer."
print(run_agent("How many days passed between 14 August 1947 and "
"20 July 1969, and what weekday was each date?"))
- The agent is the
forloop. The model, not your code, decides how many tools to call and when it knows enough to answer. max_stepsis the brake. Without it a confused model can loop for ever, and every round costs tokens.- Failures go back to the model as results instead of crashing the program. Shown “Invalid isoformat string”, a model usually corrects its call on the next round.
- Tools are looked up in a fixed dictionary, so the model can only run the functions you chose.
- DeepSeek’s models think by default. Appending the whole message keeps the model’s
reasoning_content, which DeepSeek requires during tool use (the next section explains why).
-
You
How many days passed between 14 August 1947 and 20 July 1969, and what weekday was each date?
-
Model, thinking
I need three facts: two weekdays and one difference. None depends on another, so I can ask for all three at once.
-
Model
Round 1 ends with three tool calls in one reply:
weekday(day="1947-08-14") weekday(day="1969-07-20") days_between(start="1947-08-14", end="1969-07-20") -
Harness
Runs all three functions, adds three tool messages and calls the model again.
-
Tool result
Thursday Sunday 8011 -
Model, thinking
All three results are in. Check: about 21.9 years times 365.25 days is roughly 8,000, so 8,011 is plausible.
-
Model
8,011 days passed. 14 August 1947 was a Thursday, and 20 July 1969 was a Sunday.
-
Harness
That reply has no tool calls, so the loop ends after two rounds.
Quick check
Thinking between actions
Early agents acted without explaining themselves, and lost track easily. ReAct (2022, Princeton University and Google) asked the model to write a short thought before each action, then read the observation that came back. Prompted with only one or two examples, ReAct beat agents trained by imitation and reinforcement learning on two benchmarks of household and shopping tasks, by 34 and 10 points of success rate.
Question: How many days passed between 14 August 1947 and 20 July 1969?
Thought: I need the difference between two dates. I should not count in my head.
Action: days_between[1947-08-14, 1969-07-20]
Observation: 8011
Thought: That is about 21.9 years times 365.25, roughly 8,000, so it is plausible.
Action: finish[8,011 days]
- The harness stopped the model each time it wrote “Observation:”, ran the action itself, pasted in the result and let the model carry on. Before native tool calls, this stop-word trick was how agents worked.
- Native tool calls (the last lesson) replaced the trick, and Qwen’s documentation advises against stop-word templates for its reasoning models. The idea of thinking between actions stayed.
Today’s reasoning models (the reasoning lesson) think inside the loop: after each tool result they reason again before the next action. Chinese labs made this a design goal. MiniMax calls it interleaved thinking and describes each round as plan, act, reflect. Moonshot says Kimi K2 Thinking can make 200 to 300 tool calls in a row without human help, reasoning between them. Claude’s API supports thinking between tool calls as well.
Quick check
Why long tasks are hard
An agent that is right 95 % of the time on each step sounds good. But a task only succeeds if every step goes right, and those chances multiply (the probability lesson).
P(whole task) = p × p × … × p = pⁿIf each of n steps goes right with chance p, and every step must go right, multiply.
0.95²⁰ ≈ 0.3695 % per step: only 36 % of 20-step runs succeed.
0.99¹⁰⁰ ≈ 0.37Even at 99 % per step, a 100-step task fails most of the time.
n at 50 % = ln 0.5 ÷ ln pThe step at which half of all runs have failed: about 14 steps at 95 %, about 69 steps at 99 %.
Start with the defaults: 98 % per step and 30 steps, and only a little over half the runs succeed. Slide to 100 steps and watch the chance collapse. Now choose “Check, retry once”: with a check that catches 80 % of mistakes, the same 100-step task succeeds about 65 % of the time instead of 13 %. Finally look at the last line: an agent you must trust on every run needs far better numbers than one you try once.
This interactive part needs JavaScript.
METR, a research group that measures what AI agents can do, turned this into a yardstick called the time horizon: the length of task, timed by skilled people, that an agent completes with a given chance of success. In March 2025 the best model’s 50 % time horizon was about 50 minutes, and it had doubled roughly every seven months since 2019. Asking for more reliability shrinks the horizon sharply, exactly as the multiplying chances predict:
| Time horizon | |
|---|---|
| Early 2025, tasks finished 50 % of the time | about 50 minutes |
| February to March 2026, 50 % of the time | about 12 hours (likely range 5 to 61 hours) |
| February to March 2026, 80 % of the time | about 1.5 hours |
METR’s tasks are mostly software and research work. Its May 2026 report warns that the best agents had nearly used up the task set, which cannot reliably measure horizons above about 16 hours, so the newest numbers are uncertain.
Quick check
Keeping a loop on track
The demo shows the two levers: make each step more reliable, or catch and fix mistakes before they spread. Good harnesses pull both:
- Stopping rules. The loop ends when the model answers without a tool call, or when a limit is reached: steps, tokens, money or time. OpenAI’s Agents SDK raises
MaxTurnsExceededwhen its turn limit is passed; your loop needs the same brake. - Checks that do not depend on the model’s opinion. Run the tests, compile the code, add up the totals, open the file it wrote. A real check turns a hidden mistake into a visible error the agent can fix. In the demo, the catch rate is the strongest lever.
- Errors as results. Send failures back as readable text, never as a crash. StepFun’s Step-DeepResearch kept some training runs in which a tool failed and the agent recovered correctly, so the model would learn to recover.
- A written plan. Ask the agent to keep a short to-do list and tick items off. After many steps it reminds the model of the goal, and it shows you the progress.
- Reflection. After a failed attempt, the model writes down what went wrong before trying again. Reflexion (2023) kept such notes between attempts and reached 91 % on the HumanEval coding test, against 80 % for GPT-4 alone.
- Loop detection. The same call with the same arguments, again and again, means the agent is stuck. Notice it, then stop or tell the model.
- A person at the moments that matter. Risky actions wait for approval, and the user can stop or redirect the agent at any time.
Does each one keep an agent on track, or make it drift?
-
A limit on the number of steps
Answer: Keeps it on track
-
Running the tests after every change
Answer: Keeps it on track
-
Dropping the model’s reasoning after each tool call
Answer: Makes it drift
-
A tool error that crashes the program with no message to the model
Answer: Makes it drift
-
A to-do list the agent updates as it works
Answer: Keeps it on track
-
Tool results so long that the original request is buried
Answer: Makes it drift
-
Asking the user before deleting anything
Answer: Keeps it on track
-
Letting the same failing call repeat twenty times
Answer: Makes it drift
Workflows: loops you design yourself
Between one prompt and a free agent sit workflows: fixed patterns of model calls that your code controls. Anthropic’s guide names five that keep appearing in real products:
| How it works | Good for | |
|---|---|---|
| Prompt chaining | Fixed steps; each call works on the previous call’s output, with checks in between | Tasks that split cleanly, such as outline, then draft, then translate |
| Routing | A first call sorts the request and sends it to a specialised prompt, or to a cheaper model | Help desks that get very different kinds of question |
| Parallelisation | Several calls at once, either on separate parts of the task or on the same task to compare or vote | Speed, or more confidence through agreement |
| Orchestrator and workers | One model splits the task as it goes, hands the parts to worker calls and combines the results | Tasks whose parts cannot be known in advance, such as changes across many files |
| Evaluator and optimiser | One call writes, another judges against clear criteria, and they repeat | Writing or translation with a clear standard |
| Agent | The model plans and acts in a loop with tools until it is done | Open problems that give feedback, such as tests or search results |
The “heavy” modes that top benchmark tables are workflows built on agents. Kimi K2 Thinking’s Heavy Mode runs eight attempts at once and then combines them into one answer. Alibaba’s Tongyi DeepResearch runs several research agents in parallel in its Heavy Mode, and a final step merges what they found. More attempts cost more compute and usually give better answers.
Quick check
How agents are trained now
ReAct agents were ordinary models following a prompt. Today’s agent models are trained for the loop itself, with reinforcement learning (the reasoning lesson) in environments. A survey of over 500 papers on agentic reinforcement learning (2025) puts the difference simply: ordinary training for chat rewards a single reply, while agentic training rewards a long series of decisions made in a world the model can only partly see.
| How it was trained | What it shows | |
|---|---|---|
| DeepSeek-V3.2 (DeepSeek) | Over 1,800 environments and 85,000 complex prompts for reinforcement learning on search, code and general tool use | Agent skills built at scale by trying and being scored |
| Kimi K2 Thinking (Moonshot AI) | Trained end to end to interleave reasoning with tool calls | 200 to 300 tool calls in a row; 71.3 % on SWE-bench Verified and 60.2 % on BrowseComp, by Moonshot’s count |
| MiniMax-M2 (MiniMax) | Fine-tuned on runs where thinking, actions and observations alternate, then reinforcement learning | Interleaved thinking as a habit: plan, act, reflect |
| Tongyi DeepResearch (Alibaba) | A mixture of experts with 30.5B parameters and 3.3B active per token, built on Qwen3-30B-A3B and trained as a web research agent | A plain ReAct mode, and a Heavy Mode scoring 58.3 % on BrowseComp and 38.3 % on Humanity’s Last Exam |
| Step-DeepResearch (StepFun) | Built on Qwen2.5-32B; kept the shortest successful runs, plus some runs that recovered from tool errors | A 32B ReAct agent close to the best commercial research systems on its rubric test, at under 0.5 yuan per task |
Scores are the labs’ own, from their reports. Benchmarks change quickly; the evals lesson explains how to read them.
Quick check
Remember
- An agent is a model calling tools in a loop: call the model, run its tools, add the results, repeat until it answers without a tool call or a limit is reached.
- In a workflow your code fixes the steps; in an agent the model chooses them. Use the simplest one that works.
- ReAct put thinking between actions. Today’s reasoning models think after every tool result, and their earlier reasoning must be sent back each round.
- Errors multiply: 95 % per step gives only 36 % over 20 steps. That is why METR’s 80 % time horizon is about eight times shorter than its 50 % one.
- Real checks with retries are the strongest lever. Add stopping rules, errors as results, a written plan, reflection, loop detection and a person for risky actions.
- Heavy modes run several agents in parallel and combine them: more compute, better answers.
- Agent models are now trained with reinforcement learning in thousands of environments, with Chinese labs (DeepSeek, Moonshot, MiniMax, Alibaba, StepFun) among the leaders in open models.
Words to know
- agent
- A model that calls tools in a loop, choosing each next step itself, until a task is done.
- agent loop
- Call the model, run any tools it asks for, add the results, and repeat until it answers without a tool call.
- workflow
- A system in which your code fixes the order of model calls and tools.
- step limit
- The most rounds a loop may run: a brake against endless or costly runs.
- ReAct
- Reasoning and acting: the model writes a thought, takes an action, reads the observation, and repeats.
- observation
- What the agent sees after an action: a tool result, an error or a page.
- interleaved thinking
- A reasoning model thinking again after every tool result, with its earlier reasoning kept in context.
- compounding errors
- Small chances of failure at each step multiplying into a large chance of failure over many steps.
- pass^k
- The chance that an agent succeeds on all k tries of the same task: a measure of reliability.
- time horizon
- METR’s measure: the length of task, timed by skilled people, that an agent finishes with a given chance of success.
- reflection
- The agent writing down what went wrong before it tries again.
- environment
- A task, its tools and a way to score the result, used to test or train an agent.
- agentic reinforcement learning
- Training a model with rewards for whole multi-step runs in environments, not for single replies.
- heavy mode
- Running several attempts in parallel and combining them into one answer.
Go to the source
This lesson is built on these papers and documents. Paper links open arxiv.org, a separate site.
-
ReAct: Synergizing Reasoning and Acting in Language Models
The thought, action, observation loop that almost every agent still follows.
-
Reflexion: Language Agents with Verbal Reinforcement Learning
Agents that write notes about their failures and do better on the next attempt.
-
SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering
Why the tools and screens you give an agent matter as much as the model.
-
Measuring AI Ability to Complete Long Tasks
METR’s time horizon: how it is measured, and the seven-month doubling.
-
The Landscape of Agentic Reinforcement Learning for LLMs: A Survey
A map of over 500 papers on training agents with reinforcement learning.
-
DeepSeek-V3.2: Pushing the Frontier of Open Large Language Models
Agentic task synthesis at scale and reinforcement learning in over 1,800 environments.
-
Tongyi DeepResearch Technical Report
Alibaba’s open web research agent, trained end to end, with ReAct and Heavy modes.
-
Step-DeepResearch Technical Report
StepFun’s 32B research agent: how its training runs were chosen, recovery from errors included.
-
The MiniMax-M2 Series: Mini Activations Unleashing Max Real-World Intelligence
Section 7.1 defines interleaved thinking and measures the effect of keeping earlier reasoning.
-
Building effective agents
Workflows versus agents, and the five patterns, with advice on when to use each.
-
METR: Frontier Risk Report (February to March 2026)
The 12-hour and 1.5-hour time horizons, and why the task set is nearly used up.
-
Introducing Kimi K2 Thinking
Hundreds of tool calls in a row, and how Heavy Mode combines eight attempts.
-
Interleaved Thinking Unlocks Reliable MiniMax-M2 Agentic Capability
Why the earlier reasoning must be passed back, from the lab that built around it.
-
DeepSeek API: Thinking Mode
The rule that reasoning_content must be returned during tool use, with sample code.
-
mini-swe-agent
A complete coding agent in about 100 lines: the best way to read a real loop.
Check yourself
5 questions. Tap the answer you think is right.
0 of 5 answered
Lesson complete
Answer every question above to complete this lesson.
Your progress is saved on this device only.
Next lessonHarnesses: the program around the model