Skip to content
LLM application engineering Foundation 28 min read

Prompt engineering

A prompt is not a request to a mind; it is the conditioning prefix of a probability distribution. Prompt engineering is the craft of choosing that prefix so the distribution you sample from puts its mass on the outputs you want, and then proving it did with an eval set.

10,000 ft

A pre-trained language model is a machine for continuing documents (the language-modelling objective); post-training turns it into an assistant that continues a conversation helpfully (instruction tuning). Neither step tells the model your task. The prompt does. It is the cheapest lever you have: no data pipeline, no GPU, a change ships in minutes. Every other technique in this track is built on it: structured outputs are a prompt plus a constraint, RAG is a prompt with retrieved evidence pasted in, agents are a prompt in a loop, and context engineering is prompt engineering for systems that assemble the prompt automatically. When prompting stops being enough, the next levers are retrieval (for missing knowledge) and fine-tuning (LoRA, for behaviour the prompt cannot reliably induce).

2,000 ft

The model sees one flat token sequence. Your system instructions, tool definitions, documents, examples and the user's question are all just earlier tokens; the chat template marks who said what with special tokens the model was trained on. The model then computes \(p(\text{next token}\mid\text{everything before})\) and the decoder samples. So every part of the prompt works the same way, by shifting that conditional distribution:

  1. Instructions say what the task is and why, so the model can generalise to cases you did not list.
  2. Context supplies the facts the model must use (and should be placed before the question when long).
  3. Examples show the format, the label space and the input distribution, more than they teach the rule.
  4. An output contract says exactly what shape the answer takes, ideally enforced by a schema.
  5. A reasoning budget (asking for steps, or a reasoning model's thinking) buys serial computation before the answer.
  6. Evaluation closes the loop: prompts are fragile, so you only know a prompt works when it passes a fixed set of real cases.

What a prompt is: everything the model conditions on, flattened into one token stream
What a prompt is: everything the model conditions on, flattened into one token stream. system / developer role, rules, why, tool definitions names, schemas, context documents, data, state, examples 3–5 input → output, user turn the actual question, chat template roles → special tokens, LLM p(next token | all of it), output free text or schema, one sequenceWhat a prompt is: everything the model conditions on, flattened into one token stream. system / developer role, rules, why, tool definitions names, schemas, context documents, data, state, examples 3–5 input → output, user turn the actual question, chat template roles → special tokens, LLM p(next token | all of it), output free text or schema, one sequence

Ground level

What the model actually sees

An API call with a system message and a user message looks structured, but the model never receives structure. A chat template serialises it into text with reserved tokens. The ChatML-style template used by several open-weight model families looks like this:

<|im_start|>system
You are a support assistant for a payments app. Answer only about this app.<|im_end|>
<|im_start|>user
Why was my refund declined?<|im_end|>
<|im_start|>assistant

The model's job is to continue after the final assistant header. Three consequences follow, and most prompting advice is derived from them:

  • The system prompt is not a separate channel. It is text earlier in the sequence that post-training taught the model to weight heavily. That is why it usually wins conflicts, and also why it can be overridden by sufficiently persuasive later text: the basis of prompt injection.
  • Position matters. Everything competes for attention in one sequence; where you put the question relative to a long document changes the answer (see long context).
  • Tokens are the unit of cost and of failure. A prompt is billed, cached and truncated by tokens (tokenisation); a word the tokeniser splits strangely is a word the model handles less reliably (counting letters, reversing strings, rare names).

The anatomy of a production prompt

A prompt that survives contact with real users has the same parts in nearly every product. Order them so the stable parts come first (for caching) and the volatile parts last.

Part What it does Typical size Changes
Role and task Who the model is acting as, for whom, and what a good outcome is 50–300 tokens rarely
Rules with reasons Constraints, each with the reason behind it 100–1,000 per release
Tool and schema definitions What the model may call and the shape it must emit 200–5,000 per release
Reference material Policies, product facts, glossary 0–50,000 weekly
Examples 3–5 worked input → output pairs covering the hard cases 200–3,000 per release
Dynamic context Retrieved documents, user profile, conversation state 0–100,000 every call
The question The user's message, delimited 10–2,000 every call

Delimit each part unambiguously. XML-style tags (<policy>…</policy>, <document index="3">…) work well because they are rare in user text, nest cleanly, and let your instructions refer to parts by name ("answer only from <documents>").

Instructions: specific, positive, and with the reason

Models trained to follow instructions follow them quite literally. Three habits matter most.

Say what to do, not only what not to do. "Do not use markdown" leaves the model to guess the alternative; "write in plain prose paragraphs" names it.

Give the reason. Anthropic's prompting guide gives the example of replacing "NEVER use ellipses" with "Your response will be read aloud by a text-to-speech engine, so never use ellipses since the text-to-speech engine will not know how to pronounce them". The reason lets the model generalise: it will now also avoid other things a speech engine cannot say. A rule without a reason is a pattern match; a rule with a reason is a goal.

Be specific about the hard cases. Most of a good prompt is about the 10% of inputs that are ambiguous. A worked example:

Summarise the customer's complaint. Be concise and professional.
You triage support tickets for a payments app. An on-call engineer reads your summary
on a phone in under ten seconds, so lead with what is broken, not with pleasantries.

Write at most two sentences:
1. What failed, with the amount, date and transaction id if the ticket gives them.
2. What the customer wants (refund, explanation, account change).

If the ticket contains several complaints, summarise the one involving money first.
If the ticket is not a complaint (a question, praise, spam), output exactly: NOT_A_COMPLAINT

The second prompt is longer, but every line removes a decision the model would otherwise make at random. Notice it also defines the audience and the success criterion, which is what lets the model handle a case the prompt never mentions.

Shouting does not help modern models

Prompts written for 2023-era models often used capitals and threats ("CRITICAL: you MUST…"). Newer instruction-tuned models follow the system prompt closely, and aggressive emphasis now tends to make them over-apply the rule. Anthropic's 2026 guidance explicitly recommends replacing "CRITICAL: You MUST use this tool when…" with "Use this tool when…". Emphasis is a blunt instrument; a reason is a precise one.

Examples and in-context learning

GPT-3 (Brown et al., 2020) showed that a large enough model can perform a new task from a handful of demonstrations in the prompt, with no weight update: in-context learning. Examples are still the most reliable way to fix the format, tone and granularity of an answer. But what they teach is not what most people assume.

Examples teach the shape of the task more than the rule. Min et al. (2022) replaced the gold labels in classification demonstrations with random labels and found that this "barely hurts performance" across 12 models. What mattered was that the demonstrations showed the label space, the distribution of inputs and the format. The model already knows how to classify sentiment; the examples tell it that this is the task and these are the allowed answers.

Examples inject biases. Zhao et al. (2021) showed that GPT-3's few-shot accuracy could swing "from near chance to near state-of-the-art" depending on format, example choice and order, because the model is biased towards labels that are frequent in the demonstrations (majority label bias), that appear near the end (recency bias), and that are common tokens in pre-training (common token bias). Lu et al. (2021) found that simply permuting the same examples could move a model between near state-of-the-art and random-guess performance, and that a good order for one model does not transfer to another.

So choose examples like a test designer. Cover the hard cases, not the easy ones; balance the labels; vary surface features (length, phrasing, language) that should not matter, so the model does not learn them; and keep every incidental property of the examples deliberate, because the model will copy it. Anthropic's guidance suggests 3–5 examples; beyond that the returns fall and the token cost does not.

An example that taught the wrong thing

Jarvis, Finny's assistant, once trialled a narrator prompt whose single worked example ended in Hinglish. In a live evaluation, English questions came back in Hinglish 59 times out of 207 turns, against 12 for the production prompt. Nothing in the instructions asked for Hinglish; the example's language was an incidental feature the model copied. The fix removed that example and stated the rule outright: an English question gets an English answer. The count fell back to 12. See the Jarvis case study.

Reasoning: buying computation with tokens

A transformer does a fixed amount of computation per token. A question whose answer needs many serial steps (multi-digit arithmetic, a chain of deductions) cannot be answered reliably in the first token. Letting the model write intermediate steps gives it more forward passes before it commits.

  • Chain-of-thought prompting (Wei et al., 2022) puts worked reasoning in the few-shot examples. With eight such exemplars, a 540B-parameter model reached state-of-the-art accuracy on the GSM8K maths word problems.
  • Zero-shot CoT (Kojima et al., 2022) found that appending "Let's think step by step" alone raised text-davinci-002 from 17.7% to 78.7% on MultiArith and from 10.4% to 40.7% on GSM8K.
  • Self-consistency (Wang et al., 2022) samples several reasoning paths at non-zero temperature and takes the majority answer, improving chain-of-thought by 17.9 points on GSM8K. The maths below shows why voting works and when it stops working.

Since late 2024, reasoning models are trained with reinforcement learning to produce long chains of thought on their own (reasoning models, RL with verifiable rewards). That changes the advice. With a reasoning model, you rarely need to say "think step by step" or prescribe the steps; you control the budget (an effort or thinking-token setting) and describe the goal and the constraints. Hand-written step lists can even hurt, by forcing a worse procedure than the one the model would find. With a non-reasoning model, or when latency forbids long thinking, explicit reasoning in the prompt still pays. Either way, if you parse the output, keep the reasoning and the final answer in separate, delimited places.

Long inputs: documents first, question last

Models do not use long contexts uniformly. Liu et al. (2023), "Lost in the Middle" placed the one relevant document at different positions among many distractors and found that accuracy is often highest when the relevant information is at the beginning or end of the context and "significantly degrades" in the middle, even for models built for long contexts. Chroma's 2025 context rot study of 18 models found that performance "grows increasingly unreliable as input length grows", and that even a single topically related distractor reduces accuracy.

The practical rules:

  1. Put long documents near the top, then instructions, then the question at the end. Anthropic reports that queries at the end "can improve response quality by up to 30 percent in tests", especially with complex multi-document inputs.
  2. Wrap each document in tags with its source and an index, so the model can cite it.
  3. For long-document tasks, ask the model to extract relevant quotes first, then answer from the quotes. This is a cheap form of attention steering.
  4. Send less. Retrieval exists (RAG) because a smaller, more relevant context beats a bigger one; context engineering is the discipline of deciding what goes in.

Prompts are fragile, so treat them as code

Sclar et al. (2023) changed only meaning-preserving formatting (separators, casing, spacing between fields) in few-shot prompts and found differences of up to 76 accuracy points on LLaMA-2-13B. The sensitivity persisted with larger models, more examples and instruction tuning, and which format was best correlated only weakly between models.

Two conclusions follow. First, a prompt that "works" on three hand-tried inputs is an anecdote. Second, a prompt is coupled to the model it was tuned on: upgrading the model is a change that needs the same regression testing as changing the prompt. In practice:

  • Keep prompts in version control with an id (narrate.system.v4), never inline in code paths that cannot be diffed.
  • Log the prompt id with every response, so a regression can be traced to a prompt change.
  • Maintain an eval set of real inputs with known good outputs or checkable properties, and run it on every prompt or model change (evals in practice).
  • Change one thing at a time and read the failures, not just the score.
Prompt engineering is an experimental loop, not a writing exercise
Prompt engineering is an experimental loop, not a writing exercise. define success what a good answer is, eval set 20–200 real cases, prompt v(n) versioned like code, run all cases same model, same settings, grade code checks + judge + you, read the failures cluster them, change one thing, add the new failurePrompt engineering is an experimental loop, not a writing exercise. define success what a good answer is, eval set 20–200 real cases, prompt v(n) versioned like code, run all cases same model, same settings, grade code checks + judge + you, read the failures cluster them, change one thing, add the new failure

Once you have an eval set, you can also let a machine search the prompt space. APE (Zhou et al., 2022) had an LLM propose instructions and kept the ones that scored best, matching or beating human-written prompts on most of its tasks. DSPy (Khattab et al., 2023) goes further: you declare the pipeline's modules and a metric, and an optimiser chooses instructions and few-shot demonstrations for each module. Automated optimisation is only as good as the metric, which is another reason the eval set comes first.

Prompt caching and the economics of a prefix

Inference providers cache the attention keys and values of a prompt prefix (the KV cache) so that a later request with the same prefix skips recomputing it. As of 2026, Anthropic bills a 5-minute cache write at 1.25× the base input price and a cache read at 0.1× (lower on some models), caching the prefix in the order tools, system, messages; OpenAI caches automatically and discounts cached input tokens by up to 95%. The cache only matches an exact prefix, which turns a prompt-layout choice into a cost and latency choice: stable content first, volatile content last. A timestamp in the first line of a system prompt silently disables the cache for everything after it.

A worked example. A support assistant sends a 12,000-token static prefix (instructions, tool schemas, policy) plus 800 tokens of dynamic context and question, 1,000 times within the cache lifetime. Measured in units of the base input price per token:

Per call (input) 1,000 calls
No cache 12,800 12,800,000
First call (write) 12,000 × 1.25 + 800 = 15,800
Later calls (read) 12,000 × 0.1 + 800 = 2,000 15,800 + 999 × 2,000 = 2,013,800

Input cost falls by a factor of 6.4. Time to first token falls too, because the prefill of 12,000 tokens is skipped (serving LLMs).

A cache that worked because of one layout change

When Jarvis merged its two routing calls into one, the registry of everything the model can fetch was moved into its own system message, ahead of the date, the session state and the question, with a fixed cache key. A three-call check then found 9,441 of 9,485 prompt tokens served from cache, roughly a tenth of the uncached cost per call.

Sampling settings are part of the prompt

Temperature, top-p and the maximum output length shape the distribution you sample from just as much as the words do (decoding and sampling). Use temperature 0 (or near it) for extraction, classification and routing, where you want the mode; use moderate temperature for drafting and for self-consistency, where you want diversity. Even at temperature 0, hosted models are not perfectly deterministic (batched floating-point arithmetic varies), so tests should check properties, not exact strings. Some reasoning models fix or ignore temperature; check the provider's documentation for the model you deploy.

First principles

Why should a string of text change what a fixed network computes? Start from the training objective. A pre-trained model minimises cross-entropy on next-token prediction over a huge corpus, so it approximates the corpus distribution \(p_{\text{data}}(x_t\mid x_{<t})\). The corpus is a mixture of documents written for many purposes: tutorials, forum answers, legal contracts, chat logs. A prompt is evidence about which kind of document this is, and therefore about how it continues. "Q: … A:" makes a quiz; a few labelled reviews make a labelled list; a system message in the chat format makes a helpful-assistant transcript, because post-training has made that document type dominant.

Xie et al. (2021) made this precise: if pre-training documents are generated from latent "concepts" \(\theta\) (topic, format, task), then a model that predicts well must implicitly infer \(\theta\) from the prefix. In-context learning is then Bayesian inference over \(\theta\), with the demonstrations as data. This single picture explains the empirical results above:

  • Format matters more than labels (Min et al.): format and input distribution are strong evidence about \(\theta\); a few wrong labels are weak evidence against it.
  • Order and recency matter (Zhao et al., Lu et al.): the model is not an exact Bayesian; the posterior it computes is distorted by position, and recent tokens weigh more.
  • Instructions plus reasons generalise: they are strong evidence about the task concept, not just about surface cases.

Why does reasoning text help? Because computation per token is bounded. A transformer with \(L\) layers performs a constant-depth computation per generated token. Feng et al. (2023) proved that bounded-depth transformers cannot directly output answers to basic arithmetic tasks unless model size grows super-polynomially with input length, while constant-size transformers can solve them by writing a chain of thought. Merrill and Sabharwal (2023) showed that the gain depends on the length of the chain: a logarithmic number of extra steps adds little, a linear number lets a decoder recognise all regular languages, and a polynomial number reaches exactly polynomial-time problems. A chain of thought is working memory written to the context, where the next forward pass can read it.

What breaks if you ignore this? You get prompts that rely on the model "knowing what you mean" (the posterior over \(\theta\) is broad, so outputs vary), examples that leak incidental features (the posterior locks onto the wrong concept), and questions that need ten serial steps answered in one token (the computation does not fit).

The maths

Prompting as conditioning. Given a prompt \(c\) (all tokens before the answer), an autoregressive model defines

\[ p_\phi(y \mid c) = \prod_{t=1}^{T} p_\phi\big(y_t \mid c, y_{<t}\big), \]

where \(\phi\) are the fixed weights and \(y=(y_1,\dots,y_T)\) is the output. Prompt engineering optimises \(c\) (a discrete string) rather than \(\phi\). If \(r(y)\) scores an output, the goal is \(\max_c \mathbb{E}_{y\sim p_\phi(\cdot\mid c)}[r(y)]\) over a distribution of user inputs. That is an optimisation over a discrete, high-dimensional, non-smooth space, which is why it is done by search and evaluation (manually, or with APE and DSPy) rather than by gradient.

Derivation: in-context learning as implicit Bayesian inference

Let demonstrations \(S_n=\{(x_i,y_i)\}_{i=1}^n\) and a test input \(x\). Assume each document is generated by first drawing a concept \(\theta\sim p(\theta)\), then drawing examples i.i.d. given \(\theta\). The predictive distribution for the test answer is

\[ p(y\mid x, S_n) = \int p(y\mid x,\theta)\,p(\theta\mid S_n, x)\,d\theta . \]

By Bayes' rule, ignoring the weak dependence on the unlabelled \(x\),

\[ p(\theta\mid S_n) \propto p(\theta)\prod_{i=1}^{n} p(x_i, y_i\mid\theta). \]

For two candidate concepts \(\theta^\star\) (the intended task) and \(\theta'\), the log posterior ratio is

\[ \log\frac{p(\theta^\star\mid S_n)}{p(\theta'\mid S_n)} = \log\frac{p(\theta^\star)}{p(\theta')} + \sum_{i=1}^{n}\log\frac{p(x_i,y_i\mid\theta^\star)}{p(x_i,y_i\mid\theta')} . \]

The sum has expectation \(n\,\mathrm{KL}\big(p(\cdot\mid\theta^\star)\,\|\,p(\cdot\mid\theta')\big)\) under the true concept (KL divergence), so it grows linearly in \(n\) and the posterior concentrates on \(\theta^\star\). Two readings follow. Examples that are very informative about the task (large KL from rival concepts) need fewer copies. And since \(p(x_i,y_i\mid\theta)=p(x_i\mid\theta)\,p(y_i\mid x_i,\theta)\), the \(p(x_i\mid\theta)\) term, the input distribution and format, contributes evidence even when the labels are noisy, which is what Min et al. observed. See estimation: MLE, MAP and Bayes.

Why voting helps (self-consistency). Suppose each sampled reasoning path is independently correct with probability \(p\) on a question with a binary answer. The majority of \(n\) (odd) samples is correct with probability

\[ P_{\text{maj}}(n,p) = \sum_{k=\lceil n/2\rceil}^{n}\binom{n}{k}p^k(1-p)^{n-k}. \]

If \(p>\tfrac12\), this tends to 1 as \(n\to\infty\) (Condorcet's jury theorem; by the law of large numbers the fraction of correct votes concentrates on \(p\)). With \(p=0.6\): \(n=1\) gives 0.600, \(n=5\) gives 0.683, \(n=11\) gives 0.753, \(n=41\) gives 0.903 (computed in Build it).

Real answers are not binary. If wrong answers scatter over many values, the correct answer can win a plurality even when \(p<\tfrac12\), as long as it is more likely than any single wrong answer. The catch is independence. If the correctness indicators of the \(n\) samples have pairwise correlation \(\rho\), the variance of the fraction of correct votes is \(\tfrac{p(1-p)}{n}\big(1+(n-1)\rho\big)\), which tends to \(\rho\,p(1-p)\), not zero, as \(n\to\infty\): the vote never concentrates, and the effective number of independent votes is \(n/(1+(n-1)\rho)\), which can never exceed \(1/\rho\). (The simulation below uses a blunter model of correlation, where a sample copies the first sample's answer with probability \(\rho\).) That is why self-consistency needs temperature, and why it does little for a model that makes the same mistake every time.

Contextual calibration. Zhao et al. estimate the prompt's bias by asking for the label distribution \(\hat{\mathbf p}_{\text{cf}}\) on a content-free input such as "N/A", which should be uniform. If the bias acts multiplicatively, \(\hat{\mathbf p}(x)\propto \mathbf p^{\text{true}}(x)\odot\mathbf b\), then \(\hat{\mathbf p}_{\text{cf}}\propto\mathbf b\), and the correction

\[ \mathbf q(x) = \operatorname{normalise}\big(W\,\hat{\mathbf p}(x)\big),\qquad W=\operatorname{diag}(\hat{\mathbf p}_{\text{cf}})^{-1}, \]

recovers \(\mathbf p^{\text{true}}(x)\) exactly. Here \(\hat{\mathbf p}(x)\in\mathbb{R}^K\) is the model's label distribution for input \(x\) over \(K\) labels and \(\odot\) is elementwise product. The paper reports up to 30.0 points absolute improvement in average accuracy for GPT-3 and GPT-2.

Caching. With static prefix length \(S\), dynamic length \(D\), cache-write multiplier \(w\), read multiplier \(r\) and \(N\) calls inside the cache lifetime, input cost relative to no cache is

\[ \frac{wS + D + (N-1)(rS + D)}{N(S+D)} \;\xrightarrow{N\to\infty}\; \frac{rS + D}{S + D}. \]

With \(S=12{,}000\), \(D=800\), \(r=0.1\), the limit is \(2{,}000/12{,}800 = 0.156\): a 6.4× saving, bounded by how much of your prompt is static.

0.40.60.81.0151141samples n (log scale)binary, p = 0.6plurality, p = 0.4, independentplurality, p = 0.4, correlated (ρ = 0.5)
Voting over sampled answers (real output of the code below). Independent samples converge on the right answer even when each is right only 40% of the time, because the wrong answers disagree with each other. Correlated samples never improve: the vote just echoes the first path.

Build it

Two small NumPy experiments make the maths concrete. First, self-consistency: exact majority voting and a Monte Carlo plurality vote, with and without correlated samples.

import numpy as np
from math import comb

def majority_exact(p, n):
    """P(majority correct) for a binary task: each sample correct w.p. p, independent."""
    return sum(comb(n, k) * p**k * (1 - p)**(n - k) for k in range(n // 2 + 1, n + 1))

def plurality_mc(p, n, n_wrong=4, rho=0.0, trials=200_000, seed=0):
    """Plurality vote when wrong answers scatter over n_wrong values.
    rho = chance a sample just copies the first sample (correlated reasoning paths)."""
    rng = np.random.default_rng(seed)
    probs = np.r_[p, np.full(n_wrong, (1 - p) / n_wrong)]   # answer 0 = correct
    draws = rng.choice(n_wrong + 1, size=(trials, n), p=probs)
    copy = rng.random((trials, n)) < rho
    copy[:, 0] = False
    draws = np.where(copy, draws[:, :1], draws)            # correlated samples copy sample 0
    counts = np.stack([(draws == a).sum(1) for a in range(n_wrong + 1)], 1)
    noise = rng.random(counts.shape) * 0.1                  # random tie-break
    return ((counts + noise).argmax(1) == 0).mean()

print("binary majority vote, p = 0.6")
for n in (1, 5, 11, 41):
    print(f"  n={n:>2}: {majority_exact(0.6, n):.3f}")
print("plurality, p = 0.4, wrong answers spread over 4 values")
for n in (1, 5, 11, 41):
    print(f"  n={n:>2}: independent {plurality_mc(0.4, n):.3f}   "
          f"correlated(rho=0.5) {plurality_mc(0.4, n, rho=0.5):.3f}")

Output:

binary majority vote, p = 0.6
  n= 1: 0.600
  n= 5: 0.683
  n=11: 0.753
  n=41: 0.903
plurality, p = 0.4, wrong answers spread over 4 values
  n= 1: independent 0.400   correlated(rho=0.5) 0.400
  n= 5: independent 0.548   correlated(rho=0.5) 0.428
  n=11: independent 0.707   correlated(rho=0.5) 0.419
  n=41: independent 0.962   correlated(rho=0.5) 0.400

Second, contextual calibration on a simulated three-way classifier whose prompt injects a bias towards "positive" (as a recency or majority-label bias would).

import numpy as np
rng = np.random.default_rng(1)
labels = ["positive", "negative", "neutral"]
K, N = 3, 3000

# The "true" evidence each input carries about its label (what an unbiased reader would say).
y = rng.integers(0, K, N)
logits = rng.normal(0, 1.0, (N, K))
logits[np.arange(N), y] += 1.5
p_true = np.exp(logits) / np.exp(logits).sum(1, keepdims=True)

# The prompt adds a bias: the label in the last demo ("positive") and a frequent word get a boost.
bias = np.array([3.0, 1.0, 0.6])              # multiplicative prior the prompt injects
p_model = p_true * bias
p_model /= p_model.sum(1, keepdims=True)

# Contextual calibration (Zhao et al. 2021): ask with a content-free input such as "N/A".
p_cf = bias / bias.sum()                       # what the model says about "N/A"
W = np.diag(1 / p_cf)                          # W = diag(p_cf)^-1, b = 0
q = p_model @ W
q /= q.sum(1, keepdims=True)

acc = lambda p: (p.argmax(1) == y).mean()
share = lambda p: np.bincount(p.argmax(1), minlength=K) / N
print("p_cf (content-free):", np.round(p_cf, 3))
print(f"accuracy  unbiased {acc(p_true):.3f}  prompted {acc(p_model):.3f}  calibrated {acc(q):.3f}")
print("predicted label share, prompted:  ", np.round(share(p_model), 3))
print("predicted label share, calibrated:", np.round(share(q), 3))

Output:

p_cf (content-free): [0.652 0.217 0.13 ]
accuracy  unbiased 0.767  prompted 0.654  calibrated 0.767
predicted label share, prompted:   [0.591 0.246 0.163]
predicted label share, calibrated: [0.327 0.332 0.341]

The biased prompt predicts "positive" 59% of the time on balanced data and loses 11 points of accuracy; one content-free query undoes it. The recovery is exact here because the simulated bias is exactly multiplicative; on a real model it is partial, which is what the paper measured.

Things to try

  • In the self-consistency code, set n_wrong=1 (a binary task) and p=0.45. Voting now makes things worse as \(n\) grows. Why?
  • Make the correlation depend on the sample, not all-or-nothing copying of sample 0. How much \(\rho\) can you tolerate before \(n=41\) is no better than \(n=5\)?
  • In the calibration code, make the bias input-dependent (multiply by a random factor per row). How much of the accuracy does calibration still recover?
  • With a real API: take 30 labelled examples from a task you care about, write three formattings of the same prompt (different separators and casing), and measure the accuracy spread. Compare it with the 76-point worst case in Sclar et al.

In practice

A checklist that covers most production prompts:

  1. Write the success criterion first, then 20+ real test inputs, including the ugly ones.
  2. State role, audience and goal, then rules, each with its reason.
  3. Delimit every inserted block with tags; tell the model which blocks are data, not instructions (a first line of defence against injection, not a sufficient one).
  4. Show 3–5 examples that cover hard cases and vary irrelevant features.
  5. Fix the output format, preferably with a schema (structured outputs).
  6. Give an escape hatch: a defined output for "cannot answer", so the model is never forced to invent one.
  7. Order for caching: static first, dynamic last.
  8. Version, log and evaluate every change, and re-run the eval set when the model changes.

Common misconceptions

  • "Role-play makes it smarter." "You are a world-class expert" sets tone and register; it does not add knowledge. A role helps when it specifies audience and standards ("an on-call engineer reads this on a phone"), not when it flatters.
  • "Longer prompts are better." Every irrelevant sentence is a distractor competing for attention. Add context because a failure demands it, and delete what the eval set says does nothing.
  • "A prompt that works on one model works on the next." Format sensitivity correlates only weakly across models (Sclar et al.). Re-run evals on upgrade.
  • "Prompting is a stopgap until fine-tuning." For most products the order is prompt, then retrieval, then fine-tuning, and many never need the last step. Fine-tuning teaches behaviour and format robustly; it does not reliably add facts, and it multiplies the maintenance cost.

Check yourself

Why does a system prompt usually take precedence over the user message, and why is that not a security boundary?

Both are tokens in one sequence; precedence comes from post-training, which taught the model to weight text inside the system role heavily. Because it is learned behaviour, not an access control, sufficiently persuasive text later in the sequence (a user message or a retrieved document) can still override it. Security has to come from outside the model: limiting what tools can do, validating outputs, and treating retrieved text as untrusted.

Min et al. found random labels barely hurt few-shot accuracy. Does that mean examples don't matter?

No. It means the examples' main job is to identify the task: the label space, the input distribution and the format. Those still matter a great deal (Zhao et al. and Lu et al. show accuracy swinging from chance to near state-of-the-art with format and order). In the Bayesian view, the \(p(x_i\mid\theta)\) term carries evidence about the concept regardless of label noise.

Self-consistency with 40 samples gives no gain over 1 sample on some question. Name two reasons.

(1) The samples are highly correlated: at low temperature, or because the model makes the same systematic error on every path, so votes are not independent. (2) The correct answer is not the most likely single answer (\(p\) is below the probability of the most common wrong answer), in which case voting converges confidently on the wrong one.

You add the current timestamp to the first line of a 10,000-token system prompt. What happens to cost and latency, and why?

Prompt caches match an exact prefix. A value that changes on every call at the start of the prompt makes every request a cache miss, so you pay full input price for all 10,000 tokens and the full prefill latency each time. Move the timestamp to the end, after the static content.

Why does asking for reasoning before the answer help on multi-step arithmetic, from the point of view of computation?

A transformer performs a bounded amount of computation per generated token (fixed depth). Problems whose solution requires many serial steps cannot be computed in one token by a bounded-depth model of reasonable size (Feng et al. 2023), but each written intermediate token is stored in the context and read by the next forward pass, so the chain of thought extends the serial computation with the length of the chain (Merrill and Sabharwal 2023).

Derive the limiting cost ratio of prompt caching and say what bounds the saving.

Per call after the first: \(rS + D\) instead of \(S + D\), so the ratio tends to \((rS+D)/(S+D)\). Even with free cache reads (\(r=0\)) the saving is bounded by \(D/(S+D)\): the fraction of the prompt that changes every call. Caching rewards prompts that are mostly static.

Hard: a team reports their new prompt improves accuracy from 81% to 84% on a 100-case eval set. Should they ship it?

Not on that evidence alone. With \(n=100\), the standard error of a proportion near 0.8 is about \(\sqrt{0.8\cdot0.2/100}=0.04\), so a 3-point difference is well inside noise, and format sensitivity means re-wording might swing it either way. Use a paired comparison on the same cases (count cases that flipped each way, McNemar's test), enlarge the set, and read the flipped cases. See statistics for experiments and evals.

Go deeper

Papers

Videos and lectures

  • AI prompt engineering: a deep dive — Anthropic. Practitioners who write prompts for a living, on what actually works.
  • State of GPT — Andrej Karpathy, Microsoft Build 2023. Why base and assistant models need different prompts, and the "tokens need to think" argument.

Articles and docs

  • Prompting best practices — Anthropic docs. Current, concrete guidance: reasons behind rules, examples, long-context layout, reasoning.
  • Prompt engineering guide — OpenAI docs. The same craft from the other major provider; compare where they agree.
  • Prompt Engineering — Lilian Weng, 2023. A dense research-oriented survey of in-context learning and prompting methods.
  • Fuck You, Show Me The Prompt — Hamel Husain, 2024. Why you should always read the final prompt your framework sends.

Courses

  • Anthropic courses — Anthropic. Free notebooks, including an interactive prompt engineering tutorial.

Where this leads