The agent loop and harness
Building agents · topic building-agents/agent-loop
At its core an agent is a short loop: call the model, run any tool it asks for, feed back the result, repeat until done. This topic builds that loop from scratch, rebuilds it on an agent SDK to see what the SDK takes over, and covers stop conditions and the ways a loop runs away.
Concepts
- Loop from scratch
- Writing the agent loop yourself in a few dozen lines: send the conversation and tool definitions to the model, inspect the reply, run any requested tool, append the result, and call again until the model answers without a tool request. Building it once removes the mystery from every agent product and shows where the real difficulty lies: in tools, context and stopping. glossary
- Agent SDK
- A library that provides the loop, tool plumbing, context management, permission checks and often built-in tools, so a developer supplies instructions and tools and gets an agent. An SDK saves rebuilding solved parts and encodes hard-won defaults. The cost is that its choices about context, retries and stopping are now yours to understand rather than to write. glossary
- Stop conditions
- The rules that end a run: the model answers without requesting a tool, a maximum number of turns or tokens is reached, a budget is spent, a check passes, or a human stops it. An agent with only the first rule can run indefinitely. Good harnesses combine a natural completion signal with hard limits and report which one fired. glossary
- Unbounded-loop pitfalls
- The ways a loop keeps going wrongly: retrying a failing tool forever, alternating between two fixes, satisfying a check by weakening it, re-reading the same files as context fills, or spending the whole budget on exploration. Each burns money and can cause harm through side effects. Limits, detection of repeated states and visible progress reporting are the defenses. glossary
Links
- Builds on: Tool use
- Leads to: Evaluation and testing, Design patterns, Agentic retrieval and memory
- Competencies drawing on it: Builds a tool-using agent loop
Lessons
- Building your first agent (tutorial)
- Rebuilding the loop on an agent SDK (explanation)
- Stopping the loop on purpose (tutorial)
Your reference
Each lesson above adds its takeaways and its example here once you finish it. Your reference lists every lesson you have finished.
Building your first agent
Unlocks when you finish Building your first agent.
Takeaways
- A tool is a function plus a description written for the model.
- The loop is: ask the model, run the tool it asks for, append the result, repeat until it answers or the budget runs out.
- The model never runs anything; your loop does. That is where safety controls go.
Example
Predict the output · open in the lesson
What does this print?
print(TOOLS["get_weather"]["fn"]("Lisbon"))Prints: 27°C, sun (verified in CI from site/examples/building-agents/agent-loop/tool_call.py)
Rebuilding the loop on an agent SDK
Unlocks when you finish Rebuilding the loop on an agent SDK.
Takeaways
- An agent SDK runs the loop you wrote inside the library: messages, dispatch, retries, stopping and streaming each have a name in the reference, and the pairing is your map for debugging it.
max_turnsandmax_budget_usdare unset by default, and the run ends when the model stops asking for tools. Set both for a production agent and readsubtypebeforeresult.- Compaction replaces older history with a summary, so an evaluation records tool results from the message stream or a hook instead of reading them back from the conversation.
- Below the agent SDK are the client library's tool runner and the manual loop. Drop a layer when the layer above makes a decision you need to make yourself.
Example
Predict the stop line · open in the lesson
Suppose a model keeps asking for one more city until the turn limit ends the run. The program prints two lines, and the second is the ended: line from the except. Which line does the async for body print? This example doesn't run in CI, and you check it against the SDK's reference page yourself.
Prints: stop: error_max_turns
Stopping the loop on purpose
Unlocks when you finish Stopping the loop on purpose.
Takeaways
- A harness combines stop rules because each one misses something: the model's answer, a step limit, a token or cost budget, a passing check and a person's Ctrl-C.
- The API names its own stop reasons,
end_turn,tool_use,max_tokensandpause_turn, and your loop adds the ones only it can know. - A loop runs in circles by repeating a round or by alternating between two. A check that compares with the previous round ends the first, and one that compares with every earlier round ends both.
- Progress a person can see while the loop runs is a stop rule too, and the harness reports which rule ended every run.
Example
Predict which rule fires · open in the lesson
What does this print?
show(run("Summarize the notes.", model=model_never_answers))Prints the lines below (verified in CI from site/examples/building-agents/stopping-the-loop/never_answers.py)
user: 'Summarize the notes.'
round 1: read_file(path='notes/1.md') -> {'ok': True, 'text': 'contents of notes/1.md'}
round 2: read_file(path='notes/2.md') -> {'ok': True, 'text': 'contents of notes/2.md'}
round 3: read_file(path='notes/3.md') -> {'ok': True, 'text': 'contents of notes/3.md'}
round 4: read_file(path='notes/4.md') -> {'ok': True, 'text': 'contents of notes/4.md'}
stop: max_stepsSources
AEC-13Building your first agent: the loop from scratch, then with an SDK, Agent Engineer Course (course)Academy claude-platform-101Claude Platform 101, Claude Academy (course)Academy building-with-the-claude-apiBuilding with the Claude API, Claude Academy (course)