The harness: The model in the loop
Between the frozen model and the product you use sits a layer of ordinary software: the hidden system prompt, the code that parses tool calls, the retrieval pipeline, the loop that decides when to stop. Engineers call it the harness, and it has a claim to being the most consequential code in the stack, because it’s the only part that can change after training. The weights froze months ago (Chapter 7), and Chapter 3 ended by programming the distribution they emit with sampling’s knobs. Everything else a product does — remember your conversation, search the web, run your code — is the harness, shipping on a weekly release cycle around an artifact that can’t change:
This chapter climbs from the smallest intervention to the full loop:
- Scratch space: chain of thought — buying computation with tokens.
- Voting: self-consistency — buying reliability with repeated samples.
- Guaranteed formats: structured output — masking the distribution so malformed output is impossible.
- Executable tokens: tool calls — the model reaches the world through your code.
- Retrieval: the search tool so common it became its own pattern.
- The closed loop: agents — and the two disciplines they forced into existence, context engineering and security.
Chain of thought: buying compute with tokens
Chain-of-thought prompting began as a curiosity (ask the model to “think step by step” and accuracy on math jumps). Chapter 3 explains why it works: a transformer spends a fixed forward pass per token, so the only way to get more computation on a hard problem is more tokens. The chain of thought is scratch space: intermediate state serialized into the context, where attention can retrieve it.
The idea has climbed a long ladder in four years, and you’ve seen every rung. It began as a prompt trick (2022): literally appending “think step by step” to the prompt made accuracy jump, no training involved. Then post-training absorbed it (Chapter 8): models trained on verifiable rewards (RLVR) discovered extended reasoning on their own (double-checking, backtracking), and thinking-before-answering became a trained-in behavior you no longer have to ask for. By 2025 it had become a product with a price tag: reasoning models bill for their thinking tokens, which means you now buy accuracy with inference compute directly — this is the “third scaling axis” Chapter 4 promised when model size and data ran out of road. One caution to carry over from Chapter 6: interpretability research has caught models whose written reasoning diverges from the mechanism that actually produced the answer, so read the transcript as scratch work: evidence, not an audit log.
The cheapest upgrade on top of it is self-consistency: sample several chains of thought at some temperature and take the majority final answer. Concretely: give a math word problem to the model five times at temperature 0.7. Three chains take different routes (one computes the unit price first, another scales up a ratio) and all land on **10; one misreads the question and says 12. The trick works because correct reasoning is an attractor: right answers coincide, while mistakes scatter (the 18 don’t reinforce each other). You’re climbing Chapter 9’s pass@k curve without the verifier that normally checks which one; a tally suffices. The original paper lifted grade-school-math accuracy by ~18 points with nothing but 40 samples and a vote. The one requirement is a short, extractable final answer to tally, like a number or a multiple-choice letter; no two chains produce the same essay, so for open-ended output, heavier members of the same sample-and-select family take over — sample several, have a model judge the best.
Structured output: sampling with a seatbelt
You want JSON matching a schema; the model wants to emit prose. Prompting harder helps only statistically. The robust fix is constrained decoding: compile your schema or grammar into a token-level automaton, and at each step mask the logits of every token that would violate it — set them to , and the softmax renormalizes over what’s legal:
The model’s distribution proposes; your grammar disposes. Malformed output becomes impossible: this is what “JSON mode” and schema-enforced APIs do under the hood. (APIs also expose the raw lever as logit_bias, a per-token nudge or outright ban you set by hand — the manual version of the same mask.) The distribution is an interface, and you’re allowed to program against it. (Same interface powers observability: the logprobs an API returns are a per-token confidence channel — poor at calibration (a 70%-probability token isn’t right 70% of the time), but a fine anomaly detector: a sudden dip in per-token confidence often marks a span where the model is guessing.)
One honest caveat: a careless grammar is a fabrication machine. The mask is applied token by token, blind to where the model was going: when it forbids the model’s preferred token, the renormalization promotes tokens the model ranked low — and everything after must continue a prefix the model would never have written, Chapter 3’s autoregressive original sin, now self-inflicted. The sharpest version is a schema that requires a value the model doesn’t have. If the field email must match an email pattern and the model’s honest next tokens were null or "unknown", the mask forbids honesty — so the model fabricates a syntactically perfect address, indistinguishable from a real one. The grammar didn’t just permit the fabrication; it mandated it (Chapter 8’s hallucination, now with the grammar holding the pen). And the tax is measurable beyond corner cases: Let Me Speak Freely? found reasoning accuracy declining as output-format constraints tighten.
The craft follows from the mechanism: give schemas escape hatches (nullable fields, an "other" enum option, somewhere to express uncertainty), and let the model finish thinking before the mask arrives. Reason in free prose first and extract with the grammar in a second pass, or simply put a scratchpad field first in the schema so the constrained part comes last. Constrain the envelope and leave the thinking inside it free.
Tool use: tokens as system calls
The model can’t browse, compute, or query your database. It can only emit tokens — so the stack made tokens executable. Function calling: describe your APIs in the prompt. The model (post-trained specifically for this — Chapter 8’s fingerprints) emits a structured call like {"name": "get_weather", "arguments": {"city": "Paris"}}. Your code, not the model, executes it. The result is appended to the context. Generation resumes, now conditioned on real data.
The harness writes the tool schemas into the context through the chat template (Chapter 8), usually as a block in the system prompt. The model’s call comes back as ordinary tokens in a reserved format, which the harness parses and validates — the constrained decoding above can guarantee the call parses, by masking any token that would break the schema. The result goes back in as a new message, attributed to the tool rather than to either party in the conversation.
Squint and it’s a syscall interface: an untrusted process (the model) requests privileged operations from a runtime (your code) that mediates everything. The model never does anything — it writes requests, and the blast radius is exactly what your runtime chooses to honor.
Retrieval: the standard answer to frozen weights
Retrieval-augmented generation (RAG), the most deployed pattern of the era, is the tool loop above with a search tool. The pipeline, end to end: split your documents into chunks and embed each one as a vector, offline; at query time, embed the question, fetch the nearest chunks, and paste them into the context, so the model answers from retrieved text rather than frozen memory:
Two design decisions follow from the mechanism. Chunking is a real choice: a few hundred tokens per chunk — large enough to carry meaning, small enough that several winners fit in the context (and you pay prefill on every retrieved token). And a reranker (a second pass that re-sorts the fetched chunks before they’re pasted in) exists because embedding search is blind to the pairing: each chunk’s vector was computed before anyone knew the question, so a second model that reads query and chunk together catches matches that geometry alone misses — a precision pass stacked on a recall pass. (The jargon, if you shop for these: the embedding model is a bi-encoder, the reranker a cross-encoder.)
Fine-tune for behavior, retrieve for knowledge (Chapter 8’s advice, now with its mechanism). Retrieval is also the standard answer to the knowledge cutoff: the weights froze when pre-training ended, and everything the world has done since reaches the model only through its context.
Agents: the loop, closed
Put everything above in a while loop and you have an agent: model proposes an action (ReAct established the reason-act-observe cadence; Toolformer showed models could learn tool use), runtime executes, observation enters the context, repeat until done:
One turn of a coding agent, concretely: the context holds the task and the transcript so far. The model emits a call to run the test suite; the runtime runs it and appends forty lines of failures. The model reads them and emits an edit to one file. The loop is tool use, iterated — but Chapter 9’s compounding arithmetic now governs everything. If any single unrecovered error derails the run, twenty steps at 95% each complete of runs: barely one in three.
That’s the whole trick — the coding agents and computer-using assistants of 2026 are this loop plus enormous post-training investment in not derailing over long horizons.
Context engineering: the window is the memory
The discipline agents spawned is context engineering: the context window is the agent’s entire working memory, and curating it — what to retrieve and summarize, what to evict — is the systems half of agent quality.
Picture the window at turn forty of a coding session: the system prompt and tool schemas at the top, then a transcript of every action and observation since the start — file contents, compiler errors, search results, diffs — each one permanent, because the window is append-only in spirit and finite in fact. When it fills, the standard move is compaction: summarize the older turns and evict the originals. Compaction is lossy by design — any detail the summary didn’t carry forward is gone, and the agent has no way to notice the absence. Long-horizon failures are regularly memory failures wearing a different jacket.
Two systems notes tie the loop back to Chapter 11’s serving economics. Transcripts are wildly prefix-heavy, so Chapter 11’s prefix cache makes the append-only pattern cheap: each turn pays prefill only on what’s new, but editing the middle of the context invalidates the cache and repays the whole prompt. And when a subtask would flood the window (read forty files, summarize each), harnesses spawn a subagent: a fresh context that does the work and returns only its conclusion — working memory forked, used, and discarded, so the parent’s stays clean.
Prompt injection: the unsolved problem
The security discipline agents demand is less mature. Prompt injection: instructions and data share one channel, the context, so any text an agent reads (a webpage, an email) can try to reprogram it, and an agent with tools turns that into real-world side effects. (Keep it distinct from jailbreaking — a user talking the model past its own refusal training. A jailbreak attacks the model’s character, and the user is the attacker. Injection attacks your application through content it reads, with your user as the victim — and unlike jailbreaking, it gets worse the more useful you make the agent.) There is no reliable fix yet; Simon Willison’s running series is the essential literature. Design like it’s the ’90s web, when every input was a potential attack:
- Least privilege.
- Human confirmation on irreversible actions.
- Never let untrusted input and powerful tools share a context without a plan.
The harness gets eaten
Look back at chain of thought’s ladder, because it’s the pattern for the whole layer: a harness trick (a prompt, 2022) became a trained-in behavior (RLVR, Chapter 8) became a product (reasoning models, 2025). Tool use ran the same course — Toolformer taught a model to call tools from examples, and today the behavior is installed by post-training as a matter of routine. Much of 2024’s agent scaffolding (plan-then-execute scripts, hand-tuned retry logic) has already dissolved into the weights of 2026’s models. The harness, it turns out, is where capabilities get prototyped in software before training absorbs them.
So build the harness knowing the model will eat it, and notice which parts it can’t digest: the tools themselves, your private data, and the permission boundary — no amount of post-training gives the weights your production credentials. The durable harness is the runtime; the clever prompting around it is a lease.
From pixels of handwritten digits to agents running your shell, every layer of the stack is now built from parts you understand. What remains is to step back: what it all adds up to, what’s conspicuously still broken, and where the people who build these things are pointing next. A short epilogue on where this leaves you.
Further reading
- Chain-of-Thought Prompting Elicits Reasoning in Large Language Models — the trick that became a paradigm.
- ReAct and Toolformer — the agent loop’s founding documents.
- Prompt injection — Willison’s series; required reading before you ship an agent with tools.
- State of GPT — Karpathy’s full-pipeline talk; a fine 40-minute recap of this entire book.