Education › Evals & Harness › Stage 3: Harness fundamentals

The agent loop and orchestration

Control flow, stopping conditions, retries, planning, sub-agents and parallel work.

Intermediate to advanced ~40 min read Module 12 of 20

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.

After this module you can
  • 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.

PatternHow it worksGood for
Prompt chainingFixed steps, each using the previous outputDraft, then check, then format
RoutingClassify input, send to a specialised handlerSupport triage by intent
ParallelisationIndependent calls at once, then combineReview a document for several issues
Orchestrator-workersA planner splits work and delegates to workersChanges across many files
Evaluator-optimizerOne call drafts, another critiques; loopWriting with clear quality criteria
Autonomous agentModel chooses tools in a loop until doneOpen-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.

A task-list tool the harness renders back into context
python
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.
Budgets and backoff around the model call
python
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.

taskbriefbriefbriefsummaryUserOrchestratorplans, delegatesWorker Aown contextWorker Bown contextWorker Cown contextCombineshort results
In the orchestrator-workers pattern, a planner splits a task into self-contained briefs, workers run with their own clean contexts, and only short results come back to be combined.
Tip

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.

Hands-on practice

Harden an agent loop

  1. Start with the minimal loop from the anatomy lesson and a scripted fake model that sometimes repeats calls.
  2. Add a Budget with steps, tokens and time, and a clean progress report when it is exhausted.
  3. Add loop detection for repeated identical calls and test it with the fake model.
  4. Add backoff for transient model errors and a timeout for every tool call.
  5. Add the todo_write tool and render the list into context each step.
  6. Run the same task as a fixed workflow and as an agent; compare success, steps and cost.
Cheat sheet

The agent loop and orchestration — at a glance

Main things to focus on

  • Use the simplest pattern that works; add autonomy when evals demand it.
  • Workflows: chaining, routing, parallelisation, orchestrator-workers, evaluator-optimizer.
  • Task lists improve focus and survive compaction.
  • Budgets, stop conditions, loop detection, backoff and timeouts.
  • Parallel reads, serial writes.
  • Human checkpoints where mistakes are expensive.

Patterns

chain: A -> B -> CFixed steps
route: classify -> handlerSpecialisation
parallel: fan out, combineIndependent work
orchestrator-workersDynamic delegation
evaluator-optimizerDraft and critique

Mechanics

max steps / tokens / seconds / costBudgets
same call repeated -> nudge, then stopLoop detection
backoff: 2^i + jitterTransient errors
timeout per toolNo hangs

Planning

todo_write(items)Explicit plan
one in_progress at a timeFocus
render list each stepVisible progress

Humans

approve planBefore execution
approve risky actionsDuring
interrupt and resumeCourse correction

Common pitfalls

  • An autonomous agent where a three-step workflow would do.
  • No budget, so a confused agent runs for hours.
  • Retrying non-idempotent writes after a timeout.
  • Multi-agent splits of tightly coupled work.
  • Approval prompts on everything, so users stop reading them.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →