Skip to content

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

Lessons

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.

Rebuilding the loop on an agent SDK

Unlocks when you finish Rebuilding the loop on an agent SDK.

Stopping the loop on purpose

Unlocks when you finish Stopping the loop on purpose.

Sources