Skip to content
Index Ai Academy
Phase 10 · Harness foundations

The core loop, built properly

Stop reasons, parallel tool calls, errors and turn budgets.

About 40 minutes · Model names, versions and API rules checked November 2026 · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers9

First principles

What tells a harness whether to call a tool, retry, or finish a turn?

The model response includes a stop reason. Use it as an explicit transition in a bounded loop, and return correlated tool results together when a model step requested them together.

  1. Starting point

    Model returns a message with an explicit stop reason

  2. What changes

    Harness follows the matching transition and appends the exchange

  3. Result

    Loop continues under its cap or returns the final outcome

Compare all three steps
  1. Starting point

    Model returns a message with an explicit stop reason

  2. What changes

    Harness follows the matching transition and appends the exchange

  3. Result

    Loop continues under its cap or returns the final outcome

Complete and reverse the trace

Given Model returns a message with an explicit stop reason and Loop continues under its cap or returns the final outcome, write down the missing step that connects them.

Compare with the worked step

Harness follows the matching transition and appends the exchange

Now take Harness follows the matching transition and appends the exchange and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Model returns a message with an explicit stop reason. Check that your implementation produces the result shown above.

Try it on a new case

A model response requests three tools at once, and one fails with a valid error result. What goes back into the transcript?

Show worked reasoning

Return a result for each requested ID together, including the failed tool's actionable error. The model can proceed with complete information about that turn.

Run, change, and build

Check this when debugging. Running a tool call from a reply that stopped at max_tokens.

Trace the cause · Harness decision and state
  1. Trace the action from the proposed tool call through validation to the recorded result. Predict what survives a stop.
  2. Change one permission, cost limit, or interruption point. Compare the trace and persistent state to see which rule determined the outcome.
  3. Try the same reasoning on this case. A model response requests three tools at once, and one fails with a valid error result. What goes back into the transcript?

Why it matters

The Phase 1 loop handled two cases: the model wants a tool, or it's done. Real loops meet more. Replies get cut off by the token limit. Long server-side work pauses. The API is sometimes overloaded. A model may decline. Each needs a different response, and getting one wrong causes the classic agent bugs: running a half-written tool call, retrying forever, or losing the conversation. This lesson builds a loop that handles them all.

What you'll be able to do

  • Handle every stop reason: end_turn, stop_sequence, tool_use, max_tokens, model_context_window_exceeded, pause_turn and refusal
  • Return the results of parallel tool calls together, in one user message
  • Retry rate limits and overloads with backoff, and fail fast on bad requests
  • Keep the transcript append-only and cap the number of turns
Quick check
A model's reply stops because it hit max_tokens, halfway through writing a tool call. What should the loop do?
  1. Treat the cut-off reply as the final answer
  2. Crash, since replies should never be cut off
  3. Not run the half-written call; ask again with more room
  4. Run the tool with whatever input arrived
Show the answer

Not run the half-written call; ask again with more room

Each stop reason needs its own handling. max_tokens means the reply is incomplete, so a half-written tool call may have broken or missing input, and running it could do the wrong thing.

The idea: every reply has a reason

Recall: What an agent harness is built a loop around a scripted model, and Hosts: connecting servers to a model ran a model's tool calls for real. The loop below handles every way a reply can end.

Quick check
From the lesson on what a harness is: pass the model in as a function, so a test can use a scripted one. What does this print?
def run(model, prompt):
    return model(prompt).upper()

calls = []

def scripted(prompt):
    calls.append(prompt)
    return "ok"

print(run(scripted, "status?"), calls)
  1. ok ['status?']
  2. OK ['status?']
  3. OK []
  4. OK ['ok']
Show the answer

OK ['status?']

run doesn't know or care which model it was given. The scripted one returns a fixed reply and records what it was sent, so the test can check both sides of the call. No API was used. The loop in this lesson is tested the same way, one stop reason at a time.

Every stop reason has a job

A coworker writing you a note can stop for different reasons. They've finished. They need you to fetch something. They ran out of paper. They'd rather not answer. You'd respond differently to each, and a loop has to as well. Each Messages API response has a stop_reason, and a loop should branch on all of them:

stop_reasonwhat happenedwhat the loop does
end_turnthe model finished its replyreturn the answer
stop_sequenceit wrote one of your stop_sequencesusually treat as finished
tool_useit wants one or more toolsrun them all, send all results back, loop
max_tokensit hit your max_tokens limit mid-replydon't trust the reply; retry with a bigger limit, or continue
model_context_window_exceededthe conversation and the reply filled the model's context windowdon't trust the reply; shrink the context, then call again
pause_turna long server-side tool turn was pausedsend the assistant content back as-is and call again
refusalthe model declined, for safety reasonsstop; show the user a clear message

Three of these deserve care.

Quick check
A reply comes back with stop_reason: "refusal". What should the loop do?
  1. Treat it like end_turn and return the text
  2. Send the same request again until the model answers
  3. Run the last tool again
  4. Stop, and show the user a clear message
Show the answer

Stop, and show the user a clear message

A refusal means the model declined, for safety reasons. Looping on it wastes calls, and passing it off as an answer misleads the user.

max_tokens with a tool call. If the reply was cut off while writing a tool_use block, its input may be incomplete. You wouldn't act on an instruction that stops mid-sentence. So never run it. The safe move is to send the same request again with a higher limit. Nothing was appended, so the transcript is unchanged.

model_context_window_exceeded. This one looks like max_tokens, but a bigger limit won't help: the whole window is full. Append nothing, shrink the context by clearing old tool results or compacting (the context lesson), and call again.

pause_turn. Server tools such as web search run on Anthropic's side. A long one can pause. Append the assistant's content as it is, with no new user message, and call again. The model picks up where it stopped.

Parallel tool calls

One reply can hold several tool_use blocks, for example "read these three files". It's a shopping list, and you bring everything back in one trip. The rule: every tool_use gets a tool_result with the matching tool_use_id, and all of them go in the next user message. Dropping one gets a 400 error. Sending them as separate user messages doesn't fail, because the API merges back-to-back messages from the same role, but it teaches the model to stop asking for parallel calls. The harness may run independent calls at the same time; the results still go back together.

Try it now

Four messages by the end: user, assistant, user, assistant. Read the body on every arrow.

In your own words
Which stop reasons end a reply without meaning it succeeded, and what does the loop do with each?

Write a sentence or two, then compare it with a good answer in the lesson.

In code: a loop that handles every reason

Errors from the API itself

Separate from what the model says, the HTTP call can fail. When a phone call fails, a busy signal means try again later, and a wrong number means check the number. Sort failures the same way, by whether retrying could help:

statusmeaningretry?
400bad request: your code built something invalidno: fix the code
401, 403bad key, or no permissionno
413request too largeno; shrink the context
429rate limitedyes, after the retry-after header or a backoff
500, 529server error or overloadedyes, with backoff
Quick check
Your agent's API call fails with 400 Bad Request. What should the harness do?
  1. Wait for the retry-after header, then retry
  2. Retry with exponential backoff
  3. Retry once, then switch to another model
  4. Stop and fix the code: it will fail again
Show the answer

Stop and fix the code: it will fail again

A 400 means your code built something invalid. Retrying sends the same broken request again, burning time and money.

Backoff, jitter and retry budgets are taught in Rate limits, retries and idempotency. Here you only decide which statuses reach that code. The official SDKs already retry 408, 409, 429, 5xx and dropped connections, twice by default, with exponential backoff and jitter. A harness adds a cap on total attempts and logs each retry. Never retry a 400 in a loop: the same bad request fails the same way, and an agent stuck doing that burns time and money.

Append-only transcripts

Treat the message list like a ship's log written in pen. Add each reply and each batch of results to the end, and don't edit or reorder what's already there. That's what append-only means.

There are two reasons. Prompt caching reuses an unchanged prefix, so edits near the start make every later call pay full price. And models that think keep signed reasoning blocks in their replies; changing earlier turns can invalidate them. When the context does need to shrink, use the deliberate tools in the context lesson.

A turn budget

You'd give a contractor a limit on hours, so a small job can't run on forever. A loop with no limit can run forever too: the model keeps calling tools without converging. Count model calls and stop at a budget (often 20 to 100 for coding agents). When the budget runs out, return a clear status, not an exception, so the caller can report it or ask the user to continue.

Quick check
A loop retries 429, 500 and 529 errors, doubling its wait each time. What does this print?
statuses = [529, 429, 200]
delay, waits = 1, []
for s in statuses:
    if s in (429, 500, 529):
        waits.append(delay)
        delay *= 2
print(waits)
  1. [1, 2, 4]
  2. []
  3. [1, 1]
  4. [1, 2]
Show the answer

[1, 2]

Two temporary errors mean two waits, 1 then 2 seconds. The 200 ends the retries.

Worked example

Every call gets a result

A model can ask for several tools at once. The next message must answer every one of them, matched by id, or the API rejects the whole request.

reply = [
    {"type": "text", "text": "Let me check both."},
    {"type": "tool_use", "id": "t1", "name": "get_stock", "input": {"sku": "TENT-2"}},
    {"type": "tool_use", "id": "t2", "name": "get_price", "input": {"sku": "TENT-2"}},
]

TOOLS = {"get_stock": lambda sku: 14, "get_price": lambda sku: 89.0}

results = [{"type": "tool_result", "tool_use_id": b["id"],
            "content": str(TOOLS[b["name"]](**b["input"]))}
           for b in reply if b["type"] == "tool_use"]

asked = {b["id"] for b in reply if b["type"] == "tool_use"}
answered = {b["tool_use_id"] for b in results}
print(results)
print("every call answered:", asked == answered)
It runs right here in your browser, with nothing to install.

All the results go in one user message, and their order doesn't matter since the ids match them up. Forgetting one is a common bug, so check for it when you build the message.

Quick check
A reply stops with max_tokens, and its last block is a tool_use for write_file. What should the harness do?
  1. Run write_file with whatever input arrived, since most of the file is probably there
  2. Append the reply and ask the model to try again, without changing max_tokens
  3. Not run it: the input may be cut off. Resend the same request with a higher max_tokens
  4. Return the reply to the user as the final answer, since the model has stopped
Show the answer

Not run it: the input may be cut off. Resend the same request with a higher max_tokens

A truncated tool input could write half a file. Retrying the unchanged request with more room is safe.

Worked example

One branch per stop reason

The heart of a production loop is a single function that decides what to do with each reply.

def next_action(reply):
    reason = reply["stop_reason"]
    if reason in ("end_turn", "stop_sequence"):
        return "finish"
    if reason == "tool_use":
        return "run_tools"
    if reason == "pause_turn":
        return "continue"
    if reason == "max_tokens":
        return "retry_bigger"
    if reason == "model_context_window_exceeded":
        return "shrink_context"
    if reason == "refusal":
        return "refused"
    return "unknown"

REASONS = ["end_turn", "tool_use", "pause_turn", "max_tokens",
           "model_context_window_exceeded", "refusal", "something_new"]
for r in REASONS:
    print(r, "->", next_action({"stop_reason": r}))
In the lesson you can change this and run it.

Keep an explicit "unknown" branch. APIs add stop reasons over time; a loop that treats any unknown reason as "done" might silently drop work. Better to stop and log it.

Worked example

Two calls at the same time, results in order

The calls are independent, so run them at the same time with asyncio.gather. It returns outputs in the order the calls were given, so each result still matches its id.

import asyncio

async def get_stock(sku):
    await asyncio.sleep(0.2)
    return "14"

async def get_price(sku):
    await asyncio.sleep(0.2)
    return "89.0"

CALLS = [("t1", get_stock, "TENT-2"), ("t2", get_price, "TENT-2")]

async def run_calls(calls):
    outputs = await asyncio.gather(*(fn(arg) for _, fn, arg in calls))
    return [{"type": "tool_result", "tool_use_id": cid, "content": out}
            for (cid, _, _), out in zip(calls, outputs)]

import time
start = time.perf_counter()
results = asyncio.run(run_calls(CALLS))
took = round(time.perf_counter() - start, 1)
print([r["tool_use_id"] for r in results], took, "seconds")
In the lesson you can change this and run it.
Quick check
The loop has used its 40-turn budget and the model is still calling tools. What should it do?
  1. Keep going until the model stops by itself, however many turns that takes
  2. Raise an exception and throw the transcript away, since the run failed
  3. Stop and return a clear status, such as max_turns, with the transcript intact
  4. Delete the transcript and start the whole task again from the beginning
Show the answer

Stop and return a clear status, such as max_turns, with the transcript intact

A clear status lets the caller report it, or ask the person whether to continue, without losing any work.

Drill

Which budget ran out?

A loop should stop for a reason it can report. Write exhausted(turns, max_turns, tokens, max_tokens): return "turns" if the turn budget is used up, "tokens" if the token budget is, "both" if both are, or None if the loop may continue.

def exhausted(turns, max_turns, tokens, max_tokens):
    return None


print(exhausted(40, 40, 120_000, 200_000))
In the lesson, your code is checked as you write it.
Drill

One result for every call

Write results_for(reply, tools): for each tool_use block in reply, return a tool_result dict with the same tool_use_id. The content is str(tools[name](**input)). If the tool raises, the content is "Error: " + str(err) and the dict also has "is_error": True. Keep the order of the calls.

def results_for(reply, tools):
    return []


reply = [{"type": "tool_use", "id": "t1", "name": "div", "input": {"a": 6, "b": 3}}]
print(results_for(reply, {"div": lambda a, b: a / b}))
In the lesson, your code is checked as you write it.
In your own words
The loop hits its turn budget while the model is still calling tools. What should it do?

Write a sentence or two, then compare it with a good answer in the lesson.

In a production harness: the same loop on the real API

Trying it on the API

Here is the same shape against the real endpoint. Without an API key, the academy's practice server answers, in the real response format. It always uses the first tool, so it shows the loop's shape rather than real reasoning.

import requests

TOOLS = [{"name": "get_time", "description": "Current time in a city.",
          "input_schema": {"type": "object",
                           "properties": {"city": {"type": "string"}},
                           "required": ["city"]}}]

def call(messages, max_tokens=800):
    r = requests.post("https://api.anthropic.com/v1/messages",
        headers={"x-api-key": "added-by-the-academy-server",
                 "anthropic-version": "2026-10-21"},
        json={"model": "claude-opus-5-5", "max_tokens": max_tokens,
              "tools": TOOLS, "messages": messages},
        timeout=60)
    r.raise_for_status()
    return r.json()

messages = [{"role": "user", "content": "What time is it in Lisbon?"}]
for turn in range(4):
    reply = call(messages)
    messages.append({"role": "assistant", "content": reply["content"]})
    print(turn, reply["stop_reason"])
    if reply["stop_reason"] != "tool_use":
        break
    results = [{"type": "tool_result", "tool_use_id": b["id"], "content": "14:05"}
               for b in reply["content"] if b["type"] == "tool_use"]
    messages.append({"role": "user", "content": results})
from agentlab import show
show(messages)
print([b["text"] for b in reply["content"] if b["type"] == "text"][-1][:120])

In an engineer's week, this loop is where every incident about a stuck or looping agent ends up: a status that was never branched on, a retry with no cap, or a cut-off reply that ran. Read the stop reason first.

In your own words
A user says the agent "just stopped" halfway through a task. Which field of the last reply do you read first, and why?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 4 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 8 review cards for spaced repetition

Try a quiz question

A reply contains three tool_use blocks. How should their results go back?

  1. Three tool_result blocks, each with its tool_use_id, all in the next user message
  2. Three separate user messages, one for each result, in the same order as the tool_use blocks
  3. Only the first result, in the next user message; the model will ask again for the others
  4. As text in the system prompt, labeled with each tool's name, so that the model reads them first

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 10 · about 20 hours of study

Agent harnesses

Build the software around a model that turns it into a capable, safe agent 24 lessons 1 free
  1. What an agent harness is FreeThe software around a model that turns it into an agent.35 min
  2. The core loop, built properlyStop reasons, parallel tool calls, errors and turn budgets.40 min
  3. A tool registry for agentsSchemas from functions, validation, output limits and helpful errors.40 min
  4. File and search toolsRead, write, edit by exact replacement, glob and grep inside one folder.45 min
  5. Running code safelyExecution tools, step limits, output caps and real sandboxes.45 min
  6. Giving an agent a databaseSchema as context, a query tool with caps and readable errors, guards in layers, and execution accuracy.45 min
  7. Permissions and approvalsRules, modes and approval prompts that keep a person in control.40 min
  8. Hooks and skillsExtend a harness at lifecycle events, and load know-how on demand.40 min
  9. Multi-agent systemsCoordinating many agents on one large job.35 min
  10. Managing the context windowBudgets, clearing old tool results, compaction and a cacheable prefix.45 min
  11. Memory, plans and long tasksTo-do lists, progress notes, memory files and checkpoints.45 min
  12. SubagentsHand a focused task to a fresh context with fewer tools.40 min
  13. Streaming, interrupts and sessionsLive output, stopping safely, and saving and resuming transcripts.40 min
  14. Agents as graphsState, reducers and routing, a checkpoint after every step, and pausing for a person's approval.45 min
  15. Evaluation harnessesRun agents on tasks in fresh environments and grade what they leave behind.45 min
  16. Tracing, budgets and guardrailsSee what an agent did, cap what it spends, and stop it when it loops.40 min
  17. Attack your own harnessRun fourteen attacks against a harness with switches, read which layer stops each one, score attacks stopped against ordinary tasks done, and keep every finding as a release test.40 min
  18. Capstone: build a coding agentA harness that edits a project, runs its tests and stops when they pass.45 min
  19. The same agent on the real SDKsPut the parts you built beside the tool runner and the Agent SDK, choose a surface for a job, and take an MCP server's tools into your registry with prefixed names, one rule per server and a capped result.35 min
  20. Agents that use a computerAn agent with a screen, a mouse and a keyboard: the observe-decide-act loop, what a click lands on, why a wrong hit is worse than a miss, what happens when the screen changes under a plan, and what screenshots cost.45 min
  21. Sandboxes for agents that browseTreat every page as untrusted input: check hosts properly, gate actions by their effect, and layer the defenses.45 min
  22. Protocols between agentsHand a task to an agent someone else built: agent cards, the life of a task, the messages on the wire, safe retries, and whom to trust.45 min
  23. Tracing a run end to endFollow one run across an orchestrator, subagents and tool servers: trace ids, the traceparent header, the critical path, tokens by branch, and which traces to keep.45 min
  24. Retrieval over a graphAnswer questions that hop between documents: facts as triples, a walk out from the entities a question names, and the hubs and missed facts that limit it.45 min
Practice for interviews 21 questions

AI agent interview questions and answers

Questions on designing and running agents: tools, the agent loop, permissions, context, multi-agent systems, security and evaluation.

Part of a free course 29 lessons

Free AI agents course

Learn how to build AI agents by building one: tools, the agent loop, MCP, permissions, context management and evals, ending with a coding agent that stops when its tests pass.

Part of a free course 13 lessons

LLM Harness

Build a bounded run loop, test it with scripted model responses, and recover interrupted work from an event log.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write