TEXTBOOK·ENGINEERING AI AGENTSPreviousCHAPTER 01 OF 15NextContents
01FOUNDATIONS & LANDSCAPE

Agents and compound systems

Two questions place any system on a spectrum: who chooses the next step, and how much of the outside world enters between the request and the answer. Where a system sits governs its cost, its debugging, and the data it needs.

1.1The Spectrum of Systems

The word agent is used loosely enough that it has stopped distinguishing anything. A useful way to recover the distinction is to stop asking what a system is called and start asking two questions about how it runs. First, who chooses the next computation: a programmer who wrote the sequence down before the system ever executed, or the model, at runtime, based on what it has seen so far. Second, how much information from outside the model enters the process between the first token of input and the final answer: nothing, a fixed retrieval, or a continuous stream of observations produced by actions the system itself took. Answering those two questions places any system on a spectrum with five recognizable positions, and the position determines almost everything an engineer cares about downstream, including cost variance, debugging strategy, and the shape of the data needed to improve the system.

First on the spectrum is the single model call. A prompt goes in, tokens come out, and the entire computation is one forward pass over one context window. Control flow is trivial because there is no flow. The knowledge available is whatever was in the weights at training time plus whatever the caller pasted into the prompt. This is the position most benchmark evaluations occupy, and it is the position from which most claims about model capability are made, which is worth remembering when a benchmark number is offered as evidence about a deployed system that does not run this way.

Second on the spectrum sits the fixed pipeline: several model calls chained in an order a programmer fixed in advance, each one consuming the previous one's output. A summarizer feeding a classifier feeding a formatter is a pipeline. The model still chooses nothing about control flow, but the system now has more than one place to intervene, more than one place to fail, and more than one prompt to maintain. The pipeline's cost is a sum of terms known before runtime, and its failures localize: a malformed output at stage three is a stage-three problem, and the other stages are exonerated by construction.

Third comes the position that adds non-model components that supply information or enforce constraints the model cannot supply or enforce for itself. This is the compound AI system as Zaharia and colleagues describe it in the BAIR post: a system built from multiple interacting components, some of which are models and some of which are retrievers, verifiers, symbolic solvers, code interpreters, or ranking functions. The defining move is that the answer now depends on something outside the weights. Retrieval-augmented generation is the common case, and Databricks reported that around sixty percent of the language-model applications they observed used some form of it. AlphaGeometry, pairing a fine-tuned language model with a symbolic deduction engine, is the same move in a more specialized register, and it scored between silver and gold medal level on International Mathematical Olympiad geometry problems. Control flow is still programmer-fixed at this position; what changed is the source of truth.

Workflows occupy the fourth position, where the programmer's fixed structure gains branches, loops with fixed bounds, and routing decisions that the model influences but does not invent. A router that classifies an incoming request and dispatches it to one of four specialized subpipelines is a workflow. The model is choosing among options, but the option set was enumerated in advance and the code path for each option was written by a person. This matters for a practical reason: everything the system can possibly do is still enumerable by reading the source, which means the failure surface is finite and the evaluation can in principle cover it.

Last is the agent, where the model decides at each turn what to do next, and the sequence of steps is a runtime artifact nobody wrote down. The tools are enumerated in advance, but their ordering, their repetition, their arguments, and the stopping point are not. Environmental feedback is continuous: each action produces an observation that conditions the next decision. Two runs on the same input can take different paths and both be correct. This flexibility is the entire reason to build an agent, and it is also the reason agents are more expensive to evaluate, more expensive to debug, and more expensive to run than anything to their left on the spectrum.

position = f(who picks next step, feedback per step)
The two axes that place a system on the spectrum: control-flow authorship and the rate at which external observations enter the computation.

Carrying one task across all five positions makes the differences concrete. The task: a customer writes in asking why their invoice for March is higher than February's, and the system must produce an answer the customer can act on. At position one, a single model call receives the email and generates a reply. The model has no access to the invoices, so the reply is a plausible-sounding explanation of why invoices sometimes rise, mentioning proration and plan changes and usage overages as possibilities. It is fluent, it is generic, and it is unfalsifiable, because nothing in the system ever consulted the customer's actual bill. Nine times out of ten this reply is wrong in a way the customer will notice immediately.

At position two, the fixed pipeline, the same email is first passed to an extraction call that pulls out the account identifier and the two months in question, then to a second call that drafts a reply in the correct tone using those extracted fields, then to a third call that checks the draft for prohibited phrasing. The reply is now correctly addressed and correctly formatted and still wrong about the invoice, because no stage of the pipeline ever looked at billing data. The pipeline improved presentation and did nothing for correctness, which is a useful lesson about what adding model calls buys and what it does not.

For the compound system, a retrieval component is inserted before the drafting call. The account identifier extracted at stage one queries the billing database and returns both invoices as structured records, and the drafting call receives those records in its context. Now the reply can say that the March invoice is eleven dollars higher because a line was added on the fourteenth and prorated for the remainder of the cycle. The answer is grounded in a source of truth external to the weights, and it can be checked. This single change did more for correctness than any amount of prompt refinement at positions one and two, and it is the concrete form of the BAIR argument that system design frequently beats model scaling for a fixed budget.

Position four, the workflow, adds a router at the front. The incoming email is classified into one of several intents: billing dispute, cancellation request, technical fault, or general question. A billing dispute routes into the retrieval-and-draft path just described. A cancellation routes into a different path with retention logic and a compliance check. Each path is written out in code, and the model's contribution to control flow is the single classification decision at the top. The system now handles a range of requests, and it handles each one through a path an engineer can read, test, and reason about in isolation.

In the agent case, the invoice question is handed to a model with a set of tools: query billing records, look up plan definitions, check for open credits, read the account's change history, and send a reply. Nobody wrote down the order. The model queries the invoices, notices the difference is larger than the single prorated line accounts for, checks the change history on its own initiative, finds a discount that expired at the end of February, verifies the discount's original terms in the plan definitions, and then writes a reply explaining both contributions to the increase. No pipeline author had anticipated the expired-discount case, and the agent found it because it could choose its next action after seeing the result of the previous one. On a different account with a simpler cause, the same agent stops after one query. The variable step count is the source of both the capability and the cost variance, and the two cannot be separated.

ONE TASK, FIVE POSITIONS
reply = model(email)                              # 1. single call

f = model(EXTRACT, email)                         # 2. fixed pipeline
reply = model(CHECK, model(DRAFT, f))

inv = billing.invoices(f.account, f.months)       # 3. compound: truth
reply = model(DRAFT, f, inv)                      #    enters from outside

reply = ROUTES[model(CLASSIFY, email)](email)     # 4. workflow: branches
                                                  #    readable in source

reply = loop(model, max_steps=12,                 # 5. agent: order is a
             tools=[invoices, plans, credits])    #    runtime artifact
POSITIONWHO PICKS NEXT STEPEXTERNAL FEEDBACKINVOICE EXAMPLE OUTCOME
Single callNobody, one passNoneGeneric explanation of why bills rise; unfalsifiable
Fixed pipelineProgrammer, in advanceNoneCorrect tone and format, still wrong about the amount
Compound systemProgrammer, in advanceOne retrieval per runGrounded: cites the prorated line and the amount
WorkflowProgrammer, model routesRetrieval on the chosen branchHandles disputes, cancellations, faults through separate paths
AgentModel, each turnOne observation per actionDiscovers the expired discount nobody enumerated
steps: 1 → n fixed → n fixed + tools → branch → S random
Step count across the five positions. Only the agent has a step count that is a random variable rather than a constant.

Reading the five positions in order also reveals what each transition actually purchases. Moving from one to two buys structure and separable prompts. Moving from two to three buys grounding in an external source of truth, and it is by a wide margin the most valuable transition for most applications. Moving from three to four buys coverage of a heterogeneous request population without forcing one prompt to serve every case. Moving from four to five buys the ability to handle cases nobody enumerated, at the price of a trajectory that is no longer bounded in advance. Engineers who skip straight from position one to position five typically discover that the problem they had was a position-three problem, and they have paid agent prices for a retrieval fix.

1.2When Compound Systems Win, and What They Cost

Adding components to a system is not free, and the question of when to do it deserves a sharper answer than a general preference for sophistication. Three conditions predict that a compound system will outperform a single call, and they are worth checking explicitly before any architecture is chosen. The first is the existence of an external source of truth. If the correct answer depends on facts that were not in the training data, are private, or change faster than the model is retrained, then no amount of prompting recovers them and a retrieval or query component is the only path to correctness. Invoice amounts, current inventory, a specific customer's contract terms, and last night's deployment log all fall in this category. This is the condition that made the difference at position three of the worked example, and it is the most common reason a compound system wins.

The second condition is decomposability: the task can be split into subproblems whose intermediate results are individually checkable. Checkability is the operative word. Splitting a task into three model calls whose intermediate outputs nobody can verify produces three opportunities to go wrong and no new information. Splitting it so that the first stage emits a structured extraction that can be validated against a schema, and the second stage emits a claim that can be checked against a retrieved document, produces places where an error can be caught before it propagates. The BAIR post's AlphaCode 2 example is the extreme version of this condition: generate up to a million candidate solutions, then filter and score them against the problem's own test cases, reaching roughly the eighty-fifth percentile of human competitors. That works because code has a cheap, exact verifier. Generation was never the hard part; the verifier was what made a million samples useful rather than a million ways to be wrong.

A third condition is observable action outcomes: when the system acts, it learns something it did not know before, and the observation is informative enough to change the next decision. An agent that calls a search API and reads results has this property. An agent that calls a tool whose response is always an acknowledgment with no content does not, and the loop around it is decoration. This condition is what separates agents from workflows, and its absence is the most reliable sign that a workflow would have been sufficient. When these three conditions hold together, the compound-system argument is strong: BAIR cites Medprompt, which wrapped GPT-4 in nearest-neighbor example selection and ensembling and outperformed specialized medical models, exceeding the underlying model's accuracy on medical exams by roughly nine percent, without any additional training.

Compound systems lose under the mirror-image conditions. When the task is a single well-specified transformation that the model already performs reliably, additional components add latency and failure surface in exchange for nothing. Translation of a short passage, extraction of a field from a clean document, and reformatting of structured data are all tasks where a single call is the right answer and where teams routinely build pipelines out of habit. Compound systems also lose when the subproblems are not genuinely independent, because the decomposition then hides coupling that no single component can see, and the aggregate output contains contradictions that each part considered correct. They lose when latency budgets are tight enough that serial component calls cannot fit, which is common in interactive interfaces where a several-second response is a product failure regardless of accuracy. And they lose when no verifier exists for the intermediate outputs, because in that regime the extra stages compound errors rather than catching them.

CONDITIONCOMPOUND SYSTEM WINSCOMPOUND SYSTEM LOSES
Source of truthFacts live outside the weightsAnswer is a pure transformation of the input
DecompositionSubproblems have checkable intermediatesSubproblems are coupled; no verifier exists
Action outcomesEach action returns informative observationTool returns acknowledgments only
Latency budgetSeconds available; parallelism possibleInteractive budget under one second
VolumeValue per request justifies the token billHigh volume, low margin per request

The cost accounting deserves explicit treatment because it is usually done informally and usually done wrong. Every added component contributes along three dimensions, and they do not move together. In tokens, an added model call costs its own input tokens plus its output tokens, and the input tokens include everything upstream stages have accumulated. This is the term that surprises people: a five-stage pipeline where each stage passes its full context forward does not cost five times a single call, it costs something closer to the sum of a growing series, because stage five's input contains the accumulated output of stages one through four. Context that is carried rather than summarized turns a linear pipeline into a quadratic token bill.

P(chain ok) = pⁿ (p = 0.95, n = 6 → 0.735)
Independent per-component success compounds multiplicatively. Six components at 95% each yield a system below 74%.
tokens_carried = Σ(i=1..n) ( base + Σ(j<i) out[j] )
Carrying full context forward makes token cost grow quadratically in stage count, not linearly.

In latency, the accounting depends on whether components run in series or parallel. Serial components add their latencies, and a chain of four calls at eight hundred milliseconds each is a three-and-a-half second response before any retrieval or tool time is counted. Parallel components add only the maximum, plus the aggregation call that consumes their outputs, which is why sectioning a task into concurrent branches is often the only way to keep a multi-component system inside an interactive budget. Retrieval components typically add tens of milliseconds and are rarely the bottleneck; the bottleneck is almost always the generation calls, and the useful optimization is reducing their number or their output length rather than tuning the vector store.

L_serial = Σ L[i] L_parallel = max L[i] + L_agg
Serial stages add latency; parallel branches pay only the slowest branch plus aggregation.

Along the third dimension, failure surface, each component adds its own failure modes and each interface between components adds another. A component can be unavailable, can time out, can return malformed output, or can return well-formed output that is wrong. The interfaces fail through schema drift, through silent truncation when an upstream output exceeds a downstream context budget, and through the quiet substitution of an empty result for an error. If each of n components succeeds independently with probability p, the whole chain succeeds with probability p to the n, which for p of ninety-five percent and n of six is about seventy-four percent. Independence rarely holds exactly, but the shape of the arithmetic is correct and it is the reason mature compound systems spend more code on fallbacks and validation than on the model calls themselves.

ADDED COMPONENTTOKEN COSTLATENCY ADDEDNEW FAILURE MODES
Retrieval callk chunks into next prompt (500-4000 tok)10-80 msEmpty result treated as no-context; stale index; truncation
Extra generation stageOwn input + all carried context + output400-1500 msMalformed output; schema drift at the interface
RerankerNone to the LLM20-200 msDrops the one relevant chunk; miscalibrated scores
Verifier / guard callDraft re-read as input + short output300-900 msFalse rejects; silent pass-through on timeout
Tool invocationArgs out, observation in (unbounded)Depends on toolTimeout; partial data; wrong arguments accepted
Reflection roundFull trajectory re-read + critique800-2000 msConfident revision that is worse than the draft
MEASURE THE TAIL, NOT THE MEAN
# Record per-request cost and latency, then read the tail.
rows = [(r.tokens_in*P_IN + r.tokens_out*P_OUT, r.ms) for r in runs]
cost = sorted(c for c, _ in rows)
lat  = sorted(m for _, m in rows)
p = lambda xs, q: xs[int(q * (len(xs) - 1))]
print("cost p50/p99:", p(cost, .50), p(cost, .99))
print("lat  p50/p99:", p(lat, .50), p(lat, .99))

# A p99/p50 ratio above ~10 means the mean is not a budget.
assert p(cost, .99) < BUDGET_CEILING, "tail exceeds per-request ceiling"

Two practical consequences follow. First, the marginal component must justify itself against a measured baseline, not against intuition, and the measurement should include the tail of the latency and cost distributions rather than the mean. A system whose median request costs four cents and whose ninety-ninth percentile costs three dollars has a budgeting problem the median conceals entirely. Second, cost and quality are allocations rather than fixed properties. The BAIR post makes this point with a hundred-millisecond budget that could be spent as twenty milliseconds of retrieval and eighty of generation, or the reverse, and observes that GitHub Copilot uses carefully tuned smaller models with search heuristics rather than the largest available model because the latency budget of an inline completion permits nothing else. FrugalGPT, cited in the same post, routes requests across a cascade of models and reports either about four percent better quality at equal cost or roughly ninety percent cost reduction at equal quality, depending on which end of the trade the operator chooses. The design question is not which components are good but how a fixed budget is divided among them.

1.3The Four Agentic Design Patterns

Andrew Ng's 2024 letters in The Batch organize the design space above the single call into four patterns, and the organization has held up because each pattern names a distinct mechanism rather than a distinct product category. The patterns are reflection, tool use, planning, and multi-agent collaboration. They compose: a production system usually runs two or three of them at once, and understanding which one is doing the work in a given system is the first step in debugging it.

Reflection is the pattern in which the model examines its own output and produces a critique, and then a revision conditioned on that critique. The mechanism is that generating a criticism of an existing artifact is a different and often easier task than generating the artifact correctly on the first attempt, because the critique step sees the whole draft at once and can attend to properties that were not visible while the draft was being produced token by token. Its important limitation is that reflection without an external signal is the model grading itself with the same knowledge that produced the error, which means systematic mistakes survive reflection unchanged. Reflection becomes reliably valuable when the critique is grounded in something outside the model: a test suite that ran, a linter's output, a retrieved document contradicting the draft, a schema validation failure. Ungrounded reflection tends to produce confident revisions that trade one error for another, and it costs a full re-read of the draft plus a critique plus a rewrite every round.

Tool use is the pattern in which the model is given functions it can call, such as web search, code execution, database queries, or any other capability, so that it can gather information or take action outside its own forward pass. The mechanism is the introduction of external state into the computation. Nearly everything a model cannot do by generating text, including arithmetic on large numbers, reading current data, and causing effects in other systems, becomes available through this pattern. The engineering cost is that tool descriptions occupy context, tool outputs occupy more context and are frequently much larger than expected, and every tool is a new failure surface with its own timeout, error, and malformed-response behavior. Tool use is also where the security boundary of an agentic system lives, because it is the point at which the system stops reading and starts writing.

Planning is the pattern in which the model produces a multistep plan and then executes it, rather than deciding one step at a time. Ng's illustration is writing an essay: draft an outline, then research online, then write a first draft, then revise. The mechanism is that committing to a decomposition before acting gives the later steps a shared structure and prevents the local drift that step-at-a-time selection is prone to. The cost is brittleness. A plan formed before any observation encodes assumptions about what the environment contains, and when an early step returns something unexpected, a system that follows the plan mechanically will keep executing steps that no longer make sense. Practical planning implementations therefore need a replanning trigger: a condition under which the current plan is abandoned and a new one is formed from the current state. Systems without such a trigger fail in a distinctive way, executing a sequence of individually reasonable actions toward a goal that stopped being reachable three steps earlier.

Multi-agent collaboration is the pattern in which several agents, typically the same underlying model given different instructions, tools, and context, divide the work and exchange results. Ng describes them as splitting up tasks and discussing and debating ideas to reach better solutions than a single agent would. The mechanism is partly context isolation, since each agent holds only what its role requires and therefore has more room and less distraction, and partly the diversity that different role prompts induce in the outputs. The cost is the highest of the four patterns: each agent is a full model call with its own context, inter-agent messages are tokens that buy no direct progress, and the failure modes include agents converging on a shared wrong premise, agents disagreeing with no mechanism to resolve it, and coordination overhead exceeding the benefit of the division. Multi-agent designs are worth their price when the subtasks genuinely need different tools or different context, and they are wasteful when the same model with the same tools is being asked to talk to itself.

PATTERNMECHANISMCOST PER ROUNDFAILS WHEN
ReflectionCritique then revise an existing draftDraft re-read + critique + rewriteCritique is ungrounded; the error is systematic
Tool useExternal state enters the computationTool schemas + observation tokensObservations are unbounded; tool errors are silent
PlanningCommit to a decomposition before actingOne plan call + per-step executionEnvironment contradicts the plan and nothing replans
Multi-agentRole split, context isolation, debateN full contexts + message passingAgents share a wrong premise or cannot resolve disagreement
GROUNDED REFLECTION VS SELF-GRADING
def revise(draft, verify):
    for _ in range(MAX_ROUNDS):
        report = verify(draft)          # tests, linter, schema, retrieval
        if report.ok:
            return draft
        draft = model(REVISE, draft=draft, failures=report.failures)
    return draft

# The value is in `verify`. Replacing it with model(CRITIQUE, draft)
# removes the external signal and most of the measured gain with it.

The result that made these patterns widely discussed is Ng's report on the HumanEval coding benchmark. Zero-shot, GPT-3.5 solved roughly 48.1 percent of problems, and GPT-4 solved roughly 67.0 percent. Wrapped in an agentic workflow, GPT-3.5 reached as high as about 95.1 percent, well past GPT-4 used zero-shot. Two readings of this number are worth separating. The narrow reading is that iterative workflows help on coding tasks, which is true. The broader reading, and the one the course relies on, is that the choice of system architecture around a model can move performance further than the choice of model, which reorders the engineering priorities: architecture and evaluation earn attention before model selection does.

HumanEval pass@1: GPT-3.5 48.1% GPT-4 67.0%
Zero-shot baselines reported by Ng in The Batch, 2024.
GPT-3.5 + agentic workflow: up to ~95.1%
The wrapped older model exceeds the newer model used zero-shot, on a benchmark with an exact automatic verifier.

That result also carries a qualification that is easy to lose. HumanEval problems come with unit tests, so the workflow has access to an exact, cheap, automatic verifier at every iteration. Reflection is grounded because the tests either pass or fail, and planning has a clear termination condition. Tasks without such a verifier do not reproduce these gains, and the size of the improvement in a given domain is closer to a function of verifier quality than of workflow sophistication. Before adopting an agentic workflow because of this result, the useful question is what plays the role that the unit tests played, and if the answer is that the model checks its own work, the expected gain should be revised downward substantially.

1.4The Three Engineering Challenges

The course organizes the engineering of agentic systems around three challenges, and the reason for three rather than one long list is that these three interact in a specific circuit that generates most of the field's recurring failures. The challenges are decomposition, which is the choice of what components exist and what each is responsible for; data, which is what the system records about its own execution and what that record can support; and evaluation, which is the measurement that decides whether a change was an improvement. Each is hard in isolation. Their interaction is harder, and it is the reason a change that looks local is rarely local.

Decomposition is the problem of choosing a factoring. Given a task, how many components should exist, where should the boundaries between them fall, and what should cross each boundary. The design space is combinatorially large, and the BAIR post names this as the first open challenge: even a simple retrieval-augmented application requires choosing among retrieval models, generation models, query expansion strategies, reranking, and output verification, and the number of combinations exceeds what any team can evaluate exhaustively. Two useful heuristics narrow the search. The first is to place boundaries where an intermediate result can be verified, because a boundary without a check is a place where errors pass through unnoticed and there is little reason to have put a boundary there. The second is to place boundaries where the failure modes differ, since a component that fails in one characteristic way is easier to fix than a component that fails in five.

The data challenge is that an agentic system must record enough of its own execution to support later improvement, and what counts as enough depends on the decomposition. A trace that logs only the final answer supports measuring end-to-end quality and nothing else. A trace that logs every intermediate call with its arguments, the raw observation returned, and the reason execution stopped supports attributing a failure to a step and building targeted training or evaluation data for that step. Chapter 8 develops this in detail. The point to carry into the rest of the course is that the trace schema is determined by the decomposition: the components define what steps exist, and the steps define what fields the trace has.

Evaluation is hard because agentic systems resist the measurement conventions carried over from single-model benchmarks. A single call has one output and one score. A trajectory has an outcome, a path, a cost, and a length, and a system can reach the right outcome by an unacceptable path, or fail to reach it while doing everything reasonable. Evaluations that score only the final answer will rank a lucky trajectory above a sound one, and evaluations that score only the path will penalize valid alternative routes to the same result. Chapter 10 treats this at length. The consequence relevant here is that evaluation of a compound system requires deciding what to measure at each boundary the decomposition created, which is once again a dependency running from decomposition into another challenge.

CHALLENGETHE QUESTION IT ANSWERSDETERMINED BYFAILURE WHEN NEGLECTED
DecompositionWhat components exist and where boundaries fallTask structure, available verifiersBoundaries with no check; combinatorial design search
DataWhat the system records about its own executionThe decomposition's step listTraces that support end-to-end scores only
EvaluationWhether a change was an improvementThe decomposition's boundariesStale metric measured against a system that has changed shape

Interaction among the three is what makes them a system rather than a checklist, and it runs as a circuit. A new decomposition changes what steps exist, which changes the trace schema, which changes what data is collected. The collected data is what any optimizer consumes, whether that optimizer is a prompt-tuning procedure like DSPy, a fine-tuning run, or an engineer reading failures on a Friday afternoon. The optimizer improves the system against the evaluation it is given. And an optimizer given enough freedom will find the parts of the evaluation that are cheaper to satisfy than the underlying goal, which is the specification-gaming problem in its ordinary industrial form: a retrieval component tuned against an evaluation that rewards citation presence learns to include citations, not to include correct ones.

decomposition → trace schema → optimizer → evaluation → …
The circuit. A change at any point propagates around the loop, including back to the measurement that was supposed to be independent.

That circuit closes in a way that produces a specific institutional failure. The evaluation was written against the old decomposition. The system was re-decomposed to fix a problem. The traces changed shape, but the evaluation did not, so it now measures something adjacent to what it originally measured while continuing to report a comparable-looking number. Improvement continues to be recorded and the deployed system gets worse. The defense is to treat the evaluation as a component with a version and an owner, to re-derive it whenever the decomposition changes, and to keep a held-out set of real failures that never participates in any optimization loop, so that at least one measurement stays uncontaminated by the process that is optimizing against the others.

score_reported = score_true + gaming(optimizer, eval)
Any optimizer with enough freedom finds the gap between the metric and the goal. The gap widens as optimization pressure increases.
PIN THE EVALUATION TO THE DECOMPOSITION
EVAL = {"version": 7, "decomposition_hash": hash_components(SYSTEM),
        "cases": load("eval/v7.jsonl"),
        "holdout": load("eval/holdout.jsonl")}   # never optimized against

def guard():
    if hash_components(SYSTEM) != EVAL["decomposition_hash"]:
        raise RuntimeError(
            "Components changed since eval v%d was written; "
            "re-derive per-step metrics before trusting scores."
            % EVAL["version"])

Sequencing follows from the circuit. Evaluation comes first, because without it no decomposition can be compared to another and no optimizer has an objective. Data collection comes second, because a decomposition cannot be diagnosed without traces and an evaluation cannot be extended to intermediate steps without them. Decomposition comes third and iterates, because each new factoring is a hypothesis about where the errors are, and it should be tested against a measurement that existed before it was proposed. Teams that reverse the order build an architecture, then instrument it, then write an evaluation shaped by whatever the architecture happened to make easy to measure, and are then unable to determine whether their subsequent changes helped.

These three challenges structure the remainder of the book. Decomposition is the subject of the chapters on workflow patterns, tool design, and context engineering. Data is the subject of Chapter 8 on what an agentic system records and Chapter 9 on which of that record to label and how to document it. Evaluation is the subject of Chapter 10 and the chapters on judging and on production monitoring. The chapters can be read in any order, but the circuit connecting them does not change: a change to any one of the three propagates to the other two, and a team that tracks only the one it changed will be surprised by the other two later.

STUDIO 01

Write the minimum viable architecture

Choose a real task. Specify a one-call baseline, a metric, and three failure examples. Propose exactly one compound component that targets the dominant failure, and estimate its quality gain, its latency, and the new risks it introduces — before you implement it.

KNOWLEDGE CHECK
READING
PRIMARYThe Shift from Models to Compound AI Systems — BAIR Blog, 2024
PRACTICEAgentic Design Patterns: Four AI Agent Strategies — The Batch, 2024
PRACTICEDSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines
PRACTICEFrugalGPT: Using LLMs While Reducing Cost and Improving Performance
PRACTICEBuilding Effective Agents — Anthropic Engineering