Harness evolution: from chains to graphs to code
A harness is the structure your code puts around an unpredictable model. It has moved from simple chains of prompts to explicit graphs, and then to generated code that runs and checks itself. Each step buys stronger guarantees at a higher cost.
Harness evolution in 60 seconds
- What: a harness is the structured execution framework that surrounds a probabilistic model and keeps its output usable.
- Three stages: chains (linear steps), graphs (explicit branching workflows) and code (the model writes programs that are run and tested).
- What changes: control flow moves from implied, to declared, to verified by execution.
- Choose by need: use the least complex harness that does the job. Chains are cheapest, code gives the strongest guarantees and costs the most.
- Role shift: the developer moves from writing prompts to designing the system around them.
The problem it solves
A model on its own gives a different answer each time and can say wrong things with confidence. Putting it into a product means wrapping it: deciding what it sees, what it may call, how its output is checked and what happens when a check fails. That wrapper is the harness.
Early harnesses were a few prompts in a row. That worked for demos and broke on real traffic. Each later stage solved a limit of the one before.
Stage one: chains
A chain is a fixed sequence of prompt steps. Each step takes the output of the one before. Many early production assistants followed this shape with three steps. Routing decided whether a request was in scope and which expert should handle it. Retrieval gathered material from web search and internal interfaces, and assembled a dossier so that generation could stay grounded. Generation then filtered and combined that material into the reply.
Chains are quick to build and easy to read. The weakness is that errors propagate. If routing picks the wrong expert, retrieval fetches the wrong material and generation writes a fluent answer from it. There is no branch to catch the problem, because the flow has no branches.
The first 80 percent of quality arrived fast. Closing the last gap took heavy evaluation and repeated prompt changes.
Stage two: graphs
A graph makes the control flow explicit. Each node is a task, such as a model call, a tool call or a validation. Each edge says what happens next, and edges can express branching, conditions, parallel work and retries. Because the flow is declared, you can test one branch without touching the others. See state graph for the pattern in detail.
Graphs led naturally to multi-agent designs. A top-level supervisor receives the request and hands parts of it to specialist agents. Agents talk to each other through agreed protocols, and one such agent-to-agent protocol absorbed an earlier competing one. Humans join the graph as nodes too, for clarification or approval, which is the idea behind a human checkpoint. The supervisor with workers page describes the top node.
A useful trick is to reuse infrastructure you already run. A messaging or event system that delivers in order and keeps history makes a good orchestration layer: threads give you parallel work, persistent redelivery gives you retries, and the same channel can return one reply or a stream. Memory can even be modelled as one more agent that others ask questions of.
- Conditional execution: take a branch only when a stated condition holds.
- Retries and fallbacks: repeat a failed node, or switch to an alternative node.
- Structured state: pass typed data between nodes, not loose text.
- Explicit validation: check results against schemas, business rules, or a second model before moving on.
The limit of graphs is that humans still define them. Every unusual case needs a new branch, and as the edge cases pile up the graph turns brittle and hard to reason about. That pressure pushed teams towards the third stage.
Stage three: code as the medium
In a code harness, the model reasons by writing a program. The loop is: generate code, run it in a sandbox, look at the result, refine. Code has a property that prose lacks. It either runs and passes its checks, or it does not, and that outcome is a deterministic signal the harness can act on.
- Execution sandbox: a locked-down environment with limited files, network, time and memory, where generated code can run safely.
- Instrumentation and logging: every run records the code, inputs, outputs and errors, so results can be audited and repeated.
- Validation harness: automated checks on the result, covering correctness, policy and data rules.
- Iterative refinement loop: failures feed back to the model with the error, up to a fixed number of rounds.
An internal analytics agent shows the idea. A user asks a business question. The agent writes a query and a small analysis script, runs them on sample data, and then checks the output against privacy, visibility and governance rules. If a check fails, for example because a column is restricted for that user, the failure goes back to the model, which rewrites the code. The reported benefits were faster delivery, more reliable answers, and results that can be audited and reproduced.
A worked example
Acme Bank wants an assistant that answers analysts' questions about card spending, such as "How many card transactions over 500 pounds did customers in the north region make last month?" Here is how each harness would handle it.
- Chain: route the question, retrieve a table description, and ask the model to write the answer. It is fast, but the model estimates the count from a few rows and may give a confident wrong number.
- Graph: route to a data agent, validate the question against allowed tables, run a fixed query template with the region and amount as parameters, then check that the result is a single integer. It is safer, but it only handles question shapes someone drew a branch for.
- Code: the model writes a query, the sandbox runs it on a sample of 10,000 rows, the validator confirms that no restricted columns were read and that the row count is plausible, and any failure is sent back for a rewrite. Up to three rounds are allowed.
- Outcome: the code harness handles a new question, such as the same count split by week, without any new branch. Its cost is more model calls and a sandbox to maintain.
Practices that apply to every stage
- Treat model output as untrusted input. Parse it, validate it and limit what it can trigger, as you would for text typed by an anonymous user.
- Decouple planning from execution. Let the model propose a plan, and let ordinary code run it under permission checks and limits.
- Invest in observability. Record the state at each step, traces, validation results and timings, and mask sensitive data. See failure modes.
- Build for continuous improvement. Use feedback loops, evolving prompts and policies, procedural memory for what has worked, and simulation or offline evaluation before release.
Choosing a harness
Use the least complex option that meets the need, since complexity costs code, tests, latency and on-call effort. Aim for capability per unit of cost.
- Chains: drafting, summaries, moderation and data extraction. They are the cheapest, and mistakes are usually easy to spot and cheap to fix.
- Graphs: multi-step service resolution, IT automation, compliance pipelines and onboarding flows, where the steps are known but conditions vary.
- Code: software engineering, financial analysis, legal validation, science and infrastructure automation, where results must be checked and repeated. This is the costliest and has the strongest guarantees.
The developer's job shifts too, from writing prompts to designing a system of states, validations, limits and feedback loops.
Building it
MAX_ROUNDS = 3 # refinement rounds per question
SANDBOX_TIMEOUT_S = 20 # wall-clock limit for one run
SANDBOX_MEMORY_MB = 512 # memory limit for one run
MAX_ROWS_OUT = 1_000 # cap on rows returned to the user
def answer(question: str, user, log):
feedback = None
for round_no in range(1, MAX_ROUNDS + 1):
# Placeholder: the model returns code as text, never executed directly here.
code = llm.write_code(question, allowed_tables=tables_for(user),
previous_error=feedback)
# Run in an isolated sandbox with no network and read-only sample data.
run = sandbox.execute(code, timeout_s=SANDBOX_TIMEOUT_S,
memory_mb=SANDBOX_MEMORY_MB, network=False)
log.record(round=round_no, code=code, status=run.status, error=run.error)
if run.status not in ("ok",):
feedback = run.error # send the failure back to the model
continue
# Deterministic checks on the output, not another opinion from the model.
problems = validate(run.output, user,
forbidden_columns=restricted_columns(user),
max_rows=MAX_ROWS_OUT)
if not problems:
return run.output
feedback = "; ".join(problems)
# Out of rounds: say so plainly instead of guessing.
return {"status": "unanswered", "reason": feedback}
llm, sandbox, validate and the helper functions are placeholders. The generated code is never trusted: it only runs inside the sandbox, and a rule-based check decides whether the result is released.
Design decisions
- Entry rung: start with the simplest harness that passes your evaluation set. Move up only when a measured failure cannot be fixed at the current level.
- Mix by route: put a router in front and send each request type to its own harness, rather than forcing one design on all traffic.
- State contract: define the structured state that flows between nodes or rounds, with types and required fields, so validation has something firm to check.
- Validation source: prefer deterministic checks such as schemas, rules and test runs. Use a second model as a check only where rules cannot express the requirement.
- Sandbox policy: decide the file, network, time and memory limits per use case, and who may change them.
- Loop limits: cap rounds, retries and total spend in every harness, and define the plain fallback when limits are hit.
- Human placement: add approval nodes where a wrong action is costly.
Measuring it
- Task success rate by stage: run the same labelled questions through a chain, a graph and a code harness, and compare correctness.
- Error propagation: how often a wrong early step produces a wrong final answer. It should fall as validation is added.
- Validation pass rate: the share of first attempts that pass checks, and the mean rounds needed to pass.
- Coverage of new cases: the share of unseen question shapes handled without a code or graph change.
- Cost and latency per request: tokens, sandbox time and total time, at the mean and 95th percentile.
- Escalation rate: how often a request ends in a fallback or a human.
When to use it, and when not to
| Situation | Harness | Why |
|---|---|---|
| Drafting, summarising, moderation or extraction | Chain | Steps are known and errors are cheap. A pipeline is enough. |
| Known steps with conditions, approvals and retries | Graph | Explicit branches make behaviour readable and testable. See state graph. |
| Open questions where answers must be computed and checked | Code | Execution gives a pass or fail signal that prose cannot. See coding agent. |
| Mixed traffic with different needs | Several, behind a router | Each request type gets the cheapest harness that is safe for it. |
| A task with no checks you can write | Not code | Without a validator, the loop has no signal. Use a graph with human review. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | Graphs add validation and code adds execution checks, so errors are caught earlier. | Measure each stage on the same test set before choosing. |
| Latency | Each node or refinement round adds a call. Code harnesses also wait on the sandbox. | Cap rounds, run independent nodes in parallel, and cache stable results. |
| Cost | Costs rise from chains to graphs to code, in model calls and in infrastructure. | Route simple requests to chains and keep code harnesses for the cases that need them. |
Compared with related ideas
The three stages are about who fixes the path. In a chain, the author fixes it as a line. In a graph, the author fixes it as a map, with room for conditions. In a code harness, the model proposes a program each time and the harness only fixes the rules for accepting it. See the orchestration hub.
Context engineering decides what the model sees. The harness decides what happens to what it says.
What this means for your role
Common mistakes
Further reading
- Agentic AI architecture: an overview: the hub page for this section.
- Agentic failure modes: what goes wrong inside a harness and how to contain it.
- Orchestration patterns: chains, routers, supervisors and graphs side by side.
- State graph: the graph pattern in more depth.
- Coding agent: an agent that works by writing and running code.
A harness is there to make an unpredictable model dependable. Pick the simplest one that meets your bar, validate with rules where you can, and move up a stage only when the evidence says you must.