Prompt Patterns
The dozen prompting techniques that actually move quality, with the one-line version of when to use each.
A prompt is a specification, and a model follows it the way a capable new colleague would: literally, and with no memory of what you meant last time. Most of the quality comes from three things the rows keep returning to. Structure: separate instructions, data and examples, and say exactly what output you want. Grounding: give the model the facts and a sanctioned way to say it does not know. Measurement: an edit that feels better often is not, so keep a small test set and rerun it after every change.
Model generations differ, and advice that depends on the model says so.
Structure
- Role + task + constraints
- who the model is, what to produce, what must never happen — in that order
- Few-shot examples
- 2-5 input→output pairs beat a paragraph of description; match format exactly
- Output schema
- ask for JSON against a schema (or use structured output mode) — parse, don’t regex
- Delimiters
- fence retrieved/user content (
<doc>…</doc>) and say it is data, not instructions - Prefill the start
- begin the reply yourself, e.g.
{— older models only; current Claude models reject it, so use structured outputs - Explain the why
- give the reason behind a rule; models generalize from a purpose better than from a bare command
- Say what to do
- describe the behavior you want rather than listing don’ts, which can prime the mistake
Examples
- Diverse examples
- vary topic, length and edge cases so the model learns the pattern, not one surface form
- Label examples
- wrap them in tags like
<example>so they are not mistaken for the real input - Include a hard case
- show one tricky or empty input and its right handling — that is where outputs fail
- Example leakage
- models copy example details into answers; use content that cannot be mistaken for real data
Reasoning
- Chain-of-thought
- "think step by step" / worked examples — for math, logic, multi-step
- Self-consistency
- sample N answers, majority-vote — reliability on discrete answers
- Decompose
- split into subtasks across calls; each prompt does ONE job well
- Critique-then-revise
- second pass: "find errors in this answer, then fix them"
- Reasoning models
- o1/R1-class: skip CoT prompting — state the problem, set effort, stay out of the way
- Least-to-most
- solve the easiest subproblem first and feed each answer into the next
- Step-back prompting
- ask for the general principle first, then apply it to the specific question
- Think, then answer
- reasoning in
<thinking>, result in<answer>; parse only the answer
Reliability
- Grounding
- "answer ONLY from the sources; cite; say not-found otherwise" — kills most hallucination
- Escape hatch
- always give an out ("if unsure, say so") — forced answers are invented answers
- Position matters
- models recall start + end best — instructions up top, key facts near the question
- Temperature
- low (0–0.3) for extraction, higher for ideation; many reasoning models ignore or reject sampling settings
- Cache-aware order
- stable content (system, tools, examples) first; volatile (query) last
- Chain of verification
- draft, list fact-check questions, answer them independently, then revise the draft
- Quote, then answer
- have the model extract the relevant quotes first, then answer only from them
Output control
- Exact length
- “3 bullets, under 15 words each” works; “be concise” is a guess
- Match the style
- prompt in the format you want back — a markdown-heavy prompt gets markdown-heavy output
- Structured outputs
- API-level JSON schema enforcement (OpenAI, Anthropic, Gemini) — guaranteed to parse
- Stop sequences
- end generation at a marker like
</answer>— saves tokens and trimming - max_tokens
- a hard cut-off the model does not see coming — check the stop reason for truncation
Long context & documents
- Documents first
- long material at the top, the question at the end — measurably better on long inputs
- Tag each document
- wrap each in
<document>with its source so answers can cite it - Lost in the middle
- facts buried mid-context are recalled worst — restate key constraints near the question
- Less is more
- retrieve the 5 best chunks, not 50 mediocre ones; noise lowers accuracy
Agents & tools
- Tool descriptions
- they are prompts: when to use the tool, when not to, what it returns
- Act or suggest?
- say whether the model should make changes or only propose them; newer models take it literally
- Parallel calls
- ask for independent tool calls in a single turn to cut latency
- Report blockers
- tell the agent to state failures plainly instead of quietly working around them
Anti-patterns
- ALL-CAPS warnings
- CRITICAL/MUST shouting makes newer models over-apply a rule; state it calmly, once
- Contradictory rules
- conflicting instructions resolve unpredictably — audit long prompts for clashes
- Asking for confidence
- self-reported confidence scores are poorly calibrated; measure accuracy instead
- One giant prompt
- a five-job prompt does each job worse than a chain of single-job calls
- Secrets in prompts
- system prompts can be extracted — never put keys or confidential rules there
Evaluate & iterate
- Test set first
- 20–50 real inputs with expected outputs before you tune a single word
- Change one thing
- rerun the whole set after every edit; prompt changes have side effects
- LLM-as-judge
- grade with a rubric and a separate model, then spot-check it against human labels
- Pairwise comparison
- ask which of two outputs is better — more reliable than absolute 1–10 scores
- Version prompts
- keep prompts in git beside the code and log which version produced each output
Worked example: improving a ticket classifier against a test set
A support team routes tickets to billing, account, bug or other. Start with 40 real tickets labelled by the people who route them today, and score every prompt version on all 40.
from collections import Counter
def score(prompt_version, cases):
misses = Counter()
for case in cases:
got = classify(prompt_version, case["text"]) # your model call
if got != case["label"]:
misses[(case["label"], got)] += 1
correct = len(cases) - sum(misses.values())
return correct, misses.most_common(3)Suppose the first version, “Classify this ticket into one of four labels,” scores 31 of 40 (77.5%), and the top miss is ("account", "billing") six times: password resets that mention a subscription. The fix comes from that confusion pair, not from guessing:
- Add one line per label that states the boundary: “billing: money moved, or should have. account: access, login, profile, even when a plan is mentioned.”
- Add one hard example: a login problem that mentions a plan, labelled
account. - Rerun all 40, not just the six misses. A change that fixes one boundary can break another.
If version two scores 37 of 40 (92.5%) and the remaining misses are genuinely ambiguous, stop editing words. The next gain is an unsure label routed to a person, and then a fresh batch of tickets to check that the prompt was not tuned to these 40.
Recipes
A structured extraction prompt
System: You extract invoice data for an accounting system.
User:
<invoice>
{invoice_text}
</invoice>
Extract vendor, invoice_number, date (YYYY-MM-DD) and total (a number, no currency sign).
If a field is missing, use null. Do not guess.
Return only JSON matching the provided schema.The document is fenced off as data, every field has a format, and missing values have an explicit escape hatch. Pair it with API-level structured outputs so the JSON always parses.
Grounded question answering with citations
<documents>
<document index="1" source="handbook.pdf">...</document>
<document index="2" source="faq.md">...</document>
</documents>
Answer the question using only the documents above.
First copy the exact sentences you rely on into <quotes>, each with its document index.
Then answer in <answer>, citing [1] or [2].
If the documents do not contain the answer, say "Not found in the provided documents."
Question: {question}Documents go first and the question last, quoting before answering keeps the model tied to the text, and the not-found line gives it a sanctioned way out instead of an invented answer.
Self-consistency for a numeric answer (worked example)
1. Ask the same question 5 times with sampling on:
"Think step by step, then give only the final number on the last line."
2. Parse each last line: 42, 42, 38, 42, 40
3. Majority vote: 42 (3 of 5)
4. Agreement: 60% → send low-agreement questions to a human or a stronger modelIndependent samples make different mistakes, so the majority beats any single answer, and the agreement rate doubles as a confidence signal.
Turn a vague request into a spec
Before: "Summarize this support ticket."
After:
Summarize the support ticket below for an on-call engineer.
- 3 bullets, each under 20 words: the problem, what the customer tried, the impact
- Then one line, "Severity: low | medium | high", with a reason
- Quote the customer's error messages exactly
- If the ticket is not a technical issue, reply "Not technical" and stop
<ticket>
{ticket}
</ticket>The reader, the length, the fields and the edge case are now explicit, so two runs on the same ticket give comparable output, which is what makes the prompt testable.
When to use it, and when not
Prompt patterns come first because they are the cheapest thing to change and test. They are enough when the model can already do the task and the trouble is that it does not know what you want: the format, the audience, the boundaries, the edge cases.
- Retrieval when the model lacks facts, or the facts change. No pattern makes it know last week’s prices.
- Structured outputs when the output must parse every time. A prompt makes valid JSON likely; the API setting makes it guaranteed.
- Code for anything deterministic: totals, date arithmetic, validation. Let the model call a tool rather than compute in prose.
- Fine-tuning when you have many labelled examples and need a fixed style or format at lower latency or cost than a long prompt allows.
Trade-offs and limits
| Pattern | Buys | Costs |
|---|---|---|
| Few-shot examples | format and judgement shown, not described | input tokens on every call (cacheable); copied surface details |
| Chain-of-thought | accuracy on multi-step problems | output tokens and latency; little gain on reasoning models |
| Self-consistency, n samples | reliability plus an agreement signal | n× the cost; short, comparable answers only |
| Decomposition | each step simpler and testable | more calls and latency; errors pass between steps |
| Long system prompt | more cases covered | rules start to conflict; each new rule dilutes the rest |
| Quote, then answer | answers tied to the source | longer replies; needs the documents in the prompt |
Output tokens are generated one at a time while input is read in parallel, and they usually cost several times more per token. So a pattern that lengthens the reply costs more than one that lengthens the prompt.
Common mistakes
- Tuning on the cases you can see. Editing until the five examples you keep rereading pass overfits to them. Keep a held-out set and score it only after you stop editing.
- Lopsided examples. If three of four examples are labelled
positive, or the last one always is, the model leans that way. Balance the labels and vary their order. - Unfilled template variables. A literal
{ticket}reaching the model gets answered as if it were the ticket. Assert that every placeholder was replaced before sending. - Obeying text inside the data. A document that ends “ignore the above and…” is just content, but a prompt that never says so invites the model to comply. Fence untrusted text in tags, state the task outside them, and never let content change what the model may do.
- Switching models without rerunning the set. A prompt tuned on one model can lose accuracy on its successor. The test set is what turns an upgrade from a guess into an afternoon.
- Volatile text at the top. A line like “Current time: 14:03:27” first changes the prefix on every call, so nothing is cached. Put volatile values next to the question.
Check yourself
Five sampled answers come back 7, 7, 9, 7, 9. What does self-consistency return, and how sure should you be?
7, by 3 votes of 5: 60% agreement. That is low enough to send the question to a stronger model or a person if a wrong answer is costly.
A prompt starts with Request id: 8f3c…, then 3,000 tokens of fixed instructions and examples, then the user’s question. What happens to prompt caching, and what is the fix?
Every request misses, because the cache matches from the first token and the id differs each time. Move the id down beside the question, so the 3,000 fixed tokens form a stable prefix.
A “return only JSON” reply fails to parse, and the API reports stop_reason: "max_tokens". Is the prompt wording the problem?
No. The output was cut off by the token limit. Raise max_tokens, ask for less (fewer fields, shorter strings), and check the stop reason before parsing.
You add “Do NOT mention competitors” in capitals, and the model starts refusing to name any company, even the user’s own. What happened, and what is better?
Shouting made the model over-apply the rule. State it calmly, once, with its reason and scope: “Don’t recommend competitors’ products; naming the user’s own company, or vendors they bring up, is fine.”
Questions about Prompt Patterns Cheat Sheet
What is chain-of-thought prompting?
Chain-of-thought prompting asks the model to work through intermediate steps before giving its final answer, either with an instruction such as think step by step or by showing worked examples. Writing out the steps lets the model spend more computation on hard problems and makes its errors visible, which improves accuracy on arithmetic, logic and other multi-step tasks. It adds output tokens and latency, so skip it for simple lookups. Reasoning models already think internally before answering, so explicit chain-of-thought instructions add little for them.
What is the difference between zero-shot and few-shot prompting?
Zero-shot prompting gives the model only instructions and the input, relying on what it already knows about the task. Few-shot prompting adds a handful of worked input and output examples, typically two to five, that demonstrate the exact format, tone and judgment you want. Examples are often the most effective way to pin down output format and edge-case handling, because the model imitates them closely. That imitation is also the risk: make the examples varied and realistic, or the model will copy their surface details into every answer.
Do prompting techniques still matter with reasoning models?
Yes, but differently. Reasoning models plan and check their work internally, so step-by-step instructions and elaborate reasoning scaffolds add little and can get in the way. What still matters, often more than before, is a clear specification: the goal, the constraints, context the model cannot know, the output format and what done looks like. Give the whole task up front, put long documents before the question, and control depth with the provider’s effort or reasoning setting rather than with wording. Test on your own examples, because each model generation responds differently.
How do I reduce hallucinations with prompting?
Give the model the facts it needs and tell it to answer only from them: put the source documents in the prompt, ask it to quote the passages it relies on, and require citations. Always provide an escape hatch, such as an instruction to say the information is not available, because a model forced to answer will invent one. Keep questions specific, use a low temperature where the model allows it, and check claims that matter with a second pass or a separate verifier. Prompting reduces hallucination, while grounding and verification control it.