The basic agent loop (call the model, run the tools it asks for, repeat) is simple. Making it robust is not: model calls time out, tools hang, the agent repeats itself, tasks need planning, users interrupt, and some work is better split across several model calls in a fixed pattern than left to one open-ended agent. This lesson covers the spectrum from fixed workflows to autonomous agents, the common orchestration patterns, planning with task lists, parallel tool calls, budgets and stop conditions, retries, and human checkpoints.
- Choose between a fixed workflow and an autonomous agent for a task
- Apply chaining, routing, parallelisation, orchestrator-workers and evaluator-optimizer patterns
- Add planning with an explicit task list
- Implement budgets, stop conditions, retries and timeouts
- Design human checkpoints and interruption
Workflows versus agents
A workflow runs model calls in a sequence your code defines: classify, then retrieve, then draft, then check. An agent lets the model decide the next step in a loop. Workflows are more predictable, cheaper and easier to evaluate; agents handle open-ended tasks where the steps cannot be known in advance, such as debugging. Use the simplest pattern that solves the task and add autonomy only when the evals show you need it.
| Pattern | How it works | Good for |
|---|---|---|
| Prompt chaining | Fixed steps, each using the previous output | Draft, then check, then format |
| Routing | Classify input, send to a specialised handler | Support triage by intent |
| Parallelisation | Independent calls at once, then combine | Review a document for several issues |
| Orchestrator-workers | A planner splits work and delegates to workers | Changes across many files |
| Evaluator-optimizer | One call drafts, another critiques; loop | Writing with clear quality criteria |
| Autonomous agent | Model chooses tools in a loop until done | Open-ended, multi-step tasks |
Patterns also combine. A support system might route each ticket, run a fixed workflow for simple intents, and hand only the complicated ones to an autonomous agent with a tighter budget and an approval step.
Planning with a task list
For multi-step work, asking the agent to keep an explicit task list improves focus and gives the user visibility. Expose the list as a tool (write and update items with a status) and render it compactly in context on each step. The list also survives compaction, so a long task does not lose its plan, and it gives a simple progress signal for the interface.
TODOS: list[dict] = []
def todo_write(items: list[dict]) -> str:
"""items: [{"text": str, "status": "pending" | "in_progress" | "done"}]"""
if sum(i["status"] == "in_progress" for i in items) > 1:
return "Only one item may be in_progress at a time."
TODOS[:] = items
return render_todos()
def render_todos() -> str:
mark = {"pending": "[ ]", "in_progress": "[>]", "done": "[x]"}
return "\n".join(f"{mark[i['status']]} {i['text']}" for i in TODOS)Robust loop mechanics
- Budgets: maximum steps, tokens, wall-clock time and cost per task. On reaching one, stop cleanly and report progress rather than cutting off mid-action.
- Stop conditions: no tool call (final answer), an explicit finish tool, a budget, or a user interrupt.
- Loop detection: the same tool with the same arguments several times in a row, or no change in state across steps; inject a note asking the agent to try a different approach, then stop if it persists.
- Retries: retry model calls on rate limits and transient errors with exponential backoff and jitter; do not blindly retry non-idempotent tool calls.
- Timeouts: every tool call has one; a hung command returns a timeout result the model can react to.
- Parallel tool calls: run independent read-only calls concurrently; serialise writes.
import random
import time
class Budget:
def __init__(self, steps=40, tokens=400_000, seconds=900):
self.steps, self.tokens, self.deadline = steps, tokens, time.time() + seconds
def spend(self, tokens: int) -> str | None:
self.steps -= 1
self.tokens -= tokens
if self.steps < 0 or self.tokens < 0 or time.time() > self.deadline:
return "budget exhausted"
return None
def call_with_backoff(messages, tools, attempts=5):
for i in range(attempts):
try:
return call_llm(messages, tools=tools, timeout=120)
except TransientError:
time.sleep(min(60, 2 ** i) + random.random())
raise RuntimeError("model unavailable after retries")Multiple agents: when and how
Splitting work across several agents helps when subtasks are independent and context-heavy, such as researching several topics in parallel or exploring different parts of a codebase. The orchestrator gives each worker a clear, self-contained brief with the output format it needs back, and combines short results. It hurts when subtasks are tightly coupled, because workers cannot see each other's decisions and may produce conflicting changes. Multi-agent runs also multiply token cost, so measure whether the quality gain is worth it.
Write worker briefs as if for a contractor who has never seen the project: the goal, the relevant files or sources, what is out of scope, and the exact shape of the result to return.
Humans in the loop
Design checkpoints where a human reviews before the agent continues: approving a plan before execution, approving consequential actions, and reviewing the final result. Support interruption at any time, so a user can stop, correct the direction and resume without losing state. Stream progress (current step, task list, tool calls) so the human can intervene early. Checkpoints cost attention, so place them where mistakes are expensive or irreversible rather than everywhere.