Building an Agent Graph: Where to Cut
updated 24 min
Confidence the build is real and the seams are lived; the placement policy is my call rather than a measured optimum
“A complex system that works is invariably found to have evolved from a simple system that worked.” — John Gall, Systemantics (1975)
Part one of three. From Rules to Runs covers what happens once the graph has boundaries; How You Know covers whether any of it works. Sections are numbered continuously across all three.
A how-to for engineers who have decided to build a multi-stage agent system and want to know what the parts are, how they connect, and which decisions are expensive to undo. Written from one rebuild of a production code reviewer, with the measurements that survived and the ones that didn’t.
This is not a think-piece about the future of engineering. If a paragraph here doesn’t change what you type, it failed and you should skip it.
Bottom line up front
- Write one prompt that does the whole job first. It will be mediocre. That is the point: it is the baseline every later split gets measured against, and the last version that is cheap to change.
- Fix the input and output contract second, not first. It is the only decision in the series that is expensive to undo — which is exactly why you make it after one throwaway run has shown you both ends.
- Grow the knowledge before you grow the graph. Adding structure feels like engineering and adding knowledge feels like typing. The knowledge is where the early gains are.
- Split when a stage is doing two things with different error costs, not when a diagram says so. That one tell subsumes the three seams.
- Extracting a node is extracting a function, minus the guarantee. Refactoring preserves observable behaviour by definition; a split does not, so you check it against the baseline instead of against a test.
- Typed JSON between every stage, and name the failure kinds. You cannot
count “bad JSON”, and a single
catcherases the difference between a stage that is broken and a prompt that is.
Who this is for
You have a task an LLM can nearly do. You’ve noticed that one prompt isn’t holding it. You’re about to draw a diagram with boxes and arrows.
Don’t draw the diagram yet. Read §1.
Where a section rests on an argument I’ve made at length elsewhere, I link the post instead of re-arguing it. The posts carry the argument; this carries the build.
One thing to know before you read 50 minutes of hand-rolling: DSPy already exists. Its three primitives — signatures, modules, optimizers — are a typed contract per stage, composable units behind those contracts, and a compiler that tunes the prompts for you. That is the shape this whole guide arrives at the long way round, and if you are starting from scratch you should look at it before writing any of this yourself. Generic DAG runners (Dagster, Prefect, Airflow) and durable execution engines (Temporal, Restate, DBOS) cover the executing half on the same terms.
Use them. This guide is about the decisions a framework leaves to you: where the seams actually fall, what crosses a stage boundary and what must not, which measurements turned out to be wrong and how, and what came back null. Those questions survive whatever you build on.
The short version
Part one — Where to Cut (you are here)
- Write one prompt that does the whole job — end to end, and it should be mediocre; it is the baseline every later split is measured against.
- Then fix the input and the output — six fields for this reviewer, and the only decision in the series that is expensive to undo.
- Grow the knowledge before you grow the graph — adding structure feels like engineering and adding knowledge feels like typing; the knowledge is where the early gains are.
- Where to cut — extracting nodes — it is extracting a function, right up to the point where it is not: a split has no behaviour-preservation guarantee.
- Schemas are the wire format — typed JSON between every stage, why JSON rather than YAML, and a named failure ladder because you cannot count bad JSON.
- What to put in a schema so the stage is testable — put fields in that nothing downstream consumes; you will not add the instrument later.
Part two — From Rules to Runs, sections 7 to 10. One source of truth and the compiler that isn’t there; mechanising, and what it silently drops; the runner; and why a demo is an example of the rule’s edge rather than of the rule.
Part three — How You Know, sections 11 to 16. Evals, corpus and holdouts; determinism as architecture; measuring the instrument before you trust the measurement; and the three operating sections on improving it, staying in the loop, and keeping the record.
Before any of it: Tune the Prompt Before You Split It. Do not split a prompt you have not finished tuning.
1. Write one prompt that does the whole job
This section is deliberately anticlimactic. You do not start with a graph.
Write a single prompt that takes the input to the output. Not a scaffold, not a plan, not two stages with a hand-off. One prompt, and it will be mediocre.
Tuning that prompt — running it on real work, deciding what you are optimising for, and measuring whether an edit helped — is a whole job of its own, and it is the one that pays before any of this does. It has its own how-to: Tune the Prompt Before You Split It. Come back here when an edit that fixes one case starts breaking another.
That is the point, and it buys three things. It is the baseline every later split gets measured against, so you can tell whether a split helped. It is the last version of the system that is cheap to change. And it is the fastest way to find out what the job actually needs, which is the next section — you learn more about the right input and output from one bad end-to-end run than from an afternoon of designing the contract on paper.
2. Then fix the input and the output
What arrives, and what has to come out in a form something downstream can actually consume. Concretely, for the reviewer this guide is drawn from:
in base..head, plus the repo it lands in
out [ { file, line, severity, issueCode, description, fix } ]
Six fields. That is the whole contract, and almost every decision in the rest of this guide is downstream of it.
Notice what is not in the output. No prose summary of the review — nothing consumes one, and the moment you add it some stage starts writing for a human instead of for the next program. No confidence score, because nothing downstream was going to threshold on it honestly. No reasoning: the stage that decided is not the stage that explains, and keeping the explanation out of the wire is what later lets the expensive judge stop writing prose altogether.
And notice line. That single field is why every stage downstream has to
carry a citation rather than a description — a finding that cannot name a line
cannot be checked, rendered, deduplicated or counted. The two-field object the
first stage hands the second — a rule id and a citation, not its reasoning
and not the file it just read — exists because of that one output field. See
A Pipeline Is What It Refuses to Forward.
This is the first real commitment, and it is the only decision on this page that is expensive to undo.
Everything after it is an implementation detail of this contract. That is why it comes second rather than first: write the throwaway prompt, see what the job drags in and what the caller actually needs back, and then fix the contract knowing both. Designing it before you have run anything once means guessing at both ends.
3. Grow the knowledge before you grow the graph
The first real improvement is content, not structure: more, and more specific, instruction about what you’re actually looking for. Keep going until the prompt stops absorbing it.
Most people skip this step because adding structure feels like engineering and adding knowledge feels like typing. The knowledge is where the early gains are — see Rules Are the Alpha.
Split when a stage stops fitting, not when a diagram says so. The signals are concrete: the prompt gets too long for the context you can afford; two halves want different models; a regression appears and you can’t tell which half caused it. Split the smallest piece that relieves the specific pain.
Mechanise what has gone mechanical, then keep going — more splits, more passes, cheaper models at the wide end.
The receipt: the sequence this system actually took
It started as one prompt carrying the rules. The rules grew their own extended detail files. The single pass split into a cheap, wide scout that notices and an expensive, narrow deep that judges. The parts that had become mechanical moved out into deterministic detectors. Then more splits — a cheap triage between scout and deep, a separate writer for the reader-facing prose — and more passes alongside the first.
Nobody drew the current topology at the start. Each of the later edges exists because a specific thing stopped working. The earliest ones — the first prompt, the original scout/deep split — predate the record, and I didn’t do the archaeology to reconstruct why they landed where they did.
Why the splitting is worth it
Stated once here so it doesn’t need arguing again: you cannot tune what you cannot address.
A monolith gives you exactly one dial — the whole pipeline. When something degrades you A/B the universe and learn nothing, because your effect size is smaller than your noise floor. On this system the whole-pipeline noise floor was 45% between two draws of one PR at one SHA (§11). That is larger than nearly every lever anyone wanted to test. Every split paid off not because it was cheaper but because it created a surface you could name, swap, bias and measure.
The warning that goes with it
Don’t build the sixteen-section version on day one. That buys you all of the coordination cost and none of the knowledge that justified each seam. The graph in §4 is where this ended up, not where to begin.
Related: The Harness Is the Product, Build the Operator, Keep the Factory, Ship the Result.
A lever this guide doesn’t have
While your system is still one prompt, prompt ordering is a lever you might reach for — the widely-repeated advice is that critical constraints belong in the opening fraction of the prompt. Lost-in-the-middle is real in the literature. The specific fraction people quote is invented, and I have no measurement of my own either way. We never pulled this lever and I’m not recommending it. I mention it only so you don’t read its absence from the rest of this guide as a verdict.
4. Where to cut — extracting nodes
Three seams are worth cutting on, and one tell is worth more than all three.
Cut where the stance changes. Noticing, verifying and writing are different jobs. A stage that notices should be wide, cheap and permissive. A stage that verifies should be narrow, expensive and skeptical. Asking one model to do both in one pass means picking one error budget for two jobs that need different ones. See Noticing Is Cheap.
Cut where the model tier can change. If half the work is mechanical adjudication and half is judgment, the mechanical half runs on a small model at a fraction of the cost. That’s only available to you if it’s a separate call.
Cut where the output type changes. Turning a confirmed finding into reader-facing prose is a different task from deciding whether the finding is real. Splitting them let the expensive judge stop writing prose entirely and emit a verdict, a citation and a one-line fix intent, with a cheap writer decompressing that into the comment afterwards.
What can actually go in a node
A node is an interface, not a model call. Four things fill it, and they differ on cost, latency, determinism and whether you can train them:
| determinism | cost | needs | finds | |
|---|---|---|---|---|
| Agent with a prompt | none | highest | nothing | anything you can describe |
| Mechanised program | total | ~free per run | a spec you can write | only what you wrote |
| Encoder classifier | total at temp 0 | very low | labelled data | its label set |
| Typed-decision model | bounded | low, with caveats | a question schema | its option list |
The first two are the ones the rest of this guide spends its time on. The other two are worth knowing because they occupy the gap between them.
Encoder classifiers — ModernBERT-class models rather than generative ones — are the obvious fit for a node that answers the same bounded question thousands of times: is this lead worth escalating, which pass owns this, is this comment a what-comment. They are small, fast, and trainable on your own labels. The usual blocker is having labels at all, and a graph like this one mints them as a byproduct: every refuted lead is a labelled negative at the decision boundary, which is Train on What the Gate Throws Away.
Typed-decision models — Jev is the prominent example — take typed questions and return bounded decisions, which is the right shape for a triage node. I would describe the shape rather than endorse a product: an independent benchmark put it fourth of ten on intent-classification accuracy and third most expensive per thousand decisions, because shipping the full option list on every call roughly doubles input tokens, and it cannot cache. Its real edge was tail latency. The numbers and the scope are in Noticing Is Cheap, Judgment Is Scarce.
The schema is what makes these interchangeable, and that is the point of the table. A node can start as a prompt because a prompt needs nothing, and be replaced by a classifier once the graph has produced enough labelled examples to train one — same contract, a fraction of the cost. You cannot do that swap if the stage boundary is prose.
The nearest thing you already know is extracting a function, and the discipline transfers almost exactly. One job per node. Inputs and outputs stated rather than implied — the schema is the signature. No hidden state travelling between callers. Testable on its own, which is the real reason to do it. Extract when it is doing two things. If you would split the function, split the node.
Where the analogy breaks is the part worth holding on to. Extract Function is defined, since Opdyke, as a restructuring that preserves observable behaviour — that guarantee is what makes refactoring safe to do without measuring. Splitting a node has no such guarantee. Same input, two runs, different output; and the act of splitting changes what comes out, because each half now sees less context than the whole did. A node is not a pure function and cannot be memoised, reordered or inlined on the assumption that it is.
So take the shape and not the licence. Extracting a function is free and you check it with a test. Extracting a node costs a model call, a serialisation boundary and some latency, and you check it against the baseline from §1 — which is the whole reason that baseline exists. See A Description Can’t Replace the Code for the same vocabulary collision doing damage elsewhere.
The tell, and it subsumes all three: a node should split when it is doing two things with different error costs. A false positive in noticing is cheap — the verifier drops it. A false positive in verifying ships to a human. When one prompt owns both, you cannot tune either.
The topology this produced
Two things in that picture are worth more than the boxes.
The honest counter-case: one pass was never split. The simplification pass is a single pass end to end. It’s a noticing problem the whole way — a verify stage would have nothing to verify, because the hard part isn’t deciding whether a candidate is real, it’s spotting the candidate at all. Not every pass wants the scout/deep shape. Splitting one that doesn’t buys you a stage that always says yes.
Two of these splits came from a specific failure, not a principle. The triage node exists because the scout over-fired on names and types — it would flag a call site because the identifier looked like the thing the rule cares about, without a defect line to cite. The fix was a cheap model in front, not a tighter scout, because tightening the scout costs recall and recall is the thing the scout exists for. The dup-triage node exists because the same rule kept producing several leads at one site, and the deep was paying to judge the same question repeatedly.
The null you should know about
I can’t tell you which of these splits paid off as a portfolio. The whole-graph lever log has three lines in it — two baselines and one arm. Every split above is justified by the specific pain it relieved, not by a measured before/after on the whole pipeline. That’s not an oversight I’m defending; it’s §8’s problem showing up early. “Which splits paid” is answered per-split or not at all.
5. Schemas are the wire format
Typed JSON between every stage a program reads. Not prose.
Prose between agents is un-diffable, un-testable, and lets a stage smuggle confidence — “this looks like it might be a problem” carries a hedge that no downstream code can read, so the hedge either gets ignored or gets over-interpreted, and you’ll never know which. A typed envelope with a version, a schema id and a result array makes every stage boundary a thing you can assert on. See The Raw Is the Trust Boundary.
Why JSON, and not the other options
“Typed” is the load-bearing word, but the format still matters, and JSON wins on tooling rather than beauty. Models emit it natively and every major provider now offers structured outputs or constrained decoding against a JSON schema, which turns the contract from a thing you check after the fact into a thing the decoder cannot violate. JSON Schema has validators in every language you might write the runner in. And the output is greppable and diffable, which is what makes a stored record worth storing.
The alternatives lose for specific reasons. YAML is whitespace-sensitive,
which is hostile to generated output on its own, and its type coercion is a
trap worth stating precisely: YAML 1.2’s core schema treats only
true/false as booleans, so a bare no is a string — but PyYAML and much
of the deployed world still implement YAML 1.1, where it is not. Whether
your parser silently converts a model’s no into False depends on a spec
version you probably have not checked. XML is more verbose but models are
genuinely reliable at closing tags, so it is a defensible choice if your
provider has no structured-output mode; the tooling is just thinner. Binary
formats are out because the producer is a language model.
If you do have constrained decoding, use it, and notice what changes: the
schema stops being a post-hoc check and becomes the decode constraint, which
removes envelope_parse and result_parse from the ladder below but not
item_invalid — a model can still emit a perfectly-shaped answer that is
wrong.
Three receipts, and the failure ladder is the one people need.
The failure ladder has six named kinds, not one catch
| Kind | What happened |
|---|---|
nonzero_exit |
the process died |
envelope_parse |
the outer JSON didn’t parse |
envelope_shape |
the envelope parsed and reported failure |
result_parse |
the inner payload didn’t parse |
result_not_array |
it parsed and wasn’t a list |
item_invalid |
one item failed the schema |
Naming them is what lets you count them, and the distinctions are load-bearing:
envelope_parse means the model produced garbage, item_invalid means it
produced a well-formed answer you rejected. Those need different fixes and a
single catch (e) erases the difference.
The policy attached to the ladder: the invalid channel is always surfaced, so a drop is never silent. Fail closed by default, retry once, salvage only in audit mode, repair never. Repairing invalid output is the tempting one and it’s the trap — a repaired item is a value you made up on behalf of a stage that declined to produce it. There is one exception in the whole system, and its shape is the test for whether yours qualifies — see Typing charges you too below: you may canonicalise a word you asked for; you may never repair a judgment.
One detail from the ladder that cost real money before it was noticed: a non-zero exit still has an envelope. A failed call came back with a populated usage payload showing a real dollar cost, recorded as $0.00, because the failure path never read it. A failing call is not a free call.
And the honest hole: nobody has counted any of these. There’s no counter and no tally, so I cannot tell you how often a stage emits garbage. The channel exists; the reading doesn’t. That pattern recurs — see the closing of part three.
Typing charges you too
A live run lost an entire batch to this: the schema’s disposition enum was
confirmed | rejected, and a refuter agent — an agent whose entire prompt tells
it to refute — returned refuted. One invalid entry fails the array, so the
whole batch had to be re-drawn.
That synonym was invited by our own prompt. The fix is a canonicaliser in front of the validator, not a looser schema: map the synonyms you can predict, keep the enum strict, and let the validator stay a validator. Loosening the enum would have made the same class of error unobservable instead of expensive.
The general form: when you type a boundary, you take on the job of reconciling the model’s vocabulary with yours. Budget for that. It is still worth it.
Thirteen schemas, all v1, no v2 of anything
I have no receipt at all for what a version bump costs, because it has never
happened. Every schema is .v1 and always has been. What the suffix actually
bought was naming a boundary as a boundary — the version string is a
registry key the validator dispatches on. Read it as “cheap to add, so add it,”
not as “you will need it.” Implying versioning discipline that hasn’t been
exercised would be the easy lie here.
One of the thirteen is deliberately unvalidated, with the reason written into the code where the check would be — the authoritative validator for that shape lives in another language, in another service, and duplicating it here would mean two validators drifting. A declared hole beats a validator that lies.
The untyped path is still live
Prose variants of several stages still exist and still run. The rule is simple: the untyped path survives where a human reads the output, and the typed path exists where a program does. This was never a migration to typed JSON — it was the addition of a typed path alongside a prose one, and presenting it as a migration would be the second easy lie in this section.
Related: A Description Can’t Replace the Code.
6. What to put in a schema so the stage is testable
Here’s the failure this section prevents: if a stage emits only what the next stage consumes, the stage is untestable by construction. You have no per-node signal, so every question becomes a whole-pipeline A/B, and §11’s noise floor eats it.
The fix is to put fields in the wire format for the harness, not the consumer.
Two of ours are pure instruments. Neither is consumed by any downstream stage.
confidence routes verification depth — how hard the verifier looks. It
is never used to drop a lead or skip verification, and the schema says so in
the field description, because the first thing anyone will try to do with a
confidence number is threshold on it.
confidence.basis — a short tag for why the generator believes what it
believes. Nothing reads it at runtime. It’s logged against the verifier’s later
drop rate, so that eventually you can answer: which kinds of reasoning does my
generator use when it turns out to be wrong? That’s a question you cannot ask
retroactively, because the traces you’d need don’t have the field.
Ship the instrument in the schema, because you will not add it later. Adding a field is nearly free at the moment you’re already editing the schema. Adding it in six months means a migration and a backlog of old traces that don’t have it.
A schema is not just a contract between two stages. It is the instrument.
The second rule, which generalises past schemas
When the verdict moved out of the model and into computed booleans (§10), the model’s own holistic guess was not thrown away. It’s kept in a separate field for exactly this mining. Nothing has been mined out of it yet — the field is the part that had to exist first.
When you take a decision away from the model, keep its answer as data. The disagreements between the computed verdict and the model’s discarded opinion are the highest-signal rows you will ever have for finding a missing condition. If you delete the opinion, the only thing you learn from a bad computed verdict is that it was bad.
Related: Can’t Self-Measure Recall, Evals Aren’t the Moat.
How sure I am: the build is real and the seams are lived — the stages, the schemas and the failure ladder are in production use, and the topology in §4 is what the system actually looks like rather than a diagram of what it should. The placement policy is my call, not a measured optimum: the three axes I sort rules on, and the decision to cut where the stance changes, are judgment rather than a result. The claim that a split costs you the model’s out-of-scope catches is argued from the mechanism and from detector false positives; I have not measured what a mechanised rule stopped finding, and by construction that is the hard thing to measure.
Sources
- Gall’s law — John Gall, Systemantics (1975): a complex system that works is invariably found to have evolved from a simple system that worked. The epigraph, and the argument for starting with one prompt.
- Refactoring as behaviour-preserving — Martin Fowler, Refactoring (1999; 2nd ed. 2018), after William Opdyke’s 1992 thesis. The analogy for extracting a node holds up to this guarantee and stops there.
- ModernBERT-class encoders (Answer.AI and LightOn, December 2024) — the small-classifier option for a bounded, repeated question.
- Typed-decision models — Jev (TypeSafe AI, September 2026), described for its shape rather than endorsed; the independent benchmark numbers and the scope are in Noticing Is Cheap, Judgment Is Scarce.
- My own build: the stage topology, the six-kind failure ladder, the contract, and the measurements quoted throughout.
Related: Tune the Prompt Before You Split It — do this before any of the below; From Rules to Runs — part two; How You Know — part three; Every Node Needs Its Own Runner — what executes the graph once it exists.