llm.guideChapter 13Prompt Engineering as Engineering

Prompt Engineering as Engineering

Few-shot, chain of thought, decomposition, and prompts as tested code.

Part 3: Building with LLMs. 10 sections, about 15 minutes.

Writethe prompt, as a fileRunon a fixed test setReadthe failuresChangeone thingcomparewith the last versionAn illustrative run of the loopv341/509 failures read: 6 date formats, 2 refusals, 1 tonev447/50one change: an example with an ISO dateChange one thing at a time, and keep the test set fixed,so the difference means something.
Writethe prompt, as a fileRunon a fixed test set: v3 41/50Read9 failures: 6 are date formatsChangeone thing: an ISO-date exampleComparev4 47/50, no slice worse
The working loop of prompt engineering, with an illustrative run. Reading the failures, highlighted, is what separates it from guessing.

Prompting has a reputation problem. To some it is a bag of magic phrases, and to others it is not engineering at all. Both views miss what a prompt is: the entire input to a system whose behavior you are responsible for. It deserves what any such input gets, which is a design, a version history, tests, and a clear idea of what it cannot do.

This chapter gives each technique a mechanism, so that you can predict when it will help. Its experiments use the small models from earlier chapters, and its claims about current models follow the providers’ own prompting guides as of November 2026.

13.1What a prompt is

The condition that shapes a probability distribution.

A model computes the probability of the next token given everything before it (section 2.1). The prompt is that “everything before it.” Writing a prompt is choosing the tokens that make the continuation you want the most probable one. That single idea removes both the superstition, since no phrase is magic, and the dismissal, since steering a distribution precisely is real work.

A production prompt has recognizable parts:

Rolewho the model is acting asRulesconstraints, stated positivelyOutput formata schema, or an example of the shapeExamplesa few worked casesContextretrieved documents, tool resultsTaskthe user’s actual questionStable:the same on everycall, so cacheablePer request:changes each call,so it goes last
Figure 13.1 The parts of a prompt, in the order that keeps the stable parts first so they can be cached (section 11.6).

The order serves two purposes. Stable parts first makes the prefix cacheable (section 11.6). And when the context is long, placing the documents above the question, with the question last, measurably improves answers; providers document this for their own models.

Each part has a mechanism, a cost in tokens on every request, and a way of failing that you can test for. The rest of the chapter takes them one at a time.

Common take“I found a prompt that works.”

Sharper take“A prompt is an interface to a component that behaves statistically. I design it, version it and test it like any other interface, and I can say what each line is for.”

13.2Clarity

Write for a capable colleague who has no context.

Most weak prompts are not missing a trick. They are missing information. A useful test is to hand the prompt to a capable colleague who knows nothing about the project and ask whether they could do the task from it. What they would need to ask is what the model lacks.

  • Say what you want, specifically. “In two or three sentences” works; “concisely” leaves the model to guess your meaning of the word. The same goes for tone, format and level of detail.
  • Give the reason. “Replies are read aloud by a screen reader, so avoid tables” does more than “no tables”, because the model can apply the reason to cases the rule did not list.
  • State instructions positively. “Discuss only Acme products” is safer than “do not mention competitors”, which puts the unwanted subject into the context.
  • Define done. Say what a good answer contains and what to do when the request cannot be met.

Common take“The model ignored my instructions.”

Sharper take“Usually it followed them and they were ambiguous. I reread the prompt as someone with no context, and the gap is nearly always visible.”

13.3Examples

Demonstration constrains more tightly than description.

A language model completes patterns before it follows instructions. Show it three inputs with their outputs, and the most probable continuation of a fourth input is a fourth output in the same pattern. No weights change; the examples are conditioning. This is called few-shot prompting, and it is one of the most dependable techniques there is.

ApproachPromptTypical output
Instruction only“Classify the sentiment. Be concise.”“The sentiment of this review appears to be mostly positive, because…”
With examples“Great product” → positive
“Broke in two days” → negative
“It’s fine, I guess” → neutral
“Amazing quality!” →
positive

The instruction describes the mapping. The examples demonstrate it, including the exact form of the answer. Four things are worth knowing about choosing them.

  • Cover the range. Three to five varied examples is a good default. If every example is positive, the model leans positive.
  • Order has an effect. The last example tends to pull hardest. Put a hard case there on purpose.
  • Show the edge cases. One demonstrated “ambiguous → neutral” does more than a paragraph defining ambiguity.
  • Examples are rent. Five examples of 300 tokens are 1,500 tokens on every request. Keep them in the stable part of the prompt so they are cached.

Common take“I’ll add another paragraph explaining the format.”

Sharper take“I’ll show three examples of the format. A demonstration pins the output down in a way a description can’t.”

13.4Structure and formatting

The mechanics that matter and the folklore that does not.

TechniqueWhy it works
Delimiters or tags around each kind of content, such as <document>…</document>An unambiguous boundary between instructions and material to be processed. It is also the first, and weakest, defense against instructions hidden in that material (Chapter 26)
Long material first, the question lastThe model attends best to the start and end of a long context (section 2.4)
Show the output formatAn example of the output is a pattern; a description of it is a hope. For anything a program reads, use a schema (section 11.4)
Write the prompt in the style you want backA prompt full of bullet points invites bullet points; plain paragraphs invite prose
Sequential steps as a numbered listOrder and completeness are explicit

The same structure serves controls in an interface. A dial for tone, or a phrase the user has pinned, can be passed to the model as labeled lines ahead of the text, which keeps each control separate, testable and easy to log:

KEY PHRASES
a brass [key]
CONTROLS
tone: wondrous
tension: strained
STORY SO FAR
...

Section 30.10 has a demo of dials built this way.

Then there is the folklore: offering a tip, claiming that a job depends on the answer, threats, capital letters. Where such effects have been measured they are small and unstable from one model to the next. Heavy emphasis can now do harm: current models follow instructions closely, so a rule shouted in capitals for the benefit of an older model may be applied more broadly than you meant.

The test for any technique is the one from the top of this chapter. If you cannot say what mechanism it relies on, and it does not improve the score on your test set (section 13.8), it does not belong in the prompt.

Common take“I added ‘this is VERY IMPORTANT’ and it seemed better.”

Sharper take“I can justify each line of my prompt with a mechanism and a test result. Emphasis without evidence comes out.”

13.5Chain of thought

Buying serial computation with output tokens.

Section 10.2 gave the mechanism. A transformer does a fixed amount of computation per token, and a problem that needs more sequential steps than that cannot be solved in one pass. Asking the model to write out intermediate steps gives it more passes and a place to keep results.

"23 × 47 = "                 one pass must hold the whole product: often wrong
"23 × 47, step by step:"     "23 × 40 + 23 × 7"     a later pass reads this
                             "= 920 + 161"          and then this
                             "= 1081"               an easy last step
It helps withIt does not help withBecause
Multi-step arithmetic and logicSingle-step factsThere are no intermediate steps to write down
Tasks with several constraintsKnowledge the model lacksReasoning is not retrieval; a missing fact needs a source
Checking an answer before giving itLatency-critical pathsThe steps are output tokens: slower and several times the price of input

Three mechanics matter in production.

  • Reasoning must come before the answer. Generation runs left to right, so an answer written first cannot benefit from reasoning written after it. In a schema, put the reasoning field ahead of the answer field.
  • Do not ban the reasoning and expect the accuracy. “Respond with JSON only, no explanation” removes the scratch space. Give the working a place to go: a field, or a first call that thinks and a second that formats.
  • Reasoning models have this built in. They spend thinking tokens on their own, and telling them to think step by step adds nothing (section 10.7).

One caution: the written reasoning is plausible text like any other output. Models sometimes reach a right answer through wrong steps, and the reverse. Treat the trace as an aid to quality and to debugging, not as a record of what happened inside.

Answer first1,071because23 × 40= 920+ 161the answer is fixed before any step exists; what follows can only rationalize itReasoning first23 × 40= 92023 × 7= 1611,081the answer is the last token, and it attends to every step above it
Figure 13.2 Why order matters. Generation runs left to right, so reasoning written after the answer cannot change it; the wrong answer above is the kind one pass produces.

Common take“‘Think step by step’ unlocks the model’s reasoning.”

Sharper take“It buys more computation steps, paid for in output tokens. I use it where the task needs steps, put it before the answer, and leave it out for a reasoning model.”

13.6Decomposition

A pipeline of plain prompts in place of one heroic one.

When one prompt has to classify, extract, reason, write and format, each job gets worse. The instructions compete for attention, and a single call forces one model and one temperature onto tasks that want different ones.

One promptDo everythingModelhopeA pipelineInputClassifysmall modelExtractschema outputComposelarger modelValidateplain codeOutput
Figure 13.3 One heroic prompt against a pipeline of small ones. Each stage can be tested, swapped and given the cheapest model that does its job, and the last check is ordinary code.

Splitting buys three things. Each stage can be tested on its own. Each can use the cheapest model that does it well, which is the largest cost lever from section 11.7. And a wrong answer now has an address: you can find the stage that produced it.

It also has costs, and they should be weighed.

  • Latency adds up. Three calls in sequence take about three times as long to start responding. Run independent stages in parallel and keep dependent chains short.
  • Errors compound. A classifier that is right 95% of the time feeding an extractor that is right 95% of the time gives a pipeline that is right about 90% of the time. Measure each stage and the whole.
  • Information is lost at the joins. A stage knows only what the previous one passed along. An over-eager summary between stages is a common, quiet cause of failures.

Split when stages want different models, when you need to test them separately, or when the instructions visibly interfere. Keep one prompt when the task is a single coherent job or the latency budget is tight. This pipeline shape is the skeleton of retrieval systems (Chapter 15) and of agents (Part 5).

Common take“I keep adding instructions to the prompt to cover each new case.”

Sharper take“When instructions start fighting each other I split the job into stages. Each one gets a simple prompt, its own tests, and the smallest model that handles it.”

13.7Sensitivity

Small changes in wording can move results a lot, and only measurement tells you which.

How much does the exact text of a prompt matter? The capitalizing model from Chapter 9 gives a clean test, because it was trained on one format and scores 99.5% with it. I gave it the same 200 words with six small variations of that format.

The format it was trained onWORD:·rings↵CAPS:·99.5%
Lowercase labelsword:·rings↵caps:·90%
No space after the colonsWORD:rings↵CAPS:0%
A different first labelTEXT:·rings↵CAPS:·99.5%
A different second labelWORD:·rings↵UPPER:·0%
An extra blank lineWORD:·rings↵↵CAPS:·0%
One worked example placed firstWORD:·stone↵CAPS:·STONE↵WORD:·rings↵CAPS:·0%
Figure 13.4 Real results: exact-match accuracy on 200 unseen words. One change did nothing, one cost ten points, and four destroyed the behavior completely.

Changing the first label from WORD to TEXT made no difference. Lowercase labels cost ten points. Replacing CAPS with UPPER, one character longer, dropped accuracy to zero: the model began skipping the second letter of every word, because everything it had learned was tied to positions that had now shifted by one.

You could not have ranked those edits in advance by how harmless they look. A large model is far more robust than this small one, which was trained on a single format. The difference is one of degree. A 2023 study of prompt formats found accuracy differences of up to 76 points between formats that carried the same content, on a 13-billion-parameter open model. Separators, capitalization and spacing all moved the results.

Common take“It’s just a rewording. It can’t change anything.”

Sharper take“I can’t tell by reading which rewordings are harmless. Here one was free, one cost ten points and four broke everything. I run the test set.”

13.8Prompts are code

Version them, review them, test them.

If a rewording can change behavior, then a prompt change is a release to every request that uses it. The practices are the ones software already has.

Software practiceFor prompts
Source controlPrompts live in files in the repository, never as strings scattered through the code. Every change has an author, a diff and a way back
Code reviewPrompt diffs are reviewed like logic diffs, which is what they are
TestsA fixed set of real inputs with expected outputs, run on every prompt change (Chapter 23)
A gate before mergingThe score must not fall
Versioned releasesThe prompt version is logged with every request (Chapter 24). Without it, “did the prompt change cause this?” has no answer
Gradual rolloutA new prompt goes to a small share of traffic first

How large must the test set be? Larger than intuition suggests. Suppose one prompt is truly right 80% of the time and another 85%. I simulated testing each on n examples and counted how often the worse prompt scored at least as well.

0%20%40%25501002004008001,600chance the worse prompt looks as goodtest examples per prompt50 examples: 30%400 examples: 3%
0%20%40%251004001,600chance the worse prompt looks as goodtest examples per prompt50 examples: 30%400 examples: 3%
Figure 13.5 Simulation, 40,000 trials per point. With 50 examples per prompt, the worse prompt looks at least as good as the better one about 30% of the time. It takes about 400 to push that to 3%.
Test examples per promptMargin of error on an 80% scoreChance the worse prompt scores at least as well
25± 16 points38.6%
50± 11 points30%
100± 8 points20.3%
200± 6 points10.6%
400± 4 points3.3%
800± 3 points0.5%
1,600± 2 points0%

A two-point gain on fifty examples is one example changing sides. Three habits make small test sets go further: run both prompts on the same examples and count the cases where they differ, change one thing at a time, and read the failures individually, not only the score.

Common take“I tried the new prompt on a few inputs and it looked better.”

Sharper take“A prompt without a regression suite is an untested function on the busiest path in the product. Mine are in the repository, and a change merges only if the test set says it is no worse.”

13.9Porting and optimization

A prompt is tuned to one model.

A prompt encodes assumptions about the model reading it: how literally it takes instructions, how much it says by default, what it needs spelled out. Those change between providers and between versions from the same provider, which is why providers publish a prompting guide for each model generation along with notes on what differs from the last.

Treat a model change as a migration.

  • Run the test set first, on the old prompt with the new model, to see what changed before changing anything.
  • Read the new model’s guide. Its defaults for length, formatting and initiative may differ.
  • Remove old workarounds. Lines added to compensate for a previous model’s weakness often cause the opposite problem in its successor.
  • Pin model versions in production, so that a change is something you choose to make.

Because prompts are tuned against a score, the tuning can be automated. In frameworks such as DSPy you declare what goes into each step and what should come out, supply examples and a metric, and an optimizer searches over instructions and examples, keeping what scores best. This often beats hand-tuning on the metric, and it makes porting cheaper: change the model and run the optimizer again.

It does not remove the hard parts. The optimizer needs a metric that reflects what you want and data to measure it on, which is the test set of section 13.8 once more. And a prompt optimized hard against a small set can fit that set’s quirks, so keep separate examples for the final check.

Common take“We upgraded the model, so everything will be better.”

Sharper take“A new model is a migration. I rerun the test set, read the new prompting guide, take out the workarounds written for the old model, and only then switch traffic.”

13.10The three walls

What prompting cannot fix, and where to go next.

Prompting shapes the distribution a model already has. There are three things it cannot add, and each has its own tool.

WallSymptomWhy prompting cannot fix itWhat does
KnowledgeThe model does not know your refund policy, recent events, or your private dataThe fact is not in the weights, and no phrasing puts it thereRetrieval: put the fact in the context (Chapters 14 and 15)
CapabilityThe model cannot do the reasoning even with examples, steps and decompositionYou have reached the model’s ceilingA stronger model or a reasoning setting, for the requests that need it (Chapter 10)
Style or format at scaleThousands of tokens of rules and examples, and the output still driftsIn-context pressure has a ceiling and is paid for on every requestFine-tuning: move the pattern into the weights and shrink the prompt (Chapter 17)

The discipline is to climb in order of cost, with a measurement at each step: prompt first, then retrieval if knowledge is missing, then fine-tuning if a pattern will not hold, then a larger model if capability is the limit. Do not skip a step without a test showing that the cheaper one is exhausted.

A compact way to remember it: prompting is the steering wheel. It is free to turn and instant to try, but it cannot add horsepower, which is capability, or fuel, which is knowledge.

Promptshape what the model already hasRetrievalCh. 14 and 15the knowledge wall: put the fact in contextFine-tuningCh. 17the style wall: move the pattern into weightsStronger modelCh. 10the capability wall: reasoning or a larger tier
Figure 13.6 Three walls, three tools, in order of cost. Climb a step only when a test shows the step below has failed.

Common take“The answers are still wrong. I’ll keep refining the prompt.”

Sharper take“First I work out which wall this is. If the model lacks the fact, I add retrieval. If it lacks the ability, I change the model. More prompt polish fixes neither.”

Key takeaways

  • A prompt is the condition in a conditional distribution. Prompting is steering probability, not finding magic words.
  • Write for a capable colleague with no context: be specific, give the reason, say what to do, define done.
  • Examples beat instructions, because demonstration constrains more tightly than description. Where a pattern and a rule conflict, the pattern usually wins.
  • Delimit content, put long material first and the question last, and show the output format. Drop tricks that cannot pass a test.
  • Chain of thought buys serial computation with output tokens. Reasoning must come before the answer.
  • Decompose when stages want different models or separate tests. Two stages at 95% make a pipeline at about 90%.
  • You cannot tell a harmless edit by reading it: of six small format changes, one cost nothing, one cost ten points, and four took a 99.5% model to zero.
  • With 50 test examples, the worse of two prompts looks at least as good about 30% of the time. Use hundreds, compare on the same examples, and change one thing at a time.
  • A prompt is tuned to one model. A model change is a migration: rerun the tests and remove old workarounds.
  • Prompting cannot add knowledge or capability. Name the wall, then use retrieval, a stronger model or fine-tuning.

Check your understanding

  1. A classifier built on a prompt ran at 91% accuracy for a quarter. Over the last three weeks it has slid to 82%. No code was deployed. List the causes you would check, in order, and how you would confirm each.

    Answer outline

    First the prompt: compare the logged prompt version across the period, since an edit made outside the normal release path is the most common cause. Second the model: check whether the model name is an alias that the provider moved to a newer version, and pin a dated version if so. Third the inputs: compare recent traffic with the test set for new categories, languages or formats. Fourth the examples in the prompt: do they still cover what users send? Confirm each by rerunning the fixed test set under the old and new conditions; if the test set still scores 91%, the inputs have drifted and the set needs refreshing.

  2. A teammate changed “respond concisely” to “respond in two or three sentences” and removed an example that looked redundant. On a 40-example test set, accuracy went from 85% to 87.5%. They want to ship. What do you say?

    Answer outline

    The difference is one example out of forty, far inside the noise: at that size the margin on an 85% score is about eleven points either way, and the simulation shows a worse prompt often looks better at such sizes. Two changes were also made at once, so even a real difference could not be attributed. Ask for the two edits to be tested separately, on a larger set, comparing the same examples under each version and reading the cases that changed. The specific wording is probably an improvement and the removed example is the risk, since examples often carry more than they appear to.

  3. An extraction prompt returns JSON only. It is accurate on fields copied from the document and poor on a field that must be computed, the net amount after discounts and tax. Explain the mechanism and give two fixes.

    Answer outline

    Copying a value needs one step; computing one needs several, and “JSON only” leaves the model nowhere to do them, so it must produce the result in a single pass. Fixes: add a reasoning field placed before the computed field so the working is written first, or split the job into a call that extracts the inputs and a second step that computes. Better still, extract the inputs and do the arithmetic in ordinary code, which is exact and free. A reasoning setting on the model is another option at a higher price.

Further reading

  • Chip Huyen, AI Engineering, chapter 5: prompt engineering, including defenses against prompt attacks.
  • John Berryman and Albert Ziegler, Prompt Engineering for LLMs (O’Reilly, 2024): prompts as documents the model completes, from two engineers who built an early coding assistant.
  • Your provider’s prompting guide for the model you use, and its notes on what changed from the previous model.
  • The DSPy documentation: prompts as programs with metrics, and the optimizers that tune them.

↑↓ to move↵ to openesc to close