Availit World How AI really works, in your language

Lesson 32 of 4631 minFacts checked October 21, 2026

The agent loop: think, act, look, repeat

The last lesson took one tool call apart. Put that call inside a loop, let the model decide when it has finished, and you have an agent: the thing inside coding assistants, deep-research tools and models that use a computer. This lesson writes a complete agent in plain Python, shows how thinking between actions keeps it on course, works out why long tasks fail so often, and collects the habits that make agents reliable. It ends with how labs in China and the United States now train agents directly, with reinforcement learning in thousands of environments.

In this lesson you will

  • Write a working agent loop, and say exactly when it stops
  • Explain ReAct and interleaved thinking, and why earlier reasoning must be kept
  • Calculate why small error rates sink long tasks, and read METR’s time horizons correctly
  • Keep a loop on track with stopping rules, real checks, retries and plans
  • Choose between a fixed workflow and a free agent
  • Describe how agents are trained with reinforcement learning in environments
On this page
  1. From one call to a loop
  2. A complete agent in plain Python
  3. Thinking between actions
  4. Why long tasks are hard
  5. Keeping a loop on track
  6. Workflows: loops you design yourself
  7. How agents are trained now
  8. Remember
  9. Check yourself

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.

The agent loop
  1. GoalThe user’s request, the instructions and the list of tools
  2. ThinkThe model works out what it knows and what it needs next
  3. ActIt writes one or more tool calls, and the harness runs them
  4. LookThe results are added to the context as observations
  5. 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).

agent.pypython
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 for loop. The model, not your code, decides how many tools to call and when it knows enough to answer.
  • max_steps is 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).
One run of agent.py
  1. You

    How many days passed between 14 August 1947 and 20 July 1969, and what weekday was each date?

  2. Model, thinking

    I need three facts: two weekdays and one difference. None depends on another, so I can ask for all three at once.

  3. 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")
  4. Harness

    Runs all three functions, adds three tool messages and calls the model again.

  5. Tool result

    Thursday
    Sunday
    8011
  6. 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.

  7. Model

    8,011 days passed. 14 August 1947 was a Thursday, and 20 July 1969 was a Sunday.

  8. Harness

    That reply has no tool calls, so the loop ends after two rounds.

Quick check

In agent.py, what makes the loop finish normally?

Show the answer

Answer: The model replies without asking for any tool A reply with no tool calls is the model saying “I am done”. The step limit is the backup for when that never happens.

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.

ReAct as plain text, the way it worked in 2022text
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

Your agent uses a thinking model through DeepSeek’s API. After each tool call, your code sends back only the tool results, without the model’s earlier reasoning. What happens?

Show the answer

Answer: The API refuses the request with error 400 With tools in the request, DeepSeek requires reasoning_content to be passed back. Other providers may accept the request, but the model then loses the plan it was following.

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).

Small errors multiply
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.36

95 % per step: only 36 % of 20-step runs succeed.

0.99¹⁰⁰ ≈ 0.37

Even at 99 % per step, a 100-step task fails most of the time.

n at 50 % = ln 0.5 ÷ ln p

The step at which half of all runs have failed: about 14 steps at 95 %, about 69 steps at 99 %.

Try itHow errors pile up

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:

METR time horizons of the best public models
Time horizon
Early 2025, tasks finished 50 % of the timeabout 50 minutes
February to March 2026, 50 % of the timeabout 12 hours (likely range 5 to 61 hours)
February to March 2026, 80 % of the timeabout 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

Each step of an agent goes right 99 % of the time. About how often does a 70-step task succeed completely?

Show the answer

Answer: About half the time 0.99⁷⁰ ≈ 0.49. Even a small error rate, repeated 70 times, leaves only about half the runs without a mistake.

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 MaxTurnsExceeded when 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?

0 of 8 sorted
  • 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:

Common patterns, from simplest to freest
How it worksGood for
Prompt chainingFixed steps; each call works on the previous call’s output, with checks in betweenTasks that split cleanly, such as outline, then draft, then translate
RoutingA first call sorts the request and sends it to a specialised prompt, or to a cheaper modelHelp desks that get very different kinds of question
ParallelisationSeveral calls at once, either on separate parts of the task or on the same task to compare or voteSpeed, or more confidence through agreement
Orchestrator and workersOne model splits the task as it goes, hands the parts to worker calls and combines the resultsTasks whose parts cannot be known in advance, such as changes across many files
Evaluator and optimiserOne call writes, another judges against clear criteria, and they repeatWriting or translation with a clear standard
AgentThe model plans and acts in a loop with tools until it is doneOpen 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

You must translate 10,000 product descriptions, always in the same three steps: translate, check terms against a glossary, format. What fits best?

Show the answer

Answer: A fixed workflow: a chain of prompts with a check between steps The steps are known and never change, so a workflow is cheaper, faster and easier to test. An agent would spend tokens rediscovering the same plan 10,000 times.

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.

Open agent models and how they were made
How it was trainedWhat it shows
DeepSeek-V3.2 (DeepSeek)Over 1,800 environments and 85,000 complex prompts for reinforcement learning on search, code and general tool useAgent skills built at scale by trying and being scored
Kimi K2 Thinking (Moonshot AI)Trained end to end to interleave reasoning with tool calls200 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 learningInterleaved 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 agentA 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 errorsA 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

In agentic reinforcement learning, what usually provides the reward?

Show the answer

Answer: A check at the end of the run, such as tests passing or an answer matching Automatic checks at the end of a run make it possible to score millions of attempts. Some labs even prefer shorter successful runs, so more tool calls is not better.

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.

Check yourself

5 questions. Tap the answer you think is right.

0 of 5 answered

What ends the loop in a basic agent?

Show the answer

Answer: The model answers without asking for a tool, or a limit such as the step count is reached A reply with no tool calls means the model has finished. Limits on steps, tokens, money or time catch the runs where that never happens.

What did ReAct add to agents?

Show the answer

Answer: Written reasoning between actions, so the model plans, acts and updates its plan from what it sees Thought, action, observation, repeated. Reasoning models now do the same thing natively, between tool calls.

Each step of an agent goes right 95 % of the time. Why does it fail most 30-step tasks?

Show the answer

Answer: 0.95³⁰ ≈ 0.21: the chances multiply, so most runs contain at least one mistake Every step must go right, so the per-step chances multiply. Catching and fixing mistakes is the way out.

For the same models, METR reports a 50 % time horizon of about 12 hours and an 80 % horizon of about 1.5 hours. What does the gap tell you?

Show the answer

Answer: Asking for more reliability shrinks the tasks an agent can be trusted with, by a lot Longer tasks have more steps that can go wrong. Demanding success four times in five, rather than one in two, cuts the task length by about eight times.

Which change most improves an agent’s success on long tasks?

Show the answer

Answer: Real checks, such as running tests, so mistakes are caught and retried A check that catches mistakes lets a retry fix them before they spread. Words in a prompt do much less, and removing the limit only removes the brake.

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
Previous lesson All lessons

Choose your language