The agent loop
The core cycle of model, tool call, result, repeat, and the controls that keep it from running away.
An agent is a loop: send the conversation and tools to the model, run any tool calls it requests, append the results, and call the model again until it answers without asking for a tool. Everything else, planning, memory and sub-agents, is built around that cycle.
Loops need explicit limits: a maximum number of steps, a token and cost budget, a wall-clock timeout, and a way to detect that the agent is repeating itself. Without them a confused agent will happily spend your budget going in circles.
Design for failure. Tool calls can time out or return garbage, so make tools idempotent where you can, feed errors back so the model can adapt, and checkpoint state so a long run can resume instead of restarting. Keep a human in the loop for actions that are hard to undo.
Key points
- The loop is simple. The guardrails around it are the engineering.
- Cap steps, tokens, cost and time, and detect repetition.
- Idempotent tools make retries and resumes safe.
- Require approval for irreversible actions.
Answer these out loud
- 1List four stop conditions for a research agent and what each protects against.
- 2An agent called the same failing tool 12 times. What in the loop should have prevented that?
Build it
Implement the loop in under 100 lines with two tools, a step cap, a cost budget and a repeated-call detector.
Use this from an agent
Any MCP client, including Grok, can read this lesson. See how to connect.
curl https://engineeros-delta.vercel.app/api/v1/topics/agent-loop