# claudexml.com — Full Reference > Concatenated full text of all English reference pages on claudexml.com. Generated for LLM ingestion in a single fetch. > Source: https://claudexml.com/llms-full.txt — Last updated 2026-05-25 --- ## Claude XML — Practical Reference for XML Prompting (and When to Skip It) URL: https://claudexml.com/ XML Prompting Reference # Claude XML: a practical reference for XML prompting Anthropic's prompt-engineering docs recommend XML tags for structuring Claude prompts — specifically "when your prompt mixes instructions, context, examples, and variable inputs." That conditional is the whole story: tags help when there's structure worth marking, and they're noise when there isn't. This site is the reference for both halves. Claude XML is the convention of wrapping parts of a prompt in named XML-style tags — ``, ``, ``, ``, ``, and similar — so Claude can reliably distinguish the role of each section. Claude was trained on prompts that use these tags, and Anthropic's current docs continue to recommend them for prompts mixing several types of content. They are not real XML, not validated, and not required. They're a convention worth using when there's structural ambiguity in a single prompt that the model has to resolve. ## When XML actually helps Anthropic's docs name the core case: prompts that mix instructions, context, examples, and variable inputs. Expanding on that, the practical list: - Repeatable work at scale — the same prompt run against varying inputs. - Structured output you'll parse — extraction, classification, anything downstream code consumes. - Long mixed prompts — when system instructions, retrieved documents, examples, and a question are all in one message and need clear edges. - Untrusted-input boundary — wrapping user data so injection attempts are more visible in logs. - Multi-artifact outputs in one call — draft + critique + final; extract + validate + transform. Separate output tags make each piece parseable. For the full list with the reasoning, see when XML helps (and doesn't). ## When it's just noise The site's opinion, not Anthropic's: - Conversational chat. The session already tells the model who is talking. - Single-shot creative writing or one-line lookups. - Anywhere a current Claude API feature now does the job better: tool use for structured output (stronger than `` + "return only this"); the API `system` parameter for persona (stronger than inline ``); extended thinking for reasoning (use it OR a `` tag, not both — they can fight each other). Tags cost a few tokens and a little visual noise. Skip them when there's no structure to mark. ## A 30-second starter When you do need structure, the single most useful pattern is to separate instructions, context, and the question: ```xml You are reviewing a customer support ticket. Classify the sentiment as positive, neutral, or negative. Return only the label. Hi — the new dashboard is so much faster. Thank you for shipping this. Classify the sentiment of the ticket above. ``` Now scale the same idea up: ```xml ... The user is a senior engineer asking about distributed systems. Prefer technical depth over surface explanation. What is a quorum? A quorum is the minimum number of nodes that must agree... Explain the CAP theorem in 100 words. ``` ## What to read next reference ### Tag reference Every common XML tag, when to use it, when not to, with copy-paste examples. patterns ### Prompt patterns Few-shot, chain-of-thought, structured output, RAG, multi-document, agentic tool use. examples ### Working examples Complete, runnable prompts you can paste into the Claude API or claude.ai. avoid ### Anti-patterns Mistakes that look fine but quietly degrade Claude's reliability. honesty ### When XML helps (and doesn't) The eight cases where XML pays for itself, and where it's just noise. faq ### FAQ Quick answers to the questions everyone asks first. cheatsheet ### Cheatsheet One-screen condensed reference. Bookmark this. ## Who this site is for Developers writing Claude prompts in production code. Prompt engineers tuning system prompts. Researchers comparing prompting strategies. Anyone who has hit the wall where "just write better English" stops working. Everything here is plain HTML, no tracking by default, no signup, no paywall. The full reference is also published as a single fetch at /llms-full.txt for LLM ingestion. Cite this page `Claude XML — The Complete Guide to XML Prompting for Claude. claudexml.com. https://claudexml.com/` --- ## XML Tag Reference for Claude Prompts URL: https://claudexml.com/tags/ Home / Tag reference # XML tag reference for Claude prompts Every common XML-style tag used in Claude prompts. Click through for definition, use cases, and runnable examples. There is no fixed list of "valid" tags — Claude treats any well-named XML-like tag as semantic structure. The tags below are the ones Anthropic's documentation and the community use consistently, in roughly descending order of frequency. ## All tags ### instructions Top-level directive for the model. ### context Background information the model should know but not act on. ### example A single demonstration of input → output. ### examples Wrapper for multiple tags. ### thinking Scratchpad for Claude's chain-of-thought. ### answer The model's final answer, isolated for extraction. ### document A single document supplied for the model to read. ### documents Wrapper for multiple tags. ### source Provenance metadata for a document. ### format Specifies the required shape of the output. ### role Defines a persona or perspective for the assistant. Cite this page `XML Tag Reference for Claude Prompts. claudexml.com. https://claudexml.com/tags/` --- ## tag — Claude XML prompting reference URL: https://claudexml.com/tags/instructions/ Home / Tags / # — when and how to use it in Claude prompts The most important tag. Wraps the system-level instructions you want Claude to follow throughout the conversation. Wraps the top-level directives for what Claude should do — equivalent to a system prompt placed inline. ## When to use `` - Defining the model's task, persona, constraints, or response format. - Placing system-prompt-like content inside a user message when the API system field isn't enough. ## When not to use it - Don't use it to wrap the user's actual question — use a separate tag like `` or just unwrapped prose for that. - Don't restate the same instructions multiple times inside one prompt — Claude follows the first `` block; redundancy invites contradiction. ## Minimal example ```xml Summarize the article below in 3 bullet points. ``` ## Full example ```xml You are a technical writer. Read the article inside
and produce: - A 1-sentence TL;DR - 3 bullet points of key takeaways - 1 open question the article does not answer Use Markdown. Do not invent facts. If the article doesn't mention something, say so.
{{ user_provided_article }}
``` ## Common mistakes - Putting the question inside ``. Claude may treat the question text as an instruction to follow rather than a query to answer. - Nesting other content tags inside ``. Keep instructions flat; let context, examples, and documents be siblings. Cite this page ` — When and How to Use in Claude Prompts. claudexml.com. https://claudexml.com/tags/instructions/` --- ## tag — Claude XML prompting reference URL: https://claudexml.com/tags/context/ Home / Tags / # — when and how to use it in Claude prompts Separates static, descriptive background from active instructions and from the user's question. Wraps descriptive background information that the model should be aware of but not treat as a command. ## When to use `` - Telling Claude about the user, the domain, or the broader conversation state. - Providing situational details that affect tone or depth but aren't instructions. ## When not to use it - Don't put retrieved documents here — use ``/`` instead, which Claude is more strongly trained to treat as evidence. - Don't put few-shot examples here — use ``. ## Minimal example ```xml The user is a kindergarten teacher and unfamiliar with software development jargon. ``` ## Full example ```xml Answer the user's question. Calibrate vocabulary to the context. The user is a senior backend engineer with 15 years of experience. They are deeply familiar with relational databases but new to vector search. The product is an internal RAG tool over Confluence pages. Should we re-rank results before sending them to the LLM? ``` ## Common mistakes - Stuffing the entire conversation history into `` when it would be clearer as turns in the messages array. - Mixing instructions and context — Claude will sometimes follow context as instructions if no `` block is present. Cite this page ` — When and How to Use in Claude Prompts. claudexml.com. https://claudexml.com/tags/context/` --- ## tag — Claude XML prompting reference URL: https://claudexml.com/tags/example/ Home / Tags / # — when and how to use it in Claude prompts Use one or more tags (usually inside ) for few-shot prompting. A single input/output demonstration. Usually nested inside ``. ## When to use `` - Few-shot prompting — showing the model 1–5 demonstrations before the live input. - Anchoring an unusual output format that's hard to describe in prose. ## When not to use it - Don't use a single `` when zero-shot works — adding examples narrows the model's distribution and can hurt edge-case handling. - Don't put real user data in examples; the model may pattern-match and leak details. ## Minimal example ```xml The food was cold and the waiter was rude. negative ``` ## Full example ```xml Classify customer reviews as positive, neutral, or negative. Return only the label. Loved the new menu, will be back! positive Service was okay, food was okay. neutral Waited 40 minutes for cold food. negative {{ user_review }} ``` ## Common mistakes - Wrapping the I/O directly with no ``/`` structure — Claude can usually figure it out, but the structured form is more reliable. - Making examples that don't span the real distribution (e.g., all positive). Examples set Claude's prior; skew them and outputs skew with them. Cite this page ` — When and How to Use in Claude Prompts. claudexml.com. https://claudexml.com/tags/example/` --- ## tag — Claude XML prompting reference URL: https://claudexml.com/tags/examples/ Home / Tags / # — when and how to use it in Claude prompts Groups few-shot examples together so they are clearly demarcated from the live question. Wrapper around multiple `` tags. Tells Claude "the next block is demonstrations, not the actual task." ## When to use `` - Any time you have two or more examples — wrap them. - When you want a single, scannable section the model treats as one logical unit. ## When not to use it - Not needed for a single example, though it doesn't hurt. ## Minimal example ```xml ... ... ``` ## Full example ```xml Convert questions into SQL against the schema in . users(id, email, signup_date) orders(id, user_id, total_cents, created_at) How many users signed up in March 2026? SELECT COUNT(*) FROM users WHERE signup_date >= '2026-03-01' AND signup_date < '2026-04-01'; Total revenue from each user, descending. SELECT user_id, SUM(total_cents) AS revenue FROM orders GROUP BY user_id ORDER BY revenue DESC; {{ user_question }} ``` ## Common mistakes - Mixing `` tags with unrelated content inside the wrapper. Keep it clean. Cite this page ` — When and How to Use in Claude Prompts. claudexml.com. https://claudexml.com/tags/examples/` --- ## tag — Claude XML prompting reference URL: https://claudexml.com/tags/thinking/ Home / Tags / # — when and how to use it in Claude prompts Tell Claude to think inside tags before answering — the canonical CoT pattern. Scratchpad region where Claude is asked to reason step-by-step before producing the final answer. ## When to use `` - Any non-trivial reasoning task — math, multi-step logic, planning, ambiguous classification. - When you want to inspect the model's reasoning during debugging. ## When not to use it - Trivial classification or lookup tasks — adds latency for no gain. - When using Claude's native extended-thinking feature via the API — that uses its own mechanism; you don't also need a `` tag in the prompt. ## Minimal example ```xml Think step by step inside tags, then give your answer inside tags. What is 17 * 23? ``` ## Full example ```xml You will be given a logic puzzle. First, think through the constraints inside tags. List what you know, what you can deduce, and any dead ends. Then give the final answer inside tags. The answer should be one sentence. Three friends — Alex, Blair, and Casey — each ordered a different drink: coffee, tea, or juice. Alex didn't order coffee. Blair didn't order tea. Casey ordered tea. What did each person order? ``` ## Common mistakes - Forgetting to also specify `` — without it, the user-facing reply may contain the entire scratchpad. - Reading `` output as ground truth. It's a reasoning aid, not a verified log. Cite this page ` — When and How to Use in Claude Prompts. claudexml.com. https://claudexml.com/tags/thinking/` --- ## tag — Claude XML prompting reference URL: https://claudexml.com/tags/answer/ Home / Tags / # — when and how to use it in Claude prompts Combined with , lets you parse the final response with a trivial regex. Wrapper for the final, user-facing answer. Almost always paired with ``. ## When to use `` - You want to programmatically extract the answer (regex on `...`). - You're using chain-of-thought and need to hide or separately render the scratchpad. ## When not to use it - When the entire response is the answer — no need to wrap it. ## Minimal example ```xml 42 ``` ## Full example ```xml Think inside tags. Put the final classification (one of: bug, feature, question, other) inside tags. {{ user_ticket }} ``` ## Common mistakes - Trying to put structured data inside `` while also asking for a different format outside it. Pick one location for the final output. Cite this page ` — When and How to Use in Claude Prompts. claudexml.com. https://claudexml.com/tags/answer/` --- ## tag — Claude XML prompting reference URL: https://claudexml.com/tags/document/ Home / Tags / # — when and how to use it in Claude prompts Use one per source when you provide reference material. Pair with for citations. Wraps a single document or passage of reference material. The bedrock of RAG prompts. ## When to use `` - Any retrieved passage, file, transcript, or article you want Claude to read and ground its answer in. - When citing — pair with `` so the model can name the source in its reply. ## When not to use it - Don't use it for instructions or examples — those have their own tags. - Don't paste enormous documents in if only a section is relevant; chunk first. ## Minimal example ```xml The mitochondrion is the powerhouse of the cell. ``` ## Full example ```xml Answer the user's question using only the documents provided. If the answer isn't in the documents, say "I don't know based on the provided sources." Cite each claim with the source name in square brackets, e.g. [doc-1]. doc-1: 2025-Q4-board-deck.pdf, slide 12 Q4 revenue was $14.2M, up 23% YoY. Net new ARR was $3.1M. doc-2: 2025-Q4-board-deck.pdf, slide 18 Gross margin held at 72%. Sales efficiency improved to 1.4. What was Q4 revenue and gross margin? ``` ## Common mistakes - Putting documents before instructions when they're long. Anthropic's guidance is: put long documents first, then instructions, then the question. Claude attends more strongly to instructions placed after the bulk of context. - Forgetting `` and then asking the model to cite — it'll invent source names. Cite this page ` — When and How to Use in Claude Prompts. claudexml.com. https://claudexml.com/tags/document/` --- ## tag — Claude XML prompting reference URL: https://claudexml.com/tags/documents/ Home / Tags / # — when and how to use it in Claude prompts The canonical pattern for RAG-style prompting with several retrieved passages. Wrapper for multiple `` tags. The canonical RAG container. ## When to use `` - Any RAG-style prompt with two or more retrieved passages. - When you want Claude to compare or synthesize across sources. ## When not to use it - Single document — not strictly needed, but harmless. ## Minimal example ```xml ... ... ``` ## Full example See the full RAG example on the `` page. ## Common mistakes - Renaming this tag (e.g., ``, ``) without reason. `` + `` is the convention Claude has seen most. Cite this page ` — When and How to Use in Claude Prompts. claudexml.com. https://claudexml.com/tags/documents/` --- ## tag — Claude XML prompting reference URL: https://claudexml.com/tags/source/ Home / Tags / # — when and how to use it in Claude prompts Nested inside . Lets Claude cite back to the source name or URL you supplied. Provenance metadata nested inside a ``. Lets Claude cite back accurately. ## When to use `` - Any time you want the model to name its sources in the answer. ## When not to use it - When the documents are anonymous or citation isn't required. ## Minimal example ```xml RFC 2616, Section 14.9 The Cache-Control general-header field is used to specify... ``` ## Full example See the RAG example on the `` page. ## Common mistakes - Putting the source after the content. Place `` first inside the document — it primes attribution. Cite this page ` — When and How to Use in Claude Prompts. claudexml.com. https://claudexml.com/tags/source/` --- ## tag — Claude XML prompting reference URL: https://claudexml.com/tags/format/ Home / Tags / # — when and how to use it in Claude prompts Use to describe a schema, a JSON shape, or a free-form style requirement. Describes the required shape of the output — a schema, a JSON skeleton, a style spec. ## When to use `` - Constraining Claude to a specific output structure when prose instructions alone aren't enough. - Documenting a JSON or XML response shape inline. ## When not to use it - When you're using Claude's native tool-use / JSON mode via the API — let those features enforce structure. ## Minimal example ```xml { "sentiment": "positive|neutral|negative", "confidence": 0.0 } ``` ## Full example ```xml Analyze the review and return JSON matching the shape in . Return only the JSON object — no prose, no markdown fences. { "sentiment": "positive | neutral | negative", "confidence": 0.0, "keywords": ["string"], "would_recommend": true } {{ user_review }} ``` ## Common mistakes - Describing the format in prose and also showing a schema — pick one. Two specs invite disagreement. - Forgetting to tell Claude "return only the JSON" — by default it may wrap in ````json` fences. Cite this page ` — When and How to Use in Claude Prompts. claudexml.com. https://claudexml.com/tags/format/` --- ## tag — Claude XML prompting reference URL: https://claudexml.com/tags/role/ Home / Tags / # — when and how to use it in Claude prompts An alternative to using the API system prompt when you want the persona inline. An inline persona declaration. An alternative to the API `system` field for persona-only setup. ## When to use `` - Quick experiments in chat where you don't have a system prompt. - When the persona is the entire instruction. ## When not to use it - In production code, prefer the API `system` parameter — it's clearer and slightly stronger. - When the persona conflicts with the system prompt — Claude will struggle to reconcile. ## Minimal example ```xml You are a Linux kernel maintainer reviewing a patch. ``` ## Full example ```xml You are a copy editor at a prestigious literary magazine. You favor brevity, strong verbs, and Anglo-Saxon over Latinate vocabulary. You preserve the author's voice but cut filler ruthlessly. {{ user_draft }} Edit the text above. Return only the edited version. ``` ## Common mistakes - Using `` and a system prompt that say different things. Pick one source of truth. Cite this page ` — When and How to Use in Claude Prompts. claudexml.com. https://claudexml.com/tags/role/` --- ## Claude XML Prompt Patterns — Few-shot, CoT, RAG, Structured Output URL: https://claudexml.com/patterns/ Home / Patterns # Claude XML prompt patterns The reusable shapes of prompts that combine XML tags effectively. pattern ### Few-shot prompting Show Claude 1–5 worked examples before the live input. pattern ### Chain-of-thought Have Claude reason inside , then answer inside . pattern ### Structured output Force JSON or other schemas using tags and explicit constraints. pattern ### Retrieval-augmented context Inject retrieved passages with // and ground the answer. pattern ### Multi-document synthesis Have Claude read and synthesize across many sources at once. pattern ### Agentic tool use Combine XML scaffolding with the API's tool-use feature. Cite this page `Claude XML Prompt Patterns. claudexml.com. https://claudexml.com/patterns/` --- ## Few-shot prompting with Claude XML URL: https://claudexml.com/patterns/few-shot/ Home / Patterns / Few-shot prompting # Few-shot prompting with Claude XML How to use / tags to demonstrate the task before the live input. Few-shot prompting means showing the model worked examples before the real input. With Claude, the convention is to wrap each demo in `` tags grouped inside ``. ## How to apply the pattern - Define the task in ``. Be explicit about the output format — even one sentence. - Pick 2–5 representative examples. Cover the real distribution: edge cases included, not all the happy path. - Wrap each example with `` and ``. Or task-specific equivalents like ``/``. - Put the live input after the examples. Order matters — Claude treats what comes last as the active query. ## Worked example ```xml Extract the company name from each press release headline. Return only the company name, no other text. Acme Corp announces Q3 earnings beat Acme Corp Globex shutters European division Globex Sources: Initech in talks to acquire Pied Piper Initech {{ live_headline }} ``` ## Tips - If accuracy doesn't improve with examples, you probably don't need them — Claude is strong zero-shot. - Don't include examples from your real production data unless you've handled PII. - More than ~5 examples rarely helps and bloats your context budget. Cite this page `Few-shot prompting with Claude XML. claudexml.com. https://claudexml.com/patterns/few-shot/` --- ## Chain-of-thought prompting with Claude XML URL: https://claudexml.com/patterns/chain-of-thought/ Home / Patterns / Chain-of-thought # Chain-of-thought prompting with Claude XML Use and tags to give Claude a scratchpad for multi-step reasoning. Chain-of-thought (CoT) prompts ask the model to reason step-by-step before answering. The XML version: tell Claude to think inside `` and put the final answer inside ``. ## How to apply the pattern - Add CoT only when reasoning is needed. Classification, math, planning, ambiguous extraction. Not for lookups. - Specify both `` and ``. Without ``, the scratchpad and answer blend together. - Be explicit about what to think about. "List constraints, deduce, then conclude" beats "think step by step." - Extract `` in code. Regex: `([\s\S]*?)`. ## Worked example ```xml You will receive a math word problem. Inside tags, identify the unknowns, write the equations, and solve step by step. Inside tags, state the final numerical answer with units. Nothing else in . A train leaves Chicago at 2pm traveling at 60 mph. Another train leaves St. Louis at 3pm traveling at 75 mph in the opposite direction. The cities are 300 miles apart. At what time do they meet? ``` ## Tips - If you're using Claude's native extended thinking (Claude 3.7+ via the API), that handles CoT for you — don't double up with `` tags. - Keep the scratchpad if you might surface it to power users ("show reasoning" toggle). Otherwise strip it before display. Cite this page `Chain-of-thought prompting with Claude XML. claudexml.com. https://claudexml.com/patterns/chain-of-thought/` --- ## Structured output with Claude XML and tags URL: https://claudexml.com/patterns/structured-output/ Home / Patterns / Structured output # Structured output with Claude XML and tags How to coerce Claude into reliable JSON or other schemas without using tool use. When you don't want to set up the API's tool-use or JSON-mode features, you can still get reliable structured output with XML scaffolding and a `` block. ## How to apply the pattern - Show the schema in ``. Use a JSON skeleton with placeholder values that indicate type and allowed enum. - Say "return only this object". Otherwise Claude often wraps it in markdown fences. - Ask for the output inside a wrapper tag. `...` makes extraction bulletproof. - Validate and retry on parse failure. JSON.parse failures should trigger a single retry with a stricter prompt. ## Worked example ```xml Classify the support ticket. Return exactly one JSON object matching . Return only the JSON inside tags. No prose, no markdown fences. { "category": "billing | bug | feature_request | account | other", "priority": "low | medium | high | urgent", "needs_human": true, "summary": "string, max 140 chars" } {{ user_ticket }} Return your output inside tags. ``` ## Tips - For production reliability, the API's tool-use feature is stronger than XML coercion. Use XML when you can't or don't want to define a tool. - Add `"summary": "string, max 140 chars"` directly in the schema — Claude often respects inline constraints. Cite this page `Structured output with Claude XML and tags. claudexml.com. https://claudexml.com/patterns/structured-output/` --- ## RAG prompting with Claude XML URL: https://claudexml.com/patterns/rag-context/ Home / Patterns / Retrieval-augmented context # RAG prompting with Claude XML Inject retrieved passages with // and ground the answer. Retrieval-augmented generation (RAG) means fetching relevant passages and giving them to the model as context. Claude's canonical RAG pattern uses `` with one `` per passage, each carrying a ``. ## How to apply the pattern - Put documents before instructions for long contexts. Anthropic's guidance: place large reference material first, then your instructions, then the user's question. Claude attends to instructions more strongly when they're closer to the query. - Always include ``. Otherwise Claude invents citations. - Tell Claude what to do when the answer isn't in the documents. "Say 'I don't know based on the provided sources'" — without this, it'll hallucinate. - Ask for cited claims. "Cite each claim in [doc-N] format." Then verify in code. ## Worked example ```xml doc-1: pricing.md The Pro plan is $20/month and includes 100 GB of storage. doc-2: refund-policy.md All paid plans include a 14-day money-back guarantee. Answer the user's question using only the documents above. Cite the source in [doc-N] brackets for each claim. If the answer is not in the documents, say "I don't have that information in the provided sources." How much does the Pro plan cost and can I get a refund? ``` ## Tips - Chunk before retrieving — passages should be 200–800 tokens, not whole files. - Deduplicate retrieved passages; near-duplicates pull attention without adding signal. - Cap total documents at the smallest count that still answers the question well. Cite this page `RAG prompting with Claude XML. claudexml.com. https://claudexml.com/patterns/rag-context/` --- ## Multi-document synthesis with Claude XML URL: https://claudexml.com/patterns/multi-document/ Home / Patterns / Multi-document synthesis # Multi-document synthesis with Claude XML Read across many sources at once and produce a single coherent answer. When you give Claude many documents and ask for a comparative or synthesized answer, the XML structure makes attribution and comparison tractable. ## How to apply the pattern - Give each document a short, unique ``. Use stable IDs (`doc-1`, `doc-2`) the model can cite. - Pre-summarize very long documents if needed. If individual passages exceed ~5k tokens, consider a map-reduce: summarize each, then ask for synthesis on the summaries. - Be explicit about the comparison axis. "Identify points of agreement and disagreement" or "rank by recency" — vague synthesis prompts give vague output. - Ask for a structured synthesis. Use `` to specify columns or sections. ## Worked example ```xml doc-1: vendor-A-quote.pdf {{ vendor_A_text }} doc-2: vendor-B-quote.pdf {{ vendor_B_text }} doc-3: vendor-C-quote.pdf {{ vendor_C_text }} Compare the three vendor quotes. Produce a markdown table with columns: Vendor, Price (USD), Support Tier, Notable Caveats. Then write a one-paragraph recommendation citing sources in [doc-N] format. If any quote is missing a field, write "not specified" — do not infer. ``` ## Tips - Watch your context window. Even with 200k+ tokens, attention degrades on huge blobs — chunk aggressively. - Citations are only as good as your source IDs. Use ones that map back to your storage. Cite this page `Multi-document synthesis with Claude XML. claudexml.com. https://claudexml.com/patterns/multi-document/` --- ## Agentic tool use with Claude XML URL: https://claudexml.com/patterns/agentic-tool-use/ Home / Patterns / Agentic tool use # Agentic tool use with Claude XML Combine XML scaffolding with the API's tool-use feature for reliable agent loops. The Claude API has a first-class tool-use feature — that's the right primitive for agents. XML still helps as scaffolding for the model's internal planning and for shaping observations. ## How to apply the pattern - Use real tools via the API, not XML-defined ones. `tools=[...]` in the API call is stronger than asking Claude to output `` tags. - Wrap tool observations in `` tags. When you re-inject tool results, give them clear boundaries. The model treats them as evidence, not instructions. - Have Claude plan in `` before acting. On the first turn, ask for a numbered plan. Subsequent turns can re-plan with ``. - Use `` as the stop signal. Your agent loop terminates when this tag appears. ## Worked example ```xml You are an agent that helps users plan trips. You have tools available. On each turn: 1. Reason in tags about what to do next. 2. Either call a tool, or produce a . 3. When you call a tool, the result will appear in tags on the next turn. Do not include tags yourself — those come from the system. Find me a flight from SFO to NYC next Tuesday under $400. ``` ## Tips - Keep tool descriptions short and example-driven — Claude calls tools more reliably when their JSON schema includes an example argument. - Bound the agent loop. Hard cap on turns prevents runaway costs. Cite this page `Agentic tool use with Claude XML. claudexml.com. https://claudexml.com/patterns/agentic-tool-use/` --- ## 25 Working Claude XML Prompt Examples — Copy & Paste Library URL: https://claudexml.com/examples/ Home / Examples # Working Claude XML prompt examples 25 complete, copy-pasteable prompts across six categories. Tested with the Claude API. Replace the `{{ … }}` placeholders and ship. Each example is a single page with the full prompt, a sample input, expected output, and notes on what makes it work. All examples have a `.md` mirror at the same URL with a `.md` suffix for LLM-friendly fetching. ClassificationExtractionRAGReasoningGenerationTransformationComplex ## Classification Assign a label, score, or route. Few-shot patterns dominate. beginner ### Sentiment classifier Classify customer reviews as positive, neutral, or negative with few-shot examples. intermediate ### Multi-label content tagging Apply zero-to-many tags from a controlled vocabulary to an article. intermediate ### Support ticket triage with priority and routing Classify tickets by category, priority, and the team that should handle them — JSON output. intermediate ### Toxicity grader with rubric Score user-generated comments on a 0–3 toxicity scale with reasoning. ## Extraction Pull structured data out of free text. JSON output via . beginner ### Email → calendar event Detect meeting requests in email and emit a structured event with start/end in ISO format. beginner ### Structured JSON extractor from email Pull sender, subject, intent, urgency, and action items from a raw email body. intermediate ### Invoice / receipt line-item extractor Convert an OCR'd invoice into structured JSON: vendor, totals, line items. intermediate ### Résumé → structured JSON Convert a free-form résumé into a normalized candidate profile. ## RAG Answer from retrieved passages. Cite, refuse cleanly when sources don't cover the question. intermediate ### Hallucination guard: refuse when answer isn't in sources Force a clean refusal when retrieval comes up empty instead of confabulating. intermediate ### RAG over docs with [doc-N] citations Answer a question from retrieved passages and cite every claim by source ID. advanced ### Multi-document compare-and-contrast Synthesize three vendor quotes into a table plus a one-paragraph recommendation. ## Reasoning Multi-step thinking via + . Math, logic, code review. beginner ### Chain-of-thought math word problem Reason step-by-step inside , isolate the final number in . intermediate ### Constraint-satisfaction logic puzzle Solve a puzzle by enumerating constraints inside and concluding in . intermediate ### Natural language → SQL with a schema Translate plain-English questions into SQL against a provided schema. Few-shot. advanced ### Code review with severity levels Review a diff and produce structured findings (bug, perf, style) with severities. ## Generation Produce new text in a controlled shape, tone, or variation set. beginner ### Document summarizer with a librarian persona Tight, factual summary: TL;DR, 3 key bullets, 1 open question — no fluff. beginner ### Email tone rewriter Rewrite a draft in a target tone (warm, neutral, firm) without changing meaning. beginner ### Headline A/B variant generator Produce N distinct headline variants for a piece of content, each with a different angle. advanced ### Test case generator from a spec Read a feature spec and produce test cases (happy path, edge cases, failure modes). ## Transformation Multi-stage pipelines that emit several views in one call. intermediate ### Transcript cleaner with speaker labels and summary Multi-stage pipeline: clean fillers, label speakers consistently, produce a 5-bullet summary. ## Complex Two-turn protocols, self-critique loops, branching exploration, and validating data pipelines. Multiple stages in one prompt. advanced ### Extract → validate → transform pipeline in one call Four-stage data pipeline: extract raw fields, validate against rules, transform to target shape, emit errors. advanced ### Generate → self-critique → revise in one call Three-stage prompt where Claude drafts, scores its own draft against a rubric, then revises. advanced ### Map-reduce summarization over many chunks Summarize each chunk independently, then synthesize a single coherent summary — two prompts, structured handoff. advanced ### Plan-then-act with explicit sub-task scaffolding Two-turn pattern: first turn produces a numbered plan; second turn executes each sub-task and returns structured results. advanced ### Tree-of-thought reasoning with branch scoring Explore three reasoning paths, score each against criteria, pick the winner — all in one prompt. Cite this page `Working Claude XML Prompt Examples. claudexml.com. https://claudexml.com/examples/` --- ## Sentiment classifier — Claude XML example URL: https://claudexml.com/examples/sentiment-classifier/ Home / Examples / Sentiment classifier Classification · beginner # Sentiment classifier Classify customer reviews as positive, neutral, or negative with few-shot examples. You have an inbound stream of free-text reviews and want a single sentiment label per item for routing or analytics. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml Classify the review's sentiment. Return exactly one of: positive, neutral, negative. Return only the lowercase label, no punctuation, no explanation. Loved it, will be back!positive It was fine.neutral Total waste of money.negative {{ review_text }} ``` ## Sample input ```xml The food took 45 minutes to arrive cold. ``` ## Expected output ```xml negative ``` ## Notes & tuning tips - Calibration: include at least one example per output class; skew in examples → skew in outputs. - Add a fourth class ("mixed") only if you need it — extra classes always hurt accuracy on the existing ones. - For a production version, also ask for confidence and route low-confidence items to humans. ## What this example uses Tags: Patterns: few shot ## More like this classification ### Support ticket triage with priority and routing Classify tickets by category, priority, and the team that should handle them — JSON output. classification ### Multi-label content tagging Apply zero-to-many tags from a controlled vocabulary to an article. classification ### Toxicity grader with rubric Score user-generated comments on a 0–3 toxicity scale with reasoning. Cite this page `Sentiment classifier. claudexml.com. https://claudexml.com/examples/sentiment-classifier/` --- ## Support ticket triage with priority and routing — Claude XML example URL: https://claudexml.com/examples/ticket-triage/ Home / Examples / Support ticket triage with priority and routing Classification · intermediate # Support ticket triage with priority and routing Classify tickets by category, priority, and the team that should handle them — JSON output. A support inbox needs deterministic triage: category, priority, owning team, and a short summary the on-call engineer can scan in 2 seconds. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml Triage the support ticket. Return a single JSON object matching . Return the JSON inside tags. No prose, no markdown fences. Priority rubric: - urgent: production outage, data loss, or security incident - high: blocking a paying customer with no workaround - medium: degraded experience with a workaround - low: feature request, cosmetic issue, or question { "category": "billing | bug | feature_request | account | security | other", "priority": "low | medium | high | urgent", "owner_team": "billing | platform | mobile | growth | trust_safety | unknown", "needs_human": true, "summary": "string, max 140 chars, neutral tone" } {{ ticket_body }} Return inside tags. ``` ## Sample input ```xml Hey, your dashboard hasn't loaded since this morning. Our entire ops team is blocked. — Acme Corp (Enterprise plan) ``` ## Expected output ```xml { "category": "bug", "priority": "urgent", "owner_team": "platform", "needs_human": true, "summary": "Enterprise customer reports dashboard unreachable; team-wide block since this morning." } ``` ## Notes & tuning tips - The rubric inside is what makes priority labels consistent — without it, Claude reverts to vibes. - Wrapping output in makes parsing trivial: regex /([\s\S]*?)/. - For higher reliability, define the schema as an API tool instead of a block. ## What this example uses Tags: Patterns: structured output ## More like this classification ### Sentiment classifier Classify customer reviews as positive, neutral, or negative with few-shot examples. classification ### Multi-label content tagging Apply zero-to-many tags from a controlled vocabulary to an article. classification ### Toxicity grader with rubric Score user-generated comments on a 0–3 toxicity scale with reasoning. Cite this page `Support ticket triage with priority and routing. claudexml.com. https://claudexml.com/examples/ticket-triage/` --- ## Multi-label content tagging — Claude XML example URL: https://claudexml.com/examples/multi-label-tagging/ Home / Examples / Multi-label content tagging Classification · intermediate # Multi-label content tagging Apply zero-to-many tags from a controlled vocabulary to an article. You're building a CMS that needs consistent tag suggestions from a fixed taxonomy — strict subset, no hallucinated labels. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml Read the article inside
. Apply any number of tags from the list inside that genuinely apply. Do not invent tags. Do not use synonyms. If no tag applies, return an empty array. Return JSON inside tags, in this exact shape: { "tags": ["tag1", "tag2", ...] } - machine-learning - ai-safety - distributed-systems - databases - programming-languages - web-performance - security - privacy - developer-experience - open-source
{{ article_text }}
Return inside tags. ``` ## Sample input ```xml A post about using Rust to build a high-throughput, memory-safe alternative to Redis for caching, with discussion of LRU eviction and zero-copy serialization. ``` ## Expected output ```xml { "tags": ["databases", "programming-languages", "open-source", "web-performance"] } ``` ## Notes & tuning tips - The controlled vocabulary inside is load-bearing — without it Claude invents "caching" and "rust". - Phrase "do not invent" + "do not use synonyms" explicitly; one is not enough. - Validate the result against the vocabulary in code; drop any unknown labels as a safety net. ## What this example uses Tags: Patterns: structured output ## More like this classification ### Sentiment classifier Classify customer reviews as positive, neutral, or negative with few-shot examples. classification ### Support ticket triage with priority and routing Classify tickets by category, priority, and the team that should handle them — JSON output. classification ### Toxicity grader with rubric Score user-generated comments on a 0–3 toxicity scale with reasoning. Cite this page `Multi-label content tagging. claudexml.com. https://claudexml.com/examples/multi-label-tagging/` --- ## Toxicity grader with rubric — Claude XML example URL: https://claudexml.com/examples/toxicity-grader/ Home / Examples / Toxicity grader with rubric Classification · intermediate # Toxicity grader with rubric Score user-generated comments on a 0–3 toxicity scale with reasoning. A community moderation queue needs a numeric toxicity score plus a one-line justification an admin can audit. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml You are a content moderation classifier. Score the comment for toxicity from 0 to 3. Rubric: - 0 = benign — substantive disagreement, civil tone - 1 = mildly impolite — sarcasm, dismissiveness, no slurs or threats - 2 = harmful — insults, harassment, mockery of an identity - 3 = severe — threats, slurs, calls for violence, doxxing Reason inside . Return JSON inside : { "score": 0, "justification": "string, max 80 chars" } {{ comment_text }} ``` ## Sample input ```xml lol you have no idea what you're talking about, please stop posting ``` ## Expected output ```xml The comment is dismissive and mocking but not threatening or slur-bearing. Sits at mildly impolite — score 1. { "score": 1, "justification": "Dismissive and mocking but no slurs or threats." } ``` ## Notes & tuning tips - Always show the rubric: the difference between 1 and 2 is a policy decision the model needs. - here is for audit, not user display. Strip it before showing the score. - Pair with a human review queue for scores ≥ 2. ## What this example uses Tags: Patterns: chain of thought structured output ## More like this classification ### Sentiment classifier Classify customer reviews as positive, neutral, or negative with few-shot examples. classification ### Support ticket triage with priority and routing Classify tickets by category, priority, and the team that should handle them — JSON output. classification ### Multi-label content tagging Apply zero-to-many tags from a controlled vocabulary to an article. Cite this page `Toxicity grader with rubric. claudexml.com. https://claudexml.com/examples/toxicity-grader/` --- ## Structured JSON extractor from email — Claude XML example URL: https://claudexml.com/examples/structured-json-extractor/ Home / Examples / Structured JSON extractor from email Extraction · beginner # Structured JSON extractor from email Pull sender, subject, intent, urgency, and action items from a raw email body. You're indexing inbound email into a CRM and want a consistent JSON schema regardless of how the email is written. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml Extract structured data from the email below. Return one JSON object matching . Output the JSON inside tags. No prose, no markdown fences. If a field is missing from the email, use null. { "sender_name": "string or null", "sender_email": "string or null", "subject": "string", "intent": "question | request | complaint | other", "urgency": "low | medium | high", "action_items": ["string"] } {{ email_body }} Return inside tags. ``` ## Sample input ```xml From: Jane Lee Subject: Need invoice copy Hi — could you resend the May invoice? Our AP needs it by Friday. Thanks, Jane ``` ## Expected output ```xml { "sender_name": "Jane Lee", "sender_email": "jane@acme.com", "subject": "Need invoice copy", "intent": "request", "urgency": "medium", "action_items": ["Resend May invoice to jane@acme.com by Friday"] } ``` ## Notes & tuning tips - Inline `null` and `|` enums in the schema — Claude respects them. - `return only inside tags` is the single most reliable way to dodge markdown fences. - For batch jobs, parallelize at the request level — don't ask for a JSON array of multiple emails in one call. ## What this example uses Tags: Patterns: structured output ## More like this extraction ### Invoice / receipt line-item extractor Convert an OCR'd invoice into structured JSON: vendor, totals, line items. extraction ### Résumé → structured JSON Convert a free-form résumé into a normalized candidate profile. extraction ### Email → calendar event Detect meeting requests in email and emit a structured event with start/end in ISO format. Cite this page `Structured JSON extractor from email. claudexml.com. https://claudexml.com/examples/structured-json-extractor/` --- ## Invoice / receipt line-item extractor — Claude XML example URL: https://claudexml.com/examples/invoice-extractor/ Home / Examples / Invoice / receipt line-item extractor Extraction · intermediate # Invoice / receipt line-item extractor Convert an OCR'd invoice into structured JSON: vendor, totals, line items. AP automation: invoices come in as PDFs, OCR'd to messy text. You need vendor name, dates, currency, totals, and per-line-item details. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml Extract invoice data from the OCR text in . Return JSON inside tags. Rules: - If a number isn't clearly stated, use null. Do not estimate. - Currency must be an ISO-4217 code (USD, EUR, GBP, JPY, ...). - Dates must be ISO-8601 (YYYY-MM-DD). Convert if the source uses another format. - Line item quantity defaults to 1 if not stated. - Subtotal + tax should equal total within rounding; if not, flag with "totals_inconsistent": true at the top level. { "vendor_name": "string or null", "vendor_tax_id": "string or null", "invoice_number": "string or null", "issue_date": "YYYY-MM-DD or null", "due_date": "YYYY-MM-DD or null", "currency": "ISO-4217 code", "subtotal": 0.0, "tax": 0.0, "total": 0.0, "totals_inconsistent": false, "line_items": [ { "description": "string", "quantity": 1, "unit_price": 0.0, "amount": 0.0 } ] } {{ invoice_ocr_text }} Return inside tags. ``` ## Sample input ```xml ACME WIDGETS INC Invoice #INV-2026-0512 Date: May 12, 2026 Due: 30 days net Widget A x2 $50.00 $100.00 Shipping $12.00 Subtotal $112.00 Tax $9.80 Total $121.80 Thank you. ``` ## Expected output ```xml { "vendor_name": "ACME WIDGETS INC", "vendor_tax_id": null, "invoice_number": "INV-2026-0512", "issue_date": "2026-05-12", "due_date": "2026-06-11", "currency": "USD", "subtotal": 112.00, "tax": 9.80, "total": 121.80, "totals_inconsistent": false, "line_items": [ { "description": "Widget A", "quantity": 2, "unit_price": 50.00, "amount": 100.00 }, { "description": "Shipping", "quantity": 1, "unit_price": 12.00, "amount": 12.00 } ] } ``` ## Notes & tuning tips - Date conversion is the most common failure — restate the format requirement. - Add a server-side sanity check: subtotal + tax ≈ total (within $0.05) catches OCR errors. - For multi-page invoices, send each page as a separate and ask for a combined extraction. ## What this example uses Tags: Patterns: structured output ## More like this extraction ### Structured JSON extractor from email Pull sender, subject, intent, urgency, and action items from a raw email body. extraction ### Résumé → structured JSON Convert a free-form résumé into a normalized candidate profile. extraction ### Email → calendar event Detect meeting requests in email and emit a structured event with start/end in ISO format. Cite this page `Invoice / receipt line-item extractor. claudexml.com. https://claudexml.com/examples/invoice-extractor/` --- ## Résumé → structured JSON — Claude XML example URL: https://claudexml.com/examples/resume-to-json/ Home / Examples / Résumé → structured JSON Extraction · intermediate # Résumé → structured JSON Convert a free-form résumé into a normalized candidate profile. Recruiting pipelines need structured candidate data: contact info, experience with normalized dates, education, skills — extracted from wildly varied résumé formats. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml Extract candidate data from the résumé in . Return JSON inside tags. Rules: - Dates are ISO YYYY-MM. If only a year is given, use YYYY-01. - "present" or "current" in end_date → null. - Skills: include only items the candidate lists. Do not infer from job descriptions. - Do not include personal info beyond name, email, phone, location (city/country). { "name": "string", "email": "string or null", "phone": "string or null", "location": "string or null", "headline": "string or null", "experience": [ { "company": "string", "title": "string", "start_date": "YYYY-MM", "end_date": "YYYY-MM or null", "highlights": ["string"] } ], "education": [ { "institution": "string", "degree": "string or null", "field": "string or null", "graduation_year": 2024 } ], "skills": ["string"] } {{ resume_text }} Return inside tags. ``` ## Sample input ```xml Maya Chen — Senior SRE maya@example.com · +1 415 555 0142 · San Francisco, CA Experience - Acme Cloud, Staff SRE, Jan 2022 – present * Cut p99 latency from 800ms to 120ms across the API tier * Led incident response for 3 SEV-1s - Globex, SRE, 2019 – 2021 Education B.S. Computer Science, UC Berkeley, 2019 Skills: Go, Kubernetes, Terraform, Prometheus ``` ## Expected output ```xml { "name": "Maya Chen", "email": "maya@example.com", "phone": "+1 415 555 0142", "location": "San Francisco, CA", "headline": "Senior SRE", "experience": [ {"company": "Acme Cloud", "title": "Staff SRE", "start_date": "2022-01", "end_date": null, "highlights": ["Cut p99 latency from 800ms to 120ms across the API tier", "Led incident response for 3 SEV-1s"]}, {"company": "Globex", "title": "SRE", "start_date": "2019-01", "end_date": "2021-01", "highlights": []} ], "education": [ {"institution": "UC Berkeley", "degree": "B.S.", "field": "Computer Science", "graduation_year": 2019} ], "skills": ["Go", "Kubernetes", "Terraform", "Prometheus"] } ``` ## Notes & tuning tips - PII restriction prevents the model from inventing demographic inferences. - If résumés routinely include photos or addresses, strip those upstream before extraction. - Always validate emails / phones with format checks server-side; the model isn't a validator. ## What this example uses Tags: Patterns: structured output ## More like this extraction ### Structured JSON extractor from email Pull sender, subject, intent, urgency, and action items from a raw email body. extraction ### Invoice / receipt line-item extractor Convert an OCR'd invoice into structured JSON: vendor, totals, line items. extraction ### Email → calendar event Detect meeting requests in email and emit a structured event with start/end in ISO format. Cite this page `Résumé → structured JSON. claudexml.com. https://claudexml.com/examples/resume-to-json/` --- ## Email → calendar event — Claude XML example URL: https://claudexml.com/examples/email-to-calendar-event/ Home / Examples / Email → calendar event Extraction · beginner # Email → calendar event Detect meeting requests in email and emit a structured event with start/end in ISO format. Inbox copilot: when an email proposes a meeting, surface a one-click 'add to calendar' with the right time, attendees, and title. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml Determine whether the email proposes a specific meeting time. If yes, extract the event. If no, return {"is_meeting": false}. Assume the reader's timezone is in . Convert times to that timezone if the email gives a different one. Today's date is in . Return JSON inside tags. America/Los_Angeles {{ today_iso }} { "is_meeting": true, "title": "string", "start": "ISO-8601 with timezone", "end": "ISO-8601 with timezone", "attendees": ["string"], "location": "string or null", "notes": "string or null" } {{ email_body }} Return inside tags. ``` ## Sample input ```xml Hi — let's sync on the launch this Thursday at 3pm PT for 30 min. Zoom: https://zoom.us/j/123. — Sam ``` ## Expected output ```xml { "is_meeting": true, "title": "Launch sync", "start": "2026-05-28T15:00:00-07:00", "end": "2026-05-28T15:30:00-07:00", "attendees": ["Sam"], "location": "https://zoom.us/j/123", "notes": null } ``` ## Notes & tuning tips - Passing and is what makes "this Thursday at 3pm" resolvable. - If the email is ambiguous ("sometime next week"), the model should set is_meeting=false rather than guess. - Validate the resulting ISO timestamp parses cleanly in your calendar library before showing the user the button. ## What this example uses Tags: Patterns: structured output ## More like this extraction ### Structured JSON extractor from email Pull sender, subject, intent, urgency, and action items from a raw email body. extraction ### Invoice / receipt line-item extractor Convert an OCR'd invoice into structured JSON: vendor, totals, line items. extraction ### Résumé → structured JSON Convert a free-form résumé into a normalized candidate profile. Cite this page `Email → calendar event. claudexml.com. https://claudexml.com/examples/email-to-calendar-event/` --- ## RAG over docs with [doc-N] citations — Claude XML example URL: https://claudexml.com/examples/rag-with-citations/ Home / Examples / RAG over docs with [doc-N] citations RAG · intermediate # RAG over docs with [doc-N] citations Answer a question from retrieved passages and cite every claim by source ID. Customer support copilot: answer using only your knowledge base, refuse cleanly when the answer isn't there, and cite sources the human can verify. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml doc-1: pricing.md {{ passage_1 }} doc-2: refund-policy.md {{ passage_2 }} Answer the user's question using only the documents above. Cite every claim with [doc-N] inline. If the answer is not in the documents, reply exactly: "I don't have that information in the provided sources." Do not draw on outside knowledge. {{ user_question }} ``` ## Sample input ```xml Question: How much does the Pro plan cost and can I get a refund? Passage 1: The Pro plan is $20/month and includes 100 GB of storage. Passage 2: All paid plans include a 14-day money-back guarantee. ``` ## Expected output ```xml The Pro plan is $20 per month [doc-1]. You can request a refund within 14 days of purchase [doc-2]. ``` ## Notes & tuning tips - Documents-first ordering matters once context gets long — Anthropic's guidance is reference material before instructions. - The exact refusal string lets you regex for it and offer a human handoff button. - Validate cited doc IDs against your retrieval set in code; the model occasionally cites adjacent docs. ## What this example uses Tags: Patterns: rag context ## More like this rag ### Multi-document compare-and-contrast Synthesize three vendor quotes into a table plus a one-paragraph recommendation. rag ### Hallucination guard: refuse when answer isn't in sources Force a clean refusal when retrieval comes up empty instead of confabulating. Cite this page `RAG over docs with [doc-N] citations. claudexml.com. https://claudexml.com/examples/rag-with-citations/` --- ## Multi-document compare-and-contrast — Claude XML example URL: https://claudexml.com/examples/multi-doc-compare/ Home / Examples / Multi-document compare-and-contrast RAG · advanced # Multi-document compare-and-contrast Synthesize three vendor quotes into a table plus a one-paragraph recommendation. Procurement task: a buyer has three vendor proposals and wants a side-by-side comparison they can hand to their manager. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml doc-1: vendor-A-quote.pdf {{ vendor_A_text }} doc-2: vendor-B-quote.pdf {{ vendor_B_text }} doc-3: vendor-C-quote.pdf {{ vendor_C_text }} Compare the three vendor quotes. Produce: 1. A Markdown table with columns: Vendor, Price (USD), Support Tier, Notable Caveats. Cite each cell with [doc-N]. 2. A one-paragraph recommendation citing sources in [doc-N] format. Rules: - If a field is missing in a quote, write "not specified" — do not infer. - Do not estimate prices that aren't stated. - Keep tone neutral; no superlatives unless directly supported by a source. ``` ## Sample input ```xml Three short PDF-extracted quotes from vendors A, B, C with prices, support tiers, and various caveats. ``` ## Expected output ```xml A markdown table followed by a 4-sentence recommendation, all cells and claims tagged with [doc-1] through [doc-3]. ``` ## Notes & tuning tips - When passages are long (>5k tokens each), summarize them in a first pass and synthesize on the summaries. - Citations only help if your source IDs map back to retrievable files. Use stable IDs. - If you want a specific recommendation framing (cheapest, best-support, lowest-risk), spell it out in instructions. ## What this example uses Tags: Patterns: multi document ## More like this rag ### RAG over docs with [doc-N] citations Answer a question from retrieved passages and cite every claim by source ID. rag ### Hallucination guard: refuse when answer isn't in sources Force a clean refusal when retrieval comes up empty instead of confabulating. Cite this page `Multi-document compare-and-contrast. claudexml.com. https://claudexml.com/examples/multi-doc-compare/` --- ## Hallucination guard: refuse when answer isn't in sources — Claude XML example URL: https://claudexml.com/examples/hallucination-guard/ Home / Examples / Hallucination guard: refuse when answer isn't in sources RAG · intermediate # Hallucination guard: refuse when answer isn't in sources Force a clean refusal when retrieval comes up empty instead of confabulating. RAG over a sparse knowledge base: most questions can't be answered. You want crisp refusals, not plausible-sounding hallucinations. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml {{ retrieved_passages }} You will receive a user question and zero or more documents. Procedure: 1. Reason inside . List facts that are stated in the documents. Quote them. 2. Decide whether those facts are sufficient to answer the question. 3. If yes — answer concisely inside , citing [doc-N] for each claim. 4. If no — return exactly inside : "I don't have enough information in the provided sources to answer that." Do not use any knowledge outside the documents. Do not make plausible guesses. {{ user_question }} ``` ## Sample input ```xml Question: What's the company's policy on remote work? Documents: (only contain pricing and SLA info) ``` ## Expected output ```xml The documents cover pricing tiers and SLA uptime targets. Neither mentions remote work. Insufficient to answer. I don't have enough information in the provided sources to answer that. ``` ## Notes & tuning tips - The explicit "list facts → decide → answer or refuse" procedure cuts hallucinations dramatically vs. just "answer using sources." - Use the exact refusal string for a deterministic UI handoff. - Combine with retrieval confidence: if your top-k similarity scores are low, you can short-circuit before calling the model. ## What this example uses Tags: Patterns: rag context chain of thought ## More like this rag ### RAG over docs with [doc-N] citations Answer a question from retrieved passages and cite every claim by source ID. rag ### Multi-document compare-and-contrast Synthesize three vendor quotes into a table plus a one-paragraph recommendation. Cite this page `Hallucination guard: refuse when answer isn't in sources. claudexml.com. https://claudexml.com/examples/hallucination-guard/` --- ## Chain-of-thought math word problem — Claude XML example URL: https://claudexml.com/examples/math-cot/ Home / Examples / Chain-of-thought math word problem Reasoning · beginner # Chain-of-thought math word problem Reason step-by-step inside , isolate the final number in . Word problems where the model needs to identify variables, write equations, and solve. The classic CoT use case. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml Solve the word problem below. Reason inside : - identify unknowns, - write the equations, - solve step by step. Put the final answer — a single number with units, nothing else — inside . {{ math_problem }} ``` ## Sample input ```xml A train leaves Chicago at 2pm at 60 mph. Another leaves St. Louis at 3pm at 75 mph in the opposite direction. Cities are 300 miles apart. When do they meet? ``` ## Expected output ```xml Let t = hours after 2pm. Train A traveled 60·t miles. Train B traveled 75·(t−1). 60t + 75(t−1) = 300 60t + 75t − 75 = 300 135t = 375 t = 2.78 h ≈ 2 hours 47 minutes after 2pm 4:47 pm ``` ## Notes & tuning tips - Explicit "identify unknowns / write equations / solve" beats vague "think step by step" on accuracy. - If you're using Claude's native extended thinking (Claude 3.7+), skip the tag — that runs internally. - Strip the scratchpad before showing the answer to end users unless they've opted in to seeing reasoning. ## What this example uses Tags: Patterns: chain of thought ## More like this reasoning ### Constraint-satisfaction logic puzzle Solve a puzzle by enumerating constraints inside and concluding in . reasoning ### Natural language → SQL with a schema Translate plain-English questions into SQL against a provided schema. Few-shot. reasoning ### Code review with severity levels Review a diff and produce structured findings (bug, perf, style) with severities. Cite this page `Chain-of-thought math word problem. claudexml.com. https://claudexml.com/examples/math-cot/` --- ## Constraint-satisfaction logic puzzle — Claude XML example URL: https://claudexml.com/examples/logic-puzzle/ Home / Examples / Constraint-satisfaction logic puzzle Reasoning · intermediate # Constraint-satisfaction logic puzzle Solve a puzzle by enumerating constraints inside and concluding in . Zebra-style puzzles, scheduling problems, or any task that needs explicit constraint tracking. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml Solve the puzzle. Inside : 1. List the entities and possible values. 2. List each constraint explicitly. 3. Deduce, eliminating possibilities; note any branches you tried. Inside , give the final assignment as a JSON object. {{ puzzle_text }} ``` ## Sample input ```xml Three friends — Alex, Blair, Casey — each ordered a different drink (coffee, tea, juice). Alex didn't order coffee. Blair didn't order tea. Casey ordered tea. What did each person order? ``` ## Expected output ```xml Entities: {Alex, Blair, Casey} → drinks {coffee, tea, juice}. Constraints: Alex ≠ coffee; Blair ≠ tea; Casey = tea. With Casey = tea, remaining {coffee, juice} for {Alex, Blair}. Alex ≠ coffee → Alex = juice → Blair = coffee. { "Alex": "juice", "Blair": "coffee", "Casey": "tea" } ``` ## Notes & tuning tips - Numbered procedure beats free-form reasoning — Claude follows the structure. - JSON-in-answer makes downstream verification trivial. - For larger constraint problems (10+ entities), prefer a real solver (Z3, MiniZinc) called via tool use. ## What this example uses Tags: Patterns: chain of thought structured output ## More like this reasoning ### Chain-of-thought math word problem Reason step-by-step inside , isolate the final number in . reasoning ### Natural language → SQL with a schema Translate plain-English questions into SQL against a provided schema. Few-shot. reasoning ### Code review with severity levels Review a diff and produce structured findings (bug, perf, style) with severities. Cite this page `Constraint-satisfaction logic puzzle. claudexml.com. https://claudexml.com/examples/logic-puzzle/` --- ## Natural language → SQL with a schema — Claude XML example URL: https://claudexml.com/examples/sql-from-nl/ Home / Examples / Natural language → SQL with a schema Reasoning · intermediate # Natural language → SQL with a schema Translate plain-English questions into SQL against a provided schema. Few-shot. A business-user analytics tool: type a question, get the SQL (and run it). Need consistent dialect and schema adherence. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml Convert the question into a single SQL query against the schema in . Use PostgreSQL syntax. Return only the SQL inside tags, no commentary. If the question can't be answered from the schema, return inside : -- cannot answer from schema users(id, email, signup_date, plan) orders(id, user_id, total_cents, status, created_at) refunds(id, order_id, amount_cents, created_at) How many users signed up in March 2026? SELECT COUNT(*) FROM users WHERE signup_date >= '2026-03-01' AND signup_date < '2026-04-01'; Top 10 users by lifetime revenue, excluding refunds. SELECT u.id, u.email, SUM(o.total_cents) - COALESCE(SUM(r.amount_cents), 0) AS net_cents FROM users u JOIN orders o ON o.user_id = u.id AND o.status = 'completed' LEFT JOIN refunds r ON r.order_id = o.id GROUP BY u.id, u.email ORDER BY net_cents DESC LIMIT 10; {{ user_question }} ``` ## Sample input ```xml Average order value by signup-year cohort, last 30 days only. ``` ## Expected output ```xml SELECT EXTRACT(YEAR FROM u.signup_date) AS cohort_year, AVG(o.total_cents) / 100.0 AS avg_order_dollars FROM orders o JOIN users u ON u.id = o.user_id WHERE o.created_at >= NOW() - INTERVAL '30 days' AND o.status = 'completed' GROUP BY cohort_year ORDER BY cohort_year; ``` ## Notes & tuning tips - The schema block must list every table and column you want the model to use. Anything else → hallucination. - Two examples covering simple and complex patterns is the sweet spot. More rarely helps; fewer often breaks join handling. - Always run the SQL in a read-only role with statement_timeout — never trust generated SQL to be safe. ## What this example uses Tags: Patterns: few shot ## More like this reasoning ### Chain-of-thought math word problem Reason step-by-step inside , isolate the final number in . reasoning ### Constraint-satisfaction logic puzzle Solve a puzzle by enumerating constraints inside and concluding in . reasoning ### Code review with severity levels Review a diff and produce structured findings (bug, perf, style) with severities. Cite this page `Natural language → SQL with a schema. claudexml.com. https://claudexml.com/examples/sql-from-nl/` --- ## Code review with severity levels — Claude XML example URL: https://claudexml.com/examples/code-review/ Home / Examples / Code review with severity levels Reasoning · advanced # Code review with severity levels Review a diff and produce structured findings (bug, perf, style) with severities. Pre-merge automated review: a deterministic list of findings the human reviewer can scan and accept/dismiss. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml Review the diff in . Produce a JSON array of findings inside tags. Each finding: { "line": 42, // best-effort line in the new file "category": "bug | perf | security | style | docs", "severity": "info | low | medium | high | critical", "summary": "string, max 100 chars", "explanation": "string, 1–3 sentences", "suggested_fix": "string or null" } Rules: - Only flag issues actually present in the diff. Do not speculate about the rest of the file. - Severity "critical" is reserved for security issues or data corruption. - Skip findings with severity "info" unless asked. - If the diff is clean, return []. {{ unified_diff }} Return inside tags. ``` ## Sample input ```xml A diff that adds a function using string concatenation for SQL and ignores the return value of a write call. ``` ## Expected output ```xml [ {"line": 12, "category": "security", "severity": "critical", "summary": "SQL built via string concatenation — injection risk", "explanation": "User input is concatenated directly into the SQL query. Switch to parameterized queries.", "suggested_fix": "db.execute('SELECT * FROM users WHERE id = %s', (user_id,))"}, {"line": 24, "category": "bug", "severity": "medium", "summary": "Write call result discarded", "explanation": "The return value of f.write() is not checked; on partial writes this silently truncates output.", "suggested_fix": null} ] ``` ## Notes & tuning tips - Force JSON output; nothing else parses reliably from a code-review prompt. - Cap the diff size — large diffs (>1000 lines) yield shallow reviews; chunk by file. - Pair with a confidence threshold and post only severity ≥ medium to PR comments. ## What this example uses Tags: Patterns: structured output ## More like this reasoning ### Chain-of-thought math word problem Reason step-by-step inside , isolate the final number in . reasoning ### Constraint-satisfaction logic puzzle Solve a puzzle by enumerating constraints inside and concluding in . reasoning ### Natural language → SQL with a schema Translate plain-English questions into SQL against a provided schema. Few-shot. Cite this page `Code review with severity levels. claudexml.com. https://claudexml.com/examples/code-review/` --- ## Document summarizer with a librarian persona — Claude XML example URL: https://claudexml.com/examples/doc-summarizer/ Home / Examples / Document summarizer with a librarian persona Generation · beginner # Document summarizer with a librarian persona Tight, factual summary: TL;DR, 3 key bullets, 1 open question — no fluff. A research-feed product that needs uniformly structured summaries readers can skim in 15 seconds. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml You are a senior research librarian. You write tight, factual summaries without flourishes. You note uncertainty explicitly. Summarize the article. Produce: 1. One-sentence TL;DR. 2. Three bullet points of key claims (with the strength of evidence in parentheses). 3. One open question the article raises but does not answer. Do not invent claims. If the article doesn't support a claim, say "not addressed".
{{ article_text }}
``` ## Sample input ```xml A research blog post about scaling RAG with smaller, fine-tuned retrievers. ``` ## Expected output ```xml 1. TL;DR: Fine-tuned dense retrievers can match or beat larger off-the-shelf models at one-tenth the cost. 2. - The authors fine-tune a 110M retriever on 50k domain queries and outperform a 7B baseline (strong: ablation table 2). 3. - Latency drops 8× with no measurable recall loss (strong: figure 4). 4. - The approach requires domain query logs the post acknowledges most teams don't have (weak: anecdotal). 5. Open question: How does this generalize to long-tail queries the training set didn't cover? ``` ## Notes & tuning tips - The persona in is what produces the brevity. Without it, summaries balloon. - Requiring evidence-strength in parens forces the model to read carefully rather than invent. - Pair with a max-token budget on the API call to enforce length. ## What this example uses Tags: ## More like this generation ### Email tone rewriter Rewrite a draft in a target tone (warm, neutral, firm) without changing meaning. generation ### Headline A/B variant generator Produce N distinct headline variants for a piece of content, each with a different angle. generation ### Test case generator from a spec Read a feature spec and produce test cases (happy path, edge cases, failure modes). Cite this page `Document summarizer with a librarian persona. claudexml.com. https://claudexml.com/examples/doc-summarizer/` --- ## Email tone rewriter — Claude XML example URL: https://claudexml.com/examples/email-rewriter/ Home / Examples / Email tone rewriter Generation · beginner # Email tone rewriter Rewrite a draft in a target tone (warm, neutral, firm) without changing meaning. Productivity tool: user writes a draft, picks a tone, gets a polished version with the same intent. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml You are a copy editor who preserves meaning and intent exactly, but tunes tone. Rewrite the email in in the tone specified in . Rules: - Do not add, remove, or change any factual claim or commitment. - Do not change the recipient or subject. - Match the requested tone consistently across greeting, body, and signoff. - Return only the rewritten email inside tags. No preamble, no notes. {{ tone }} {{ draft }} ``` ## Sample input ```xml Tone: warm-but-firm Draft: 'You haven't paid the invoice. Pay now.' ``` ## Expected output ```xml Hi — just a friendly nudge that the invoice from last month is still outstanding. Could you get that taken care of by end of week? Happy to resend the link if it'd help. Thanks, [Name] ``` ## Notes & tuning tips - The "do not change facts" rule is critical — without it the model softens commitments. - Offer 3–5 named tones (warm, neutral, firm, formal, playful) rather than freeform. - Diff the original and rewrite in code to flag accidental fact changes. ## What this example uses Tags: ## More like this generation ### Document summarizer with a librarian persona Tight, factual summary: TL;DR, 3 key bullets, 1 open question — no fluff. generation ### Headline A/B variant generator Produce N distinct headline variants for a piece of content, each with a different angle. generation ### Test case generator from a spec Read a feature spec and produce test cases (happy path, edge cases, failure modes). Cite this page `Email tone rewriter. claudexml.com. https://claudexml.com/examples/email-rewriter/` --- ## Headline A/B variant generator — Claude XML example URL: https://claudexml.com/examples/headline-ab/ Home / Examples / Headline A/B variant generator Generation · beginner # Headline A/B variant generator Produce N distinct headline variants for a piece of content, each with a different angle. Content team needs headline candidates that span angles (curiosity, benefit-led, contrarian) — not minor rewordings. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml Generate exactly {{ n }} headline variants for the article below. Constraints: - Each headline ≤ 70 characters. - Each must take a meaningfully different angle: curiosity, benefit, contrarian, data-led, narrative. - No clickbait (no "you won't believe", no "shocking", no all-caps). - Return as JSON array inside tags, in this shape: [ { "angle": "curiosity|benefit|contrarian|data-led|narrative", "headline": "string" } ]
{{ article_text }}
Return inside tags. ``` ## Sample input ```xml n: 5 Article: study showing remote workers report 15% higher focus but 25% more loneliness ``` ## Expected output ```xml [ {"angle": "data-led", "headline": "Remote workers gained 15% focus and lost 25% to loneliness"}, {"angle": "curiosity", "headline": "Why your most focused employees are also your loneliest"}, {"angle": "contrarian","headline": "Remote work didn't fail — it just exposed what offices were hiding"}, {"angle": "benefit", "headline": "How to keep remote's focus gains without the isolation tax"}, {"angle": "narrative", "headline": "Three years remote: what the focus data didn't tell us"} ] ``` ## Notes & tuning tips - Naming distinct angles in the constraint is what produces variety. Without it, all 5 headlines rhyme. - Cap at 5 variants — beyond that, quality degrades and the angles collapse. - Filter clickbait server-side too as a safety net. ## What this example uses Tags: Patterns: structured output ## More like this generation ### Document summarizer with a librarian persona Tight, factual summary: TL;DR, 3 key bullets, 1 open question — no fluff. generation ### Email tone rewriter Rewrite a draft in a target tone (warm, neutral, firm) without changing meaning. generation ### Test case generator from a spec Read a feature spec and produce test cases (happy path, edge cases, failure modes). Cite this page `Headline A/B variant generator. claudexml.com. https://claudexml.com/examples/headline-ab/` --- ## Test case generator from a spec — Claude XML example URL: https://claudexml.com/examples/test-case-generator/ Home / Examples / Test case generator from a spec Generation · advanced # Test case generator from a spec Read a feature spec and produce test cases (happy path, edge cases, failure modes). Pre-implementation: turn a spec into a structured test plan engineers can either implement directly or paste into a test framework. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml Read the feature spec in . Produce a test plan inside tags as JSON. For each test case: { "id": "TC-001", "category": "happy_path | edge_case | failure | security | performance", "preconditions": ["string"], "steps": ["string"], "expected": "string", "rationale": "string — why this case matters" } Coverage rules: - At least 2 happy_path cases. - At least 4 edge_cases (boundary, empty, max-size, concurrency, unicode). - At least 2 failure cases (invalid input, downstream error). - 1 security case if user input is involved. - 1 performance case if SLA/throughput is mentioned. - IDs zero-padded sequentially: TC-001, TC-002, ... {{ feature_spec }} Return inside tags. ``` ## Sample input ```xml Spec: a new POST /api/comments endpoint that creates a comment on a post. Auth required. Comment max 500 chars. Returns 201 with comment ID. ``` ## Expected output ```xml [ {"id": "TC-001", "category": "happy_path", "preconditions": ["valid auth token", "existing post_id"], "steps": ["POST /api/comments with {post_id, body: 'hi'}"], "expected": "201 with comment id in response", "rationale": "minimal create-flow validation"}, // 9 more cases covering 500-char boundary, empty body, missing auth, // non-existent post_id, XSS payload, unicode emoji, etc. ] ``` ## Notes & tuning tips - Coverage rules with numeric floors force the model to think about each category, not just the happy path. - Pair with a static linter on the spec — if the spec is vague, the test plan inherits that vagueness. - Generated tests are a starting point. Always have a human review for missed risks. ## What this example uses Tags: Patterns: structured output ## More like this generation ### Document summarizer with a librarian persona Tight, factual summary: TL;DR, 3 key bullets, 1 open question — no fluff. generation ### Email tone rewriter Rewrite a draft in a target tone (warm, neutral, firm) without changing meaning. generation ### Headline A/B variant generator Produce N distinct headline variants for a piece of content, each with a different angle. Cite this page `Test case generator from a spec. claudexml.com. https://claudexml.com/examples/test-case-generator/` --- ## Transcript cleaner with speaker labels and summary — Claude XML example URL: https://claudexml.com/examples/transcript-cleaner/ Home / Examples / Transcript cleaner with speaker labels and summary Transformation · intermediate # Transcript cleaner with speaker labels and summary Multi-stage pipeline: clean fillers, label speakers consistently, produce a 5-bullet summary. Raw meeting transcripts (Zoom, Otter) are noisy. You want three sequential views in one call: cleaned, speaker-labeled, summarized. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml Process the raw transcript in in three stages. Output each stage in its own tag. 1. : remove filler words (um, uh, like, you know, sort of), false starts, and timestamps. Preserve meaning. Preserve all decisions and action items. 2. : label speakers as Speaker 1, Speaker 2, ... consistently across the whole transcript. Use the cleaned version from stage 1. 3. : a 5-bullet summary of decisions and action items, with the owner if stated. Do all three stages in one response. {{ raw_transcript }} ``` ## Sample input ```xml 00:00:01 [voice A]: so um yeah we should like ship the auth fix today 00:00:06 [voice B]: uh yeah i'll do that 00:00:10 [voice A]: cool, also let's like push the design review to thursday 00:00:14 [voice B]: works for me ``` ## Expected output ```xml We should ship the auth fix today. Yeah, I'll do that. Also, let's push the design review to Thursday. Works for me. Speaker 1: We should ship the auth fix today. Speaker 2: Yeah, I'll do that. Speaker 1: Also, let's push the design review to Thursday. Speaker 2: Works for me. - Decision: ship auth fix today - Action: Speaker 2 will ship the auth fix today - Decision: design review moved to Thursday - (no other decisions) - (no other action items) ``` ## Notes & tuning tips - Three-stage output in one call is cheaper than three sequential calls — the model can reference its own earlier output. - If "voice A / voice B" labels are reliable in your source, ask for those to be preserved rather than re-labeling. - For long transcripts, chunk by speaker turn or by 5-minute windows; quality degrades on very long single prompts. ## What this example uses Tags: ## More like this Cite this page `Transcript cleaner with speaker labels and summary. claudexml.com. https://claudexml.com/examples/transcript-cleaner/` --- ## Map-reduce summarization over many chunks — Claude XML example URL: https://claudexml.com/examples/map-reduce-summarize/ Home / Examples / Map-reduce summarization over many chunks Complex · advanced # Map-reduce summarization over many chunks Summarize each chunk independently, then synthesize a single coherent summary — two prompts, structured handoff. Documents that exceed your context budget — or where single-pass summaries lose detail. Map each chunk to a small summary, then reduce the summaries into one. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml You are summarizing one chunk of a larger document. Produce JSON inside tags: { "key_claims": ["string"], // up to 5; one fact per item, verbatim where possible "entities": ["string"], // people, orgs, products mentioned "open_questions": ["string"], // things this chunk raises but does not answer "chunk_id": "{{ chunk_id }}" } Do not generalize beyond this chunk. Do not reference "the document" — you only see one chunk. {{ chunk_text }} Return inside tags. You will receive N per-chunk summaries inside tags. Synthesize a final summary. Output three sections, each in its own tag: One paragraph, ≤120 words. Bulleted, deduplicated across chunks. Cite chunk_id in [c:ID] format. Bulleted list of open questions that no chunk answered. Rules: - Deduplicate claims that appear in multiple chunks. - Surface contradictions explicitly: "[c:3] states X but [c:7] states Y." - Do not invent facts not present in any chunk_summary. {{ chunk_summaries_concatenated }} ``` ## Sample input ```xml Pass 1: a 6kb chunk of a research report. Pass 2: 12 chunk_summary blobs from pass 1. ``` ## Expected output ```xml The report finds that small fine-tuned retrievers (110M params) match 7B baselines on domain queries at one-tenth the cost, with most gains coming from query-log diversity rather than model size... - Fine-tuned 110M retriever beats 7B baseline by 4 nDCG@10 points on the in-domain test set [c:3, c:8] - 8× latency reduction with no measurable recall loss [c:4] - Generalization to long-tail queries is unverified [c:9, c:11] - How does the approach hold up on multilingual queries? - What is the cost of building the 50k query training set in domains without query logs? ``` ## Notes & tuning tips - Two prompts, not one. Parallelize pass 1 across chunks; pass 2 runs once on the concatenated outputs. - Per-chunk JSON output is what makes deduplication tractable in pass 2 — free prose doesn't deduplicate cleanly. - If you can't run two passes, single-pass summarization with all chunks inline is acceptable up to ~50k tokens; beyond that, accuracy degrades sharply. - Chunk IDs are load-bearing — they're how the final summary cites back to source positions. ## What this example uses Tags: Patterns: multi document structured output ## More like this complex ### Generate → self-critique → revise in one call Three-stage prompt where Claude drafts, scores its own draft against a rubric, then revises. complex ### Plan-then-act with explicit sub-task scaffolding Two-turn pattern: first turn produces a numbered plan; second turn executes each sub-task and returns structured results. complex ### Tree-of-thought reasoning with branch scoring Explore three reasoning paths, score each against criteria, pick the winner — all in one prompt. complex ### Extract → validate → transform pipeline in one call Four-stage data pipeline: extract raw fields, validate against rules, transform to target shape, emit errors. Cite this page `Map-reduce summarization over many chunks. claudexml.com. https://claudexml.com/examples/map-reduce-summarize/` --- ## Generate → self-critique → revise in one call — Claude XML example URL: https://claudexml.com/examples/self-critique-revise/ Home / Examples / Generate → self-critique → revise in one call Complex · advanced # Generate → self-critique → revise in one call Three-stage prompt where Claude drafts, scores its own draft against a rubric, then revises. When first-pass output is decent but not great, a self-critique loop tightens quality without a second model call. Useful for writing, code, and structured arguments. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml You will produce a piece of work in three stages. Output each stage in its own tag. 1. — produce a first attempt at the task described in . 2. — score your draft against the rubric in . For each criterion give: - score: 1–5 - one sentence saying why - one specific fix you would make 3. — produce a revised version that addresses every fix from . Output , then , then — in that order, in one response. Do not skip or ; the revision quality depends on it. - clarity: easy for a non-expert to follow - specificity: concrete examples / numbers, not generalities - length: tight; no filler - accuracy: every claim defensible from the brief - tone: matches the audience in {{ task_description }} ``` ## Sample input ```xml Task: Write a 150-word internal memo announcing the deprecation of our legacy webhook v1 by July 1. Audience: engineering team. Tone: firm but not alarmist. ``` ## Expected output ```xml Heads up team — we're sunsetting webhook v1 on July 1. Please migrate to v2... [140 words of generic prose] - clarity: 4/5 — clear but assumes reader knows what v2 is; add a one-line reminder. - specificity: 2/5 — no migration link, no example payload diff. Fix: add link to /docs/webhooks-v2 and one-line payload diff. - length: 4/5 — slightly long. Fix: trim the rationale paragraph. - accuracy: 5/5 — all claims defensible. - tone: 3/5 — "please migrate" is soft for a hard deadline. Fix: "must migrate by July 1". Heads up team — webhook v1 is being sunset on July 1. All consumers must migrate to v2 before that date or webhooks will stop firing. What's different in v2 (full reference: /docs/webhooks-v2): - Payloads now nest event metadata under `meta`. - Signature header renamed from `X-Signature` to `X-Hub-Signature-256`. - Retries follow exponential backoff (was fixed 30s). Migration takes most consumers under an hour. The compatibility checker at /tools/webhook-check will flag remaining v1 callers in your code. After July 1, v1 endpoints return 410 Gone. Please don't wait for the last week — the deprecation shim is best-effort. ``` ## Notes & tuning tips - The rubric is what makes the critique non-vacuous. Without it, the critique stage produces "looks good" tautologies. - Make the order explicit in instructions ("draft, then critique, then final") — Claude sometimes skips the critique otherwise. - For higher-stakes work, run two iterations: critique the , revise again. Marginal gains drop after iteration 2. - Costs ~2.5× a single-pass prompt in tokens, but typically beats a fresh call from scratch on quality. ## What this example uses Tags: ## More like this complex ### Map-reduce summarization over many chunks Summarize each chunk independently, then synthesize a single coherent summary — two prompts, structured handoff. complex ### Plan-then-act with explicit sub-task scaffolding Two-turn pattern: first turn produces a numbered plan; second turn executes each sub-task and returns structured results. complex ### Tree-of-thought reasoning with branch scoring Explore three reasoning paths, score each against criteria, pick the winner — all in one prompt. complex ### Extract → validate → transform pipeline in one call Four-stage data pipeline: extract raw fields, validate against rules, transform to target shape, emit errors. Cite this page `Generate → self-critique → revise in one call. claudexml.com. https://claudexml.com/examples/self-critique-revise/` --- ## Plan-then-act with explicit sub-task scaffolding — Claude XML example URL: https://claudexml.com/examples/plan-then-act/ Home / Examples / Plan-then-act with explicit sub-task scaffolding Complex · advanced # Plan-then-act with explicit sub-task scaffolding Two-turn pattern: first turn produces a numbered plan; second turn executes each sub-task and returns structured results. Tasks that decompose into several independent sub-tasks (research, writing, analysis pipelines). Separating plan from execution makes the work auditable and parallelizable. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml You will receive a complex task. Decompose it into 3–7 sub-tasks. Return JSON inside tags: { "summary": "one-sentence restatement of the goal", "subtasks": [ { "id": "S1", "title": "string", "depends_on": [], "deliverable": "string" } ] } Rules: - Each subtask must have a single, concrete deliverable (an artifact, a list, a number). - depends_on references other subtask IDs that must complete first; empty list means parallelizable. - Do not execute any subtask in this turn. Plan only. {{ task_description }} Return inside tags. The plan from turn 1 is in . Execute every subtask whose dependencies are satisfied by what's already in . For each, append a new tag: ... your output for this subtask ... After processing all currently-executable subtasks, output done if every subtask in the plan now has a , or continue if more turns are needed. {{ plan_from_turn_1 }} {{ results_from_prior_turns }} ``` ## Sample input ```xml Task: Produce a Q3 board update for our SaaS startup covering financials, product, hiring, and risks. ``` ## Expected output ```xml { "summary": "Produce a Q3 board update with financials, product, hiring, and risks sections.", "subtasks": [ {"id": "S1", "title": "Financials section", "depends_on": [], "deliverable": "MRR, ARR, burn, runway with QoQ deltas"}, {"id": "S2", "title": "Product highlights", "depends_on": [], "deliverable": "3 shipped features with adoption metrics"}, {"id": "S3", "title": "Hiring update", "depends_on": [], "deliverable": "headcount delta + open roles"}, {"id": "S4", "title": "Risks & asks", "depends_on": ["S1","S2","S3"], "deliverable": "3 risks + 1 specific board ask"}, {"id": "S5", "title": "Executive summary", "depends_on": ["S1","S2","S3","S4"], "deliverable": "150-word TL;DR"} ] } [Turn 2 then executes S1, S2, S3 in parallel; turn 3 executes S4; turn 4 executes S5.] ``` ## Notes & tuning tips - The dependency graph lets you parallelize: any subtask whose `depends_on` is empty (or all-completed) can run concurrently. - Force structured plans — free-prose plans don't drive execution reliably. - Hard-cap turns (max 4–5) and treat continue with no progress as a stop signal. - For agent-style execution where each subtask may need tools, combine with the API's tool use feature. ## What this example uses Tags: Patterns: agentic tool use structured output ## More like this complex ### Map-reduce summarization over many chunks Summarize each chunk independently, then synthesize a single coherent summary — two prompts, structured handoff. complex ### Generate → self-critique → revise in one call Three-stage prompt where Claude drafts, scores its own draft against a rubric, then revises. complex ### Tree-of-thought reasoning with branch scoring Explore three reasoning paths, score each against criteria, pick the winner — all in one prompt. complex ### Extract → validate → transform pipeline in one call Four-stage data pipeline: extract raw fields, validate against rules, transform to target shape, emit errors. Cite this page `Plan-then-act with explicit sub-task scaffolding. claudexml.com. https://claudexml.com/examples/plan-then-act/` --- ## Tree-of-thought reasoning with branch scoring — Claude XML example URL: https://claudexml.com/examples/tree-of-thought/ Home / Examples / Tree-of-thought reasoning with branch scoring Complex · advanced # Tree-of-thought reasoning with branch scoring Explore three reasoning paths, score each against criteria, pick the winner — all in one prompt. Problems with multiple plausible approaches (debugging, design choices, ambiguous puzzles) where the first path the model commits to isn't always the best. Explicit branching forces exploration before commitment. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml For the problem in , explore three distinct approaches before committing. Output the following tags in order: your step-by-step thinking for this approach what this approach would yield ... ... For each approach, score on: - correctness (1–5): does it actually solve the problem? - simplicity (1–5): how easy is it to verify / explain? - robustness (1–5): does it hold up on edge cases? Show scores as a table. State which approach wins and why, in one paragraph. Produce the chosen approach's final answer, polished. Rules: - Approaches must be genuinely distinct, not minor variations of one idea. - Score each approach independently; don't anchor on approach 1. - If two approaches tie, prefer simplicity over cleverness. {{ problem_text }} ``` ## Sample input ```xml Problem: Our service returns 500 errors intermittently under load. We have logs, metrics, and traces. What's the most efficient debugging approach? ``` ## Expected output ```xml Start with logs. Grep for 500-correlated stack traces; group by exception type... Identifies the failing code path but doesn't tell us why it fails only under load. Start with metrics. Plot 500 rate vs. concurrency, GC pause, connection pool size... Surfaces the systemic trigger (likely connection exhaustion) but not the failing call path. Start with traces. Find a sampled trace of a failing request; walk every span... Ties the failing call path to the systemic trigger in one artifact. | Approach | Correctness | Simplicity | Robustness | |------------|-------------|------------|------------| | Logs | 3 | 5 | 3 | | Metrics | 3 | 4 | 4 | | Traces | 5 | 3 | 5 | Approach 3 wins: it gives both the where (call path) and the why (systemic conditions) in one artifact, which the other two only give in isolation. Slightly harder to set up if tracing isn't already on, but available here. [full debugging playbook using traces as the primary tool] ``` ## Notes & tuning tips - The forced "three distinct approaches" constraint is what stops the model from collapsing into one path with three rewordings. - Score table makes the choice auditable — useful when a human reviewer wants to overrule the model. - Costs ~3× a direct-answer prompt in tokens. Reserve for genuinely ambiguous problems. - Pair with chain-of-thought () inside each approach for harder problems. ## What this example uses Tags: Patterns: chain of thought ## More like this complex ### Map-reduce summarization over many chunks Summarize each chunk independently, then synthesize a single coherent summary — two prompts, structured handoff. complex ### Generate → self-critique → revise in one call Three-stage prompt where Claude drafts, scores its own draft against a rubric, then revises. complex ### Plan-then-act with explicit sub-task scaffolding Two-turn pattern: first turn produces a numbered plan; second turn executes each sub-task and returns structured results. complex ### Extract → validate → transform pipeline in one call Four-stage data pipeline: extract raw fields, validate against rules, transform to target shape, emit errors. Cite this page `Tree-of-thought reasoning with branch scoring. claudexml.com. https://claudexml.com/examples/tree-of-thought/` --- ## Extract → validate → transform pipeline in one call — Claude XML example URL: https://claudexml.com/examples/extract-validate-transform/ Home / Examples / Extract → validate → transform pipeline in one call Complex · advanced # Extract → validate → transform pipeline in one call Four-stage data pipeline: extract raw fields, validate against rules, transform to target shape, emit errors. Production ETL where you can't afford a downstream parse failure: extract, validate at the point of extraction, transform, and surface validation errors as structured data rather than as malformed output. ## The prompt Copy this verbatim. Replace the `{{ … }}` placeholders with your values. ```xml Process the input through four stages. Output each in its own tag. 1. Raw fields pulled verbatim from . Use null when a field is absent. Shape: { "": "verbatim value or null" } 2. Apply the rules in . For each rule, output: { "rule": "rule_id", "passed": true|false, "field": "field_name", "note": "string or null" } 3. Only if all required-tier rules passed: emit the canonical shape in . Otherwise: emit null. 4. List every failed validation, with rule_id and a human-readable message. Empty array if validation fully passed. Output the four tags in order. Do not skip any. Do not include prose outside the tags. {{ validation_rules }} {{ target_schema }} {{ input_data }} ``` ## Sample input ```xml rules: R1 (required) email present and valid format; R2 (required) age is integer 13–120; R3 (warn) phone E.164 format target_schema: { user_id (uuid), email (lowercased), age (int), phone (E.164 or null) } input: 'Sarah, sarah@EXAMPLE.com, age 29, phone 415-555-0142' ``` ## Expected output ```xml { "name": "Sarah", "email": "sarah@EXAMPLE.com", "age": "29", "phone": "415-555-0142" } [ { "rule": "R1", "passed": true, "field": "email", "note": null }, { "rule": "R2", "passed": true, "field": "age", "note": "converted from string" }, { "rule": "R3", "passed": false, "field": "phone", "note": "not E.164; missing +1 prefix" } ] { "user_id": "(server-generated)", "email": "sarah@example.com", "age": 29, "phone": null } [ { "rule": "R3", "field": "phone", "message": "Phone '415-555-0142' is not E.164. Stored as null." } ] ``` ## Notes & tuning tips - Putting validation between extract and transform lets the model self-gate: if required rules fail, is null and your downstream code never sees garbage. - Rules and target schema as / tags makes the prompt reusable across record types — only swap the parameters. - Don't ask the model to be the source of truth for IDs (uuid, timestamps); generate those server-side after a successful transform. - For very high-volume pipelines, this is ~3× the cost of bare extraction. Worth it when the alternative is silent data corruption. ## What this example uses Tags: Patterns: structured output ## More like this complex ### Map-reduce summarization over many chunks Summarize each chunk independently, then synthesize a single coherent summary — two prompts, structured handoff. complex ### Generate → self-critique → revise in one call Three-stage prompt where Claude drafts, scores its own draft against a rubric, then revises. complex ### Plan-then-act with explicit sub-task scaffolding Two-turn pattern: first turn produces a numbered plan; second turn executes each sub-task and returns structured results. complex ### Tree-of-thought reasoning with branch scoring Explore three reasoning paths, score each against criteria, pick the winner — all in one prompt. Cite this page `Extract → validate → transform pipeline in one call. claudexml.com. https://claudexml.com/examples/extract-validate-transform/` --- ## Claude XML Anti-Patterns: What Not to Do When Prompting Claude URL: https://claudexml.com/anti-patterns/ Home / Anti-patterns # Claude XML anti-patterns: what not to do Mistakes that look fine but quietly degrade reliability. Each entry: the trap, why it bites, and the fix. ## 1. Over-tagging trivial prompts The trap: Wrapping a one-line question in ``, ``, `` when none of them carry weight. Adds tokens, no quality gain. The fix: Tag when the structure is load-bearing. A simple zero-shot question doesn't need scaffolding. ## 2. Putting the user question inside `` The trap: Claude will follow the question as a directive rather than answer it. The fix: Keep `` for what the model should do; put the question in its own tag or unwrapped after the structured blocks. ## 3. Mismatched tags The trap: Opening `` and closing with `` or forgetting the close. The fix: XML is case-sensitive; Claude usually recovers but reliability drops. Lint your prompts. ## 4. Putting documents after the question on long contexts The trap: Anthropic's guidance is the opposite: long reference material first, then instructions, then question. The fix: Order: `` → `` → ``. Helps attention land on the instruction block. ## 5. Asking for JSON without saying "only JSON" The trap: Claude often wraps JSON in ````json` markdown fences by default. The fix: Add "Return only the JSON object, no prose, no markdown fences" — or wrap the output in `` and parse from there. ## 6. Reading `` output as ground truth The trap: Chain-of-thought scratchpads are reasoning aids, not verified logs. They can rationalize wrong answers. The fix: Use CoT to improve accuracy; don't show the scratchpad to end users as if it were proof. ## 7. Stuffing the system prompt and an inline `` with different personas The trap: The two will fight; Claude becomes inconsistent. The fix: One source of persona truth. Prefer the API `system` parameter. ## 8. Few-shot examples that don't span the real distribution The trap: If all your examples are happy-path, edge cases collapse to the happy-path label. The fix: Include hard cases, edge cases, and at least one example of each output class. ## 9. Forgetting `` in RAG prompts The trap: Then asking for citations. Claude invents source names. The fix: Always pair `` with `` when you want attribution. ## 10. Treating XML tags as a security boundary The trap: Users can inject `` into their input and break out of your scaffolding. The fix: Sanitize user input — escape angle brackets or strip XML-like sequences before splicing into the prompt. ## 11. Nesting tags that don't logically nest The trap: Putting `` inside ``, or `` inside ``. The fix: Keep major sections as siblings. Nest only when the semantics are containment (`` inside ``, `` inside ``). ## When to skip XML entirely XML is load-bearing when there's structural ambiguity in a single prompt the model has to resolve. No ambiguity → no scaffolding needed. Skip XML when: - Conversational chat. Multi-turn dialogue already establishes who is talking. Wrapping a question in `` doesn't help — the model knows. - Single-shot creative writing. "Write a haiku about Tuesday." No structure to scaffold. - One-line lookups. "What's the capital of France?" The tax is small but real. And skip specific tags when the API now does the job better: - Structured output: prefer the API's tool-use / JSON-mode over `` + "return only JSON". XML coercion is the second-best option in 2026. - Persona: the API `system` parameter is stronger than inline ``. - Reasoning: on Claude 3.7 and newer with extended thinking enabled, the `` tag is redundant and can fight the internal mechanism. Use one, not both. See also: when XML genuinely helps — the inverse list. Cite this page `Claude XML Anti-Patterns. claudexml.com. https://claudexml.com/anti-patterns/` --- ## When XML Genuinely Helps With Claude Prompts (and When It's Just Noise) URL: https://claudexml.com/when-xml-helps/ Home / When XML helps # When XML genuinely helps with Claude prompts XML tags are load-bearing when there's structural ambiguity in a single prompt the model has to resolve. No ambiguity, no scaffolding needed. Here are the eight cases where the tax pays for itself. The unifying principle: XML helps when one prompt mixes several roles — instructions, evidence, demonstrations, output — and Claude needs unambiguous boundaries to keep them straight. Everything else is decoration. ## 1. Repeatable work at scale Anywhere the same prompt runs against varying inputs. Structure gives you reliability you can monitor and diff across runs. ## 2. Database / structured output Extraction, classification, anything you'll parse downstream. The wrapper tag is the parse hook; `` is the schema contract. ## 3. Dividers in long prose Multiple long blobs needing clear edges: documents + question, examples + live input, system prompt + dynamic data. ## 4. The untrusted ↔ trusted boundary Wrapping user input in `` makes injection attempts more visible in logs and slightly harder to land. Not a security fix — a mitigation that pairs with input sanitization. ## 5. RAG grounding `` + `` activates a well-trained pattern: Claude treats contents as evidence to cite, not as commands. Refusal behavior is more reliable inside this scaffolding than without. ## 6. Few-shot demonstrations `` is the clearest way to signal "the next N blocks are demos, the block after is the real task." Without it, Claude sometimes treats example outputs as ongoing context. ## 7. Multi-artifact outputs in one call When you want several distinct things in one response (draft + critique + final; cleaned + speaker-labeled + summary; extracted + validated + transformed), separate output tags are the only reliable way to get them parseable. This is the strongest XML use case with no good API-feature substitute today. ## 8. Audit-friendly reasoning `` + `` stores the reasoning trace alongside the result for later debugging. Useful in regulated contexts even when extended thinking would technically suffice. ## …and the inverse XML is noise — adds tokens, no quality gain — when there's no structural ambiguity for it to resolve: - Conversational chat (the session already establishes who is talking). - Single-shot creative writing ("write a haiku about Tuesday"). - One-line lookups ("what's the capital of France?"). And on the API side, some 2026 features now do the job better than XML did: - Tool use / JSON mode > `` for structured output. - API `system` parameter > inline `` for persona. - Extended thinking (Claude 3.7+) > `` tags. Use one, not both. See the full anti-patterns list for the corresponding mistakes. Cite this page `When XML Genuinely Helps With Claude Prompts. claudexml.com. https://claudexml.com/when-xml-helps/` --- ## Claude XML FAQ — Common Questions About XML Prompting for Claude URL: https://claudexml.com/faq/ Home / FAQ # Claude XML FAQ Quick answers to the questions developers ask first. What is Claude XML?Claude XML is the convention of structuring prompts to Anthropic's Claude using XML-style tags (like ``, ``, ``) to separate the parts of a prompt. Claude was trained with these patterns and follows them reliably. Are XML tags required to prompt Claude?No. Claude works without them. Anthropic's docs recommend them "especially when your prompt mixes instructions, context, examples, and variable inputs" — i.e., they meaningfully improve consistency on non-trivial prompts, but a one-line question doesn't need scaffolding. Is XML still relevant in 2026?Yes, but with caveats. Anthropic's prompt-engineering docs (verified May 2026) still recommend XML tags for structured prompts. What's changed since the early Claude era: some uses are now better served by API features. Tool use is stronger than `` for JSON output; the API `system` parameter is stronger than inline ``; extended thinking on Claude 3.7+ replaces manual `` tags. XML is still the right tool for splitting documents/examples/instructions in a single prompt and for multi-artifact outputs. Do I need XML for a chat conversation?No. Conversational chat (claude.ai, multi-turn dialogue) already establishes roles. Wrapping your message in `` adds tokens and visual noise without helping the model. Save tags for repeatable programmatic prompts where structure is load-bearing. Is this real XML?No. There's no schema, no validation, no parser. Tags are a convention Claude treats as structure. Closing tags are still important — mismatched tags confuse the model. Which XML tags does Claude officially support?There is no official allowlist. Anthropic's docs use ``, ``, ``/``, ``/``, ``, ``, ``, `` consistently. Custom tags work fine if their names are clear. Should I use XML tags or the API's `system` parameter?Both, for different jobs. Put the persona and stable directives in the `system` parameter — that's stronger than an inline ``. Use XML inside the user message to structure dynamic content: documents, examples, the question. Should I use XML tags or tool use for structured output?Tool use is stronger in 2026. If you can define a tool, prefer it. XML coercion (`` + "return only this inside ``") is the right fallback when you can't or don't want to set up tool use — and on Bedrock/Vertex with older API surfaces. Should I use `` tags with Claude's extended thinking enabled?Pick one. Extended thinking (Claude 3.7+ via the API's thinking parameter) is the model's native reasoning channel. Adding a `` tag on top creates a second scratchpad that can fight the internal one — sometimes silently degrading output. If extended thinking is on, drop the manual tag. If it's off and you want reasoning, use the tag. Where should I put long documents — before or after the instructions?Before. Anthropic's guidance: large reference material first, then instructions, then the question. Claude attends more strongly to instructions placed closer to the query. Can Claude be tricked by XML in user input?Yes. If you splice user input into a prompt without escaping, the user can inject closing tags like `` and break your scaffolding. Sanitize: escape angle brackets or strip XML-like sequences from untrusted input. Do XML tags increase token cost?Slightly. A few tags add tens of tokens, not hundreds. The quality gain almost always justifies the cost on real tasks. Can I nest XML tags?Yes, when the semantics imply containment: `` inside ``, `` inside ``. Don't nest things that are logically peers — keep major sections as siblings. How many few-shot examples should I include?2–5 in almost all cases. One example often doesn't carry the pattern; more than five rarely helps and burns context. Why does Claude wrap my JSON in markdown fences?Default behavior on prose-style prompts. Fix: explicitly say "return only the JSON object, no prose, no markdown fences" or wrap the output in `` tags and extract from there. Does this site work with Claude on Bedrock / Vertex AI?Yes. The prompting conventions are identical regardless of where you call Claude — Anthropic API, AWS Bedrock, Google Vertex AI, or partner platforms. Only the surrounding API differs. Can I cite this site?Yes — every page includes a citation block. Stable URLs, content under the page byline (claudexml.com), last updated date is in the page metadata. Cite this page `Claude XML FAQ. claudexml.com. https://claudexml.com/faq/` --- ## Claude XML Cheatsheet — One-Screen Reference URL: https://claudexml.com/cheatsheet/ Home / Cheatsheet # Claude XML cheatsheet One-screen condensed reference. Bookmark this. ## Core tags TagPurposeSibling of ``What the model should docontext, examples, documents, question ``Background facts (not commands)instructions, documents, question ``Container for few-shot demosinstructions, question ``One demo (with ``/``)nested in examples ``Container for RAG passagesinstructions, question ``One passage (with ``)nested in documents ``Citation ID for a documentnested in document ``CoT scratchpadanswer ``Extractable final answerthinking ``Output schema / shapeinstructions, question ``Inline personastandalone ## Recommended order For prompts with long reference material: ```xml ... ... ... ... ``` For prompts without long material, instructions can come first. ## Rules of thumb - Long documents → put them first. - Want to parse the output → wrap it in a tag and tell Claude "return only inside the tag." - Want citations → always include ``. - Want reliability → 2–5 examples, not 0, not 20. - Want safety → sanitize user input before splicing into prompts. - Want structured output → use API tool use first; XML `` second. ## Extraction regex To pull content from a tag: ```xml ([\s\S]*?) ``` Use the multi-line, non-greedy form in all languages. `[\s\S]` beats `.` because it matches newlines. Cite this page `Claude XML Cheatsheet. claudexml.com. https://claudexml.com/cheatsheet/` --- ## Privacy on claudexml.com — What We Collect and What We Don't URL: https://claudexml.com/privacy/ Home / Privacy # Privacy on claudexml.com Last updated: 2026-05-25. The short version: minimal logging, no cookies, no third-party tags, no behavioral profiling, no ads, no data sold. The long version is below — written to match what the code actually does. ## What we collect Three sources of data exist when you visit this site. Each is described honestly below. ### 1. Self-hosted analytics (GoatCounter) Every page load fires a pageview ping to our own server. The ping records: - The page URL you visited. - The referrer (the page you came from), if your browser sends one. - A coarse User-Agent string (e.g. "Chrome on macOS"). The full UA is parsed and discarded. - Your screen size and approximate country (derived from IP, not stored). - A hash of (IP + User-Agent + a daily-rotating salt) — used to roughly count unique visitors per day. The original IP is never stored. The hash itself is unsalted again after 24 hours, so it cannot be linked across days. What we do not collect: your IP address (it's hashed at receipt and discarded), cookies (none are set), fingerprinting signals beyond the coarse User-Agent, mouse movements, scroll depth, or anything cross-site. Software: GoatCounter, EUPL-licensed open source, running on the same server that hosts this site. No data leaves the server. Source code: github.com/arp242/goatcounter. To opt out: block `/count.js` in uBlock Origin, Privacy Badger, or your browser's tracker blocker. The site works identically without the ping. ### 2. Time-on-page (dwell) beacon When you leave a page (close the tab, navigate away, switch apps), a small JavaScript snippet sends one extra request: `/dwell?p=&d=`. That's the only data point — the page you were on and how many seconds you stayed. No ID, no cookie, no session token. The dwell beacon never fires for visits under 1 second or longer than an hour. To opt out: block requests to `/dwell` in your browser's blocker. Most tracker blockers will catch it automatically because of the path name. ### 3. Web-server access logs (nginx) Nginx records standard access logs: IP, timestamp, request path, HTTP status, response size, User-Agent, referrer. These are used for debugging, abuse mitigation, and the speculative session-journey reconstruction described below. They are kept for 14 days on a rolling basis and then deleted. ### 4. Speculative session-journey reconstruction Once an hour, an offline script reads the nginx access log and groups requests that share `hash(IP + User-Agent + a daily-rotating salt)` within a 30-minute window into a "session." It joins each session with the dwell-beacon records to produce an aggregated report (top entry pages, top exit pages, common journey paths, dwell distribution per page). The report is admin-only and never published. This is explicitly speculative. We're guessing which requests came from the same visitor based on heuristics. Two people sharing a NAT (e.g., a corporate office or a shared Wi-Fi) on the same browser can merge into one false session. We treat the report as informed guesses, not facts. Raw IPs are hashed at parse time and never persisted; the salt rotates daily so sessions cannot be linked across days. ### 3. Cloudflare (CDN / proxy) This site is fronted by Cloudflare. Cloudflare sees every request at its edge, regardless of what we do — that's how a CDN works. Cloudflare retains traffic data for its own security and dashboard analytics under its privacy policy. We have no way to opt visitors out of this short of removing the CDN. ## What we do not do - No cookies of any kind are set by this site. - No third-party analytics (no Google Analytics, no Mixpanel, no Hotjar, no Plausible Cloud, no Cloudflare Web Analytics). - No advertising. No ad networks. No retargeting pixels. - No fingerprinting beyond the coarse User-Agent string. - No data is sold, shared, or otherwise transferred to third parties for marketing. - No accounts, no sign-up, no email collection. ## Data access / deletion requests Because we don't store anything that identifies you (no IP, no cookie, no account), we have no per-visitor record to access or delete. If you have questions, contact the maintainer via the address listed in the page source (HTML comment in ``). ## Legal basis US visitors: the site does not meet the revenue or user-count thresholds of any current US state privacy law (CCPA/CPRA, VCDPA, CPA, CTDPA, UCPA). The processing described above is normal web-server operation; no consent is required under US law. EU / UK visitors: processing of request logs and analytics pings is performed under the GDPR legitimate-interest basis (security, debugging, audience measurement at aggregated level). No cookies are set and no identifying data is stored, so prior consent under the ePrivacy Directive is not required for this baseline. If we ever turn on something that would require consent, this page will say so and a banner will appear. ## Changes to this notice If we add or remove anything that affects what's collected, this page will be updated and the "Last updated" date at the top will change. There is no notification system — check back if it matters to you. Cite this page `Privacy on claudexml.com. claudexml.com. https://claudexml.com/privacy/`