This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Building with AI (Stage 2)

Hands-on architecture for building AI systems.

Where Foundations explains the pieces and Deep Dives go deeper, Stage 2 is about assembling them into real systems — with diagrams for the architecture.

Roadmap

flowchart LR
    A[AI system design] --> S[Scaling to production] --> V[Serving models] --> B[Building a RAG system]
    B --> C[Agentic RAG] --> D[The agent harness] --> E[Loop engineering]
    E --> F[From prompts to graphs] --> G[AI code structure] --> H[Tooling and frameworks]

In this section

  1. AI system design — the standard shape of an AI app.
  2. Scaling to production — gateway, caching, serving, queues, reliability, cost at scale.
  3. Serving models — the inference layer: self-hosting, quantization, engines, queuing, routing.
  4. Building a RAG system — end-to-end reference architecture.
  5. Agentic RAG — retrieval driven by an agent, not a fixed pipeline.
  6. The agent harness — the loop, context, tools, memory, guardrails.
  7. Loop engineering — designing the loops themselves: closed loops, validators, orchestration.
  8. From prompts to graphs — the five engineering disciplines as one evolution.
  9. AI code structure — how to organize an AI app codebase.
  10. Tooling & frameworks — SDKs, frameworks, MCP, deployment.

Prerequisites

Work through Stage 0 — Foundations and Stage 1 — Deep Dives first — Stage 2 builds directly on both.

1 - AI System Design

The standard shape of an AI app — the model is one component among several.

Building an AI feature is mostly systems work — the model is one component among several. This page gives you the standard shape to build around.

The big picture

flowchart LR
    U[User] --> App[Your AI app]
    App --> Model[Model API - hosted LLM]
    App --> Data[(Your data - docs, DBs)]

A user talks to your app; your app talks to a hosted model and to your data. You own everything except the model itself.

The standard components

flowchart LR
    U[User] --> UI[Frontend - web or chat]
    subgraph App[Your AI app]
      UI --> Orch[Orchestrator / harness]
    end
    Orch --> Vec[(Vector store - embeddings)]
    Orch --> Model[Model API - LLM]
    Orch --> Tools[Tools / external systems]
    Orch -. traces .-> Obs[Observability]

The orchestrator (harness) is the brain you build: it assembles the prompt, manages the context window, runs the agent loop, calls tools, and applies guardrails.

Where each foundation concept lives

ConceptLives in
Prompting, contextOrchestrator
Embeddings, RAGVector store + retrieval
Tools, agentsOrchestrator loop + tools
Guardrails, securityAround inputs and outputs
Evaluation, observabilityCross-cutting, around everything

Design principles

  • The model is stateless — you own state and context.
  • Put determinism in code, judgment in the model.
  • Ground with data, constrain with schemas, gate risky actions.
  • Measure everything — evals offline, traces online.
  • Version your prompts — prompts are code: keep them in the repo, review changes, and record which version produced which output (it’s how you debug “it worked yesterday”).
  • The right stack, not the biggest — RAG, agents, memory, and MCP each earn their place only when the problem demands them; the strongest systems use the fewest components that solve the task, because every extra one is latency, cost, and attack surface.

This page is the shape of an AI app. Making that shape survive real traffic — gateways, caching, serving, queues, reliability, and cost at scale — is Scaling to production.

Sources

2 - Scaling to Production

What breaks when real traffic arrives — and the system-design patterns that keep an AI app fast, cheap, and reliable.

Goal

A working API call is the start. Once an AI app has real users, new problems appear: latency climbs, token cost balloons, the model provider rate-limits you, and one failure takes the whole request down. This page is the advanced half of AI system design — the infrastructure layer that makes an app fast, affordable, and reliable at scale.

The story: 10 users → 10,000 users

A RAG chatbot that’s perfect for 10 users breaks in predictable ways at 10,000. Each pattern below fixes one specific break:

flowchart LR
    U[Users] --> GW[API gateway - auth, rate limit, routing]
    GW --> Ca{Cache hit?}
    Ca -->|yes| Ret[Return cached]
    Ca -->|no| Q[Queue - async and long jobs]
    Q --> App[App / orchestrator]
    App --> RAG[(Vector DB / RAG)]
    App --> MS[Model serving - API or self-hosted, with fallback]
    MS --> App
    App --> GR[Guardrails in and out]
    GR --> U
    Obs[Observability] -.-> GW & App & MS

The request path

API gateway — the single front door. It authenticates, enforces rate limits (so one user can’t exhaust your provider quota), and routes requests. For AI apps its most valuable job is multi-provider routing: send traffic to a primary model, fail over to a secondary when the primary is down or throttled, and route cheap requests to a cheap model.

Load balancing — spread requests across app instances (and across provider API keys / regions) so no single one is the bottleneck. AI twist: balance by token load, not just request count — one long-context request can cost 100× a short one.

Caching — the cheapest request is the one you don’t send

Two layers, different keys:

  • Exact cache — same input string → return the stored answer. Trivial and free; only hits identical repeats.
  • Semantic cache — embed the query and reuse a past answer when a new question is close enough in meaning (“what’s your refund window?” ≈ “how long do I have to return something?”). Catches paraphrases an exact cache misses.
  • Prompt cache — a provider feature: reuse a repeated prompt prefix (system prompt, big context) to cut latency and cost on every call. Different from the two above — it caches inside one request path, not across users.

Cache what’s stable (docs, FAQs). Don’t cache what must be fresh or per-user (account data, anything with a guardrail decision) — a stale cached answer to the wrong user is worse than a slow one.

Model serving

Managed API (Claude, GPT) is the default: no GPUs, instant scale, pay per token. Reach for self-hosting an open model only when you have a concrete reason — data can’t leave your network, extreme volume makes per-token pricing lose to fixed GPU cost, or you need a fine-tuned model in the loop. Self-hosting buys control and costs you ops: GPU capacity, batching (group concurrent requests through the GPU for throughput), and autoscaling become your problem. Most teams should stay on the API far longer than they think.

The whole inference layer — deciding to self-host, quantizing the weights, and picking an engine — is Serving models.

Queues and async

A model call can take seconds to minutes — too long to hold an HTTP request open at scale. Put long or bursty work on a queue: the request returns immediately with a job id, a worker pool processes the queue, and the client polls or gets a webhook. This absorbs traffic spikes (the queue buffers instead of the app falling over) and lets you cap concurrency to what your provider quota allows. Essential for agent and batch workloads; a short single-shot chat can stay synchronous.

Admission control, backpressure, and cache-aware routing across replicas are in Load balancing & queuing.

Reliability

Models fail, time out, and rate-limit — design for it:

  • Timeouts + retries with backoff — but retry only idempotent calls, and cap attempts so a provider outage doesn’t amplify into a self-inflicted flood.
  • Fallback — primary model errors → try a secondary provider or a smaller model.
  • Circuit breaker — after repeated failures to a provider, stop calling it for a cooldown instead of hammering a dead endpoint.
  • Graceful degradation — when the AI path is fully down, return something useful: cached results, keyword search instead of RAG, or an honest “try again shortly” — never a 100% outage because one model is unavailable.

Each failure mode wants a different response — see Routing & fallback.

Cost and capacity at scale

Cost per call is a Stage 0 topic; at scale it becomes a system concern: route easy requests to cheap models, cache aggressively, cap context size, and batch where latency allows. Track cost per request in observability so a prompt change that doubles tokens shows up as a bill, not a surprise. Set a per-user and global budget ceiling — an agent loop with no cost cap is an open wallet.

Example — the chatbot, scaled

The 10-user chatbot at 10,000 users: an API gateway rate-limits and fails over between two model providers; a semantic cache serves ~30% of questions with zero model calls; long answers go through a queue so spikes don’t topple the app; a circuit breaker + fallback to a smaller model keeps it up during a provider incident (degraded, not down); and per-request cost traces catch the day someone’s prompt tweak doubles spend. Same product — now it survives contact with real traffic.

Strengths & limitations

  • Strengths — these patterns are the difference between a demo and a service: predictable latency, a cost ceiling, and uptime that survives a provider outage.
  • Limitations — every layer is complexity you must run and debug; a cache serves stale answers if invalidation is wrong; aggressive fallback can hide quality drops (a cheaper model answering silently). Add each layer when a real symptom demands it — not upfront. The right-sized-stack rule applies here most of all.

Sources

3 - Serving Models

The inference layer — whether to self-host, how to make a model fit, how to serve it fast, and how to survive failure.

Goal

Everything between “I have a model” and “my app can call it under load.” The AI API taught you to make one call; AI system design and scaling to production surveyed the system around it. This section is the layer in between — the inference layer — and it is the part of the stack a managed API hides from you until the day you need it.

The layer

flowchart LR
    App[Your app] --> GW[Gateway - routing and fallback]
    GW --> LB[Queue and load balancer]
    LB --> ENG[Serving engine - vLLM or TensorRT or SGLang]
    ENG --> W[Model weights - quantized]
    W --> GPU[GPU or CPU you chose]

Read the diagram right to left and you have the order of this section: you pick the hardware, you make the weights fit it, you put an engine in front of them, you put a queue in front of the engine, and you put a router in front of everything.

In this section

The order is a dependency chain, not a menu — each page assumes the one above it:

#PageThe question it answers
1Local vs cloudShould you self-host at all?
2QuantizationHow do you make the weights fit the hardware?
3Serving enginesHow do you get throughput out of one GPU?
4Load balancing & queuingHow do you go from one replica to many?
5Routing & fallbackWhat happens when a model is slow, expensive, or down?

If you never self-host, read 1 and 5. Page 1 tells you why staying on a managed API is usually right, and page 5 applies to managed APIs unchanged — routing and fallback are the two patterns every production AI app needs regardless of who runs the GPU.

What each layer buys you

LayerLeverTypical gainCost of pulling it
Hardware choiceOwn GPUs vs pay per tokenFixed cost beats per-token above a volume thresholdOps, capacity planning, idle spend
QuantizationNumeric precision of the weights2–4× less VRAM, 1.5–3× faster decodeSome quality loss — must be measured
Serving engineMemory layout and batching5–20× throughput over a naive loopA new system to operate and tune
Queue + load balancerAdmission control across replicasSurvives spikes instead of collapsingAdded latency, more moving parts
Routing + fallbackWhich model answersBig cost savings, no single point of failureBehaviour varies by which model served you

Each row is only worth pulling when the row above it is already tuned. Quantizing a model that a managed API could serve you is a classic case of solving the wrong problem.

Where to go next

Most teams should read page 1, conclude “stay on the API”, implement page 5, and come back to pages 2–4 the year they actually need them.

Sources

  • Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention (2023) — arXiv:2309.06180
  • Frantar et al., GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers (2022) — arXiv:2210.17323
  • Lin et al., AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration (2023) — arXiv:2306.00978
  • Zheng et al., SGLang: Efficient Execution of Structured Language Model Programs (2023) — arXiv:2312.07104

3.1 - Local vs Cloud

Whether to run the model yourself — the three reasons that justify it, and the costs nobody puts in the spreadsheet.

The gate for this whole section.

Goal

Decide honestly whether to self-host an open model or stay on a managed API. This is the most expensive decision in the section, it is usually made for the wrong reason, and every other page here only matters if you answer “self-host.”

The three options

OptionWhat you runWhat you pay forScales by
Managed APINothingTokensSomeone else’s problem
Managed open modelNothing; an open model on a provider’s GPUsTokens, or GPU-hoursProvider autoscaling
Self-hostedWeights, engine, GPUs, the lotGPU-hours, whether or not you use themYou, deliberately

The middle row is the one people forget. Providers serve open weights per-token, which gets you model choice and portability without owning a single GPU. It is the right first step away from a closed API — not a jump straight to your own cluster.

flowchart LR
    Start[Need inference] --> Q1{Must data stay in your network}
    Q1 -->|yes| Self[Self-host]
    Q1 -->|no| Q2{Do you need a custom fine-tuned model}
    Q2 -->|yes| Q3{Will a provider host your adapter}
    Q3 -->|no| Self
    Q3 -->|yes| Managed[Managed open model]
    Q2 -->|no| Q4{Is spend high and steady enough to beat GPU cost}
    Q4 -->|yes| Managed
    Q4 -->|no| API[Managed API]

The three reasons that justify self-hosting

Only three hold up. If your reason is not on this list, it is probably a preference.

  • Data residency — the text legally cannot leave your network. Regulated industries, some government work, some EU data agreements. This is the only reason that is not a trade-off: it is a constraint, and it settles the question by itself.
  • Volume economics — per-token pricing is a rental. Above some steady throughput, owning or reserving GPUs is cheaper. The key word is steady: GPUs bill while idle, so bursty traffic destroys the arithmetic that made self-hosting look good.
  • A model no one will serve you — a fine-tune, a merge, a research model, or one with a licence that keeps it off managed platforms. See Adaptation before assuming you need this.

Reasons that do not justify it: latency (a nearby managed region usually wins), cost at low volume (it never wins), privacy as a feeling rather than a contract term (read the provider’s zero-retention terms first), and “we want control” without naming what you would do with it.

Sizing the hardware

The first number is VRAM for the weights: roughly parameters × bytes per parameter. At FP16 that is 2 bytes each, so a 7B model needs ~14 GB before anything else.

Model sizeFP16INT8INT4
7B~14 GB~7 GB~4 GB
13B~26 GB~13 GB~7 GB
70B~140 GB~70 GB~35 GB

Then add the part that surprises people: the KV cache, the per-request memory holding attention state for every token in flight. It grows with context length and with the number of concurrent requests, and at high concurrency it can rival the weights themselves. A model that “fits in 24 GB” may fit exactly one user.

This is why the next page exists: quantization is how you buy back the headroom, and serving engines is how you stop the KV cache from wasting it.

The costs nobody puts in the spreadsheet

The comparison is usually written as GPU-hours vs token spend, and that is the easy half:

  • Idle time. A managed API costs nothing at 3 a.m. A reserved GPU costs the same at 3 a.m. as at peak. Compare against your average utilisation, not your peak.
  • Ops. Driver and CUDA versions, engine upgrades, OOM crashes at 2 a.m., capacity planning, and a rollback story. This is a standing engineering cost, not a one-off setup.
  • Model upgrades. Providers ship a better model and you change a string. Self-hosted, you re-benchmark, re-quantize, re-tune, and redeploy.
  • The quality gap. Open weights have closed much of the distance, but on the hardest reasoning and tool-use work the frontier closed models are still ahead. Measure it on your eval set before committing.

Strengths & limitations

  • Strengths of self-hosting — data never leaves; fixed, predictable cost at steady high volume; any model you like, including your own fine-tunes; no provider rate limits or deprecation schedule.
  • Limitations — real ops burden; idle GPUs bill anyway; you own every failure; the quality ceiling is whatever open weights offer today; and the break-even point is far higher than most teams estimate, because the spreadsheet usually omits everything in the section above.

Stay on the managed API until you can name which of the three reasons applies to you.

Where to go next

Sources

3.2 - Quantization

Trading numeric precision for memory and speed — FP16, INT8, INT4, and the GPTQ, AWQ, and GGUF formats that implement it.

How a model that needs 140 GB runs on a 48 GB card.

Goal

Understand the one lever that decides whether a model fits your hardware at all, what it costs you in quality, and which of the confusing format names — AWQ, GPTQ, GGUF — you actually need.

What it is

A model’s weights are numbers. Training produces them at high precision; inference rarely needs that precision. Quantization stores each weight in fewer bits — 16 down to 8, or 4 — and dequantizes on the fly during the matrix multiplications.

You get three things at once, and pay for them in one currency:

flowchart LR
    W[Weights at FP16] --> Q[Quantize to fewer bits]
    Q --> M[Less VRAM]
    Q --> S[Faster decode - less memory traffic]
    Q --> C[Cheaper GPU fits the model]
    Q --> L[Some quality loss]

Speed is the part people miss. Token generation is memory-bandwidth bound, not compute-bound: the GPU reads the entire weight set for every token it produces. Halve the bytes and you roughly halve the reading, which is why INT4 decodes faster than FP16 on the same card even though the arithmetic is no simpler.

The precision ladder

PrecisionBitsMemory vs FP16Typical qualityUse it for
FP32322× moreReferenceTraining, almost never inference
FP16 / BF1616baselineThe baseline everything is measured againstThe default serving precision
FP880.5×Near-lossless on modern hardwareNewer NVIDIA GPUs with native support
INT880.5×Very close to baselineThe safe production choice
INT440.25×Noticeable but often acceptableFitting a big model on a small card
INT3 / INT23–20.19× / 0.13×Degrades badlyExperiments, not production

BF16 vs FP16: same 16 bits, split differently. BF16 keeps FP32’s exponent range with less mantissa, so it rarely overflows — it is the safer default where hardware supports it.

The honest shape of the curve: FP16 → INT8 costs almost nothing. INT8 → INT4 is where you start trading real quality, and it hurts small models much more than large ones. A 70B model at INT4 generally beats a 13B model at FP16 on the same VRAM budget — when you must choose, take the bigger model at lower precision.

The three formats

This is the part that confuses people, because the three names are not the same kind of thing.

FormatWhat it isRuns onReach for it when
GPTQA post-training quantization algorithm, layer-by-layer, using a calibration setGPUYou want mature 4-bit GPU support and broad tooling
AWQAn algorithm that protects the ~1% of weights the activations care about mostGPUYou want better 4-bit quality than GPTQ, and fast kernels
GGUFA file format / container, from llama.cpp, holding weights at many quantization levelsCPU, Apple Silicon, GPU offloadYou are running locally, on a Mac, or without a CUDA GPU

So GPTQ and AWQ answer “how were the weights rounded?”; GGUF answers “what file is this, and what runs it?”. Comparing AWQ to GGUF is comparing a method to a container.

AWQ’s idea in one line: not all weights matter equally — a small fraction, identified by looking at activation magnitudes rather than the weights themselves, carries most of the quality, so scale those before rounding and the damage drops. In practice AWQ usually edges out GPTQ at the same bit width, and both are far better than naive round-to-nearest.

GGUF k-quants: inside GGUF you will see names like Q4_K_M or Q5_K_S. Read them as bits · k-quant · size variant — Q4_K_M is 4-bit, k-quant, medium. The k-quants mix precisions across a tensor, spending more bits where they matter. Q4_K_M is the usual recommended default; Q5_K_M if you have the room; below Q4 only if you must.

What to measure

Quantization is the one change in this section that can silently make your product worse, so never ship it on vibes. Before and after, on the same inputs:

  • Your eval set — task accuracy on real queries, not a public benchmark. See Evaluation in practice.
  • Tokens per second at your real concurrency, not single-stream.
  • Peak VRAM including the KV cache under load, not just the weights at rest.
  • Format adherence — quantized models degrade at structured output and tool calling noticeably earlier than they degrade at prose. If an agent depends on clean JSON, test that specifically.

That last point is the practical trap: a 4-bit model that still writes fluent paragraphs may have quietly become unreliable at emitting a valid tool call.

Strengths & limitations

  • Strengths — 2–4× memory reduction turns an impossible deployment into a cheap one; faster decode as a free side effect; INT8 is close to lossless; pre-quantized checkpoints mean you usually download rather than compute anything.
  • Limitations — quality loss is real, task-dependent, and worst on small models, long contexts, and structured output; the format must match your serving engine and GPU; quantizing yourself needs a calibration set and GPU hours; and it does nothing for the KV cache, which is often what actually ran you out of memory.

Where to go next

  • Put an engine in front of the quantized weights → Serving engines.
  • Decide whether you should be self-hosting at all → Local vs cloud.
  • Change the model’s behaviour, not its precision → Adaptation.

Sources

3.3 - Serving Engines

vLLM, TensorRT-LLM, and SGLang — what an inference engine does that a naive loop cannot, and which to pick.

Why the same GPU serves 5 users or 100, depending on the software in front of it.

Goal

Understand what a serving engine actually does, why it is worth 5–20× the throughput of a straightforward generation loop, and how to choose between the three engines that matter.

The two phases of a request

Every generation splits into two phases with completely different performance characters, and almost everything an engine does follows from this split:

PhaseWhat happensBound byCost shape
PrefillProcess the whole prompt at once, fill the KV cacheComputeOne big parallel pass
DecodeEmit one token, append to the KV cache, repeatMemory bandwidthHundreds of tiny sequential passes

Prefill is a sprint; decode is a long walk. During decode the GPU is mostly waiting on memory while its compute units idle — which is exactly the gap an engine fills by running many requests’ decode steps together.

flowchart LR
    R[Request] --> P[Prefill - prompt to KV cache]
    P --> D[Decode - one token at a time]
    D --> D
    D --> Out[Response]

What an engine buys you

Three ideas do most of the work:

  • Continuous batching. Static batching waits for a whole batch to finish before starting the next, so one long generation holds nine short ones hostage. Continuous batching works at token granularity: the moment a sequence finishes, a queued request takes its slot. This alone is the single largest throughput win.
  • PagedAttention. The KV cache used to be allocated as one contiguous block per request, sized for the worst case — wasting most of it. vLLM borrowed virtual memory’s trick: split the cache into fixed-size pages, allocate on demand, share pages between sequences with a common prefix. Waste drops from ~60–80% to a few percent, and that recovered memory becomes concurrency.
  • Prefix reuse. Requests sharing a leading prefix — a long system prompt, a few-shot block, a conversation history — can share its KV cache instead of recomputing it. When your prompts have a big fixed head, this cuts prefill dramatically.

The result is that throughput is mostly a memory management problem, not a math problem. An engine is worth far more than a faster GPU.

The three engines

EngineCore ideaHardwareStrongest atCost
vLLMPagedAttention + continuous batchingNVIDIA, AMD, othersGeneral-purpose serving; the defaultLittle — easiest to adopt
TensorRT-LLMAhead-of-time compiled, hardware-specific kernelsNVIDIA onlySqueezing the last 20–40% of latency out of known hardwareA build step per model and per GPU; rigid
SGLangRadixAttention — a prefix tree over the KV cacheNVIDIA, AMDHeavy shared prefixes: agents, many-turn chat, structured programsNewer, smaller ecosystem

RadixAttention in one line: keep the cached prefixes in a radix tree so any new request automatically reuses the longest matching prefix already in memory, instead of only handling the one prefix you told it to cache. That is why it shines for agent loops, where every iteration resends a long and largely identical context.

Choosing one

flowchart TD
    Start[Need to self-host] --> A{Do requests share long prefixes}
    A -->|yes - agents or long system prompts| SG[SGLang]
    A -->|no| B{Is latency the binding constraint}
    B -->|no| V[vLLM]
    B -->|yes| C{Fixed NVIDIA hardware and one model}
    C -->|yes| TRT[TensorRT-LLM]
    C -->|no| V

Start with vLLM. It is the honest default: broad model support, good throughput out of the box, and the least operational surprise. Move to TensorRT-LLM only when you have measured a latency target you are missing on hardware you control and will not change soon. Reach for SGLang when your workload is prefix-heavy, where it wins by construction rather than by tuning.

The knobs that matter

Whichever engine you pick, the same few dials decide behaviour:

  • Max concurrent sequences — how many requests share the GPU. Too high and per-user latency collapses; too low and the GPU idles.
  • KV cache memory fraction — how much VRAM the cache may claim. Raising it buys concurrency and takes room the weights may need.
  • Max context length — caps the worst-case cache per request. Advertising a 128k window you cannot serve at concurrency is a common self-inflicted outage.
  • Tensor parallelism — split one model across several GPUs when it will not fit on one.

Every one of these is the same trade: more concurrency, worse tail latency. Decide which you are optimising before you touch them, and watch both in observability.

Strengths & limitations

  • Strengths — order-of-magnitude throughput over a naive loop; near-complete recovery of wasted KV memory; OpenAI-compatible endpoints in all three, so your app code barely changes.
  • Limitations — one more system to run, tune, and upgrade; throughput gains come from batching, which raises single-request latency; model and quantization format support varies per engine; and a compiled engine like TensorRT-LLM must be rebuilt for every model and GPU change, which is a real release-process cost.

Where to go next

Sources

3.4 - Load Balancing & Queuing

Going from one replica to many — admission control, backpressure, cache-aware routing, and autoscaling on the right signal.

The front door, and what it does when too many people arrive.

Goal

Keep a fleet of model replicas fast and honest under bursty traffic: decide what to admit, what to queue, what to reject, and which replica each request should go to. This page deepens §Queues and async for the self-hosted case.

Why the usual load balancer is wrong here

A web load balancer assumes requests are short, cheap, and interchangeable. Model requests are none of those:

AssumptionReality for inference
Requests take millisecondsThey take seconds to minutes
Cost per request is uniformA 200-token and a 100k-token prompt differ by 500×
Any replica is equally goodThe replica holding your prefix in cache is far cheaper
CPU shows saturationA GPU pinned at 100% may still have capacity, or none
Round-robin spreads load evenlyIt spreads requests evenly and load terribly

So the interesting decisions move from “pick a backend” to “should this run now, and where.”

flowchart LR
    C[Clients] --> AD[Admission control]
    AD --> Q[Queue]
    Q --> RT[Cache aware router]
    RT --> R1[Replica 1]
    RT --> R2[Replica 2]
    RT --> R3[Replica 3]
    AD --> Rej[Reject fast with retry hint]

Admission control and backpressure

The queue is not a place to hide an overload — an unbounded queue turns a capacity problem into a latency problem, and every request in it eventually times out anyway. Serve work you can finish:

  • Bound the queue. Past the limit, reject immediately with a 429 and a Retry-After. A fast, honest rejection is better service than a request that waits 90 seconds and then fails.
  • Set a queue-time budget. Drop requests that have waited longer than the client will, and stop paying to compute answers nobody is still listening for.
  • Estimate cost before admitting. Prompt tokens are known up front and max_tokens bounds the rest, so you can reject a request that cannot possibly fit your latency target.
  • Separate the queues. Interactive chat and overnight batch should not share a line. Give each its own queue and concurrency budget, or the batch job will starve your users.

Backpressure must reach the caller. If your API accepts everything and silently buffers, clients keep sending and the collapse is just delayed — and worse, invisible until it is total.

Cache-aware routing

This is the one big inference-specific win. Because a serving engine caches KV state for prompt prefixes, routing a request to the replica that already holds its prefix skips most of prefill.

  • Sticky by prefix / session — hash the system prompt or conversation id and send matching requests to the same replica. Enormous for multi-turn chat and agent loops, where each turn resends a nearly identical context.
  • Least-pending, not round-robin — route by each replica’s queue depth and KV-cache occupancy, the metrics that actually reflect load.
  • Keep an escape hatch — stickiness that survives a hot replica becoming overloaded is a bug. Fall back to the least-loaded replica when the preferred one is saturated.

Autoscale on the right signal

GPU utilisation is a poor scaling signal: a decode-bound replica shows high utilisation while mostly waiting on memory. Scale on what users feel:

SignalWhy it works
Queue depth / queue wait timeDirectly proportional to the latency users experience
KV cache occupancyThe real capacity ceiling — when it is full, concurrency stops
Time to first tokenThe user-visible symptom of prefill contention

Two cautions. GPU replicas take minutes to become ready — model download, load, and warm-up — so scale on a leading indicator and keep warm headroom; reactive scaling arrives after the spike is over. And scale down slowly: flapping a GPU pool is expensive in both money and cold starts.

Strengths & limitations

  • Strengths — a bounded queue plus admission control converts a total collapse into graceful, honest degradation; cache-aware routing is close to free throughput on prefix-heavy workloads; queue-depth autoscaling tracks user experience far better than CPU or GPU utilisation.
  • Limitations — every layer adds latency and another thing to operate; stickiness fights even load balancing and needs an override; queue-time budgets and admission thresholds are workload-specific and must be tuned with real traffic; and none of this helps if a single replica is misconfigured — it will just distribute the problem evenly.

Where to go next

Sources

3.5 - Routing & Fallback

Sending each request to the right model, and keeping the app alive when that model is slow, expensive, or down.

The two patterns every production AI app needs — self-hosted or not.

Goal

Stop treating “the model” as one fixed dependency. Route each request to the cheapest model that can handle it, and degrade gracefully when a model is overloaded, rate-limited, or gone. This page deepens §Reliability and applies unchanged whether you self-host or call a managed API.

The gateway

Both patterns live in one place: a model gateway between your app and every model, so that “which model answers” becomes a policy decision rather than a constant scattered through your code.

flowchart LR
    App[App] --> GW[Model gateway]
    GW --> CL{Classify request}
    CL -->|simple| Small[Small cheap model]
    CL -->|hard| Large[Large capable model]
    Small --> V{Good enough}
    V -->|no| Large
    Large --> Err{Error or timeout}
    Err -->|yes| FB[Fallback provider]
    Err -->|no| Out[Response]
    FB --> Out

Build this as a thin internal layer, not a rewrite: one function that takes a request and returns a response, owning the model choice, the retry, and the fallback chain.

Routing — the right model per request

Most traffic does not need your best model. Classification, extraction, routing, summarising, and reformatting are handled well by small models at a fraction of the cost and latency.

StrategyHow it decidesGood forWatch out for
Static by taskThe call site says which modelClear, distinct workloadsDrifts out of date as models change
Escalation / cascadeTry the cheap model, escalate if the answer fails a checkMixed difficulty in one endpointTwo calls when it escalates — the check must be cheaper than the saving
ClassifierA tiny model or heuristic labels difficulty firstHigh volume, wide difficulty spreadThe classifier is now a thing to evaluate
CapabilityNeeds vision, tools, a long context, or JSONMultimodal and agentic appsConfig sprawl

Escalation is the highest-leverage version, and it lives or dies on the check: a grader, a schema validation, a confidence signal, or a retrieval-grounding test. If deciding costs as much as the big model, the cascade has bought you nothing.

Two rules that keep this honest. Route on a measured difference, not a guess — build the routing policy against your eval set, and re-check it when models change. And log which model served each request, or you will be debugging a quality complaint with no idea what produced the answer.

Fallback — surviving failure

Models fail in five distinguishable ways, and they do not want the same response:

FailureRight response
Rate limit (429)Back off and retry, honour Retry-After, then shed to another provider
Timeout / slowCancel and retry once elsewhere — do not stack retries on a struggling endpoint
Server error (5xx)Retry with jitter, then trip the circuit breaker
Content filter / refusalDo not retry blindly — it will refuse again. Surface it or reroute deliberately
Bad output (invalid JSON)Retry once with the error fed back; then fall back to a stricter or larger model

The mechanics that make this safe:

  • Retry with exponential backoff and jitter, capped. Uncapped retries during a provider outage turn one failure into a self-inflicted flood.
  • Circuit breaker. After repeated failures, stop calling that endpoint for a cooldown and fail fast to the fallback. Hammering a dead provider only spends your own latency budget.
  • Hedged requests, carefully. Firing a second call when the first exceeds its p95 cuts tail latency but multiplies cost — cap it to a small fraction of traffic.
  • Idempotency. Retries are only safe if a duplicated call cannot double-charge or double-write. Pass a request key and make tool side effects idempotent, especially inside an agent loop.

Graceful degradation

The last line of defence is deciding what “broken” looks like to the user. In descending order of quality: cached answer → smaller or older model → non-AI path (keyword search instead of RAG, a template instead of a generated summary) → an honest error that says when to come back.

Never let one provider’s outage become a 100% outage. Design the degraded path before you need it, and exercise it — an untested fallback is not a fallback.

Decide in advance which is worse for your users: a slower answer, a weaker answer, or no answer. Every choice on this page follows from that.

Strengths & limitations

  • Strengths — routing often cuts spend substantially with no quality loss on easy traffic; fallback removes the single point of failure; the gateway centralises cost tracking, logging, and model swaps in one place.
  • Limitations — answers now vary by which model served them, which complicates evaluation and reproducibility; cascades add latency when they escalate; every provider added is another contract, prompt format, and behaviour to maintain; and prompts tuned for one model are rarely optimal on its fallback, so quality on the degraded path must itself be measured.

Where to go next

Sources

4 - Building a RAG System

The full production pipeline — every stage, why it’s there, and a concrete example.

Builds on RAG in Foundations. A production RAG system is much more than Documents → Embeddings → LLM. It’s two pipelines that meet at the store — an offline ingest pipeline and an online query pipeline — with a chain of stages in each. The thesis to keep in mind:

Answer quality depends far more on retrieval than on the LLM. The model is the reasoning engine; retrieval is where the engineering happens.

flowchart TB
    subgraph Ingest[Ingest pipeline - offline]
      D[Documents - PDF, scans, HTML] --> P[Parse + OCR] --> M[Extract metadata]
      M --> C[Chunk] --> E1[Embed]
    end
    E1 --> V[(Vector store + keyword index)]
    subgraph Query[Query pipeline - online]
      Q[Question] --> QR[Rewrite query] --> R[Hybrid retrieve + metadata filter]
      R --> F[Fuse - RRF] --> RR[Cross-encoder rerank] --> CC[Compress context]
      CC --> G[Generate + cite] --> CF[Confidence score] --> A[Answer or escalate]
    end
    V --> R

Ingest pipeline (offline)

Runs when data changes, not per request — no model retraining needed.

  • Parse + OCR — turn messy real documents into clean text. Why: if parsing is wrong, everything downstream is garbage. Example: a scanned invoice PDF → OCR extracts the text and a layout-aware parser keeps the table intact, so Total: $4,012 isn’t split from its label. Handle PDFs, Word, HTML, images, tables, and code blocks distinctly.
  • Extract metadata — attach {source, page, section, date, …} to each chunk. Why: it powers filtering and citations — without it you can’t scope “only 2026 Pro-plan docs” or cite a source. Example: {source: handbook.pdf, page: 12, section: "Refunds", date: 2026}.
  • Chunk — split into retrievable passages. Why: chunk size is a top-3 quality lever. Example: recursive chunking that splits on headings then paragraphs, with ~15% overlap so a thought isn’t cut mid-sentence. See chunking strategies.
  • Embed — vectorize each chunk with an embedding model. Use the same model for documents and queries.
  • Store — index vectors (+ metadata) in a vector store and build a keyword index alongside for hybrid search.

Query pipeline (online)

Runs per question — this chain is where most quality is won or lost.

  • Rewrite query — the user’s words are often not the best search query. Why: better query → better recall. Example: “how long to send it back?” → rewritten to “return / refund window policy”; or expanded into several rephrasings. See query transformation.
  • Hybrid retrieve + filter — run vector (meaning) and BM25 (exact terms) together, scoped by metadata. Why: each covers the other’s blind spot. Example: “error E-4012” — vector finds the paraphrased troubleshooting doc, BM25 finds the exact code; the metadata filter limits it to the current product version.
  • Fuse (RRF) — merge the two ranked lists with Reciprocal Rank Fusion into one ordering. Why: combines dense and sparse fairly without hand-tuned weights.
  • Cross-encoder rerank — re-score the top ~50 with a model that reads query and passage together, keep the top few. Why: far more accurate than embedding similarity, so the best passage ranks first. Example: a passage that merely mentions the keywords drops below the one that actually answers the question.
  • Compress context — trim each surviving chunk to just the relevant sentences. Why: cuts tokens and raises faithfulness by removing distraction. Example: a 1,200-token chunk → the 2 sentences that state the refund window. See context compression.
  • Generate + cite — build the augmented prompt, call the model, and cite the chunk each claim came from. Why: citations make answers verifiable and are the antidote to hallucination. Example: “Refunds are within 30 days [handbook.pdf p.12].”
  • Confidence score + escalate — judge how well-grounded the answer is. Why: you need to know when to abstain instead of guessing. Example: low retrieval scores or an answer no chunk supports → return “not confident — escalating to a human” rather than a fluent hallucination. Ties into guardrails and responsible AI.

The components you build

ComponentJob
Ingestion jobParse/OCR → extract metadata → chunk → embed → store (scheduled or on change)
Embedding modelSame model for documents and queries
Vector + keyword storeSimilarity search + BM25 (pgvector)
RetrieverQuery rewrite → hybrid retrieve → filter → RRF → rerank → compress
OrchestratorBuild the prompt, call the model, format citations, score confidence

Getting it right

Most RAG quality problems are retrieval problems, not model problems. Add stages in order of payoff — hybrid search and re-ranking first, then compression and confidence — and evaluate retrieval and generation separately (see Evaluation in practice). Don’t build the whole chain on day one; add each stage when a real failure demands it. At scale, this pipeline also needs caching, queues, and reliability — see Scaling to production.

Sources

5 - Agentic RAG

Retrieval driven by an agent that decides when, what, and how often to retrieve — not a fixed pipeline.

Builds on Agentic AI and Types of RAG. In standard RAG the pipeline is fixed — always retrieve once, then generate. Agentic RAG hands that control to an agent: it decides whether, what, and how often to retrieve, using retrieval as a tool.

Standard vs. agentic

flowchart LR
    Q1[Question] --> R1[Retrieve once] --> G1[Generate] --> A1[Answer]

Standard RAG, above, is one fixed pass. Agentic RAG, below, is a loop the agent controls:

flowchart TD
    Q[Question] --> A[Agent reasons]
    A --> D{Need to retrieve?}
    D -->|no| Ans[Answer]
    D -->|yes| R[Pick query + source, retrieve]
    R --> C{Enough to answer?}
    C -->|no| A
    C -->|yes| Ans

What the agent decides

  • Whether to retrieve at all — some questions don’t need it.
  • What query to use — often a rewrite of the user’s question, or several sub-queries.
  • Which source — different vector stores, a web search, a database, an API.
  • How many rounds — retrieve, read, then retrieve again for a follow-up fact (multi-hop).
  • Whether the context is enough — re-retrieve or ask for clarification if not.

Retrieval becomes a tool the agent calls, not a fixed first step.

A multi-hop question shows the difference: “Does our retention policy allow deleting the audit logs of a churned customer?” Standard RAG retrieves once — probably the retention policy — and answers with half the picture. An agentic loop retrieves the retention policy, notices audit logs are governed separately, retrieves the audit-log policy, then checks the churn-specific clause: three lookups, each shaped by what the last one said.

When to use it

  • ✅ Multi-hop questions — the answer needs a fact that requires a second lookup.
  • ✅ Multiple sources — the agent routes to the right one.
  • ✅ Ambiguous queries — the agent can rewrite, or ask, before retrieving.
  • ❌ Simple Q&A over one corpus — standard RAG is faster, cheaper, and more predictable.

The trade-off

More capable, but more latency, cost, and moving parts — and harder to make reliable (the agent can loop or retrieve poorly). Add guardrails, step limits, and evaluation — especially the retrieval-quality checks in Advanced RAG. Reach for agentic RAG only when standard or advanced RAG genuinely falls short.

Sources

6 - The Agent Harness

The scaffolding that runs an agent — the loop, context management, tool execution, memory, and guardrails.

Builds on Agentic AI. The model is the engine; the harness is everything around it that turns a single model call into a working agent. This page is how one is built.

What the harness owns

flowchart LR
    subgraph Harness
      Loop[Agent loop]
      CtxM[Context manager]
      ToolR[Tool executor]
      Mem[Memory]
      Guard[Guardrails / permissions]
    end
    Harness --> Model[Model API]
    Harness --> Tools[Tools]

The loop

At its core the harness runs one loop until the task is done:

flowchart TD
    In[User goal] --> Ctx[Assemble context]
    Ctx --> M[Call model]
    M --> Dec{Tool call?}
    Dec -->|no| Out[Return answer]
    Dec -->|yes| G[Check guardrails / permissions]
    G --> Ex[Execute tool]
    Ex --> Up[Append result, update memory]
    Up --> Ctx

Each turn: assemble the context, call the model, and if it returns a tool call, execute it, append the result, and loop — until the model answers or a stop condition fires.

The hard parts

  • Context management — the window is finite; as the loop grows you must summarize or trim old tool results, or the run breaks. This matters most on a retry: carrying the whole failed transcript forward wastes the window and re-anchors the model on its own dead ends. Keep the lesson, the current state of the artifact, and the criteria it has to meet — drop the rest.
  • Tool execution — validate arguments, gate risky actions behind approval, run parallel calls, and return errors as results the model can recover from.
  • Memory — carry facts across turns (and sessions) without stuffing everything into the window.
  • Stop conditions — max steps, loop detection, and a token/time budget, so a stuck agent ends gracefully instead of spinning. A real-world set: stop after 20 steps or 100k tokens; stop if the same tool is called with the same arguments twice in a row; on stop, summarize progress instead of failing silently.
  • Guardrails — apply input/output checks and security on every turn, not just the first.

One harness runs one agent’s loop. Designing the loops themselves — validators, closed loops, orchestration of many workers — is the next page: Loop engineering.

Skills — packaged procedures

Beyond tools, mature harnesses support skills: packaged instructions for a specific kind of task (a deploy checklist, a review procedure, a report format) that load into context when that task comes up. Tools give the agent capabilities; skills give it procedures — the difference between handing someone a terminal and handing them the runbook.

Build vs. buy

You rarely hand-write all of this:

  • Write your own loop — full control; the most work. Lab 2 builds one from scratch in eight steps.
  • Use a framework / SDK — the loop, tool handling, and context management come built in.
  • Managed service — a provider hosts the loop and the tool sandbox for you.

Choosing among these is the Tooling & frameworks topic, coming next.

Sources

7 - Loop Engineering

Designing the loop as a system — its parts, its shapes, and when you need an SDK at all.

Goal

Answer the questions a builder actually asks about loops: what is loop engineering, what are its parts, how many loops do I need, how many shapes are there, why is it needed — and do you have to code one on an SDK, or can Claude Code / Codex do it? Each question has its own page; this is the map.

What it is

Loop engineering is designing the iteration itself, instead of doing the iterating. Prompt engineering shapes one model call; the harness runs one agent’s loop; loop engineering designs the system of loops: what repeats, who checks the result, what counts as “done”, and what stops it. In one line: you stop being the person who prompts the agent — you build the thing that prompts the agent.

Crucially, looping is a way of organising a system, not a model. It isn’t a feature you switch on; it’s a pattern almost any agent framework can run, depending on how you wire the pieces. That’s why the paradigm is shifting from Prompt → Output to Goal → Loop → Evaluate → Improve → Repeat → Result — and why both Anthropic and OpenAI now push engineers to build the loop, not just the prompt.

The maturity ladder

Each generation fixed the last one’s failure — this is the shape of the whole field, and the map for the pages below:

flowchart LR
    subgraph P1["1 · Prompt engineering — human drives every iteration"]
      H[Human] --> A1[Agent] --> O1[Output]
      O1 -. feedback .-> H
    end
    subgraph P2["2 · Loop engineering — agent improves its own work"]
      G2[Goal] --> A2[Agent] --> R2[Research] --> D2[Draft] --> E2[Evaluate] --> I2[Improve]
      I2 --> A2
    end
    subgraph P3["3 · Orchestrated looping — teams iterate until done"]
      G3[Goal] --> Orc[Orchestrator - breaks down the goal]
      Orc --> RA[Research agent] & CA[Coding agent] & TA[Testing agent]
      RA & CA & TA --> EV[Evaluation agent - checks quality]
      EV -. next round .-> Orc
    end
    P1 ==> P2 ==> P3
YearLoopLesson it taught
2022ReAct — reason → act → observe, one model, one loopIteration beats one-shot answers
2023AutoGPT — goal-seeking loopFamous for spinning forever → loops need stop conditions
2025Ralph loop — the same prompt re-run against fixed anchor filesPersistent anchors keep long runs coherent
Early 2026Productised loops — a validator decides when work is done“Done” must be checked, not self-declared
Mid 2026Orchestration — a supervisor schedules and coordinates worker loopsOne loop doesn’t scale; teams of loops do

The five pages

PageQuestion it answers
The parts of a loopWhat’s inside a production loop
The four levels of loopsHow many loops you need, and what each one buys
Open vs. closed loopsWhich shape to choose, and when
Fleet loopingHow looping scales to teams of agents
Building a loopOff-the-shelf tool or your own SDK

The two framings compose. Levels tell you how many loops to wrap around the work; the axes below describe each individual loop you end up with — so any loop you meet is a point on three independent axes:

AxisOptionsDetailed in
ArchitectureOpen (explore) vs closed (measured)Open vs. closed
TopologySingle worker vs orchestrated fleetFleet looping
OversightHuman in / on / out of the loopFleet looping

Why you need it

  • One-shot calls cap out — quality comes from iterate-and-verify, and doing that manually makes you the bottleneck.
  • Trust requires a validator — unreviewed agent output doesn’t ship; a loop with a checker turns “plausible” into “verified”.
  • Cost control requires closure — open exploration is unpredictable spend; closed loops with thresholds make cost and quality measurable per run, so each run can be improved.

You stop being the person who prompts the agent — you build the thing that prompts the agent.

When orchestration is warranted, the structure those coordinated loops run on is a graph — see From prompts to graphs for where loop engineering sits in the wider lineage.

Sources

7.1 - The Parts of a Loop

The six components of a production loop — and why the worker is the least interesting one.

What’s inside a production loop.

What it is

A production loop has six parts. The worker — the agent doing the task — is the least interesting one; the parts around it are what turn a demo into something you can trust unattended.

flowchart LR
    D[Discovery - finds work] --> B[Backlog and decomposition]
    B --> W[Worker loop - does the task]
    W --> V[Validator - checks the result]
    V -->|pass| Done[Merge and record]
    V -->|fail, with feedback| W
    S[Stop conditions - rounds, tokens, time] -.-> W
    M[Memory and anchors - skills, project rules] -.-> W

The six parts

  • Discovery / automations — finds work without a human trigger: a schedule, a webhook, a scanner. This is what lets a loop run unattended; see the four levels for the trigger types and where to put them.
  • Decomposition — an orchestrator breaks the goal into tasks a worker can own. See fleet looping when this goes multi-level.
  • Worker — an agent with tools and MCP connectors; parallel workers get git worktrees so they don’t overwrite each other.
  • Validator — a second judgment (LLM-as-judge, a test suite, or both) that decides pass/fail — never the worker grading itself.
  • Stop conditions — max rounds, token budget, loop detection: the AutoGPT lesson, inherited from the harness.
  • Memory & anchors — skills, project rules, and agent memory so each round builds on the last instead of rediscovering it.

Example

A nightly dependency-update loop: discovery is the cron trigger; decomposition splits “update all packages” into one task per package; the worker bumps a version and runs the build; the validator is the test suite; stop conditions cap it at three fix attempts per package; anchors are the project’s upgrade notes so it doesn’t re-learn known breakages. Only the worker is an “agent” — the other five are what make it safe to leave running overnight.

Sources

7.2 - The Four Levels of Loops

Loops nest — each level wraps the one below it and buys one thing the inner loop can’t give you.

How many loops you need, and what each one buys.

What it is

The four levels are not four kinds of loop. They are one loop wrapped four times — each level surrounds the level below it and adds a property the inner loop cannot produce on its own. So the question is never “which loop is this?” but how many do I need?

flowchart TB
    subgraph L4["Level 4 · Hill climbing — the harness gets better"]
      subgraph L3["Level 3 · Event-driven — something starts the run"]
        EV[Event - chat message, schedule, repo hook] --> M
        subgraph L2["Level 2 · Verification — a grader decides what done means"]
          subgraph L1["Level 1 · Agent loop — the work gets done"]
            M[Model] --> T[Tool call] --> O[Observation] --> M
          end
          M --> R[Agent output]
          R --> G{Meets the rubric}
          G -->|no, with feedback| M
        end
        G -->|yes| OUT[Result posted back to the system]
      end
      OUT --> TR[Traces of past runs]
      TR --> AN[Analysis agent - finds the repeating failure]
      AN --> UP[Better prompts, skills, memory]
      UP -.-> M
    end

The four levels

LevelWhat it addsWhat it costsDetailed in
1 · Agent loop — the model calls tools until it decides the task is doneAutomationA model call per stepThe agent harness
2 · Verification loop — a grader scores the result against a rubric and sends failures back with feedbackReliabilityLatency and tokens on every retryOpen vs. closed loops
3 · Event-driven loop — a signal from outside starts the runReach — the agent lives where the work already happensInfrastructure, and the risk of firing on the wrong thingThis page
4 · Hill-climbing loop — traces from past runs feed an agent that improves the harnessImprovement over timeAn eval set you trustSelf-improving agents

Level 2 also changes the economics of level 1. A grader that keeps sending work back is a correctness budget you can spend elsewhere: a cheaper model plus a strict grader often beats the strongest model alone, because the grader catches what the cheap model got wrong and the retries still cost less. You are trading latency for money. See choosing a model for the tier ladder that trade runs on.

Level 3 is the one nobody plans for. A loop nobody starts is a loop nobody uses. The trigger is a schedule, a message in a chat channel, a repository event (a PR opened, an issue labelled), an incoming email, or an alert from a scanner. The rule is to put the trigger where the work already is — an agent that needs people to visit a separate tool is how an internal agent quietly dies.

Example — a docs agent, level by level

The same agent, wrapped one level at a time:

  • Level 1 — it clones the repository, reads the current page, writes a new one, and opens a pull request with the diff. Useful, but somebody has to ask it, and somebody has to check it.
  • Level 2 — a grader now runs before it reports back: no dead links, and CI green. On a fail, the reasons go back to the agent and it tries again. Reviewers stop receiving broken PRs.
  • Level 3 — a message in the team’s #docs-please channel starts the run, and the finished PR is posted back to the same thread. Nobody learns a new tool, so people actually use it.
  • Level 4 — an analysis agent reads the traces of the last hundred runs and notices the same failure repeating: the agent keeps missing the style guide, because nothing ever put it in context. It proposes adding the guide as a skill. That change is itself a pull request.

Levels 1 to 3 automate the work. Level 4 automates the improvement of the thing that does the work — which is why it compounds and the others don’t.

Where the human goes

Automating the loop is not the same as removing the person. Spend human judgment where it changes the outcome, and nowhere else:

LevelWhere the human sitsUse it when
1Approves a sensitive tool call before it runsThe action is irreversible or external — money moves, mail sends, records are deleted
2Is the grader, or reviews what the grader passedThe rubric is still forming, or the signal is too fuzzy to score automatically
3Reviews the finished artifactThe output is a proposal, not an action — a PR, a draft, a plan
4Approves changes to the harness before they mergeAlways, until the eval set is strong enough to merge on a score

Responsible AI owns the placements themselves and the warning that comes with them: a reviewer buried in approvals rubber-stamps, which is worse than no gate at all.

Sources

7.3 - Open vs. Closed Loops

The architecture axis — explore freely, or measure against criteria defined upfront.

The architecture axis — which shape to choose, and when.

What it is

The names come from control theory: a closed loop feeds its output back and corrects against a reference; an open loop runs without that feedback path. For agents:

  • Open loop — the agent gets a goal and freedom: it explores, reasons, and decides its own next steps. There are no predefined success criteria; the run ends when the agent declares itself done or the budget runs out, and a human judges the output afterwards.
  • Closed loop — the goal ships with explicit success criteria and a validator defined before the run. Every iteration is measured against them; failures feed back into the next round; “done” means the threshold was passed, not “the agent felt finished”.
flowchart LR
    subgraph O["Open loop"]
      G1[Goal] --> A1[Agent explores and decides] --> R1[Output]
      R1 --> H1[Human judges afterwards]
    end
    subgraph C["Closed loop"]
      G2[Goal + criteria] --> W2[Worker] --> V2[Validator]
      V2 -->|pass threshold| D2[Done]
      V2 -->|fail + feedback| W2
    end
QuestionOpen loopClosed loop
Who decides the next step?The model, at runtimeThe process, designed upfront
What does “done” mean?Agent self-declares, or budget diesValidator passes a threshold
Cost per runUnpredictableBounded (rounds × budget)
Result across runsVariesRepeatable
Can it improve?Hard — nothing is measuredRun over run — every run is scored
Main riskToken burn, drift, quality by luckA wrong rubric gets enforced at machine speed; solutions outside the frame get missed

When to choose which

Choose open when the problem itself is unexplored: you don’t yet know what “good” looks like, it’s a one-off spike (“figure out why these tests are flaky”, “map this legacy codebase”), and a human will read the output directly. Exploration is the one thing a closed loop can’t do — its criteria would have to exist already.

Choose closed when the task repeats, runs unattended (CI, schedules), spends real money, or its output ships without a human watching every step. Production defaults to closed for exactly those reasons.

They’re stages, not rivals

The two aren’t rivals — they’re stages of the same lifecycle: run the task open a few times to discover the criteria, then freeze those criteria into a validator and close the loop. The autofixer case study went exactly this way: the first fixes were exploratory and hand-reviewed; once the review rubric stabilised, it became the reviewer agent’s rubric.

Open to explore, closed to operate — a task that repeats enough deserves to be closed.

Sources

7.4 - Fleet Looping

How looping scales from one self-correcting agent to a coordinated team — and who watches it.

The topology and oversight axes — scaling looping up.

What it is

At the simplest level, one agent loops on its own work: research → draft → evaluate against the goal → fix the weak spots → repeat until it’s good enough. You no longer prompt each step; the agent runs the loop for you.

Fleet looping is that same idea at scale. An orchestrator takes the overall goal and breaks it into parts; it hands each part to a specialist agent; each specialist can further delegate narrower work to its own sub-agents. The whole task tree keeps cycling through four phases until the goal is met:

flowchart TB
    G[Goal] --> Orc[Orchestrator]
    Orc --> S1[Specialist - research] & S2[Specialist - build] & S3[Specialist - test]
    S1 --> A1[sub-agent] & A2[sub-agent]
    S2 --> A3[sub-agent] & A4[sub-agent]
    subgraph Cycle["Every node cycles"]
      Dc[Discover] --> Pl[Plan] --> Ex[Execute] --> Vf[Verify]
      Vf -. not done .-> Dc
    end

If a single self-looping agent is one person endlessly revising their own draft, a fleet is a whole team running a project end to end. You define the goal; the system runs until it meets the criteria.

The two axes it introduces

Fleet looping is where two of the three loop axes come alive:

  • Topology — single loop (one worker; simpler and usually enough) vs orchestrated (a supervisor plus specialised workers). Orchestrate only when tasks genuinely parallelise or need separate maker and checker roles — a fleet multiplies both cost and failure modes.

  • Oversight — how far you step back:

    • Human in the loop — approves each step (highest control, lowest throughput).
    • Human on the loop — monitors and intervenes on exception.
    • Human out of the loop — reviews outcomes only.

    This is the same ladder as responsible AI’s placements, applied to loops: you graduate from sitting inside one loop to designing loops that watch other loops.

Why it needs discipline

A fleet without evaluation gates at each phase produces confident AI slop at scale — many loops amplifying a bad rubric faster than any human can catch it. The gate (a validator) is what keeps a fleet’s output above the “meets the standard” bar. That’s why most tasks still deserve one worker and a schedule, not a fleet: orchestration is a cost you pay only when the work truly parallelises.

Example

“Publish a launch article.” The orchestrator spawns a research specialist (which delegates sub-agents to gather sources and competitor pages), a drafting specialist, and an editing specialist that acts as the evaluation gate. Each cycles discover → plan → execute → verify; the editor rejects drafts that miss the brief, feeding notes back — until the piece clears the bar. One goal in, a finished article out, no human writing a single prompt per step.

Sources

7.5 - Building a Loop

Off-the-shelf coding agent or your own SDK — and a real closed loop, taken apart.

How you actually build one — and a worked example.

SDK, or Claude Code / Codex off the shelf?

The honest answer: start with the tools — you already own a production-grade loop. Claude Code and Codex are loop products: harness, tools, skills, MCP, stop conditions all built in. There’s a ladder, and each rung must be earned:

  1. Use the tool interactively — you are the orchestrator. Fine for daily work.
  2. Script the tool — run it headless in CI on a schedule with a fixed prompt, skills, and MCP servers. This is already loop engineering — no SDK, and it covers most closed-loop automation (nightly triage, lint-fix sweeps, doc updates).
  3. Code on an SDK (Agent SDK, LangGraph, Microsoft Agent Framework) only when the loop needs what a tool can’t give you: custom topology (a fixer and a reviewer with different models talking to each other), your own validator logic and thresholds, or the loop is your product and needs its own UI, state, and versioning.

Rule of thumb: if your loop is one worker + a schedule, script the tool you have. If it’s several roles negotiating, that’s when an SDK earns its complexity.

Case study — a static-analysis autofixer

A real closed loop I built when security scans (SonarQube) started piling up minor issues faster than humans cleared them:

flowchart LR
    Cron[Nightly schedule] --> Fix[Fixer agent - Sonnet]
    SQ[SonarQube MCP] --> Fix
    Fix -->|classify, label, patch, PR| Rev[Reviewer agent - Opus, judge with rubric]
    Rev -->|pass| PR[PR ready for humans]
    Rev -->|fail + feedback| Fix
    Lim[Hard limit - N rounds] -.-> Fix

A fixer (Sonnet) pulls issues via the SonarQube MCP server, classifies and labels them, patches the safe ones, and opens a PR. A reviewer (Opus) judges the patch against a rubric; on fail it feeds the reasons back to the fixer — at most N rounds (the hard limit), then it stops rather than spins. The whole thing runs on a schedule in GitHub Actions, orchestrated with an agent framework plus skills (guidelines, incremental-implementation, sonar-guardrails).

Every axis shows up: closed loop, human on the loop (they review PRs, not steps), orchestrated topology — and it only needed an SDK because two different models negotiate; the discovery half could have been a scripted coding agent.

Strengths & limitations

  • Strengths — throughput without a human bottleneck; a validator makes quality enforced, not hoped for; closed loops give you a cost ceiling and improve run over run; the maker–checker split catches what self-review can’t.
  • Limitations — validators can be gamed or wrong (judge bias — calibrate against human labels); loops amplify a bad prompt or rubric at machine speed; orchestration multiplies cost and failure modes — most tasks still deserve one worker and a schedule, not a fleet.

Sources

8 - From Prompts to Graphs

Five “engineering” disciplines in five years — what each one added, and why the names keep changing.

Goal

Make sense of the vocabulary explosion: prompt → context → harness → loop → graph engineering, five terms in about five years. This page places them on one timeline, gives one worked example per era, and shows the structural line that separates them — so the next new “-engineering” term lands in a mental model instead of adding to the confusion.

The one distinction that organizes all five

Each discipline exists because the previous one hit a wall. But they split cleanly into two groups:

flowchart LR
    subgraph Single["Single agent — stacked layers"]
      P[Prompt · 2022] --> C[Context · 2025] --> H[Harness · Feb 2026]
    end
    subgraph Multi["Coordination — many loops"]
      L[Loop · Jun 2026] --> G[Graph · Jul 2026]
    end
    H --> L
  • Prompt, context, harness are three layers of the same single-agent problem — how one model gets the right instruction, the right knowledge, and the right guardrails.
  • Loop and graph are about coordination — how work repeats and how multiple agents divide it. A graph is just what a loop becomes when one loop isn’t enough.

That’s the whole map. The rest of this page is what each layer adds.

What each era added

Read this as a ladder — every rung solves a failure the rung below couldn’t:

EraDisciplineWhat it addsThe failure it fixes
2022PromptShaping one exchange—
2025ContextEverything the model knows beyond the promptA perfect prompt still can’t add knowledge the model lacks
Feb 2026HarnessConstraints and gates around the agentA good prompt won’t stop an agent from rm -rf-ing your repo
Jun 2026LoopThe plan–execute–verify cycle and what counts as doneOne call can’t check and fix its own work
Jul 2026GraphMany loops wired via nodes, edges, shared stateOne sequential loop stalls on work that needs parallel, specialized roles

Prompt engineering — shaping one exchange

“Summarize this contract in five bullet points; use only the text provided.” You are tuning the single instruction. This is the whole game when the model already knows what it needs and the task is one turn.

Wall: the model can’t answer about your documents — no prompt contains knowledge the model was never given.

Context engineering — managing what the model knows

You assemble everything around the prompt: retrieved documents (RAG), memory, tool definitions, session history — and, just as important, what to leave out so the context window stays lean. Example: a support bot answers about this customer’s plan because context engineering put the account record and the relevant policy in the window.

Wall: now the agent can act (edit files, call APIs) — and nothing stops it from acting wrongly at scale.

Harness engineering — constraints and gates

The harness is the scaffolding that keeps an agent in bounds: permissions, sandboxes, approval gates, tool allow-lists. Example: a coding agent may edit files freely but a gate blocks shell deletes and requires human approval before it merges. A good prompt is a request; a harness is an architectural stop — the agent can’t cross the line even if it decides to.

Wall: a single pass is rarely right; quality needs iterate-and-check.

Loop engineering — the repeat cycle

Design the plan–execute–verify loop: what triggers each step, who validates the result, what counts as done, and what stops it. Example: the SonarQube autofixer — a fixer patches, a reviewer judges, feedback loops back, bounded by a hard limit.

Wall: one loop, running sequentially, chokes when a job needs different specialists or parallel work.

Graph engineering — wiring many loops together

When one loop isn’t enough, you model the work as a graph: nodes (agents or steps), edges (what flows to what, including conditional branches), and shared state (what every node can read and write). A supervisor no longer does the work — it routes.

flowchart TB
    In[Goal] --> Plan[Planner node]
    Plan --> R1[Retriever node A]
    Plan --> R2[Retriever node B]
    R1 --> W[Writer node]
    R2 --> W
    W --> Crit{Critic node - good enough?}
    Crit -->|no| Plan
    Crit -->|yes| Out[Answer]
    State[(Shared state)] -.-> Plan & R1 & R2 & W & Crit

Example: a research assistant where a planner splits the question, two retriever nodes run in parallel against different sources, a writer merges, and a critic node loops back on a conditional edge until the answer passes. Each node is its own small loop; the graph is the wiring.

This is where multi-agent systems and the “orchestration” rung of loop engineering meet: graph engineering is the structure that orchestration runs on. Notably, the idea isn’t new — frameworks like LangGraph modeled nodes/edges/state before the term “graph engineering” existed, which is the tell that some of this is new vocabulary for existing architecture.

Don’t confuse this execution graph (nodes = agents/steps, edges = control flow) with a knowledge graph (nodes = entities, edges = relations) used as shared agent memory — same word, different graphs; see Multi-agent systems.

Layers vs. renamed eras — a caution

Two of these transitions are real new architecture; some are mostly naming. Harness → loop → graph appeared in about five months — a pace that says as much about marketing as about engineering. The useful reading:

  • Genuinely distinct: prompt, context, and harness stack — a real system does all three at once, they’re not alternatives.
  • Closely related: loop and graph are the same coordination idea at different scales — one cycle vs. many wired together.

So when the next “-engineering” term arrives, ask: is this a new layer of the single-agent problem, a new scale of coordination, or a new word for something the frameworks already do? That question is the durable takeaway; the labels will keep changing.

How they stack in one real system

They aren’t a menu — a production agent uses all of them at once:

LayerIn a coding agent
PromptThe task you type
ContextThe files, history, and docs it’s given
HarnessIts permissions, sandbox, approval gates
LoopEdit → run tests → fix, until green
GraphA planner delegating to coder + reviewer + tester sub-agents

Sources

9 - AI Code Structure

How to organize an AI application codebase — prompts, tools, retrieval, evals, and a thin orchestrator.

An AI app has more moving parts than a normal service — prompts, tools, retrieval, guardrails, evals. Cramming them into one file makes them impossible to test or change. A little structure keeps each concern separate and swappable.

A suggested layout

app/
├── prompts/          # versioned prompt templates (not inline strings)
├── tools/            # tool definitions + handlers, one per tool
├── retrieval/        # ingestion + query: chunk, embed, vector store
├── orchestrator/     # the harness: assemble context, run the loop
├── guardrails/       # input/output checks, PII redaction
├── evals/            # eval sets + runners (run in CI)
├── observability/    # tracing, logging, metrics
├── clients/          # model API client(s)
└── config/           # settings, model ids — no secrets in code

How the pieces depend

flowchart TD
    Orch[Orchestrator] --> Prompts[Prompts]
    Orch --> Tools[Tools]
    Orch --> Retrieval[Retrieval]
    Orch --> Guard[Guardrails]
    Orch --> Client[Model client]
    Evals[Evals] -. test .-> Orch
    Obs[Observability] -. wrap .-> Orch

Principles

  • Prompts are files, not string literals — version them, diff them, test them (see Prompt engineering).
  • One tool = one module — a definition + a handler you can test in isolation (see Tool & function calling).
  • Keep retrieval separate — the ingest and query pipelines are their own layer, not tangled into the orchestrator.
  • A thin orchestrator — the harness just wires the pieces together; keep logic in the pieces.
  • Evals are first-class — an eval set is your test suite; run it in CI on every prompt or model change.
  • Config and secrets out of code — model ids and settings in config; secrets in the environment, never in prompts or the repo.

Why it pays off

When retrieval quality drops, you swap models, or a prompt regresses, you change one place — and your evals tell you whether it worked, instead of hunting through a monolith.

Sources

10 - Tooling & Frameworks

The ladder from writing your own agent loop to a fully managed one — SDKs, frameworks, MCP, and deployment.

Expands the “build vs. buy” note from The agent harness. You rarely build an agent from scratch — there’s a ladder from write everything to a provider runs it for you.

Four ways to build an agent

ApproachYou writeHarness & hostingReach for it when
Manual loopthe reason → act → observe loop yourselfyou build + you hostyou want total control, no dependency
SDK tool runnerjust your tool functionsSDK runs the loop; you hosta custom-tool agent without hand-writing the loop
Agent SDKa prompt + configSDK is a full harness with built-in tools; you hosta batteries-included coding / file agent on your infra
Managed serviceagent config + tool resultsprovider runs the loop and hosts a sandboxyou want no infra: hosted, stateful, scheduled

Concrete examples: the Anthropic API SDK’s Tool Runner (client.beta.messages.tool_runner) is a tool runner; the Claude Agent SDK is an Agent SDK (Claude Code packaged as a library); Anthropic Managed Agents is a managed service.

Don’t confuse: Tool Runner vs. Agent SDK

They sound alike but differ:

  • A tool runner is part of the model API’s SDK. It loops over tools you define — no built-in tools, no filesystem, you host the compute.
  • An Agent SDK (e.g. the Claude Agent SDK) is a full agent harness with built-in tools (read, write, edit, bash, search), context management, and subagents.

Agent frameworks

LangGraph and the Microsoft Agent Framework (MAF) are provider-agnostic orchestration libraries — you compose steps, state, and multi-agent flows, and can swap the underlying model. Use one when you want portable orchestration across models and tools rather than one vendor’s agent.

MCP servers

Whatever you build on, MCP lets it connect to tools and data through a standard interface — connect to an existing MCP server instead of hand-wiring each integration. Most SDKs and managed services can use MCP servers.

Deployment

  • Self-host — you run the loop in your own server / container and own scaling, retries, and state.
  • Managed — the provider hosts the loop and a per-session sandbox, and can run agents on a schedule.

How to choose

flowchart TD
    Start[Need an agent] --> Q1{Want a provider to host it?}
    Q1 -->|yes| Managed[Managed service]
    Q1 -->|no| Q2{Need a batteries-included coding / file agent?}
    Q2 -->|yes| SDK[Agent SDK]
    Q2 -->|no| Q3{Just custom tools, minimal code?}
    Q3 -->|yes| TR[SDK tool runner]
    Q3 -->|no| Manual[Manual loop]

Prefer the simplest option that fits — most custom-tool agents are a tool runner. Reach for a framework or a managed service only when you need what it adds.

Sources