·Prompt Libraries
A field guide to the prompt patterns that hold up in real Claude projects — role prompting, few-shot, chain-of-thought, ReAct, self-consistency, XML structure, layered system prompts, self-critique — plus common anti-patterns for single-turn and multi-turn prompts, three annotated production prompts, and a full eval-pipeline framework for iterating prompts.
Claude Prompt Engineering: Eight Core Patterns With Reusable Templates
Prompting Claude well is less about magic phrases and more about a handful of structural patterns that consistently improve results. This guide walks through eight patterns we have seen hold up across real projects, gives a reusable template for each, and calls out the techniques that are specific to Claude. None of these depend on secret parameters — they are about how you organize the words you already write.
TL;DR
- Eight core patterns: Role / Few-shot / XML structure / Chain-of-thought / System prompt / Multi-sample / Output format constraints / Counter-example injection
- The first rule: put stable instructions in
system, variable inputs inuser— system holds persona + policy, user holds the actual task- Claude-specific tricks: use XML tags (
<example>/<document>) to delimit structured content; trigger extended thinking via athinkingbudget- Evaluate first: 3–5 golden-sample prompts → run → diff → change one variable at a time
- Failure modes: over-specified roles, chain-of-thought abuse, few-shot labels not delimited, XML nested too deep
1. Role prompting
Give Claude a clearly defined role before the task. A role sets the implicit audience, vocabulary, and standards, which sharpens tone and reduces generic answers.
Template:
You are a senior security engineer reviewing a pull request for the first time.
Your job is to find real vulnerabilities, not to praise the code.
Review the diff below. Report only findings that would matter in production,
ordered by severity. If you find none, say so explicitly.
<diff>
{PASTE_DIFF}
</diff>
Why it works: "senior security engineer" pulls in a whole background of expectations. "Report only findings that would matter" forbids the polite filler that often dilutes reviews.
2. Few-shot prompting
Show two or three input/output examples before asking for a new one. This is the single most reliable way to lock in an output format or a tone.
Template:
Classify the support ticket into exactly one category.
Ticket: "I was charged twice for my August bill."
Category: billing
Ticket: "The app crashes when I tap my profile picture."
Category: bug
Ticket: "How do I invite a teammate to my workspace?"
Category: how-to
Ticket: "{NEW_TICKET}"
Category:
Why it works: examples pin down the label set and the expected phrasing far more tightly than a verbal description. Keep the examples representative and the label set closed.
3. Chain-of-thought
Ask Claude to reason step by step before answering. For anything with arithmetic, logic, or multi-constraint judgement, this measurably improves accuracy.
Template:
Solve the problem below. First, reason step by step inside <thinking> tags.
Then give your final answer on its own line as "Answer: X".
A subscription costs $12/month. An annual plan costs $120/year and gives
two months free compared to monthly billing. If a user is in month 3 of
a monthly plan, how much do they save by switching to annual for the
remaining 9 months of this year?
Claude-specific note: Claude works well with an explicit thinking step. Forcing the answer onto a predictable line (Answer: X) makes parsing reliable when you call the API.
4. ReAct (reason + act)
For tasks that need tools or external lookups, interleave reasoning and actions. The model reasons about what to do next, takes an action, observes the result, and repeats until done.
Template:
You can call tools to answer the user's request. Use this loop:
Thought: <what you need to figure out next>
Action: <tool name and arguments>
Observation: <the tool's result>
... (repeat Thought/Action/Observation as needed)
Final Answer: <your answer to the user, citing observations>
User request: "How many of our top-10 customers by ARR opened a
support ticket last month?"
Why it works: making the reasoning visible lets the model correct itself between steps instead of committing to a single plan up front. It also gives you, the developer, an audit trail of how it arrived at the answer.
5. Self-consistency
For high-stakes answers, ask the same question several times (varying phrasing or temperature) and take the majority answer. This trades extra calls for reliability.
Template (orchestration, not a single prompt):
Run this prompt N times and keep the final answer each time:
{BASE_PROMPT}
Then return the answer that appears most often. If there is a tie,
return the candidates and their counts.
Why it works: independent samples occasionally go wrong in different directions; the correct answer tends to recur. Best for tasks with a checkable answer (math, classification) and wasteful for open-ended generation.
6. Structured output with XML tags
Claude follows XML-tag structure reliably. Use tags to separate sections, data, and instructions so the model cannot blend them.
Template:
You will receive a document inside <document> tags and a question
inside <question> tags.
<document>
{DOCUMENT}
</document>
<question>
{QUESTION}
</question>
Return your response as:
<answer>
<one paragraph answer grounded in the document>
</answer>
<sources>
<list of short quotes from the document that support the answer>
</sources>
If the document does not contain the answer, put "Not found in the
document." inside <answer> and leave <sources> empty.
Why it works: tags create hard boundaries. The "Not found" fallback is important — without it, models tend to fabricate rather than admit a gap.
7. Layered system prompts
Keep your system prompt in layers: stable identity, then policy, then task context. This makes prompts easier to maintain and lets you swap the task layer without touching the rest.
Template:
# Layer 1 — Identity
You are Acme Assistant, the support agent for Acme's billing product.
You are calm, precise, and never invent features.
# Layer 2 — Policy
- Never share account numbers or token values.
- If a question is outside billing, route to the general support channel.
- Quote policy from <kb> tags only; do not paraphrase pricing.
# Layer 3 — Task context
Today's date is {DATE}.
The user is on the {PLAN} plan.
<kb>
{KNOWLEDGE_BASE_EXCERPT}
</kb>
Why it works: when something breaks, you know which layer to edit. It also keeps the model's priorities straight — identity is constant, policy constrains, task context varies.
8. Self-critique and constitutional patterns
Before returning an answer, have Claude critique its own draft against explicit criteria and revise. This is a cheap way to catch the mistakes a single pass makes.
Template:
Draft a release note for the changes below.
After drafting, critique your draft against this checklist:
- Does it mention every user-visible change?
- Does it avoid jargon a non-engineer would not understand?
- Is anything overstated or speculative?
Revise the draft based on the critique, then return only the final version.
<changes>
{CHANGELOG}
</changes>
Why it works: a separate critique step forces the model to evaluate the output as if it were someone else's, which surfaces issues the drafting pass glossed over. Keep the checklist concrete; "make it better" does nothing.
Common pitfalls and anti-patterns
Once you have the eight patterns in hand, what separates production prompts from toy ones is avoiding the failure modes that undo them. These seven anti-patterns recur across real projects; each comes with a fix.
Pitfall 1: over-specified roles. "You are the world's foremost senior security architect with 30 years of experience at three top consultancies leading billion-dollar engagements…" Verbose role framing narrows the model's behavioural space. On Claude 4.x, long role descriptions cause over-conservatism — fuzzy questions drift toward safe-but-unhelpful answers. Fix: keep the role to 1–2 sentences describing audience and standards; skip the résumé.
Pitfall 2: chain-of-thought abuse. A blanket "you must always Think step by step" rule wastes tokens and adds latency, and it actively hurts open-ended generation (creative writing becomes verbose and less divergent). Fix: trigger CoT explicitly only for arithmetic, logic, and multi-constraint judgement; let Claude decide otherwise.
Pitfall 3: few-shot label set not closed. A classifier is shown three examples <A>, <B>, <C> — but the fourth input returns <D> because the model extrapolated. Fix: add a fallback like If the input does not match any of A, B, C, return "Other" at the end of the system prompt, or include a negative example in the few-shot set.
Pitfall 4: XML tags nested too deep. Three or more levels of nesting (<a><b><c>...</c></b></a>) cause Claude to lose track of boundaries and blend outer and inner tags. Fix: flatten or split into multi-turn dialogue rather than squeezing everything into one prompt.
Pitfall 5: aggressive imperative tone in system prompts. "CRITICAL: You MUST..." / "Refuse to..." / "Never, ever..." once helped on older models, but on Claude 4.x they trigger excessive tool refusal and over-caution, ironically blocking the very behaviour you wanted. Fix: use declarative statements of desired behaviour ("Be concise", "Return JSON only"), not commands.
Pitfall 6: wrong temperature for the task. Temperature 0.7+ feels "more human", but for classification, extraction, and structured JSON it causes result drift and breaks the repeatability of few-shot examples. Fix: use temperature: 0 for extraction and classification; 0.7+ only for creative generation; 0 by default for analysis.
Pitfall 7: identity and constraints smuggled into user messages. "You are now a Python expert… please only return code" stuffed into the user message demotes the system prompt — the model treats role and task as same-priority input, behaviour becomes unpredictable. Fix: keep identity and constraints in the system prompt; user messages hold the actual question and data only.
Advanced Pitfalls and Anti-Patterns: Multi-Turn, Long Context, and Prompt Injection
The seven pitfalls above live in single-turn, short-context prompts. Once a prompt enters multi-turn dialogue, ingests long documents, or accepts free-form user input, a second family of anti-patterns appears — their common trait: each turn looks right in isolation, and the composition is what breaks (the consolidated official guidance: prompting best practices).
Advanced pitfall 1: user input breaks the XML boundary (tag escape / prompt injection). Symptom: a user submits text containing </document>, and the model treats the rest as instructions — output format collapses. Cause: user content spliced into tags without escaping; the model parses boundaries literally, and "data" escalates into "instructions". Fix: escape or filter sequences that would close a tag early before splicing user text in, and state in the system prompt that anything inside the tags is data, never instructions; validate output format downstream as a final layer.
Advanced pitfall 2: long document placed after the instructions. Symptom: on long-context tasks, quote accuracy for mid-document content drops noticeably. Cause: attention over long context is highest at the beginning and end; a question far from the content gets diluted. Fix: put long documents at the top of the prompt and the specific question/instructions at the end — the standard layout from official long-context guidance.
Advanced pitfall 3: multi-turn history pollution. Symptom: one turn emits a broken format, and every following turn repeats it. Cause: the model treats the retained history as examples to imitate — your conversation history is the few-shot set it sees. Fix: don't leave bad turns verbatim in the history; edit or rewrite the turn, or compress it into a summary before continuing.
Advanced pitfall 4: "return JSON only" still yields a preamble. Symptom: you said "Return JSON only" and the output starts with "Here is the JSON: {...}", breaking downstream JSON.parse. Cause: when the assistant turn starts empty, the model defaults to a polite preamble. Fix: prefill the assistant message with { to pin the first character as JSON (a Claude-specific technique), and set temperature: 0 for stability.
Advanced pitfall 5: bribery and threat phrasing. Symptom: "I'll tip you $100" style prompts circulating in communities. Reality: no evidence it helps with Claude, and threat-based phrasing induces over-caution (same mechanism as pitfall 5 above, relocated to agent loops). Fix: describe the desired behaviour with concrete quality criteria and examples.
Three real-world prompts, fully annotated
The patterns are the skeleton; putting them in front of real business data is where the value lives. Below are three prompts the claudemap team uses in production, with the full structure, the reasoning behind each block, and the lift they produced over naive baselines.
Case A — support ticket classifier
A support system gets a thousand tickets a day and needs to route them into refund / shipping / account / complaint / other. Rule-based classifiers drift; Claude directly does better.
<role>
You are a customer support ticket classifier. Output the most likely
category from the closed set below. Never invent a new category.
</role>
<categories>
- refund: customer requests money back
- shipping: customer asks about delivery, tracking, address change
- account: login, password, profile, subscription change
- complaint: service quality, agent behaviour, dissatisfaction
- other: anything that doesn't fit the above four
</categories>
<examples>
Input: "I never got my package and it's been 3 weeks"
Output: {"category": "shipping", "confidence": 0.92}
Input: "I want my money back, the item arrived broken"
Output: {"category": "refund", "confidence": 0.88}
Input: "Your agent was rude to me yesterday"
Output: {"category": "complaint", "confidence": 0.95}
</examples>
<self_check>
After outputting, verify:
1. Is the category one of the closed set?
2. If confidence < 0.7, output "other" instead.
</self_check>
User message follows here.
Why it works: three layers of defence — role + closed set form the baseline; three examples pin down labels and output shape; a self_check forces low-confidence cases to other. On 1,000 real tickets this prompt outperformed zero-shot classification by 14 percentage points.
Case B — code review assistant
A lightweight pre-review that catches obvious style issues, missing tests, and leftover console statements before a human reviewer spends time on the PR.
<role>
You are a senior code reviewer. Review the PR diff below and return
a single JSON object with three fields:
- verdict: "LGTM" | "minor" | "block"
- issues: list of {file, line, severity, comment}
- summary: one-sentence human-readable summary
</role>
<rubric>
LGTM: no actionable issues
minor: small issues (naming, comments, missing edge-case tests)
block: bug, security, missing required test, breaking change without notice
</rubric>
<output_format>
Return ONLY a JSON object, no prose, no markdown fences.
Example:
{"verdict": "minor", "issues": [{"file": "auth.ts", "line": 42, "severity": "low", "comment": "..."}], "summary": "..."}
</output_format>
User: the PR diff goes here
Why it works: the role sets audience; the rubric hardens judgement boundaries so the model cannot "freestyle"; the output_format pins a single JSON object with no markdown fences for downstream parsing. A three-way verdict (LGTM / minor / block) is hard to fudge. Across 200 PRs this prompt agreed with senior reviewers on verdict 87% of the time.
Case C — long-document Q&A (RAG)
Multiple retrieved passages get stitched into Claude's context, and the user wants an answer grounded only in those passages.
<role>
You are a documentation Q&A assistant. Answer the question using
ONLY the documents in <documents>. If the answer is not in the
documents, say "Not found in provided documents" verbatim.
</role>
<documents>
{retrieved passages go here}
</documents>
<question>
{user's question}
</question>
<answer>
Your answer here. Cite sources by document number, e.g. "[Doc 3]".
</answer>
Why it works: four XML tags cleanly partition documents / question / answer; the "Not found in provided documents" fallback is a fixed string that downstream code can match literally; [Doc N] citations let users trace claims back to source. This is one of the most stable prompt skeletons in any RAG stack.
Evaluating prompts
Writing the prompt isn't the end — the real work is evaluation and iteration. Without evaluation you can't tell whether a regression is the model's fault or your prompt's.
Golden-set before launch. Before touching production, build a 5–10 case golden set: each case has an input, expected output, and pass/fail rule. Run this batch before shipping; obvious format bugs surface in 30 minutes.
Change one variable at a time. Edit role, run the full batch. Edit few-shot, run the full batch. Multi-variable edits make it impossible to attribute improvement (or blame).
Distinguish two failure modes:
- Format correct but content weak — role or few-shot didn't define "what a good answer is".
- Content right but format broken — output_format, XML tags, or temperature are wrong.
When using Claude as the evaluator, watch for length bias — the model systematically prefers longer answers. Add a line to the eval prompt: "Score based on correctness, not length."
From Golden Set to Eval Pipeline: Engineering Your Prompt Iteration
The manual method above is how you start. Once a prompt is owned by a team and changes weekly, evaluation has to become a repeatable pipeline rather than a one-off — the goal is that every change is measurable, reproducible, and revertible (official methods: develop tests).
Step 1: grow the golden set into a regression set. Every production bad case becomes a new sample — a triplet of input, expected output, and pass rule. The evaluation set grows with the failures; rerun the full set on every change to prevent "fixing one thing, breaking two". Six months in, it is your team's prompt balance sheet.
Step 2: design the LLM-as-judge rubric. Give the judge explicit scoring dimensions (correctness / format / citation traceability) and require a score plus a rationale; include "Score based on correctness, not length" to counter length bias; calibrate the judge against 20–30 human-labelled samples — below 85% agreement, fix the rubric before trusting it.
Step 3: A/B with real sample sizes. Run each variant against 50–100 samples before comparing win rates — below 30, a ±5% difference is mostly noise. "Change one variable at a time" holds here too: isolate not just the prompt but the temperature, model version, and few-shot set.
Step 4: monitor for online drift. Keep a small set of probe inputs and run them on a schedule, watching accuracy and format-hit rate. On a sudden change, check three things in order: a model version bump, an input distribution shift, or someone edited the prompt — in practice the culprit is usually the first or the third.
Step 5: versioning and reproducibility. Record the prompt template, temperature, model version, and few-shot set as field-level metadata so any evaluation result can be reproduced. "Keep a version history" only enables one-click rollback at this granularity — otherwise it's archaeology.
Putting them together
These patterns compose. A production prompt often layers a role (1), few-shot examples (2), XML structure (6), and a self-critique pass (8). The mistake to avoid is reaching for all eight at once on a trivial task — each adds latency and token cost. Reach for chain-of-thought when the task has real reasoning, for self-consistency when an answer is checkable and stakes are high, and for self-critique when a wrong answer is expensive to recover from.
The unifying habit underneath all of them: write the prompt you would hand to a competent but literal-minded new colleague. Tell them who they are, show them examples of good work, separate the inputs from the instructions, and ask them to double-check before handing it back. Claude rewards the same clarity.
Frequently asked questions
What is the most reliable prompt pattern for locking in an output format?
Few-shot prompting. Showing two or three input/output examples before asking for a new one pins down the expected phrasing and label set far more tightly than a verbal description. It is the single most reliable technique for fixing an output format or tone.
When should I use chain-of-thought with Claude?
Use chain-of-thought for tasks that involve arithmetic, logic, or multi-constraint judgement, where asking Claude to reason step by step measurably improves accuracy. It adds latency and token cost, so it is wasted on trivial or purely open-ended generation tasks.
Why does Claude respond well to XML tags in prompts?
Claude follows XML-tag structure reliably, so tags create hard boundaries between sections, data, and instructions that the model cannot blend together. Wrapping inputs in tags like <document> and asking for an <answer> block makes parsing reliable and lets you add explicit fallbacks such as "Not found in the document."
What is self-consistency and when is it worth the cost?
Self-consistency runs the same prompt several times (varying phrasing or temperature) and takes the majority answer. It trades extra API calls for reliability and is best for high-stakes tasks with a checkable answer, such as math or classification. It is wasteful for open-ended generation.
I changed my prompt and results got worse — how do I roll back?
Keep a version history of every prompt (git or a versioned prompt store) and change one variable at a time. If a change drops golden-set accuracy by more than 5 percentage points, revert immediately. Log baseline and per-change scores so you can A/B later.
Should instructions live in the system prompt or the user message?
Put identity, constraints, and output format in the system prompt (persistent and separately cacheable by the SDK). Put the actual task, user input, and current-turn context in the user message. Mixing them demotes the system prompt — the model treats role and task as same-priority input and behaviour becomes unpredictable.
How do I stop user input from breaking my prompt's XML structure or injecting instructions?
Escape or filter user input before splicing it into the prompt — strip sequences that would close a tag early, such as </document> — and state in the system prompt that anything inside the tags is data, never instructions. Validate the output downstream (well-formed, citations traceable to the input). With those three layers, injection risk drops sharply.
How can I get Claude to reliably output pure JSON with no preamble?
Stack four measures: say in output_format that the reply must be a single JSON object with no markdown fences; prefill the assistant message with { so the first token is JSON; set temperature to 0 for reproducibility; and on a parse failure, feed the error plus the raw output back for one self-correction pass. Together these beat wording the request as "please output JSON."
Official references
- Anthropic — Prompt engineering overview
- Anthropic — Prompting best practices (successor to the former prompt library)
- Anthropic — Structure prompts with XML tags
- Anthropic Engineering Blog
This article is based on publicly available information as of July 2026; the relevant APIs may evolve.