Newsletter, guides
How a coding agent loop works: Think, act, observe
A coding agent is a loop around one model call. See the four states, a working Python loop, every stop_reason to handle and the rules that end it.
A coding agent is a while loop around one model call. Each turn, you send the model the conversation so far and a list of tools. If it answers with tool calls, your code runs them, appends the results to the conversation and calls the model again. If it answers with plain text, the loop ends. Claude Code, Cursor’s agent and Aider all run some version of this loop. The intelligence is in the model, the tools and the prompt. The loop itself is about 30 lines.
This guide shows the four states of that loop, a complete loop in Python against the Claude API, every stop reason you need to handle, and the rules that stop a loop that is going nowhere.
Key takeaways
- An agent is a loop: think, act, observe, repeat, until the model replies without a tool call.
- The model never runs anything. It returns a structured tool call, and your runtime decides whether and how to run it.
- Check
stop_reasonon every reply:tool_usemeans run the tools,end_turnmeans done, and the others need their own handling. - Return a
tool_resultfor everytool_useblock, including failures, or the next request is rejected. - Every loop needs a step budget and a repeat check, so a stuck agent stops early instead of burning tokens.
- Modern agents are ReAct with structured tool calls instead of parsed
Thought:andAction:text.
Why can’t a chatbot fix a failing test?
Because a chatbot makes one model call and stops. It can tell you what the fix might be. It cannot open auth.py, run the test, read the failure and try again.
Fixing a test takes several actions in a row, and each one depends on the result of the last. Read the file. Run the test. See the error. Edit. Run again. The thing that makes that possible is a loop: after each action, the result goes back into the conversation and the model thinks again with it in view.
The model does not change between turns. The runtime around it does the work of running tools and carrying results forward. That runtime is the agent.
What are the four states of an agent loop?
Think, act, observe and done. Everything else, such as planning steps, sub-agents and reflection prompts, is a way of arranging these four.
- Think. The model gets the full message history and the tool list. It replies with text, tool calls, or both.
- Act. For each tool call, the runtime checks it, runs it, and captures the output or the error. This is where
read_file,edit_fileor a bash command actually happens. - Observe. Each result goes back into the conversation as a
tool_resultblock, linked to its call by id. - Done. The model replies with no tool calls, and the loop returns its answer.
When you watch Claude Code scroll past in a terminal, you are watching these states in order: it reads, edits, runs the tests, reads the output, and goes again.
What does a minimal coding agent loop look like in Python?
Here is a complete loop with the Anthropic Python SDK. It has two tools, a step budget and a check on every stop reason that matters.
# filename: mini_agent.py
# description: A coding agent loop: think, act, observe, until done or out of steps.
import subprocess
from pathlib import Path
from anthropic import Anthropic
client = Anthropic()
MODEL = 'claude-opus-5-5' # any current Claude model with tool use
MAX_STEPS = 25
WORKSPACE = Path('.').resolve()
TOOLS = [
{
'name': 'read_file',
'description': 'Read a text file in the repository and return its contents.',
'input_schema': {
'type': 'object',
'properties': {'path': {'type': 'string'}},
'required': ['path'],
},
},
{
'name': 'run_tests',
'description': 'Run the test suite with pytest and return the last 4000 characters of output.',
'input_schema': {'type': 'object', 'properties': {}},
},
]
def run_tool(name: str, args: dict) -> str:
if name == 'read_file':
path = (WORKSPACE / args['path']).resolve()
if not path.is_relative_to(WORKSPACE):
raise ValueError('path is outside the repository')
return path.read_text()[:20_000]
if name == 'run_tests':
run = subprocess.run(['pytest', '-q'], capture_output=True, text=True, timeout=300)
return (run.stdout + run.stderr)[-4000:]
raise ValueError(f'unknown tool: {name}')
def run_agent(task: str) -> str:
messages = [{'role': 'user', 'content': task}]
for _ in range(MAX_STEPS):
reply = client.messages.create(
model=MODEL, max_tokens=4096, tools=TOOLS, messages=messages
) # Think
messages.append({'role': 'assistant', 'content': reply.content})
if reply.stop_reason != 'tool_use': # Done, or something to handle
return '\n'.join(b.text for b in reply.content if b.type == 'text')
results = []
for block in reply.content:
if block.type != 'tool_use':
continue
try:
output, failed = run_tool(block.name, block.input), False # Act
except Exception as e:
output, failed = f'error: {e}', True
results.append({
'type': 'tool_result',
'tool_use_id': block.id,
'content': output,
'is_error': failed,
})
messages.append({'role': 'user', 'content': results}) # Observe
return f'Stopped after {MAX_STEPS} steps without finishing.'
Three details are easy to get wrong. The assistant’s reply goes into the history before the results, unchanged. Every tool_use block gets a tool_result with the same id, even when the tool failed, and is_error tells the model it failed. And the user message that carries the results holds only tool_result blocks.
Add more tools and this becomes a real coding agent. Give it a shell with the layers in the bash tool guide and a code search tool like the one in the ripgrep guide. If you would rather not write the round trip yourself, the Anthropic SDKs include a tool runner that runs your tools and sends results back for you.
Which stop reasons does the loop need to handle?
The loop above treats anything other than tool_use as the end. That is fine to start with, but Anthropic documents seven stop reasons, and a production loop should handle each one on purpose.
stop_reason |
What it means | What the loop should do |
|---|---|---|
tool_use |
The model is calling one or more tools. | Run them and send back a tool_result for each. |
end_turn |
The model finished its answer. | Return the answer. |
max_tokens |
The reply hit your max_tokens limit. |
Raise the limit or continue. Retry a cut-off tool call. |
pause_turn |
A server tool loop hit its iteration limit. | Send the content back as it is, so the model continues. |
stop_sequence |
The model emitted one of your stop sequences. | Check which one, then act on it. |
refusal |
The model declined to respond. | Read stop_details, then stop or use a fallback. |
model_context_window_exceeded |
The reply filled the context window. | Treat it as cut off. Trim history or summarize. |
The trap is max_tokens. If the reply was cut off in the middle of a tool call, the call is incomplete. Running it, or ending the loop as if the agent were done, both give you wrong results. Retry with a higher limit.
How does a coding agent know when to stop?
The happy path is the model replying without a tool call. But you cannot rely on that alone. A model that is stuck will keep calling tools. Give every loop three exits:
- The model is done.
stop_reasonisend_turn. Return its answer. - The budget ran out. The loop has run
MAX_STEPStimes. Stop and say so. Pick the budget from the task: small for a single fix, larger for a long coding session. - The agent is repeating itself. It made the same tool call with the same input as the step before. Stop, or tell it in the next message that it is going in circles.
# filename: repeat_check.py
# description: Stop when the agent makes the same tool calls twice in a row.
import json
last_calls = None
# inside the loop, after a tool_use reply:
calls = [(b.name, json.dumps(b.input, sort_keys=True)) for b in reply.content if b.type == 'tool_use']
if calls == last_calls:
return 'Stopped: the agent repeated the same tool calls.'
last_calls = calls
Compare the calls, not only the results. Running the tests twice in a row after an edit is normal and gives different output. Reading the same file twice with nothing in between is a sign of a stuck agent. These checks are what separate a demo from an agent you can leave running.
How do Claude Code and other coding agents build on this loop?
They keep the same loop and add three things around it. A small agent such as pi shows the loop with few extras: see the practitioner guide to pi for code review, docs and triage.
First, a bigger tool set. Claude Code’s tools include reading, editing and writing files, running bash, and searching with Glob and Grep. Each tool is a function in the runtime and a schema the model sees. The loop does not change. It just has more tools to dispatch to.
Second, a long system prompt. It teaches the model how to work: read before editing, run the tests after a change, ask the user when a task is unclear. None of that is in the loop code. It is in the first message.
Third, permission checks in the act step. Before a tool runs, the runtime decides whether it is allowed, needs the user’s approval, or is blocked. In Claude Code you set these with permission rules. The model can ask for anything. The runtime decides what runs.
How is a coding agent different from a ReAct agent?
It is the same loop with a sturdier way of passing actions. The ReAct paper (Yao and others, 2022) had the model write Thought:, Action: and Observation: lines as plain text, and the runtime parsed the action out with string matching. One stray format change and the parser broke.
Today’s coding agents use the model’s tool-calling API instead. The model returns a structured tool_use block with a name, an id and JSON input. The runtime sends back a structured tool_result. Nothing is parsed from prose.
Coding agents also run much longer loops than the original ReAct tasks and add planning, sub-agents and context management. Remove those and you are back to think, act, observe. For how a tool call travels between your code and the model, see the tool calling guide.
What to do next
- Copy
mini_agent.py, point it at a small repository with one failing test, and print every message so you can watch the history grow. - Add an
edit_filetool and watch the agent read, edit and rerun the tests on its own. - Handle
max_tokensandrefusalexplicitly instead of treating them as done. - Add the repeat check, then give the agent an impossible task and confirm it stops instead of spinning.
- Open the source of an open-source agent such as Aider and find its loop. It is shorter than you expect.
- Watch the full loop, tools and permission checks built live in the free autonomous Claude Code agent session.
Frequently asked questions
What is an agent loop?
An agent loop is the cycle that turns one model call into a multi-step task. The model replies, the runtime runs any tool calls in that reply, appends the results to the conversation, and calls the model again. The loop ends when the model replies without a tool call, or when a step budget or repeat check stops it.
How does Claude Code work under the hood?
Claude Code runs an agent loop around Claude with a set of tools for reading, editing and writing files, running bash commands, and searching code with Glob and Grep. A system prompt teaches it how to work, and permission rules decide which tool calls run, need approval, or are blocked. The loop itself is simple. The tools, prompt and permissions do the heavy lifting.
What does stop_reason tool_use mean?
It means the model wants your application to run one or more tools. The reply contains tool_use blocks, each with a name, an id and input. Run each one and send back a user message with a tool_result block for every call, using the same id. If a tool fails, still return a result and set is_error to true.
How do AI coding agents avoid infinite loops?
They use several exits. The model ending its turn without a tool call is the normal one. A maximum step count stops a run that goes on too long. A repeat check stops an agent that makes the same tool call with the same input twice in a row. Without these, a stuck agent keeps calling tools until a timeout or your budget stops it.
Is a ReAct agent the same as a coding agent?
They share the same loop of thinking, acting and observing. ReAct had the model write its actions as text that the runtime parsed. Coding agents use structured tool calls from the model’s API, which are far more reliable. Coding agents also run longer loops and add planning, sub-agents and permission checks on top.
Sources
- Handling stop reasons, Anthropic, October 2026: the seven
stop_reasonvalues and how a loop should respond to each. - Tool use with Claude, Anthropic, October 2026: the client tool round trip with
tool_useandtool_result, and the SDK tool runner. - Tools reference, Anthropic Claude Code docs, October 2026: Claude Code’s built-in tools and permission rules.
- ReAct: Synergizing Reasoning and Acting in Language Models, Yao et al., arXiv, October 2022: the original think, act, observe loop written as parsed text.
Build what you just read, with Param, live
You read the guide
- Free Live LabBuild a Second Brain with Claude CodeA second brain over your notes, docs and Linear that answers with sources and serves the same memory to any agent over MCP.Free seat
- ProWatch the video coursesDesign a Software Factory for Your Coding Agents, Build Your First Software Factory Execution Harness and each new course as the sessions are cut. The first lesson of each is free after you sign in.$149 a year
- WorkshopAI Agents in Production for EngineersA multi-agent system deployed with an identity per agent, permissions, guardrails, an LLM gateway, traces and evals, plus a checklist for your own agents.$497
- BuildcampAgentic AI Buildcamp for Engineers & PMsDesign, build and deploy a production agentic AI system in four weeks$997
Or watch the recording: Build an Autonomous Claude Code Agent
