Single-agent tool loop
One model decides, one tool runs, the result comes back, and the model decides again until the job is done or a budget runs out.
Established: described the same way by several independent primary sources and in wide production use. Described independently by Anthropic (the agent as a model running tools in a loop with environment feedback), OpenAI (the single-agent run loop), the ReAct paper and 12-Factor Agents; in production in every coding agent on the market.
Input The test `parses dates with timezones` in parser.test.ts is failing. Fix it. The ordinary case: read, run, edit, re-run, answer. Six decisions, four tool calls.
Every step in words
The developer’s request is the first and only trusted instruction. It is written into the context window along with the project notes and the list of available tools.
The model cannot fix what it has not seen. Reading the test first is the cheapest way to learn what "failing" means here. This is a decision, so it is a model call.
A tool is ordinary code. It returns the file contents, which are appended to the context as data. The model has not run during this step.
Every turn, code outside the model compares steps, tokens and elapsed time against the limits. 1 of 12 steps used; the loop may continue.
The test file explains the expectation but not the current behaviour. Running the suite gives the actual failure message, which is better evidence than guessing from the source.
The test runner executes in a sandbox with a 60-second timeout and returns exit code 1 plus the log. The log is the evidence the next decision will use.
The log names the cause: the offset is parsed but not applied. The model proposes a diff. Because editing changes the world, the permission mode decides whether a human sees it first.
The loop is in a cautious permission mode: edits wait for a human. The developer reads the diff and approves it once. In a trusted mode this step would not appear.
The edit tool checks that the old text still matches, applies the replacement, and returns a confirmation. Deterministic; no model involved.
An edit is a hypothesis. The model re-runs the suite to turn it into evidence rather than declaring success.
Exit code 0. The loop now has proof, not a claim.
With passing tests in context, the model chooses to answer instead of calling another tool. That choice is what ends the loop.
The developer receives the summary, the diff and the test log. Five model calls, four tool calls, one approval.
The problem it solves
A task takes several steps and the order depends on what each step reveals: read this, run that, look at the result, decide what next. Scripting that order by hand means writing a new program per task.
- What the human needs
- A developer wants to hand over a bounded job, watch what the agent does, and step in when it heads the wrong way, without scripting the steps.
- What the agent does
- The agent reads the request and the tool results so far, chooses one tool to call (or decides it is finished), the tool runs as ordinary code, the result is appended to the context, and the cycle repeats.
- What the human sees
- The developer sees a streaming trace of tool calls, approves risky ones, and can interrupt at any step. The loop ends with an answer, a question back to the developer, or a budget stop.
After this page you can
- Tell the difference between the model deciding and a tool running.
- Explain why the loop needs a stop condition and a budget.
- Predict what happens when a tool fails and when a tool result contains instructions.
- Recognise the moments a developer can see and interrupt.
How it works
- The request and any standing context (project notes, tool list) enter the context window.
- The model reads the whole context and emits either a tool call or a final answer.
- If it is a tool call, the tool runs as deterministic code and returns a result (or an error).
- The result is appended to the context. Nothing is interpreted as instructions; it is data for the next decision.
- A budget check runs every turn: steps, tokens, time. If it is exhausted, the loop stops and asks the developer.
- The model decides again. When it answers instead of calling a tool, the loop ends.
The baseline scenario in the stage above plays these steps with a worked example. Open "Every step in words" under the stage for the full trace, including why each step happened.
When to use it
- The task needs several steps whose order depends on what each step reveals.
- Tools exist that can verify the work (tests, linters, a query that checks a result).
- A developer is present to supervise, or the tool set is read-only.
When not to
- One model call with the right context answers the question: a summary, a classification, a rewrite.
- The sequence is known in advance: write a workflow or plain code instead.
- The task needs hours of work or many parallel threads: a loop will overflow its context; see orchestrator–worker and the stateful graph.
Trade-offs
| Reliability | Verification by running tools is a real gain over a single call; the model can still loop or misread a result. | |
|---|---|---|
| Latency | Each decision is a model call; a five-decision task takes a minute, not a second. | |
| Cost | Five to ten model calls per task, with a growing context each time. | |
| Complexity | The simplest agentic architecture: one loop, one model, a tool list. | |
| Observability | The trace is linear and complete; every step is a decision or a tool result. | |
| Maintainability | Adding a capability means adding a tool, not a workflow. | |
| Security | Safe when tool results are data and dangerous tools are gated; unsafe the moment a send tool joins a read tool. | |
| Human control | The developer sees every step and can approve, interrupt or redirect. |
Three bars mean strong (or cheap); one bar means weak (or costly). Ratings are editorial and relative to the other patterns in this library, not measurements.
Security posture
Turn on Trust boundaries in the stage to see the zones on the diagram. The controls below sit on the nodes named; the "Break" scenarios show an attack and the control working.
| Control | Threat | Where |
|---|---|---|
| Tool results are dataThe runtime never promotes tool output to the instruction role; the system prompt names the developer as the only source of instructions. | Prompt injection through files, pages and API responses. | read · tests · context[simonwillison.net][Model Context Protocol] |
| Allowlisted commands and gated editsThe shell tool runs only allowlisted commands; edits outside the project directory are refused; in cautious mode edits wait for approval. | A compromised decision runs a destructive command. | tests · edit · developer[Anthropic] |
| Budget outside the modelSteps, tokens and seconds are counted in operator code and stop the loop. | A stuck loop burns cost indefinitely. | budget[HumanLayer (GitHub)] |
| No external sendThis loop has no tool that communicates outside the machine; one leg of the lethal trifecta is absent by design. | Exfiltration of private data read during the task. | agent[simonwillison.net] |
Failure scenarios
| Failure | Trigger and effect | Recovery |
|---|---|---|
| Tool timeoutscenario: tool-timeout | A tool hangs on a network call. Without a wrapper timeout the loop waits forever. | The wrapper kills the call and returns an error as data; the model retries with a different approach. |
| Instructions inside a tool resultscenario: injection | A file, web page or API response contains text addressed to the agent. The model may propose a harmful action. | Tool results are data; dangerous tools are allowlisted and gated; the trace shows the attempt. |
| Runaway loopscenario: budget-stop | The model repeats the same failing call. Cost and time grow with no progress. | The step budget stops the loop and hands the partial state to the developer. |
| Context overflow | Large tool outputs fill the window. Earlier decisions fall out of view; the model repeats work. | Compaction at a threshold, output size limits in tool wrappers, notes written to a file. |
Architecture and implementation
Inputs
requeststring- The developer’s task.
toolsToolSpec[]- Name, description, JSON-schema arguments and the wrapper that runs each tool with its own timeout and allowlist.
budget{ maxSteps, maxTokens, maxSeconds }- Limits enforced outside the model.
permissionMode'ask' | 'auto-edit' | 'trusted'- Which tool calls wait for a human.
Outputs
answerstring- The final message when the model chooses to answer.
traceStep[]- Every decision and tool result, in order, for the developer and for evals.
stopReason'answered' | 'asked' | 'budget' | 'interrupted'- Why the loop ended.
State schema
stepnumber- Turns taken so far; compared against the budget every turn.
tokensnumber- Approximate context size; compaction triggers above a threshold.
lastToolstring | null- The tool the model chose on the last turn, for the trace.
status'running' | 'awaiting approval' | 'tool error' | 'budget exhausted' | 'waiting for developer' | 'done'- Where the loop is, in words a human can read.
Framework-neutral pseudocode
context = [system_notes, request]
for step in 1..budget.maxSteps:
decision = model(context, tools) # one model call
if decision.kind == "answer":
return decision.text, trace
if decision.kind == "ask":
return ask_developer(decision.question)
if needs_approval(decision.tool, permissionMode):
if not developer_approves(decision): continue
result = run_tool(decision.tool, decision.args) # wrapper: timeout, allowlist, size cap
context.append(tool_result(result)) # data, not instructions
if tokens(context) > budget.maxTokens:
context = compact(context)
stop("budget", trace) In the frameworks
- Claude Code The reference single-agent loop: CLAUDE.md as standing context, permission modes for tool approval, autocompact near the context limit, subagents for verification. [Anthropic]
- OpenAI Agents SDK Runner.run executes the loop: model call, tool execution, repeat, until a final output or max_turns. [OpenAI]
- LangGraph The prebuilt ReAct agent is this loop as a two-node graph (model, tools) with a conditional edge; use it before writing a custom graph. [LangChain]
Testing
- Replay recorded tool results against the loop to assert the decision sequence stays stable for a fixed task.
- Inject a timeout, a refused command and an instruction-bearing file; assert the loop ends in the expected stopReason.
- Property: the loop never exceeds maxSteps or maxTokens, for any tool behaviour.
Evaluation
- Outcome grading: did the tests pass at the end? Score pass@k over several runs per task; pass^k when consistency matters.
- Read a sample of transcripts every week; count unnecessary tool calls and budget stops.
Deployment
- Run tools in a sandbox with a per-call timeout and an output size cap.
- Log every decision and tool result with the step number; the trace is the audit record.
- Default to the cautious permission mode; widen it per project, never globally.
Where it helps in software delivery
- 1 Discover and define useful here
A research loop over search and read tools is the simplest agentic research setup.
Example Summarising what five support tickets have in common, with every claim traced to a ticket.
- 4 Development and implementation central to this stage
Coding agents are this loop: read, run, edit, re-run. It is the unit every other development pattern is built from.
Example Fixing a failing test, implementing a small feature from a plan, running a migration script under supervision.
- 5 Testing and validation strong fit
A loop that can run the suite can also write a test, run it, and iterate until it exercises the case.
Example Generating a regression test for a reported bug and confirming it fails before the fix and passes after.
- 8 Operations and monitoring strong fit
Incident triage is a loop over read-only tools: logs, metrics, recent deploys. The budget and the read-only tool set keep it safe.
Example An on-call assistant that gathers evidence for an incident and proposes, but does not execute, a remediation.
- 9 Maintenance and evolution strong fit
Dependency and API upgrades are a loop over the same tools: bump the version, run the tests, read the failures, fix, re-run. The test suite is the stop condition.
Example Upgrading a library across a repository, with the loop stopping when the suite is green or the budget runs out and the developer takes over.
Open the SDLC explorer to start from a stage instead.
What the human sees
The interaction patterns a person meets when this architecture runs. The run waits for a person at: Developer.
References and provenance
-
An agent is a model using tools in a loop based on environmental feedback, with stopping conditions such as a maximum number of iterations.
evidence Building effective agents, Anthropic, Erik Schluntz and Barry Zhang, published 2024-12-19. Verified 2026-10-18.
-
Interleaving reasoning and acting with environment observations improves task success over reasoning alone.
evidence ReAct: Synergizing reasoning and acting in language models, arXiv, Shunyu Yao et al., published 2022-10-06. Verified 2026-10-18.
-
Standing context files, permission allowlists, test-first iteration and compaction are the practical controls around the loop.
framework Claude Code: best practices for agentic coding, Anthropic, published 2025-04-18. Verified 2026-10-18.
-
Own the control flow and the context window; keep errors compact in context; a budget outside the model.
practitioner 12-Factor Agents: principles for building reliable LLM applications, HumanLayer (GitHub), Dex Horthy, undated. Verified 2026-10-18.
-
Removing the external-communication capability from a loop that reads untrusted content removes the exfiltration path.
practitioner The lethal trifecta for AI agents: private data, untrusted content, and external communication, simonwillison.net, Simon Willison, published 2025-06-16. Verified 2026-10-18.
-
Single-agent systems should be exhausted before adding agents.
convention Building agents (developer learning track), OpenAI, undated. Verified 2026-10-18.
Published 2026-10-18 · observed 2026-10-18 · last verified 2026-10-18 · updated 2026-10-18 · v1 · review status: draft
Evidence kinds: evidence: evidence-backed recommendation from a primary source; convention: established industry convention; several sources agree; framework: how one framework implements it. version-specific; practitioner: a practitioner’s observation, not independently verified; emerging: an emerging technique with thin evidence; editorial: our interpretation.
Share: https://agentsandhumans.ai/agentic/patterns/single-agent-loop · the stage's Share button links to a scenario and step; Export downloads the trace as JSON, labelled as a learning simulation.
The Agents & Humans Briefing
How humans and agents work together: the day's field notes and the patterns behind them, in one short email around noon UTC.
Free. No spam. Unsubscribe anytime.