Prompt Engineering · Advanced Techniques

Advanced Prompting Techniques

XML tags, prompt chaining, meta-prompting, output constraints, and Anthropic's official pattern library. These techniques separate professional Claude users from power users — the difference between good outputs and consistently excellent outputs.

🏷️ XML Tags⛓️ Prompt Chaining🪞 Meta-Prompting📐 Output Engineering

XML Tags for Prompt Structure

Anthropic's official documentation recommends using XML-style tags to clearly separate different components of complex prompts. This dramatically improves how Claude parses and responds to long, multi-component prompts.

🔑 Why Anthropic Recommends XML Tags

Claude was trained on internet text that included HTML/XML, so it understands that content within tags is semantically distinguishable. Tags create a clear visual and semantic boundary between different types of information in a prompt — context vs. instructions vs. data vs. expected output format. This reduces Claude's risk of "confusing" which part of a long prompt is the task vs. the background.

Basic XML Tag Patterns

XML-Structured Prompt
<context>
I am a college junior majoring in Economics conducting research
on behavioral economics for my thesis. My advisor specializes
in decision theory. I have a strong statistics background.
</context>

<task>
Explain the difference between prospect theory and expected
utility theory. Focus on how each predicts behavior differently
in loss-aversion scenarios.
</task>

<requirements>
- Use one concrete numerical example for each theory
- Explain the mathematical difference in how probabilities are "weighted"
- Mention at least two empirical studies that support prospect theory
- Keep the explanation under 500 words
</requirements>

<output_format>
Use headers: "Expected Utility Theory" | "Prospect Theory" | 
"Key Differences" | "Empirical Evidence"
</output_format>

XML Tags for Document Analysis

Document Analysis Template
<document>
[Paste the document, paper, or text to be analyzed here]
</document>

<analysis_task>
Based ONLY on the document above (do not use outside knowledge):
1. What is the central argument?
2. What evidence does the author provide?
3. What assumptions underlie the argument?
4. What is NOT addressed that should be?
</analysis_task>

<grounding_instruction>
If any of your points cannot be directly supported by a
quote or specific reference to the document, say so explicitly.
</grounding_instruction>

Common XML Tag Vocabulary

TagUse ForExample
<context>Background informationYour background, the situation, project details
<task>The specific requestWhat you want Claude to do
<document>Content to analyzePapers, emails, code, articles
<requirements>Constraints and rulesLength limits, tone, format rules
<example>One-shot/few-shot examplesInput→output demonstrations
<output_format>Response structureHeaders, sections, specific format
<thinking>Invite CoT reasoning"Use these tags to think through..."
<data>Input data to processCSV data, user records, test cases

Prompt Chaining

Prompt chaining breaks complex tasks into a sequence of simpler prompts where the output of each becomes the input of the next. This is one of the most powerful techniques for production-quality work.

Prompt Chain — Research Paper Creation
CHAIN OVERVIEW:
Input (research topic) → [Step 1] → [Step 2] → [Step 3] → [Step 4] → Final Paper

Step 1 — RESEARCH OUTLINE PROMPT:
"Given my topic [X], create a detailed research outline with:
thesis, 5 main arguments, key evidence needed for each,
and 3 potential counterarguments."
→ OUTPUT: Structured outline

Step 2 — EVIDENCE GATHERING PROMPT:
[Paste Step 1 output]
"For each argument in this outline, suggest 2-3 types of
evidence I should look for and keywords for Google Scholar."
→ OUTPUT: Research directions

Step 3 — SECTION DRAFTING PROMPT:
[Paste outline + evidence directions]
"Write the first draft of Section 2 ([title]) using this outline.
Target: 600 words, academic tone, leave [SOURCE NEEDED] placeholders
where I need to add real citations."
→ OUTPUT: Draft section

Step 4 — REVISION PROMPT:
[Paste draft section]
"As a strict academic editor, critique this section and rewrite
it to address the 3 most important weaknesses you identified."
→ OUTPUT: Polished section

Prompt Chaining for Code Development

Code Development Chain
STEP 1 — DESIGN: "Design the architecture for [feature]. List: - Functions/classes needed - Data flow between them - Edge cases to handle Don't write code yet." STEP 2 — IMPLEMENTATION: [Paste Step 1 output] "Implement the architecture you just designed. Write clean, production-quality code with: - Type hints - Comprehensive docstrings - Error handling for each edge case you identified" STEP 3 — TESTING: [Paste Step 2 output] "Write a comprehensive test suite for this code. Include: happy path tests, edge cases, error cases. Explain what each test is verifying and why it matters." STEP 4 — REVIEW: [Paste all previous output] "Review the full implementation + tests as a senior engineer. Find any remaining issues, then write a refactored final version."

Meta-Prompting — Claude Improves Your Prompts

Meta-prompting is asking Claude to write, evaluate, or improve prompts — for itself or for other tasks. This is a fast way to generate better prompts when you're not sure how to phrase something.

Prompt Improvement

👤 Meta-Prompt — Improve My Prompt
Here is a prompt I wrote for Claude. Evaluate it and rewrite an improved version that would get better results: My prompt: "Make my essay better." Analysis needed: 1. What's missing from this prompt? (be specific) 2. What assumptions is it forcing Claude to make? 3. Write an improved version that specifies context, requirements, and output format 4. Explain each improvement you made

Prompt Generation

👤 Meta-Prompt — Generate a Prompt for Me
I want to use Claude regularly to help me prepare for job interviews in data science. Write me a comprehensive system prompt that I can paste into a Project Instructions field that would turn Claude into the ideal DS interview prep coach. Include: - The role/persona Claude should take - The types of questions it should ask me - How it should give feedback (structure, harshness level) - What it should and shouldn't do - Example interaction flows

Output Engineering

Output engineering means precisely specifying the structure, format, and content of Claude's response to eliminate editing and post-processing work.

JSON Output Engineering

For developer use cases, you can instruct Claude to produce structured JSON output that feeds directly into code:

JSON Output Prompting
Analyze this student feedback and return ONLY a JSON object (no explanatory text, no markdown) in exactly this format: { "overall_sentiment": "positive|negative|mixed", "sentiment_score": [number 1-10], "key_themes": ["theme1", "theme2"], "specific_praise": ["praise point 1"], "specific_criticisms": ["criticism 1"], "action_items": ["suggested improvement 1"], "priority_level": "high|medium|low" } Feedback to analyze: "[paste feedback here]"

Structured Report Engineering

Report Structure Template
Produce a report using EXACTLY this structure: # [Title] ## Executive Summary (2-3 sentences max) [Key finding + main recommendation] ## Analysis ### [Subtopic 1] - Finding: [one sentence] - Evidence: [brief] - Implication: [brief] ### [Subtopic 2] [same structure] ## Recommendations 1. [Actionable recommendation — start with a verb] 2. [...] ## Open Questions - [What remains unknown] Do not add any sections. Do not omit any sections.

Response Prefilling (API Only)

In the Claude API, you can "prefill" the beginning of Claude's response — starting it with specific text that forces the output to begin a certain way. This is powerful for controlling format.

Python — Response Prefilling
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Analyze this business case: [case]"},
        # Prefill Claude's response to force a specific opening
        {"role": "assistant", "content": "```json\n{"}  
    ]
)
# Claude will continue from the prefill, producing pure JSON output
# This eliminates the "here is the JSON:" preamble Claude often adds

Grounding & Source Control

Grounding techniques constrain Claude to only use information you've provided — preventing hallucination for high-stakes tasks:

Grounding Instructions
# Prevent hallucination for factual questions: "Answer the question below based ONLY on the provided document. If the document does not contain enough information to answer the question fully, say 'The document does not address this' rather than drawing on outside knowledge." # For citation-heavy work: "Only make claims that you can directly support with a quote from the document provided. For each claim, include the supporting quote in brackets: [claim] (Source: 'exact quote')" # For code review: "Review only the code provided. Do not suggest architectural changes beyond the scope of the existing codebase you've seen."

Hard Constraints Prompting

Sometimes you need Claude to absolutely, definitely follow a rule. Use clear constraint language:

🚫

Absolute Prohibitions

"Under no circumstances provide [X]. This is a hard requirement that overrides everything else."

Mandatory Inclusions

"Every response MUST include [X]. If you cannot include it, explain why rather than omitting it silently."

📏

Hard Length Limits

"Your entire response must be under 100 words. If you cannot answer in 100 words, give the most important 100 words and note what was cut."

🔒

Scope Restrictions

"Limit your analysis strictly to [domain]. If asked about unrelated topics, redirect: 'That's outside my focus for this conversation.'"

Multi-Pass Review Pattern

For high-stakes work (thesis chapters, important code, major decisions), use a structured multi-pass approach where each pass focuses on a different dimension:

Multi-Pass Review Template
Review the [document/code] below in THREE separate passes. Label each pass clearly and complete it before starting the next. PASS 1 — LOGIC AND ACCURACY: - Are all claims factually correct? - Is the reasoning logically valid? - Are there any internal contradictions? PASS 2 — STRUCTURE AND COMPLETENESS: - Does the structure serve the argument/purpose? - What important elements are missing? - Are any sections disproportionate in length? PASS 3 — CLARITY AND EXPRESSION: - Flag anything confusing or unclear - Identify the 3 weakest sentences - Note any jargon that needs defining for the target audience After all three passes, provide: TOP 3 PRIORITIES for revision. [Document to review here]

Anthropic Prompt Library Patterns

Anthropic maintains an official Prompt Library with tested, production-quality prompts. Key patterns from their library that students should know:

📊

Data Extraction

Reliable JSON extraction from unstructured text — useful for processing survey responses, classifying emails, extracting entities from documents.

💡

Brainstorming

Divergent thinking prompts that prevent Claude from anchoring on the first idea — generates genuinely diverse options rather than variations of one idea.

🔍

Hallucination Reduction

Patterns that explicitly ask Claude to separate high-confidence claims from uncertain ones — critical for any factual output.

🛡️

Safe Task Decomposition

Breaking complex risky tasks into verifiable steps — each step is simpler, safer, and can be checked before proceeding.

📚 Official Resources to Bookmark
🏆 The Advanced User's Philosophy

Advanced prompting isn't about knowing the most techniques — it's about having a reliable debugging process when outputs aren't right. The expert mental model:

  1. Got a bad output? → Ask why Claude produced it before re-prompting
  2. Is context missing? → Add XML-tagged context
  3. Wrong format? → Engineer the output structure explicitly
  4. Reasoning error? → Add CoT or break into a chain
  5. Hallucination? → Add grounding constraints or source-only restriction
  6. Inconsistency? → Use few-shot examples or hard constraints