# Prompt Engineering: A Systematic Guide to Specs, Layers, Examples and Evaluation

> Design the prompt as a task interface: write a task spec, layer system, examples and context, separate format errors from wrong judgments with an eval set, and use data to decide when few-shot, chain-of-thought or structured output pays off. Includes a runnable ticket-triage experiment.

- URL: https://dmxsf.com/en/wiki/applications/prompt-engineering/
- [DMXSF](https://dmxsf.com/en/about/)
- Intermediate
- Updated: 2026-11-24
- Tags: Prompting, Reasoning, Evaluation

## After this page you will be able to

- Explain what a prompt is to the model: a token sequence rendered by a chat template, and what separates the system and user roles.
- Turn a vague need into a checkable task spec, then layer the system message, examples and context accordingly, with stable content first.
- Use a labelled eval set to split failures into format errors and wrong judgments, and pick the right remedy: rules, examples, constrained decoding or validation and retry.
- Judge by accuracy and token cost whether few-shot examples, chain-of-thought (CoT) and structured output pay off for a given task.

The experiments on this page all use one small model, `Qwen/Qwen2.5-1.5B-Instruct` (Apache-2.0 license), run on an Apple M2 Max CPU in float32 with greedy decoding (PyTorch 2.10.0, transformers 5.3.0). Code and output sit side by side. The data is a hand-written demo set of 24 tickets and 12 word problems: it demonstrates the method and does not rank any model.

## What a prompt is to the model

An LLM does one thing: given all the previous tokens, predict the next one (see [language modeling and next-token prediction](https://dmxsf.com/en/wiki/foundations/next-token-prediction/)). The prompt is everything you put into "the previous tokens". The `system`, `user` and `assistant` roles of a chat API are not three separate channels. A **chat template** renders them into one piece of text with special markers. Here is Qwen2.5's template:

```python
from transformers import AutoTokenizer

name = "Qwen/Qwen2.5-1.5B-Instruct"
tok = AutoTokenizer.from_pretrained(name)

ticket = "My card was charged but the order still shows unpaid."
msgs = [
    {"role": "system", "content": "You triage tickets. Output JSON only."},
    {"role": "user", "content": ticket},
]
for m in (msgs, msgs[1:]):  # first with a system message, then without
    text = tok.apply_chat_template(
        m, tokenize=False, add_generation_prompt=True)
    print(text)
    print("%d tokens\n" % len(tok(text).input_ids))
```

Output:

```text
<|im_start|>system
You triage tickets. Output JSON only.<|im_end|>
<|im_start|>user
My card was charged but the order still shows unpaid.<|im_end|>
<|im_start|>assistant

33 tokens

<|im_start|>system
You are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>
<|im_start|>user
My card was charged but the order still shows unpaid.<|im_end|>
<|im_start|>assistant

40 tokens
```

Three things can be read from this output:

1. **Roles are separated by special tokens.** `<|im_start|>` and `<|im_end|>` cut the messages apart, and post-training teaches the model to read this format as "who is speaking" (see [post-training](https://dmxsf.com/en/wiki/post-training/)).
2. **There is a system message even when you write none.** Without one, this template inserts `You are Qwen, created by Alibaba Cloud. You are a helpful assistant.`, which moves the count from 33 to 40 tokens. Hosted APIs may also prepend hidden system content before your messages, and OpenAI's [prompt caching guide](https://platform.openai.com/docs/guides/prompt-caching) mentions it. So the prompt the model sees is often longer than the one you wrote.
3. **The rendering ends with `<|im_start|>assistant`.** The model continues from there, and every word you wrote is a condition on that continuation, so wording, order and format all change the output distribution. Decoding settings change it too, see [decoding and sampling](https://dmxsf.com/en/wiki/inference/decoding-and-sampling/).

"System beats user" is not a protocol guarantee either. It is a trained tendency. [Wallace et al. (2024)](https://arxiv.org/abs/2404.13208) argue that models often give a developer's system prompt the same priority as text from untrusted users and third parties, and propose training models on data for an "instruction hierarchy". So **do not treat the system prompt as a security boundary**: permissions, validation and human confirmation belong outside the prompt, as the security section below explains.

## A running example: ticket triage

An online store wants to sort support tickets into three classes and hand them to different downstream systems:

| Class | Meaning | Example | `requires_human` |
| --- | --- | --- | --- |
| `faq` | General rules, policies or how-to, not tied to the user's own order | "Do you accept returns within seven days without a reason?" | `false` |
| `order_lookup` | Asks about the status of the user's own order, refund or shipment, with nothing abnormal | "Where is order A1001 right now?" | `false` |
| `escalation` | A money problem, physical safety, a complaint or a legal dispute | "My card was charged but the order still shows unpaid" | `true` |

The output must be one JSON object with just two fields, `task_type` and `requires_human`. The eval set has 24 tickets, 8 per class. 12 are **dev** (the development set, used to look at failures and edit the prompt) and 12 are **test** (held out, looked at only at the end). It includes deliberate boundary pairs: "How long does a refund usually take to arrive?" asks about general policy, while "Can you check how far along the refund for order B2002 is?" looks up the user's own order.

<details>
<summary>The data and the prompts (click to see the code)</summary>

```python
DEV = [
    ("Do you accept returns within seven days without a reason?", "faq"),
    ("How do I change my default shipping address?", "faq"),
    ("How long does a refund usually take to arrive?", "faq"),
    ("How can I redeem loyalty points for cash?", "faq"),
    ("Where is order A1001 right now?", "order_lookup"),
    ("I ordered yesterday. When will it ship?", "order_lookup"),
    ("Can you check how far along the refund for order "
     "B2002 is?", "order_lookup"),
    ("The tracking for my Bluetooth earbuds says in "
     "transit. When will they arrive? Order C3003.", "order_lookup"),
    ("My card was charged but the order still shows "
     "unpaid. What do I do?", "escalation"),
    ("Three unauthorized charges hit my account. Fix this "
     "right now!", "escalation"),
    ("Support keeps passing me around. Solve this or I "
     "will file a complaint with the consumer protection "
     "agency.", "escalation"),
    ("The power bank I received gets very hot and the case "
     "is bulging. I am worried about safety.", "escalation"),
]

TEST = [
    ("Can I get a VAT invoice for my purchase?", "faq"),
    ("Are pre-order items non-refundable?", "faq"),
    ("Do you ship overseas, and how is shipping calculated?", "faq"),
    ("How do I cancel an order that has not shipped yet?", "faq"),
    ("Please check whether order D4004 has left the "
     "warehouse.", "order_lookup"),
    ("What is the tracking number for the keyboard I "
     "bought last week?", "order_lookup"),
    ("Has the return request for order E5005 been approved?", "order_lookup"),
    ("Which city is the parcel for order F6006 in now?", "order_lookup"),
    ("I was charged twice for the same order. Please "
     "refund the extra charge immediately.", "escalation"),
    ("I never placed an order but got a payment text "
     "message. Was my account stolen?", "escalation"),
    ("The product is nothing like the description. I have "
     "talked to a lawyer and plan to sue.", "escalation"),
    ("My baby burned a hand on the bottle you sell. I "
     "demand compensation and accountability.", "escalation"),
]

SHOTS = [
    ("How does shipping insurance pay out?", "faq"),
    ("Has the parcel for order G7007 been delivered?", "order_lookup"),
    ("The refund I received is 50 dollars short, and "
     "support keeps ignoring it.", "escalation"),
]

MATH = [
    ("Ben has 23 apples, gives 8 to a classmate, then buys 3 boxes "
     "with 12 apples each. How many apples does he have now?", 51),
    ("A bookshelf has 4 shelves with 18 books on each. After 15 "
     "books are borrowed, 6 are returned. How many books are on the "
     "shelf now?", 63),
    ("The canteen made 120 buns in the morning and sold 3/4 of them. "
     "In the afternoon it made 30 more. How many buns are there now?", 60),
    ("A car drives at 60 km/h for 2.5 hours, rests, then drives at "
     "80 km/h for 1.5 hours. How many kilometers does it cover in "
     "total?", 270),
    ("A jacket is priced at 200 dollars with a 20 percent discount, "
     "and then a 30 dollar coupon is applied. How many dollars does "
     "the buyer finally pay?", 130),
    ("A class has 45 students, and there are 7 more boys than girls. "
     "How many girls are there?", 19),
    ("Amy reads 14 pages a day. After 6 days, 59 pages are still "
     "unread. How many pages does the book have?", 143),
    ("A case of milk holds 24 cartons. Sam buys 5 cases, drinks 37 "
     "cartons, and gives 2 cases to a neighbor. How many cartons are "
     "left?", 35),
    ("A tank holds 500 liters. Every minute 15 liters flow out and "
     "8 liters flow in. How many liters are in the tank after 20 "
     "minutes?", 360),
    ("The average of three numbers is 24, and two of them are 20 and "
     "31. What is the third number?", 21),
    ("Leo has 150 dollars. Each week he saves 25 dollars and spends "
     "10 dollars. How many dollars does he have after 12 weeks?", 330),
    ("A rectangular garden is 18 m long and 12 m wide. A tree is "
     "planted every 3 m along the perimeter. How many trees are "
     "planted?", 20),
]

V1 = (
    "You triage e-commerce support tickets. Read the ticket and output JSON "
    "with the fields task_type (one of faq, order_lookup, escalation) and "
    "requires_human (true or false)."
)

RULES = (
    "\n"
    "Classification rules:\n"
    "- faq: asks about general rules, policies or how-to, not tied to the "
    "user's own order.\n"
    "- order_lookup: asks for the status or details of the user's own order, "
    "refund or shipment, with nothing abnormal.\n"
    "- escalation: involves a money problem (double charge, unauthorized "
    "charge, charged but unpaid), physical safety, a complaint or a legal "
    "dispute.\n"
    "requires_human is true only for escalation.\n"
)

STRICT = "Output a single JSON object, with no code fence and no explanation."

COT = (
    "Think step by step. Start with 'Analysis:' and explain in one or two "
    "sentences which kind of ticket it is. Then, on the last line, output a "
    "single JSON object, with no code fence."
)

SYS_DIRECT = (
    "You are a math assistant. Output only the final numeric answer, with no "
    "units and no explanation."
)

SYS_COT = (
    "You are a math assistant. Reason step by step, and write the last line "
    "as 'Answer: ' followed by the number."
)
```

</details>

### Build the evaluation before you edit the prompt

The small harness below underlies all the experiments. `chat` calls the model (greedy decoding, so the same input always gives the same output), `parse` and `label_of` score the output, and `evaluate` runs the eval set one case at a time. The three verdicts answer different questions:

| Metric | Meaning | Question it answers |
| --- | --- | --- |
| `valid` | The whole output is valid JSON with the right field types and values | Can downstream code use it directly? |
| `label` | The last label word in the output equals the gold label, whatever the format | Did the model judge correctly? |
| `both` | Both hold | How many cases succeed end to end? |

Keeping "format error" and "wrong judgment" apart matters because their remedies are completely different, as the results show.

```python
import json
import re

import torch
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained(name, dtype=torch.float32)
LABELS = ("faq", "order_lookup", "escalation")

def chat(messages, max_new_tokens=60):
    """Greedy decoding; return the new text and its token count."""
    enc = tok.apply_chat_template(
        messages, add_generation_prompt=True,
        return_tensors="pt", return_dict=True)
    with torch.no_grad():
        out = model.generate(
            **enc, max_new_tokens=max_new_tokens, do_sample=False,
            repetition_penalty=1.0)  # turn off Qwen's default 1.1: pure greedy
    new = out[0, enc["input_ids"].shape[1]:]
    return tok.decode(new, skip_special_tokens=True), len(new)

def parse(text):
    """Strict: the whole output is valid JSON with right types and values."""
    try:
        obj = json.loads(text.strip())
    except json.JSONDecodeError:
        return None
    if (isinstance(obj, dict) and obj.get("task_type") in LABELS
            and isinstance(obj.get("requires_human"), bool)):
        return obj
    return None

def label_of(text):
    """Lenient: the last label word in the output, to separate format errors
    from wrong judgments."""
    hits = [(text.rfind(w), w) for w in LABELS if w in text]
    return max(hits)[1] if hits else None

def build(system, shots=()):
    """Return ticket -> messages; few-shot examples are user/assistant turns."""
    def make(ticket):
        msgs = [{"role": "system", "content": system}]
        for text, gold in shots:
            answer = {"task_type": gold, "requires_human": gold == "escalation"}
            msgs.append({"role": "user", "content": text})
            msgs.append({"role": "assistant", "content": json.dumps(answer)})
        msgs.append({"role": "user", "content": ticket})
        return msgs
    return make

def evaluate(make, cases, max_new_tokens=60):
    """Call the model once per case and record the output and three verdicts."""
    rows = []
    for ticket, gold in cases:
        text, n = chat(make(ticket), max_new_tokens)
        obj = parse(text)
        rows.append({
            "ticket": ticket, "gold": gold, "text": text, "n": n,
            "valid": obj is not None,
            "label": label_of(text) == gold,
            "both": obj is not None and obj["task_type"] == gold,
        })
    return rows

def show(name, split, rows):
    n = len(rows)
    cnt = lambda key: "%d/%d" % (sum(r[key] for r in rows), n)
    tokens = sum(r["n"] for r in rows) / n
    print("%-5s%-6s%-8s%-8s%-8s%4.0f" % (
        name, split, cnt("valid"), cnt("label"), cnt("both"), tokens))
```

### What happens without a schema

Start with the plainest prompt, which only says "output JSON" and names no fields:

```python
reply, n = chat([
    {"role": "system", "content": "You triage tickets. Output JSON only."},
    {"role": "user", "content": DEV[8][0]},
])
print("fields:", re.findall(r'"([^"]+)"\s*:', reply))
print("code fence:", "```" in reply)
print("accepted by parse:", parse(reply) is not None)
```

Output:

```text
fields: ['status', 'description']
code fence: True
accepted by parse: False
```

The model returned a code-fenced block whose field names it made up (`status` and `description`) instead of the `task_type` and `requires_human` we want, so `parse` rejected it. Saying "output JSON" does not constrain fields, values or types: all of that has to be written into the prompt and then checked by code.

## Step 1: write the task as a spec, then write the prompt

How good the prompt is depends on whether the task was thought through first. Answer four questions before writing; the table gives the answers for ticket triage:

| Question | Answer for ticket triage |
| --- | --- |
| What does the user really want done? | Sort the ticket into one of three classes so downstream systems can route it |
| What inputs does the model get? | A piece of ticket text, with or without an order number |
| What must the output satisfy? | One JSON object with fixed fields and values and no extra text |
| When should it refuse, ask back or degrade? | If none of the three classes fits, there needs to be a fourth exit (say `other`, or hand off to a person), otherwise the model has to force the ticket into one of them |

"Summarize this document" looks simple, yet it leaves out at least: who the summary is for, how long it should be, which points to keep, whether to list risks, and whether to use a fixed template. If you do not write these down, the model has to guess.

Every constraint in the spec should be **checkable**. Anthropic's prompting guide offers a simple test: hand the prompt to a colleague who knows nothing about the task and ask them to follow it. If they would be confused, so will the model.

| Vague | Checkable |
| --- | --- |
| "Keep it short" | "At most 80 words" |
| "Be professional" | "Use the tone of technical documentation, no exclamation marks or emoji" |
| "Output JSON" | "Output one JSON object; `task_type` is one of faq, order_lookup, escalation; `requires_human` is a boolean" |
| "Do not make things up" | "If the material has no answer, reply 'not in the material'" |

The same guide also suggests stating the **reason** behind an instruction (for example "the reply will be read aloud by a speech engine, so do not use ellipses"), which lets the model generalize to cases you did not list.

## Step 2: layer the messages, stable content first

Piling every requirement into the user message mixes the task with the rules, lets the rules drift over a long conversation, and produces a template that keeps growing and gets less stable. Layering is better, because the layers differ in responsibility and in how often they change:

*Figure: System sets the rules, Examples show what a good answer looks like, Context supplies this request's evidence and User states the current task. Layering by change frequency makes a prompt easier to maintain, regression-test and cache.*

| Layer | What goes in | How often it changes |
| --- | --- | --- |
| System | Role, rules, output format, refusal limits | Almost never |
| Examples | Few-shot examples, edge cases | Occasionally |
| Context | RAG passages, tool results, business state, conversation history | Every request |
| User | The current request | Every request |

Layering pays off in three ways: rules do not fade in a long conversation, you can A/B test one layer on its own, and putting the stable layers first lets the serving stack reuse a cache.

### Stable content first: prefix caching

A serving stack can reuse the KV cache of a shared prefix (see [KV cache](https://dmxsf.com/en/wiki/inference/kv-cache/)) across requests, provided the prefix tokens are identical. OpenAI's prompt caching guide is explicit about this: reuse requires the whole rendered prefix to match, and it advises putting stable developer instructions and shared reference material first, and moving timestamps, user-specific content and other dynamic content to the end. The cell below counts, with the tokenizer, how many leading tokens two different tickets share under two layouts:

```python
def common_prefix(a, b):
    n = 0
    for x, y in zip(a, b):
        if x != y:
            break
        n += 1
    return n

system = V1 + RULES + STRICT
tickets = (DEV[0][0], DEV[8][0])  # two different tickets
layouts = {
    "rules first": lambda t: [
        {"role": "system", "content": system},
        {"role": "user", "content": t}],
    "ticket first": lambda t: [
        {"role": "user", "content": t + "\n\n" + system}],
}
for name, make in layouts.items():
    ids = [tok(tok.apply_chat_template(
        make(t), tokenize=False, add_generation_prompt=True)).input_ids
        for t in tickets]
    print("%s: request 1 has %d tokens, the first %d match request 2" % (
        name, len(ids[0]), common_prefix(*ids)))
```

Output:

```text
rules first: request 1 has 163 tokens, the first 147 match request 2
ticket first: request 1 has 179 tokens, the first 24 match request 2
```

With the rules first, the two requests share their first 147 tokens (about 90% of request 1), which a server can reuse. With the ticket first, only 24 tokens match, and those 24 are exactly the template's default system block and the user marker, with none of the rules in them. The earlier the unchanging part sits in the request, the more of it a cache can absorb.

There is a second rule of thumb for long documents. Anthropic's long-context advice is to put long documents at the top of the prompt and the question at the end, and it states that in its tests this improved response quality by up to 30 percent, especially for complex multi-document inputs. That points the same way as "stable first, variable last". As for where evidence sits inside a context, the results of [Lost in the Middle](https://dmxsf.com/en/blog/lost-in-the-middle/) are a reminder that information at the beginning or end is used more easily than information buried in the middle.

## Step 3: start from a minimal prompt and fix what the numbers show

We start from the simplest prompt and add things step by step, in three versions. V2 adds the rules and the format sentence together, so their separate contributions cannot be told apart here; in a real project, try them separately.

| Version | System content | Examples |
| --- | --- | --- |
| V1 | One sentence naming the task and the fields | None |
| V2 | V1, three classification rules, and the line "Output a single JSON object, with no code fence and no explanation" | None |
| V3 | Same as V2 | 3 examples as user/assistant turns, where the assistant reply is bare JSON |

The procedure: look at failures and edit the prompt on dev only, and leave test for the end.

```python
make = {
    "V1": build(V1),
    "V2": build(V1 + RULES + STRICT),
    "V3": build(V1 + RULES + STRICT, SHOTS),
}
runs = {}
print("name split valid   label   both    tokens")
for name, fn in make.items():
    for split, cases in (("dev", DEV), ("test", TEST)):
        runs[name, split] = evaluate(fn, cases)
        show(name, split, runs[name, split])

print()
for name in make:
    rows = runs[name, "dev"] + runs[name, "test"]
    fence = sum("```" in r["text"] for r in rows)
    strbool = sum(bool(re.search(r'"requires_human":\s*"', r["text"]))
                  for r in rows)
    print("%s: %d with a code fence, %d with the boolean written as a string"
          % (name, fence, strbool))

print()
for name in ("V2", "V3"):
    for r in runs[name, "dev"] + runs[name, "test"]:
        if not r["label"]:
            print("%s wrong (gold %s, predicted %s):" % (
                name, r["gold"], label_of(r["text"])))
            print("  " + r["ticket"])
print()
bad = [r for r in runs["V2", "dev"] if not r["valid"]]
print("V2 output with a format error:")
print(repr(bad[0]["text"]))
```

Output (`valid`, `label` and `both` are defined in the table above, and `tokens` is the average number of output tokens per case):

```text
name split valid   label   both    tokens
V1   dev   0/12    11/12   0/12      23
V1   test  0/12    10/12   0/12      22
V2   dev   7/12    12/12   7/12      19
V2   test  9/12    10/12   8/12      19
V3   dev   12/12   12/12   12/12     15
V3   test  12/12   12/12   12/12     15

V1: 24 with a code fence, 0 with the boolean written as a string
V2: 3 with a code fence, 5 with the boolean written as a string
V3: 0 with a code fence, 0 with the boolean written as a string

V2 wrong (gold order_lookup, predicted faq):
  Has the return request for order E5005 been approved?
V2 wrong (gold escalation, predicted faq):
  I never placed an order but got a payment text message. Was my account stolen?

V2 output with a format error:
'```json\n{\n  "task_type": "faq",\n  "requires_human": false\n}\n```'
```

The widget below makes this table switchable: pick a version to see valid, label and both on the two 12-case splits plus the failure-cause counts — V1's judgment is mostly right and the failure is all format; V3 locks the format without improving judgment.

Reading the table row by row:

1. **V1: the format fails first.** `valid` is 0 out of 24 while `label` is 21 out of 24. The model mostly knows which class to pick, and the trouble is almost entirely format: all 24 outputs were wrapped in a code fence. The fix is a format requirement, not doubting that the model can classify.
2. **V2: rules and a format sentence help on both counts, but the format is not locked.** `valid` rises to 16 of 24 and `label` to 22 of 24. Only 3 outputs still have a fence, but 5 write the boolean as a string. `both` is 7 of 12 on dev and 8 of 12 on test, and two judgments are still wrong: "Has the return request for order E5005 been approved?" (order_lookup) and "I never placed an order but got a payment text message" (escalation) were both predicted as faq.
3. **V3: three examples lock the format and fix both judgments.** `valid`, `label` and `both` are all 24 of 24, and the average output shrinks to 15 tokens. None of the three examples is a copy of an eval ticket, so this is not memorization. Still, it is 24 tickets, one model and greedy decoding. Run the same design on the Chinese tickets (see the Chinese edition of this page) and V3 fixes the format but still gets one ticket wrong, a different one from V2. A perfect score on 24 tickets is not a guarantee.

So after every prompt change, look at which tickets got better and which got worse, not just at the total, and add the newly failing ones to the regression set.

## Few-shot examples: give a decision standard, not a pile

Few-shot prompting shows the model directly what kind of input belongs to the task and what counts as a good output. A few studies are worth remembering. Each one is a result on particular models and tasks, so do not extrapolate freely:

| Study | Finding |
| --- | --- |
| [Brown et al. (2020)](https://arxiv.org/abs/2005.14165), GPT-3 | Tasks and demonstrations are specified purely through text, with no gradient updates; scaling up the model greatly improves few-shot performance |
| [Min et al. (2022)](https://arxiv.org/abs/2202.12837) | Randomly replacing the labels in the demonstrations barely hurts performance on a range of classification and multiple-choice tasks, across 12 models; what drives performance is that the demonstrations show the label space, the distribution of the input text and the overall format |
| [Zhao et al. (2021)](https://arxiv.org/abs/2102.09690) | The prompt format, the choice of examples and even their order can move accuracy from near chance to near state of the art; one cause is the model's bias toward certain answers, such as those near the end of the prompt or common in pre-training |
| [Sclar et al. (2023)](https://arxiv.org/abs/2310.11324) | In few-shot settings, changing only the formatting of the prompt, in ways that keep the meaning, gave performance differences of up to 76 accuracy points on LLaMA-2-13B; the sensitivity remains with larger models, more examples or instruction tuning, and the best format correlates only weakly between models |

Back in our experiment: V3 writes the examples' assistant replies as bare JSON, and the model then outputs bare JSON, which agrees with Min et al.: examples first teach format and label space. In practice you can follow this table:

| Practice | Reason |
| --- | --- |
| Usually 3 to 5 examples, covering edge cases rather than piling up | Anthropic's guide recommends 3-5 and stresses examples that are relevant, diverse and cover edge cases |
| Make the examples' format identical to the output you want | The model copies the format, including the parts you did not want |
| Keep the classes roughly balanced among the examples and watch the order | Zhao et al. found a bias toward answers near the end or common ones |
| Keep examples out of the eval set | Otherwise the score is memorized |
| Try zero-shot first, then add examples if needed | Advice from OpenAI's guide for reasoning models; the examples must match the instructions closely, or they may hurt |
| Re-evaluate whenever you change the model | The best format correlates only weakly between models |

## Chain-of-thought: use it when it fits, skip it when it does not

Chain-of-thought (CoT) prompting makes the model write intermediate reasoning steps before the answer. [Wei et al. (2022)](https://arxiv.org/abs/2201.11903) gave a 540B-parameter model eight chain-of-thought exemplars and reached state-of-the-art accuracy on the GSM8K math word-problem benchmark, surpassing even a fine-tuned GPT-3 with a verifier. [Kojima et al. (2022)](https://arxiv.org/abs/2205.11916) found that just adding "Let's think step by step" before the answer (zero-shot CoT) raised InstructGPT (text-davinci-002) from 17.7% to 78.7% on MultiArith and from 10.4% to 40.7% on GSM8K. [Wang et al. (2022)](https://arxiv.org/abs/2203.11171) replaced greedy decoding with sampling several reasoning paths and voting (self-consistency), and the paper's abstract reports a 17.9% improvement on GSM8K.

In our small experiment, take 12 multi-step word problems (the answers are checked by code) and compare "answer directly" with "reason step by step":

```python
def numbers(text):
    return re.findall(r"-?\d+(?:\.\d+)?", text.replace(",", ""))

def answer_number(text):
    """First number after the last 'Answer:', else the last number."""
    if "Answer:" in text:
        nums = numbers(text.rsplit("Answer:", 1)[1])
        return float(nums[0]) if nums else None
    nums = numbers(text)
    return float(nums[-1]) if nums else None

print("mode              correct   avg tokens")
for mode, system, budget in (("direct answer", SYS_DIRECT, 40),
                             ("step by step", SYS_COT, 300)):
    results = []
    for question, gold in MATH:
        text, n = chat([{"role": "system", "content": system},
                        {"role": "user", "content": question}], budget)
        results.append((answer_number(text) == gold, n))
    right = sum(ok for ok, _ in results)
    tokens = sum(n for _, n in results) / len(results)
    print("%-16s %2d/%d      %5.0f" % (mode, right, len(MATH), tokens))
```

Output:

```text
mode              correct   avg tokens
direct answer     0/12         10
step by step     11/12        164
```

Answering directly, the model got none of the 12 right. Asked to write out its steps, it got 11 right, at the cost of the average output growing from 10 tokens to 164, about 16 times as long. The one miss is a real reasoning error, not a formatting one: for the tank that loses 15 liters and gains 8 liters per minute, the model took the net change as +7 per minute instead of -7 and answered 640 instead of 360, so step by step is not a guarantee. The problems are hand-written and the answers were checked with code, but 12 problems are far too few to measure a model: they show a direction and nothing more. Wei et al. and Kojima et al. report the same direction on much larger benchmarks.

Now look at the same model on ticket triage. This time keep V2's rules but replace the format sentence with a chain-of-thought instruction: think step by step, start with `Analysis:` and one or two sentences, then put the JSON on the last line. A first wording that only asked for an analysis before the JSON was ignored by this model, and most of its outputs were bare JSON, so how well a model follows such an instruction is part of what you test:

```python
import textwrap

make_cot = build(V1 + RULES + COT)
print("name split valid   label   both    tokens")
cot_rows = {}
for split, cases in (("dev", DEV), ("test", TEST)):
    cot_rows[split] = evaluate(make_cot, cases, max_new_tokens=160)
    show("CoT", split, cot_rows[split])
print()
for line in cot_rows["dev"][0]["text"].splitlines():
    print(textwrap.fill(line, 76))  # layout only: wrap long lines
```

Output (compare with the two V2 lines above):

```text
name split valid   label   both    tokens
CoT  dev   0/12    11/12   0/12      51
CoT  test  0/12    12/12   0/12      52

Analysis: This ticket is about a general rule or policy question, not tied
to the user's own order. It does not involve any abnormal status or details
of an order, nor does it involve money problems, physical safety,
complaints, or legal disputes.

{
  "task_type": "faq",
  "requires_human": false
}
```

Compared with V2, analyzing first changes three things:

1. Label accuracy is about the same: 11 of 12 on dev and 12 of 12 on test, 23 of 24 in total, against 22 of 24 for V2. One ticket more is well inside the noise of a 24-ticket set.
2. The average output grows from about 19 tokens to more than 50, about 2.7 times as long, and latency and cost rise with it.
3. The whole output is no longer valid JSON (`valid` is 0 of 24): the model writes an analysis first, so downstream code needs an extra step to extract the JSON, which is one more place to fail.

This gives a task table:

| Task | Reason first? | Why |
| --- | --- | --- |
| Multi-step arithmetic, logic, multi-condition decisions | Yes | The intermediate steps are the computation |
| Classification, extraction, rewriting, format conversion | Not by default | The answer does not depend on long reasoning, and it adds tokens and format risk |
| Output that must be a stable structure | Keep the reasoning apart from the final answer | Reasoning text mixed into the output breaks parsing; see [structured outputs and function calling](https://dmxsf.com/en/wiki/applications/structured-output-and-function-calling/) |

Models with built-in reasoning (often called reasoning models) generate a long chain of thought on their own before answering, so the prompting strategy changes too. OpenAI's guide for reasoning models (consulted in November 2026) says these models work best with simple, direct prompts, that techniques such as "think step by step" may not improve performance and can sometimes hinder it, and its advice includes avoiding chain-of-thought prompts, trying zero-shot before few-shot, using delimiters to mark the parts of the input, and being specific about the success criteria. Anthropic's guide (also consulted in November 2026) explains that its newer models use adaptive thinking, where the `effort` parameter and the complexity of the query together decide how long to think, and that if a model thinks more often than you want you can steer it in the prompt, for example by writing that thinking adds latency and should be used only when it meaningfully improves answer quality, typically for multi-step problems. Whether a model has built-in reasoning, whether you can turn it off and how you tune it differ by model, so follow the documentation of the model you use. The shared principle is to stop teaching it how to think and to state the goal, the constraints and the acceptance criteria.

## Structured output, RAG and tools: the prompt is only part of the answer

The focus of the prompt differs by scenario, and each scenario has things the prompt cannot replace:

| Scenario | What the prompt must state | What you need beyond the prompt |
| --- | --- | --- |
| Structured output | The schema, what each field means, how to express a missing value, no extra text | Constrained decoding or a structured-output API, parse validation, retry on failure; see [structured outputs and function calling](https://dmxsf.com/en/wiki/applications/structured-output-and-function-calling/) |
| RAG | Answer only from the given material, admit when evidence is missing, cite sources, point out conflicts between sources | Retrieval and reranking quality, context assembly, layered evaluation; see [RAG in practice](https://dmxsf.com/en/wiki/applications/rag/) |
| Tool calling | When to call, when not to, where the arguments come from, what to do on failure | Tool schemas, permissions, timeouts and retries |
| Long context | Long documents first and the question last, with tags around each document | Control the total length and test position sensitivity; see [long context](https://dmxsf.com/en/wiki/architecture/long-context/) |

Structured output in particular cannot rest on the prompt alone. In the experiment above, V2 already said "Output a single JSON object, with no code fence and no explanation", yet 8 of 24 outputs still could not be parsed strictly (3 with a code fence and 5 with the boolean written as a string). In production, either use a structured-output API or constrained decoding so that invalid tokens cannot be sampled at all, or parse and validate in code, retry with the error message on failure, and track the failure rate.

### Security: untrusted content can carry instructions

When the context contains untrusted content such as web pages, emails or retrieved passages, instructions inside it may be followed by the model as if they were commands. This is called indirect prompt injection. [Greshake et al. (2023)](https://arxiv.org/abs/2302.12173) argue that LLM-integrated applications blur the line between data and instructions, and demonstrate attacks on real systems. OWASP lists prompt injection first in its 2025 list of risks for LLM applications (LLM01:2025) and says that, because of the stochastic nature of models, it is unclear whether fool-proof prevention exists, so the aim is to reduce the impact. Its mitigations translate directly into prompt and system design:

- constrain the model's role, capabilities and limits in the system prompt, and require strict adherence to the context;
- define the expected output format and validate it with deterministic code;
- separate external content, mark it as untrusted and limit its influence on instructions;
- give the model least-privilege access, run tools from code and keep secrets away from the model;
- require human approval for high-risk actions;
- run adversarial tests regularly, treating the model as an untrusted user when testing trust boundaries.

## Evaluation and the iteration loop

The most common trap in prompt work is to change the prompt and then ask only "does it feel better?". A steadier approach turns it into a loop:

*Figure: Good prompt iteration changes one kind of problem at a time, runs a fixed regression set and watches for side effects. That is how you tell a prompt that is more reliable from one that merely looks more careful.*

1. **Collect failures into the eval set and never remove them.** Bad cases from production and human labels make the best test cases.
2. **Classify the failures.** At least separate format errors, wrong judgments and overreach or fabrication, because they have different remedies: examples, constrained decoding and validation for format; rules and examples for judgment; permissions and system design for overreach.
3. **Change one kind of problem at a time.** If you change several things at once, you cannot tell which one worked.
4. **Use dev to look at failures and test only to decide.** Tuning repeatedly against the same cases inflates the score, and the held-out set exists to reveal that.
5. **Look at side effects, not just the total.** A stricter schema may hurt free-form answers, so the eval set should cover standard cases, paraphrases, long-context cases, risky cases and format cases.
6. **Manage prompts like code.** Keep them in version control and record them together with the model version; re-evaluate when you change the model. Anthropic's guide gives the same advice: a technique measured on one model should be rechecked against your own evals before you apply it to another.
7. **Mind the sample size.** One case in a 12-case set is 8.3 points, so a small gap is not an improvement; see [the statistics of evaluation](https://dmxsf.com/en/wiki/evaluation/eval-statistics/) for how to handle this properly.

## How to choose a strategy

First decide what the main problem of the task is, then pick the matching strategy, instead of stacking every technique:

| Main problem of the task | Prefer | Do not rush to add |
| --- | --- | --- |
| A stable structured output (classification, extraction, routing) | A schema, rules, examples that match the output exactly, and constrained decoding if needed | Long reasoning |
| Multi-step reasoning and planning | A step-by-step template or CoT; for reasoning models, only the goal and constraints | Many examples |
| Answers grounded in evidence (RAG, document Q&A) | Answer only from the given material, admit insufficient evidence, cite sources | Letting the model improvise |
| Calling external tools | State when to call, when not to, where arguments come from and what to do on failure | Scattering the rules across several places |

## Common mistakes

| Mistake | Why it is wrong | What to do |
| --- | --- | --- |
| Treating prompt engineering as a word-swapping game | Without an eval set you cannot tell improvement from luck | A fixed eval set plus a held-out set, one kind of problem at a time |
| Repeating "you must output JSON" when the format is wrong | One format sentence only suppresses part of the problem: after V2 added "no code fence", fenced outputs dropped from 24 to 3 but not to zero, and three bare-JSON examples brought them to 0. Repeating the sentence has limited effect | Use examples, constrained decoding or structured outputs, plus validation and retry |
| The more examples the better | Too many or too long examples drown the instructions, and covering edge cases matters more than the count | 3 to 5, covering edge cases |
| Adding "reason step by step" to every task | Not every task benefits: on this page's classification task, analyzing first changed label accuracy by one ticket (23 of 24 against 22 of 24) while making outputs about 2.7 times longer and adding a step to extract the JSON | Measure on your own eval set first |
| Tuning on one model and assuming it transfers | The best format correlates only weakly between models | Rerun the evaluation when you change the model |
| Not telling a model limit from a prompt problem | A model limit calls for a stronger model or fine-tuning, a prompt problem for editing the prompt, and the remedies are completely different | Try a stronger model on the same eval set to see where the ceiling is |

## Summary and exercises

**Key points:**

1. The prompt is the condition for the model's continuation: the chat template renders system, user and assistant into one token sequence with special markers, and the priority between roles is a trained tendency, not a security boundary.
2. Write a checkable task spec first, then layer the prompt with stable content first, which helps both maintenance and prefix-cache hits.
3. Use the eval set to split failures into format errors and wrong judgments. An explicit format sentence removes most format errors, examples make the format steadier, and constrained decoding plus validation finish the job; wrong judgments call for rules, examples or a stronger model, and the failing case stays in the regression set.
4. Few-shot examples first teach format, label space and input distribution; chain-of-thought pays off only on multi-step reasoning, and for classification-type tasks you have to measure it.
5. The prompt is only part of the answer: validation, retries, permissions and human confirmation belong outside it, and prompt changes need an eval set, a held-out set and version management.

### Quick self-check

**1. What does a chat template do with the system and user messages?**

- [ ] It sends them through two separate channels that the model processes independently
- [x] It renders them into one token sequence with special markers, and the model continues after the final assistant marker
- [ ] It writes the system message permanently into the model weights
- [ ] It checks outside the model whether the user has permission

> Roles are told apart by special tokens such as `<|im_start|>`, and the whole request is really one piece of text. "System beats user" is a trained tendency, not a protocol guarantee, so permission checks cannot rest on the system prompt alone.

**2. In this page's experiment, V1 has `valid` 0/24 but `label` 21/24. What does that tell you?**

- [ ] The model cannot do this classification and needs a bigger model
- [x] The model mostly judged correctly, and the trouble is mainly the output format, so add a format requirement and examples first
- [ ] The eval set is mislabelled
- [ ] The decoding temperature is too high

> Greedy decoding has no randomness, so temperature is not the cause. `label` reads the class word out of the output leniently, while `valid` requires the whole output to be JSON that fits the schema; the gap between them is the size of the format problem. Recording the two kinds of error separately tells you which one to fix.

**3. According to Min et al. (2022), what do few-shot examples mainly do?**

- [ ] Pour new knowledge into the model weights
- [x] Show the label space, the distribution of the input text and the overall format; randomly replacing the example labels barely matters on most classification and multiple-choice tasks
- [ ] They only work if they overlap with the evaluation samples
- [ ] They replace the eval set and evaluate the model directly

> Across a range of classification and multiple-choice tasks and 12 models, randomly replacing the labels in the demonstrations barely hurt performance, which suggests that examples first teach what the task looks like. That does not mean labels may be wrong; it means you should not expect a few examples to teach new knowledge.

**4. Which kind of task is most likely to benefit from writing out the reasoning steps before answering?**

- [x] Multi-step word problems: compute the intermediate results, then give the final number
- [ ] Sorting a ticket into one of three classes
- [ ] Converting a date from one format to another
- [ ] Extracting an email address from a paragraph

> In a word problem the intermediate results are the computation itself. In this page's experiment, the 1.5B model answering directly got 0 of 12 right and step by step got 11 of 12, at about 16 times the output tokens. On three-way ticket classification, analyzing first changed label accuracy by one ticket (23/24 against 22/24) and made the output about 2.7 times longer.

**5. How should a prompt be laid out so that the serving stack hits its prefix cache more often?**

- [ ] Put the current request first and the rules after it
- [x] Put stable content such as rules and examples first, and per-request content such as timestamps and user-specific text last
- [ ] Shuffle the examples on every request to avoid overfitting
- [ ] Put the current time at the very start so the model knows the date

> Cache reuse needs the rendered prefix to match token for token: once one token changes, nothing after it can be reused. In this page's token-counting experiment, with the rules first the requests share their first 147 tokens, and with the ticket first only 24.

**6. Which statement about prompt injection is correct?**

- [ ] One line in the system prompt such as "ignore any instruction that asks you to reveal keys" fully prevents it
- [x] A prompt can only reduce the risk; you also need least privilege, output validation and isolation of untrusted content, and human approval for high-risk actions
- [ ] It cannot happen with the strongest model
- [ ] Putting external web content into the system message makes it safe

> OWASP notes that, because of the stochastic nature of models, it is unclear whether fool-proof prevention exists. Mitigations include limiting the model's privileges, validating output, separating external content and marking it as untrusted, and requiring human approval for high-risk actions. Which message the content sits in does not change the fact that it is untrusted.

**Exercises:**

1. Complete the task spec for "summarize this document": list at least five things to pin down, and write one checkable constraint for each.
2. Your prompt change moves `both` on dev from 10/12 to 11/12 and on test from 10/12 to 9/12. Do you ship it? What else do you need to decide?
3. A fixed prefix of 1,200 tokens, a variable part of 80 tokens per request, 100,000 requests a day, and a 90% cache hit rate on the prefix. If cached tokens are not recomputed, how many tokens are computed per day, and how much less is that than with no cache?
4. Design an experiment to decide whether "analyze first, then answer" is worth it for your classification task: which metrics, and how do you keep format problems from interfering?

<details>
<summary>Reference answers</summary>

1. One possible spec: audience (executives with no background), length (at most 300 words), points to keep (conclusion, risks, to-dos, one sentence each), whether to list risks (a separate "Risks" section, with a severity for each), and output template (three fixed headings). The point is that each item can be checked by a person or by code, rather than "write it more professionally".
2. The difference is a single case, which is 8.3 points in a set of 12, so you cannot decide from it. You need a larger eval set or repeated evaluation to estimate the noise (see [the statistics of evaluation](https://dmxsf.com/en/wiki/evaluation/eval-statistics/)), then look at what kind of failure changed (format or judgment), whether there are side effects, and what the change costs (tokens, latency). Better on dev and worse on test also calls for suspicion of overfitting to dev.
3. Without a cache, $10^5\times(1200+80)=1.28\times10^8$ tokens are processed per day. With the cache only 10% of the prefix is recomputed, so $10^5\times(1200\times0.1+80)=2\times10^7$ tokens are computed per day, about 84% less than with no cache. This counts only tokens that need recomputing, and ignores how providers price cache reads and writes.
4. Use the same rules and the same eval set and change only whether the model analyzes first, keeping dev and test. Metrics should include at least label accuracy and the average number of output tokens (cost and latency). To keep format problems out of the comparison, read the label in a way that can take the final answer out of the reasoning text (this page's `label_of`), and record format validity separately so the two kinds of error are not mixed.

</details>

## Further reading

- How prompts elicit reasoning: the [Chain-of-Thought Prompting walkthrough](https://dmxsf.com/en/blog/chain-of-thought-prompting/) on this site, and the original paper by Wei et al., [Chain-of-Thought Prompting Elicits Reasoning in Large Language Models](https://arxiv.org/abs/2201.11903).
- Evidence use in long contexts: the [Lost in the Middle explainer](https://dmxsf.com/en/blog/lost-in-the-middle/).
- Connect prompts to retrieval: [RAG in Practice: Chunking, Hybrid Retrieval, Reranking and Evaluation](https://dmxsf.com/en/wiki/applications/rag/); make output reliably usable by programs: [Structured Outputs and Function Calling: From JSON Mode to Constrained Decoding](https://dmxsf.com/en/wiki/applications/structured-output-and-function-calling/).
- Bring prompt iteration into a full evaluation loop: [LLM Evaluation Methodology: Benchmarks, Contamination and a Workflow](https://dmxsf.com/en/wiki/evaluation/llm-evaluation/) and [The Statistics of Evaluation: pass@k, Confidence Intervals and Sample Size](https://dmxsf.com/en/wiki/evaluation/eval-statistics/).
- Examples and format sensitivity: Min et al., [Rethinking the Role of Demonstrations](https://arxiv.org/abs/2202.12837); Zhao et al., [Calibrate Before Use](https://arxiv.org/abs/2102.09690); Sclar et al., [Quantifying Language Models' Sensitivity to Spurious Features in Prompt Design](https://arxiv.org/abs/2310.11324).
- Security: Wallace et al., [The Instruction Hierarchy](https://arxiv.org/abs/2404.13208); Greshake et al., [Not what you've signed up for](https://arxiv.org/abs/2302.12173); and OWASP's [LLM01:2025 Prompt Injection](https://genai.owasp.org/llmrisk/llm01-prompt-injection/).
- Provider guides (all consulted in November 2026): Anthropic's [Prompting best practices](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices), and OpenAI's [Reasoning best practices](https://platform.openai.com/docs/guides/reasoning-best-practices) and [Prompt caching](https://platform.openai.com/docs/guides/prompt-caching).

## Companion code

[Prompting, measured](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/prompt-engineering): The chat template rendered by hand, what a prefix cache can reuse, scorers that separate format failures from wrong judgments, the twelve word problems re-solved in code, and how far a 12-ticket eval set can be trusted. With --hf the page's experiments are rerun on Qwen2.5-1.5B-Instruct.

- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run applications/prompt-engineering`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/prompt-engineering/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/prompt-engineering/README.en.md)
- [`prompting.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/applications/prompting.py)
- [`prompt_data.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/applications/prompt_data.py)
- [`hf.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/applications/hf.py)
- [Find this lab in the catalog](https://dmxsf.com/en/code/#prompt-engineering)

## FAQ

### What does prompt engineering actually do?

It is not about magic phrases. It designs the task interface for a model: write the task as a checkable spec, place rules, examples, evidence and the current request in separate layers, then use a labelled eval set to tell format errors from wrong judgments, changing one kind of problem at a time and rerunning the set. Good prompts come from task breakdown and an evaluation loop, not from random rewording.

### What do the system message, the user message and few-shot examples each control?

The system message holds the stable role, rules and output format. The user message holds the current request. Examples show the format, the label space and the decision boundary. Retrieved passages and tool results supply evidence for this request. The chat template joins them all into one token sequence, and the priority between them is a trained tendency, not a security boundary.

### When should I use chain-of-thought prompting?

Use it for multi-step reasoning, such as word problems and multi-condition decisions. In this page's small experiment, a 1.5B model solved 0 of 12 word problems when answering directly and 11 when reasoning step by step. On three-way ticket classification, analyzing first changed label accuracy by only one ticket (23 of 24 against 22 of 24) while making the output about 2.7 times longer. Models with built-in reasoning usually do not need a step-by-step prompt, and OpenAI's guide for reasoning models advises avoiding one. Compare with and without it on your own eval set before shipping.

### How do I know a prompt change is an improvement?

Keep a fixed eval set with typical cases and past failures, and hold some of it out for the final decision. Change one kind of problem at a time, compare format validity, judgment accuracy and token cost, and check for side effects. With few cases, a single one is worth several points (1 of 12 is 8.3 points), so do not treat a small gap as an improvement.

### Should I start with prompting, RAG or fine-tuning?

Start by getting the prompt and the eval set right: it is the cheapest and fastest to iterate, and it exposes unclear requirements. Add RAG when knowledge changes or answers need sources. Consider fine-tuning when you need a stable change in behavior, style or output format and have enough high-quality data. They can be combined, and each one needs evaluation to be trusted.
