
Claude Prompting
- 25 installs
- 10 repo stars
- Updated July 24, 2026
- duyet/claude-plugins
Prompt-engineering guidance for Anthropic's Claude models - structuring prompts, system instructions and patterns to get reliable output from Claude.
About
A prompt-engineering skill focused on Anthropic's Claude models - how to structure prompts, system instructions and patterns that get reliable, well-formatted output from Claude. It is one of a set of per-model prompting guides in this plugin collection. A solo builder reaches for it when integrating Claude into an app or agent and wants model-specific prompting technique rather than generic advice.
- Claude-specific prompt structuring
- System-prompt and instruction patterns
- Reliable-output techniques for Anthropic models
Claude Prompting by the numbers
- 25 all-time installs (skills.sh)
- Ranked #9,764 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/duyet/claude-plugins --skill claude-promptingAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 25 |
|---|---|
| repo stars | ★ 10 |
| Last updated | July 24, 2026 |
| Repository | duyet/claude-plugins ↗ |
What it does
Prompt-engineering guidance for Anthropic's Claude models - structuring prompts, system instructions and patterns to get reliable output from Claude.
Who is it for?
Getting reliable output from Claude
Skip if: Non-Anthropic models
Files
Claude Prompt Engineering
Claude is Anthropic's AI assistant designed to be helpful, harmless, and honest. It excels at long-context tasks, follows complex instructions precisely, and works best with well-structured prompts using XML-style tags.
When to Invoke This Skill
Use this skill when:
- Crafting prompts specifically for Claude/Anthropic models (default: Claude Sonnet 4.5)
- Working with long documents or large context (up to 1M tokens with Sonnet 4.5 beta)
- Using structured prompts with XML-style tags
- Implementing extended thinking for complex reasoning
- Requiring precise instruction following
- Building agentic workflows with parallel tool use
Claude's Identity & Characteristics
| Attribute | Description |
|---|---|
| Personality | Helpful, harmless, honest |
| Constitutional AI | Built-in safety and ethical guidelines |
| Context Window | Up to 1M tokens (Sonnet 4.5 beta), 200K standard |
| Strengths | Long-context analysis, instruction following, document understanding, agentic tasks |
| Prompt Style | Structured, clear, XML-style formatting |
| Extended Thinking | Optional reasoning trace feature with tool use |
Universal Prompting Techniques (Claude-Adapted)
1. Zero-Shot Prompting
Claude responds well to clear, direct zero-shot prompts.
Good Example:
Extract the key dates and events from the following text:
<text>
[paste text]
</text>
Output format: JSON with keys "date", "event", "description"Less Effective:
Can you tell me what dates are in this text?2. Few-Shot Prompting (Multishot)
Use well-formatted examples with XML structure.
<examples>
<example>
<input>
The conference is scheduled for March 15, 2025 in San Francisco.
</input>
<output>
{
"date": "2025-03-15",
"event": "conference",
"location": "San Francisco"
}
</output>
</example>
<example>
<input>
Our next board meeting is on June 22nd.
</input>
<output>
{
"date": "2025-06-22",
"event": "board meeting"
}
</output>
</examples>
<input>
The product launches on September 1st in New York.
</input>
<output>3. Chain-of-Thought Prompting
Claude has an Extended Thinking feature that shows reasoning (enabled via API, output in response):
I need to decide between these two job offers. Let me think through this step by step.
<job_offer_a>
[details]
</job_offer_a>
<job_offer_b>
[details]
</job_offer_b>
Please analyze both offers, show your reasoning, and provide a recommendation.API enables extended thinking; response includes:
<thinking>
First, let me analyze the compensation...
Then consider the growth potential...
The work-life balance factors are...
The company stability differs by...
</thinking>
<answer>
[conclusion]
</answer>4. Zero-Shot CoT
Simply add "Let's think step by step" or similar:
What's the most efficient route to visit all these cities?
Let's think step by step.5. Prompt Chaining with XML Tags
Break complex tasks using XML delimiters:
Chain Step 1:
<task>
Extract relevant quotes from this document related to [topic].
</task>
<document>
[paste document]
</document>
<output_format>
<quotes>
<quote>[relevant quote 1]</quote>
<quote>[relevant quote 2]</quote>
</quotes>
</output_format>Chain Step 2:
<task>
Summarize the extracted quotes and synthesize key insights.
</task>
<quotes>
[from previous response]
</quotes>
<output_format>
<summary>
[executive summary]
</summary>
<key_insights>
<insight>[insight 1]</insight>
<insight>[insight 2]</insight>
</key_insights>
</output_format>6. ReAct Prompting
Use structured thought-action-observation cycles:
<question>
[research question]
</question>
<thought_1>
[what needs to be done first]
</thought_1>
<action_1>
[tool use or information gathering]
</action_1>
<observation_1>
[result from action]
</observation_1>
<thought_2>
[next step based on observation]
</thought_2>
<final_answer>
[conclusion]
</final_answer>7. Tree of Thoughts
Use multiple reasoning paths with XML structure:
<problem>
[complex problem]
</problem>
<thought_paths>
<path_1>
<assumption>[approach 1]</assumption>
<reasoning>[step-by-step]</reasoning>
<conclusion>[result]</conclusion>
</path_1>
<path_2>
<assumption>[approach 2]</assumption>
<reasoning>[step-by-step]</reasoning>
<conclusion>[result]</conclusion>
</path_2>
<path_3>
<assumption>[approach 3]</assumption>
<reasoning>[step-by-step]</reasoning>
<conclusion>[result]</conclusion>
</path_3>
</thought_paths>
<synthesis>
[best path and why]
</synthesis>Claude-Specific Best Practices
1. Use XML-Style Tags for Structure
Claude's official courses extensively use XML tags:
<context>
[background information]
</context>
<task>
[what needs to be done]
</task>
<examples>
[example inputs and outputs]
</examples>
<input>
[the actual input to process]
</input>
<output_format>
[expected format]
</output_format>2. Structure Long Prompts Hierarchically
From Anthropic's official courses:
[TASK_CONTEXT]
Setting the stage and overall context
[TONE_CONTEXT]
How Claude should approach the task
[INPUT_DATA]
The actual data to work with
[EXAMPLES]
Few-shot examples
[TASK_DESCRIPTION]
Specific task details
[IMMEDIATE_TASK]
The immediate action to take
[OUTPUT_FORMATTING]
Expected output structure3. Leverage Extended Thinking
For complex reasoning, enable Claude's extended thinking via the API:
API Syntax (Python SDK):
response = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
thinking={
"type": "enabled",
"budget_tokens": 8192
},
messages=[{
"role": "user",
"content": "Analyze this complex problem..."
}]
)Prompt-Side (XML structure for expected output):
<task>
[complex reasoning task]
</task>
<thinking>
[Claude will show its reasoning here]
</thinking>
<answer>
[final answer]
</answer>Key Points:
budget_tokenssets max tokens for reasoning (must be <max_tokens)- Claude 4.5 returns summarized thinking by default
- First few lines are more verbose (useful for prompt engineering)
- You're billed for full thinking tokens, not summary tokens
4. Use System Prompts Effectively
System prompts set Claude's behavior:
System: You are a technical writer specializing in API documentation. Your responses are always:
- Clear and concise
- Technically accurate
- Formatted with Markdown
- Focused on developer needs
User: [your actual query]5. Prefill Claude's Response
Guide the format by starting Claude's response:
<task>
Analyze this document and extract key findings.
</task>
<document>
[paste document]
</document>
<response>
<summary>
[Claude continues from here]6. Cache Control for Long Prompts
Optimize for repeated prompts:
<cached_content cache_control="{\"type\":\"ephemeral\"}">
[large context that doesn't change]
</cached_content>
<task>
[specific task that varies]
</task>7. Claude 4.5 Agent Features
Claude 4.5 introduces powerful agent capabilities:
Parallel Tool Use - Claude can use multiple tools simultaneously:
<task>
Analyze this data and create a visualization.
</task>
<tools>
- Web search for market data
- Code execution for analysis
- File write for chart output
</tools>
Claude will execute these in parallel when possible.Memory Files - Claude can maintain knowledge across sessions:
<task>
When working on ongoing projects, create a memory file to track:
- Key decisions and rationale
- Project context and constraints
- Preferences and patterns
</task>
Claude will automatically update and reference memory files when given local file access.Extended Thinking with Tools - Reasoning can pause to use tools:
# API: Enable extended thinking with tool use
response = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
thinking={
"type": "enabled",
"budget_tokens": 8192
},
tools=[web_search_tool],
messages=[{
"role": "user",
"content": "Research [topic] and provide a comprehensive analysis."
}]
)
# Claude can now use web search DURING extended thinking,
# alternating between reasoning and information gathering.Anti-Patterns to Avoid
| Anti-Pattern | Why It Fails | Better Approach |
|---|---|---|
| Ambiguous instructions | Claude follows literally | Be explicit about requirements |
| Missing output format | Unpredictable formatting | Always specify format |
| No structure in long prompts | Claude may lose track | Use XML tags and sections |
| Ignoring context window limits | Truncation issues | Be mindful of 200K/1M limits |
| Over-constraining creativity | Reduces Claude's helpfulness | Balance structure with flexibility |
Quick Reference Templates
Document Analysis
<task>
[specific analysis task]
</task>
<document>
[paste document]
</document>
<output_format>
[expected structure]
</output_format>Code Generation with Examples
<task>
Write a function that [description]
</task>
<requirements>
[specific requirements]
</requirements>
<examples>
<example>
<input>[input example]</input>
<output>[expected output]</output>
</example>
</examples>
<output_format>
[code in specified language]
</output_format>Data Extraction
<task>
Extract [specific fields] from the following text
</task>
<input_text>
[paste text]
</input_text>
<output_format>
JSON with keys: [list keys]
</output_format>Extended Thinking
# API: Enable extended thinking
response = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=4096,
thinking={
"type": "enabled",
"budget_tokens": 8192
},
messages=[{
"role": "user",
"content": """
<task>
[complex reasoning task]
</task>
Please show your reasoning step by step, then provide the final answer.
"""
}]
)
# Response will include <thinking> block followed by <answer>Model Capabilities Reference
| Feature | Claude Sonnet 4.5 | Claude Haiku 4.5 | Claude Opus 4.5 | Notes |
|---|---|---|---|---|
| Context Window | 200K / 1M (beta) | 200K | 200K | Sonnet 4.5: 1M with beta header |
| Extended Thinking | ✅ Yes | ✅ Yes | ✅ Yes | With tool use support |
| Max Output | 64K tokens | 64K tokens | 64K tokens | Unified across 4.5 |
| Vision | ✅ Yes | ✅ Yes | ✅ Yes | Image analysis |
| Parallel Tool Use | ✅ Yes | ✅ Yes | ✅ Yes | Claude 4.5 feature |
| Memory Files | ✅ Yes | ✅ Yes | ✅ Best | Local file knowledge |
| Code | ✅ Excellent | ✅ Good | ✅ Best | Opus 4.5: SOTA coding |
| Speed | Fast | Fastest | Moderate | Default: Sonnet 4.5 |
Recommendation: Start with Claude Sonnet 4.5 - best balance of intelligence, speed, and cost for most use cases. Use Opus 4.5 for complex coding, Haiku 4.5 for speed-critical tasks.
Migration Notes (Claude 3 → 4.5)
If you're migrating from Claude 3.x to Claude 4.5:
| Change | Impact | Action |
|---|---|---|
| Default model | Sonnet 3.5 → Sonnet 4.5 | Update model IDs in code |
| Context window | 200K → 1M (beta) available | Requires beta header for 1M |
| Parallel tools | New capability | Update prompts to leverage parallel execution |
| Memory files | New capability | Grant file access for persistent knowledge |
| Extended thinking + tools | New capability | Can now use tools during reasoning |
| Max output | 8K → 64K tokens | Adjust output expectations |
API Migration:
# Old (Claude 3.5)
model="claude-sonnet-3-5-20240620"
# New (Claude 4.5)
model="claude-sonnet-4-5-20250929" # or use alias "claude-sonnet-4-5"Most prompting techniques remain unchanged—XML tags, system prompts, and structured outputs work identically.
Prompt Element Checklist
When creating Claude prompts, consider including:
- [ ] Task Context: Overall purpose and setting
- [ ] Tone Context: How Claude should approach it
- [ ] Input Data: The actual content to process
- [ ] Examples: Few-shot demonstrations (if needed)
- [ ] Task Description: Specific instructions
- [ ] Immediate Task: What to do right now
- [ ] Output Format: Expected structure
- [ ] Prefill: Start of Claude's response (optional)
See Also
references/basics.md- Foundational Claude prompting conceptsreferences/techniques.md- Detailed technique explanationsreferences/xml-formatting.md- XML tag patterns and usagereferences/patterns.md- Reusable Claude prompt patternsreferences/examples.md- Concrete examples from Anthropic coursesgrok-promptingskill - For Grok/xAI-specific guidancegemini-promptingskill - For Google Gemini-specific guidance
Claude Prompt Engineering - Basics
What is Prompt Engineering for Claude?
Prompt engineering for Claude is the practice of crafting effective instructions to elicit optimal responses from Anthropic's AI models. Claude's unique characteristics—constitutional AI, long-context windows, and strong instruction following—require specific prompting strategies.
Why Claude-Specific Prompting?
While universal prompting techniques apply to all LLMs, Claude has unique characteristics:
1. Constitutional AI: Built-in safety and ethical guidelines 2. Long Context: Up to 200K token context window 3. XML Preference: Official docs extensively use XML-style tags 4. Extended Thinking: Optional reasoning trace feature 5. Strong Instruction Following: Excels at precise instruction adherence
Core Principles for Claude
1. Structure with XML-Style Tags
Claude's official documentation and courses heavily use XML tags for organization:
<context>[background info]</context>
<task>[what to do]</task>
<input>[data]</input>
<output_format>[expected format]</output_format>2. Be Clear and Direct
Claude follows instructions precisely. Ambiguity leads to unpredictable results.
Good:
<task>Extract all email addresses from the text.</task>
<output_format>Comma-separated list</output_format>Less Effective:
Can you find the emails?3. Specify Output Format
Always tell Claude how you want the output structured:
<output_format>
JSON with keys: "name", "email", "company"
</output_format>4. Use Few-Shot Examples
When format matters, show Claude examples:
<examples>
<example>
<input>Jane Doe, jane@example.com, Acme Inc</input>
<output>{"name": "Jane Doe", "email": "jane@example.com", "company": "Acme Inc"}</output>
</example>
</examples>5. Leverage Long Context
Claude can analyze entire documents (up to 200K tokens):
<task>Analyze this research paper and summarize findings.</task>
<document>
[entire paper]
</document>Claude Model Family
| Model | Best For | Speed | Context |
|---|---|---|---|
| Claude 3.5 Sonnet | Coding, analysis, tool use | Fast | 200K |
| Claude 3 Opus | Complex reasoning, writing | Medium | 200K |
| Claude 3 Haiku | Speed, cost-efficiency | Very Fast | 200K |
Prompt Structure from Anthropic Courses
Official Anthropic courses teach this hierarchical structure:
1. TASK_CONTEXT - Overall setting and purpose
2. TONE_CONTEXT - How Claude should approach the task
3. INPUT_DATA - The actual data to process
4. EXAMPLES - Few-shot demonstrations
5. TASK_DESCRIPTION - Specific task details
6. IMMEDIATE_TASK - The immediate action to take
7. OUTPUT_FORMATTING - Expected output structure
8. PRECOGNITION - Anticipating issues (optional)System Prompts vs User Messages
System Prompt:
- Sets Claude's overall behavior and persona
- Persists across the conversation
- Not visible to end users in production
- Best for: role definition, behavioral guidelines
User Message:
- The actual task or query
- Visible in conversation
- Best for: specific requests, data input
Example:
System: You are a technical documentation specialist. Your responses are always:
- Clear and concise
- Formatted in Markdown
- Focused on developer needs
- Technically accurate
User: Write documentation for this API endpoint...Extended Thinking Feature
Claude can show its reasoning process:
{
"thinking": {
"type": "enabled",
"budget_tokens": 4096
}
}This causes Claude to output <thinking> tags with its reasoning before the final answer.
When to Use Claude
| Scenario | Why Claude? |
|---|---|
| Long document analysis | 200K context window |
| Precise instruction following | Constitutional AI training |
| Code generation | Sonnet excels at coding |
| Tool use | Excellent function calling |
| Structured output | Follows format precisely |
| Ethical considerations | Built-in safety guidelines |
Common Use Cases
1. Document Analysis
<task>Summarize key findings from this research paper.</task>
<document>[paste paper]</document>
<output_format><summary>...</summary><key_points>...</key_points></output_format>2. Code Generation
<task>Write a function that validates email addresses.</task>
<language>Python</language>
<requirements>- Use regex
- Return boolean
- Include docstring</requirements>3. Data Extraction
<task>Extract names and emails from this text.</task>
<input_text>[paste text]</input_text>
<output_format>JSON list of objects</output_format>4. Content Transformation
<task>Rewrite this for a technical audience.</task>
<input>[casual explanation]</input>
<output_format>Technical documentation in Markdown</output_format>Getting Started Checklist
- [ ] Define your task clearly
- [ ] Choose appropriate Claude model
- [ ] Structure prompt with XML tags
- [ ] Provide examples if format matters
- [ ] Specify output format
- [ ] Consider using system prompt for context
- [ ] Test and iterate
Key Differences from Other Models
| Aspect | Claude | Grok | Gemini |
|---|---|---|---|
| Prompt Style | Structured/XML | Conversational | Flexible |
| Strength | Long-context | Real-time knowledge | Multimodal |
| Constraints | Constitutional | Relaxed | Balanced |
| Best For | Analysis, code | Current events | Multimodal tasks |
| Format | XML tags preferred | Natural language | System instructions |
Claude Prompt Examples
Real-world examples from Anthropic's official courses and documentation.
---
Example 1: Call Transcript Analysis
From Anthropic Courses - Real World Prompting
<task>
Analyze this customer support call transcript and extract structured information.
</task>
<transcript>
Agent: Thank you for calling Acme Smart Home Support. This is Alex. How may I assist you today?
Customer: Hi Alex, my Acme SmartTherm isn't maintaining the temperature I set. It's set to 72 but the house is much warmer.
Agent: I'm sorry to hear that. Let's troubleshoot. Is your SmartTherm connected to Wi-Fi?
Customer: Yes, the Wi-Fi symbol is showing on the display.
Agent: Great. Let's recalibrate your SmartTherm. Press and hold the menu button for 5 seconds.
Customer: Okay, done. A new menu came up.
Agent: Perfect. Navigate to "Calibration" and press select. Adjust the temperature to match your room thermometer.
Customer: Alright, I've set it to 79 degrees to match.
Agent: Great. Press select to confirm. It will recalibrate, which may take a few minutes. Check back in an hour to see if it's fixed.
Customer: Okay, I'll do that. Thank you for your help, Alex.
Agent: You're welcome! Is there anything else I can assist you with today?
Customer: No, that's all. Thanks again.
Agent: Thank you for choosing Acme Smart Home. Have a great day!
</transcript>
<examples>
<example>
<transcript>
[previous complete interaction example]
</transcript>
<analysis>
Main issue: SmartTherm not maintaining set temperature
Resolution: Guided customer through recalibration process
Follow-up: Not required, but customer should check effectiveness after an hour
Ambiguities: None identified
</analysis>
<output>
{
"summary": {
"customerIssue": "SmartTherm not maintaining set temperature",
"resolution": "Guided customer through SmartTherm recalibration process",
"followUpRequired": false,
"followUpDetails": null
},
"status": "COMPLETE",
"ambiguities": []
}
</output>
</example>
<example>
[insufficient data example]
</example>
</examples>
<output_format>
<analysis>
Main issue: [identify the problem]
Resolution: [how it was resolved]
Follow-up: [is follow-up needed?]
Ambiguities: [unclear information]
</analysis>
<json>
{
"summary": {
"customerIssue": "[issue description]",
"resolution": "[how resolved]",
"followUpRequired": [boolean],
"followUpDetails": "[details or null]"
},
"status": "[COMPLETE/INSUFFICIENT_DATA]",
"ambiguities": ["[list any ambiguities]"]
}
</json>
</output_format>Why It Works:
- XML structure for clear organization
- Examples show exact output format expected
- Handles edge cases (insufficient data)
- Clear categorization of transcript elements
---
Example 2: Document QA with Prompt Chaining
From Anthropic Documentation
Step 1: Extract Relevant Quotes
<task>
You are a helpful assistant. Your task is to help answer a question given in a document.
The first step is to extract quotes relevant to the question from the document, delimited by ####.
Please output the list of quotes using <quotes></quotes> tags.
Respond with "No relevant quotes found!" if no relevant quotes were found.
####
[document text]
####
</task>
<question>
What are the main prompting techniques mentioned in the document?
</question>Response:
<quotes>
<quote>Chain-of-thought (CoT) prompting</quote>
<quote>Generated knowledge prompting</quote>
<quote>Least-to-most prompting</quote>
<quote>Self-consistency decoding</quote>
<quote>Complexity-based prompting</quote>
</quotes>Step 2: Synthesize Answer
<task>
Given a set of relevant quotes (delimited by <quotes></quotes>) extracted from a document and the original document (delimited by ####), please compose an answer to the question.
Ensure that the answer is accurate, has a friendly tone, and sounds helpful.
</task>
<question>
What are the main prompting techniques mentioned in the document?
</question>
####
[original document]
####
<quotes>
[from Step 1 response]
</quotes>Why It Works:
- Breaks complex task into verifiable steps
- Each step has clear output format
- Can debug intermediate results
- Reduces complexity of individual prompts
---
Example 3: Code Review with Structured Output
<role>
You are a senior Python engineer conducting a code review. You are thorough but constructive, focused on correctness, maintainability, and performance.
</role>
<task>
Review this Python function for correctness, style, and best practices.
</task>
<code>def calculate_discount(price, customer_type): if customer_type == "vip": return price 0.8 elif customer_type == "regular": return price 0.95 else: return price
</code>
<output_format>
<review>
<summary>
[overall assessment - 1-2 sentences]
</summary>
<issues>
<issue>
<severity>[critical/major/minor]</severity>
<location>[function/line]</location>
<description>[what's wrong]</description>
<suggestion>[how to fix]</suggestion>
</issue>
</issues>
<positives>
<positive>[what's done well]</positive>
</positives>
<improved_version>[improved code with fixes]
</improved_version>
</review>
</output_format>Expected Response:
<review>
<summary>
The function works correctly but lacks input validation, documentation, and flexibility for discount rates.
</summary>
<issues>
<issue>
<severity>major</severity>
<location>function signature</location>
<description>No type hints or docstring documenting parameters and return value</description>
<suggestion>Add type hints and comprehensive docstring</suggestion>
</issue>
<issue>
<severity>major</severity>
<location>price parameter</location>
<description>No validation that price is a positive number</description>
<suggestion>Add validation: if price <= 0: raise ValueError</suggestion>
</issue>
<issue>
<severity>minor</severity>
<location>customer_type parameter</location>
<description>Hardcoded discount rates make function inflexible</description>
<suggestion>Consider accepting discount rates as parameters or using a configuration dict</suggestion>
</issue>
</issues>
<positives>
<positive>Clear, simple logic that's easy to understand</positive>
<positive>Handles all customer_type cases with else clause</positive>
</positives>
<improved_version>from typing import Literal
def calculate_discount( price: float, customer_type: Literal["vip", "regular", "guest"] ) -> float: """ Calculate discounted price based on customer type.
Args: price: Original price (must be positive) customer_type: Type of customer ("vip", "regular", or "guest")
Returns: Discounted price
Raises: ValueError: If price is not positive """ if price <= 0: raise ValueError("Price must be positive")
discount_rates = { "vip": 0.20, # 20% discount "regular": 0.05, # 5% discount "guest": 0.00 # No discount }
discount = discount_rates.get(customer_type, 0.00) return price * (1 - discount)
</improved_version>
</review>---
Example 4: Data Extraction with Schema
<task>
Extract structured event information from the following text.
</task>
<input_text>
The annual Tech Summit 2025 will be held at the Moscone Center in San Francisco from March 15-17. Early bird registration is open until February 1st at $499. Regular pricing is $699. The event features keynote speakers from major tech companies and workshops on AI, cloud computing, and cybersecurity. Contact events@techsummit.com for more information.
</input_text>
<schema>
{
"type": "object",
"properties": {
"event_name": {"type": "string"},
"dates": {
"type": "object",
"properties": {
"start": {"type": "string"},
"end": {"type": "string"}
}
},
"location": {
"type": "object",
"properties": {
"venue": {"type": "string"},
"city": {"type": "string"}
}
},
"pricing": {
"type": "array",
"items": {
"type": "object",
"properties": {
"tier": {"type": "string"},
"price": {"type": "number"},
"deadline": {"type": "string"}
}
}
},
"topics": {"type": "array", "items": {"type": "string"}},
"contact": {"type": "string"}
}
}
</schema>
<output_format>
JSON matching the above schema
</output_format>Expected Response:
{
"event_name": "Tech Summit 2025",
"dates": {
"start": "March 15, 2025",
"end": "March 17, 2025"
},
"location": {
"venue": "Moscone Center",
"city": "San Francisco"
},
"pricing": [
{
"tier": "early_bird",
"price": 499,
"deadline": "February 1, 2025"
},
{
"tier": "regular",
"price": 699,
"deadline": null
}
],
"topics": ["AI", "cloud computing", "cybersecurity"],
"contact": "events@techsummit.com"
}---
Example 5: Extended Thinking for Complex Reasoning
<thinking_budget_tokens>8192</thinking_budget_tokens>
<task>
A company has 100 employees distributed across 3 departments: Engineering (40 people), Sales (35 people), and Operations (25 people).
The company needs to form a cross-functional committee of 8 people with these requirements:
- At least 2 people from each department
- Exactly 1 committee chair (from any department)
- At least 3 people total from Engineering + Sales combined
How many different ways can the committee be formed?
Show your reasoning step by step.
</task>
<output_format>
<thinking>
[detailed reasoning process]
</thinking>
<answer>
[final answer with explanation]
</answer>
</output_format>Claude's Extended Thinking Output:
<thinking>
Let me break this down systematically.
First, I need to understand the constraints:
- Total committee size: 8 people
- Minimum from each department: 2 people
- Exactly 1 chair (from any department)
- Engineering + Sales combined: at least 3 people
Let me think about the department distributions first...
The minimum distribution is 2-2-2 (Engineering-Sales-Operations), which uses 6 people.
We need 2 more people to reach 8.
The Engineering + Sales requirement of at least 3 means:
- If we have 2 Engineering and 2 Sales, that's 4 - which satisfies the requirement
- If we have 2 Engineering and 1 Sales (minimum), that's 3 - which satisfies
- If we have 1 Engineering and 2 Sales (minimum), that's 3 - which satisfies
So the E+S constraint is automatically satisfied by the "at least 2 from each" constraint.
[continues with detailed combinatorial analysis...]
</thinking>
<answer>
To solve this, I need to consider the distribution of committee members across departments, then account for the chair selection.
**Step 1: Department Distributions**
The constraint "at least 2 from each department" means we start with 2-2-2 (6 people) and need to add 2 more from any departments.
Possible distributions (E-S-O):
1. 4-2-2
2. 3-3-2
3. 3-2-3
4. 2-4-2
5. 2-3-3
6. 2-2-4
[continues with calculation...]
**Total: 1,353,120 different ways to form the committee**
</answer>---
Example 6: ReAct Pattern for Research
<task>
Research and answer: What were the key factors that led to the success of the iPhone when it launched in 2007?
</task>
<thought_1>
To answer this question comprehensively, I need to consider:
1. The technological context of 2007
2. What existing phones were like
3. What the iPhone introduced that was new
4. Market reception and reviews
5. Sales figures and impact
Let me start by researching the state of smartphones before the iPhone.
</thought_1>
<action_1>
<tool>search</tool>
<query>smartphone market before iPhone 2007 BlackBerry Nokia Windows Mobile</query>
</action_1>
<observation_1>
[search results showing phones required physical keyboards, styluses, had limited web browsing, etc.]
</observation_1>
<thought_2>
Now I understand the baseline. Let me research what the iPhone actually introduced and how it was different.
</thought_2>
<action_2>
<tool>search</tool>
<query>iPhone original launch features 2007 multi-touch touchscreen App Store mobile Safari</query>
</action_2>
<observation_2>
[search results about capacitive touchscreen, pinch-to-zoom, full web browsing, visual voicemail, iPod integration]
</observation_2>
<thought_3>
Now let me look at the initial reception and reviews to understand how it was perceived at launch.
</thought_3>
<action_3>
<tool>search</tool>
<query>iPhone 2007 launch reviews reception critics "Jesus phone" Walter Mossberg</query>
</action_3>
<observation_3>
[results about overwhelmingly positive reviews, "device that changed everything", etc.]
</observation_3>
<final_answer>
Based on my research, the key factors that led to the iPhone's success were:
**1. Revolutionary User Interface**
- Capacitive multi-touch screen (no stylus needed)
- Intuitive pinch-to-zoom and gesture controls
- Fluid, responsive animations
**2. Full Internet Experience**
- Mobile Safari that showed real web pages (not mobile versions)
- Best-in-class web browsing on a phone
**3. Integration of Multiple Devices**
- Combined iPod + phone + internet communicator
- Eliminated need to carry multiple devices
**4. Software Ecosystem Vision**
- App Store announced (though not available at launch)
- Set foundation for third-party applications
**5. Timing and Market Context**
- Existing smartphones were complex and required styluses
- BlackBerry focused on enterprise, not consumers
- Nokia and Windows Mobile had poor user experiences
The iPhone didn't just incrementally improve phones—it redefined what a phone could be.
</final_answer>---
Example 7: Few-Shot for Text Classification
<task>
Classify the customer support ticket into one of these categories:
- "technical_issue"
- "billing_question"
- "feature_request"
- "account_management"
</task>
<examples>
<example>
<input>
I can't log into my account. I keep getting "invalid password" even though I'm sure I'm using the right one.
</input>
<output>
{"category": "account_management", "confidence": 0.95, "reason": "Login/authentication issue"}
</output>
</example>
<example>
<input>
How much does the Pro plan cost? I don't see pricing on your website.
</input>
<output>
{"category": "billing_question", "confidence": 0.90, "reason": "Pricing inquiry"}
</output>
</example>
<example>
<input>
It would be great if you could add dark mode. The white background hurts my eyes at night.
</input>
<output>
{"category": "feature_request", "confidence": 0.98, "reason": "Suggestion for new functionality"}
</output>
</example>
<example>
<input>
The export to CSV feature isn't working. When I click it, nothing happens.
</input>
<output>
{"category": "technical_issue", "confidence": 0.92, "reason": "Functionality not working as expected"}
</output>
</example>
</examples>
<input>
I'd like to upgrade my subscription from Basic to Pro. How do I do that?
</input>
<output>---
Example Analysis Table
| Example | Key Techniques | Why Effective |
|---|---|---|
| 1. Call Analysis | Few-shot, XML structure, edge cases | Shows exact output format |
| 2. Document QA | Prompt chaining, XML delimiters | Breaks complex task into steps |
| 3. Code Review | Role definition, structured output | Clear review criteria |
| 4. Event Extraction | Schema definition, precise format | Eliminates ambiguity |
| 5. Committee Math | Extended thinking, step-by-step | Shows reasoning process |
| 6. iPhone Research | ReAct pattern, thought-action-observation | Systematic research approach |
| 7. Ticket Classification | Few-shot with confidence levels | Shows classification reasoning |
---
Key Takeaways from Anthropic's Examples
1. XML Structure is Universal: All official examples use XML-style tags 2. Examples Drive Format: Few-shot examples are crucial for format-sensitive tasks 3. Break Down Complexity: Prompt chaining for multi-step tasks 4. Specify Everything: Output format, constraints, requirements 5. Handle Edge Cases: Examples should cover what to do with insufficient data 6. Show Reasoning: Extended thinking or structured reasoning for complex tasks 7. Use Roles: Define Claude's persona for specialized tasks
Claude Prompt Patterns
Reusable prompt patterns optimized for Claude's structured approach and long-context capabilities.
---
Document Analysis Patterns
Document Summarization
<task>
Summarize the following document, focusing on key findings and implications.
</task>
<document>
[paste document up to 200K tokens]
</document>
<output_format>
<summary>
[executive summary - 2-3 sentences]
</summary>
<key_points>
<point>[key finding 1]</point>
<point>[key finding 2]</point>
<point>[key finding 3]</point>
</key_points>
<implications>
[implications of findings]
</implications>
</output_format>Quote Extraction
<task>
Extract all quotes relevant to [topic] from this document.
</task>
<document>
[paste document]
</document>
<output_format>
<quotes>
<quote>
<content>[quote text]</content>
<context>[surrounding context]</context>
<relevance>[why it's relevant]</relevance>
</quote>
</quotes>
</output_format>Multi-Document Comparison
<task>
Compare these documents on [criteria].
</task>
<documents>
<document id="1">
<title>[document title]</title>
<content>[content]</content>
</document>
<document id="2">
<title>[document title]</title>
<content>[content]</content>
</document>
</documents>
<output_format>
<comparison>
<similarities>
<similarity>[description]</similarity>
</similarities>
<differences>
<difference>
<aspect>[what differs]</aspect>
<doc1>[doc 1 position]</doc1>
<doc2>[doc 2 position]</doc2>
</difference>
</differences>
<synthesis>
[overall synthesis]
</synthesis>
</comparison>
</output_format>---
Data Extraction Patterns
Structured Extraction
<task>
Extract the following fields from the text: [list fields]
</task>
<input_text>
[paste text]
</input_text>
<output_format>
JSON with keys: [field1], [field2], [field3]
</output_format>Entity Recognition
<task>
Identify and categorize named entities in the text.
</task>
<input_text>
[paste text]
</input_text>
<entity_types>
<type>PERSON</type>
<type>ORGANIZATION</type>
<type>LOCATION</type>
<type>DATE</type>
</entity_types>
<output_format>
<entities>
<entity>
<text>[span from text]</text>
<type>[entity type]</type>
<confidence>[high/medium/low]</confidence>
</entity>
</entities>
</output_format>Table Extraction
<task>
Extract structured data from this unstructured text.
</task>
<input_text>
[paste text with embedded data]
</input_text>
<schema>
JSON array of objects with properties: [field1], [field2], [field3]
</schema>
<output_format>
[
{"[field1]": "value", "[field2]": "value", "[field3]": "value"},
...
]
</output_format>---
Content Transformation Patterns
Text Rewriting
<task>
Rewrite the following text for [target audience].
</task>
<input_text>
[paste original text]
</input_text>
<constraints>
- Maintain factual accuracy
- Adapt tone appropriately
- Preserve key information
- Keep under [word count] words
</constraints>
<output_format>
[rewritten text]
</output_format>Format Conversion
<task>
Convert this [source format] to [target format].
</task>
<input>
[paste content in source format]
</input>
<conversion_rules>
- Preserve all data
- Adapt structure to target format
- Handle edge cases [specifically]
</conversion_rules>
<output_format>
[target format structure]
</output_format>Content Expansion
<task>
Expand this brief content into a comprehensive [article/guide/tutorial].
</task>
<brief_content>
[paste brief content]
</brief_content>
<requirements>
- Add relevant examples
- Include explanatory details
- Structure with clear sections
- Target length: [word count]
</requirements>
<output_format>
<expanded_content>
<title>[title]</title>
<introduction>[intro]</introduction>
<section>
<heading>[section heading]</heading>
<content>[content]</content>
</section>
<conclusion>[conclusion]</conclusion>
</expanded_content>
</output_format>---
Code Generation Patterns
Function Implementation
<task>
Write a [language] function that [description].
</task>
<requirements>
- Function signature: [signature]
- Handle edge cases: [list cases]
- Include error handling
- Add docstring
</requirements>
<examples>
<example>
<input>[example input]</input>
<output>[expected output]</output>
</example>
</examples>
<output_format>[function code]
</output_format>Code Review
<role>
You are a senior [language] engineer conducting a code review.
</role>
<task>
Review this code for correctness, style, and best practices.
</task>
<code>[paste code]
</code>
<output_format>
<review>
<summary>[overall assessment]</summary>
<issues>
<issue>
<severity>[critical/major/minor]</severity>
<location>[where in code]</location>
<description>[what's wrong]</description>
<suggestion>[how to fix]</suggestion>
</issue>
</issues>
<positives>
<positive>[what's done well]</positive>
</positives>
<recommendations>
<recommendation>[improvement suggestion]</recommendation>
</recommendations>
</review>
</output_format>Code Explanation
<task>
Explain what this code does, line by line if necessary.
</task>
<code>[paste code]
</code>
<audience_level>
[beginner/intermediate/advanced]
</audience_level>
<output_format>
<explanation>
<overview>[high-level description]</overview>
<breakdown>
<line number="1">
<code>[code snippet]</code>
<explanation>[what it does]</explanation>
</line>
[continue for key lines]
</breakdown>
<key_concepts>
<concept>[important concept used]</concept>
</key_concepts>
</explanation>
</output_format>---
Analysis Patterns
Sentiment Analysis
<task>
Analyze the sentiment of this [review/feedback/comment].
</task>
<input>
[paste text]
</input>
<output_format>
<sentiment_analysis>
<overall_sentiment>
[positive/negative/neutral]
<confidence>[1-10]</confidence>
</overall_sentiment>
<aspects>
<aspect>
<feature>[what's being discussed]</feature>
<sentiment>[positive/negative/neutral]</sentiment>
<quotes>
<quote>[supporting quote]</quote>
</quotes>
</aspect>
</aspects>
<key_phrases>
<phrase sentiment="[positive/negative]">[phrase]</phrase>
</key_phrases>
</sentiment_analysis>
</output_format>SWOT Analysis
<task>
Conduct a SWOT analysis for [company/product/initiative].
</task>
<subject>
[description of subject]
</subject>
<context>
[relevant background information]
</context>
<output_format>
<swot_analysis>
<strengths>
<strength>[description]</strength>
</strengths>
<weaknesses>
<weakness>[description]</weakness>
</weaknesses>
<opportunities>
<opportunity>[description]</opportunity>
</opportunities>
<threats>
<threat>[description]</threat>
</threats>
<strategic_implications>
[what SWOT means strategically]
</strategic_implications>
</swot_analysis>
</output_format>Root Cause Analysis
<task>
Perform a root cause analysis of this [problem/issue].
</task>
<problem_description>
[describe the problem]
</problem_description>
<available_information>
[what we know about the situation]
</available_information>
<output_format>
<root_cause_analysis>
<problem_statement>[clear problem statement]</problem_statement>
<contributing_factors>
<factor>[potential cause]</factor>
</contributing_factors>
<root_causes>
<cause>
<description>[root cause]</description>
<evidence>[supporting evidence]</evidence>
</cause>
</root_causes>
<recommended_actions>
<priority>[high/medium/low]</priority>
<action>[specific action]</action>
<expected_outcome>[what it should achieve]</expected_outcome>
</recommended_actions>
</root_cause_analysis>
</output_format>---
Decision Support Patterns
Option Comparison
<task>
Compare these options for [decision context].
</task>
<options>
<option id="A">
<name>[option name]</name>
<description>[description]</description>
<criteria>
<criterion name="cost">[value]</criterion>
<criterion name="time">[value]</criterion>
<criterion name="quality">[value]</criterion>
</criteria>
</option>
<option id="B">
[...]
</option>
</options>
<output_format>
<comparison>
<trade_offs>
<trade_off>
<criterion>[what's being traded]</criterion>
<option_a>[A's position]</option_a>
<option_b>[B's position]</option_b>
<winner>[which wins this criterion]</winner>
</trade_off>
</trade_offs>
<recommendation>
[which option to choose and why]
</recommendation>
<caveats>
[important considerations or risks]
</caveats>
</comparison>
</output_format>Risk Assessment
<task>
Assess the risks associated with [proposed action/decision].
</task>
<proposal>
[describe what's being proposed]
</proposal>
<context>
[relevant context and constraints]
</context>
<output_format>
<risk_assessment>
<risks>
<risk>
<description>[what could go wrong]</description>
<probability>[low/medium/high]</probability>
<impact>[low/medium/high]</impact>
<mitigation>[how to address]</mitigation>
</risk>
</risks>
<overall_risk_level>
[low/medium/high]
</overall_risk_level>
<go_no_go>
[recommendation on whether to proceed]
</go_no_go>
</risk_assessment>
</output_format>---
Learning & Explanation Patterns
Concept Explanation
<task>
Explain [concept] to [target audience].
</task>
<audience>
[description of audience knowledge level]
</audience>
<requirements>
- Start with basics
- Use analogies where helpful
- Include examples
- Address common misconceptions
- Target length: [duration/word count]
</requirements>
<output_format>
<explanation>
<introduction>
<hook>[engaging opening]</hook>
<definition>[clear definition]</definition>
<importance>[why it matters]</importance>
</introduction>
<core_concepts>
<concept>
<name>[concept name]</name>
<explanation>[explanation]</explanation>
<example>[concrete example]</example>
</concept>
</core_concepts>
<common_misconceptions>
<misconception>
<belief>[what people think]</belief>
<reality>[what's actually true]</reality>
</misconception>
</common_misconceptions>
<summary>
[key takeaways]
</summary>
</explanation>
</output_format>Step-by-Step Tutorial
<task>
Create a step-by-step tutorial for [how to do something].
</task>
<topic>
[what the tutorial covers]
</topic>
<skill_level>
[beginner/intermediate/advanced]
</skill_level>
<output_format>
<tutorial>
<title>[catchy title]</title>
<prerequisites>
<prerequisite>[what learners need before starting]</prerequisite>
</prerequisites>
<steps>
<step number="1">
<title>[step title]</title>
<description>[what to do]</description>
<code>[if applicable]</code>
<expected_result>[what should happen]</expected_result>
<troubleshooting>[common issues]</troubleshooting>
</step>
</steps>
<next_steps>
[what to learn next]
</next_steps>
</tutorial>
</output_format>---
Research & Synthesis Patterns
Literature Review
<task>
Synthesize findings from these research papers on [topic].
</task>
<papers>
<paper>
<title>[paper title]</title>
<authors>[authors]</authors>
<key_findings>[findings]</key_findings>
</paper>
[...]
</papers>
<output_format>
<synthesis>
<themes>
<theme>
<name>[theme name]</name>
<supporting_papers>
<paper>[paper title]</paper>
</supporting_papers>
<consensus>[what papers agree on]</consensus>
<disagreements>[where they differ]</disagreements>
</theme>
</themes>
<research_gaps>
<gap>[what hasn't been studied]</gap>
</research_gaps>
<future_directions>
[recommended areas for future research]
</future_directions>
</synthesis>
</output_format>Competitive Analysis
<task>
Analyze the competitive landscape for [market/product category].
</task>
<focus>
[our company/product]
</focus>
<competitors>
[competitor information]
</competitors>
<output_format>
<competitive_landscape>
<market_overview>
[market size, growth, trends]
</market_overview>
<competitor_analysis>
<competitor>
<name>[company]</name>
<strengths>
<strength>[what they do well]</strength>
</strengths>
<weaknesses>
<weakness>[areas where they're weak]</weakness>
</weaknesses>
<market_position>[their positioning]</market_position>
</competitor>
</competitor_analysis>
<opportunities>
<opportunity>
<description>[market gap]</description>
<why_it_exists>[why competitors aren't addressing]</why_it_exists>
<how_to_win>[our advantage]</how_to_win>
</opportunity>
</opportunities>
</competitive_landscape>
</output_format>---
Pattern Selection Guide
| Goal | Pattern | Why |
|---|---|---|
| Summarize long content | Document Summarization | Leverages 200K context |
| Pull specific info | Quote Extraction | Targeted, structured |
| Convert unstructured data | Structured Extraction | Precise output control |
| Transform content | Content Transformation | Clear requirements |
| Generate code | Function Implementation | Examples + requirements |
| Analyze sentiment | Sentiment Analysis | Multi-aspect approach |
| Make decisions | Option Comparison | Structured trade-offs |
| Explain concepts | Concept Explanation | Audience-aware |
| Review literature | Literature Review | Synthesizes multiple sources |
Claude Prompt Engineering - Techniques
Detailed guide to universal prompting techniques adapted specifically for Claude.
---
1. Zero-Shot Prompting
What It Is
Asking Claude to perform a task without examples.
Claude-Specific Approach
Claude excels at zero-shot when prompts are clear and well-structured.
Examples
Simple Extraction:
<task>
Extract all product names and prices from the following text.
</task>
<input_text>
The iPhone 15 Pro costs $999, while the Samsung Galaxy S24 is priced at $899. The Google Pixel 8 comes in at $699.
</input_text>
<output_format>
JSON list of objects with "product" and "price" keys
</output_format>Analysis:
<task>
Analyze the sentiment of this customer review.
</task>
<review>
I've been waiting for this feature for months! Absolutely love it and can't imagine going back.
</review>
<output_format>
Sentiment: [positive/negative/neutral]
Confidence: [1-10]
Key phrases: [list]
</output_format>Tips
- Always specify output format
- Use XML tags for structure
- Be explicit about requirements
---
2. Few-Shot Prompting (Multishot)
What It Is
Providing examples to guide Claude's responses.
Claude-Specific Approach
Use XML structure to organize examples clearly.
Template
<task>
[description of what Claude should do]
</task>
<examples>
<example>
<input>[example input]</input>
<output>[expected output]</output>
</example>
<example>
<input>[example input]</input>
<output>[expected output]</output>
</example>
</examples>
<input>
[actual input to process]
</input>
<output>
[Claude completes here]Example: Text Classification
<task>
Classify the following email as "urgent", "normal", or "low_priority" based on its content.
</task>
<examples>
<example>
<input>
Subject: Meeting tomorrow
Hi, just confirming our meeting at 2pm tomorrow.
</input>
<output>
{"classification": "normal", "reason": "Routine scheduling matter"}
</output>
</example>
<example>
<input>
Subject: URGENT: Server down!!!
Production server is not responding. Need immediate assistance!
</input>
<output>
{"classification": "urgent", "reason": "Production system down"}
</output>
</example>
<example>
<input>
Subject: Monthly newsletter
Here's our monthly update with company news and events.
</input>
<output>
{"classification": "low_priority", "reason": "Routine informational content"}
</output>
</example>
</examples>
<input>
Subject: Quick question about the report
Hey, I had a question about one section in the Q3 report. When you have a chance...
</input>
<output>Tips
- 3-5 examples usually sufficient
- Examples should cover edge cases
- Format examples exactly as you want output
---
3. Chain-of-Thought Prompting
What It Is
Prompting Claude to show its reasoning step-by-step.
Claude-Specific Approach
Use the Extended Thinking feature or XML-structured reasoning.
Option A: Extended Thinking (API)
{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 4096,
"thinking": {
"type": "enabled",
"budget_tokens": 8192
},
"messages": [
{"role": "user", "content": "Solve this complex problem..."}
]
}Option B: XML-Structured Reasoning
<task>
Determine the most efficient delivery route for these packages.
</task>
<locations>
Warehouse: 123 Main St
Delivery 1: 456 Oak Ave
Delivery 2: 789 Pine Rd
Delivery 3: 321 Elm Blvd
</locations>
<thinking>
First, let me consider the distances between locations...
Then I need to account for traffic patterns at different times...
The package priority/urgency factors are...
Let me calculate the most efficient sequence...
</thinking>
<route>
[final recommendation]
</route>Example: Math Problem
<task>
The odd numbers in this group add up to an even number: 15, 32, 5, 13, 82, 7, 1.
Is this true or false? Show your reasoning.
</task>
<thinking>
I need to identify all the odd numbers in the group: 15, 5, 13, 7, 1
Now I'll add them: 15 + 5 = 20, 20 + 13 = 33, 33 + 7 = 40, 40 + 1 = 41
41 is an odd number, not an even number.
Therefore, the statement is false.
</thinking>
<answer>
False. The sum of odd numbers (15, 5, 13, 7, 1) is 41, which is odd.
</answer>Tips
- Use Extended Thinking for complex reasoning
- Budget tokens must be ≥1024 and < max_tokens
<thinking>tags structure reasoning well
---
4. Zero-Shot CoT
What It Is
Adding a simple phrase to trigger reasoning without examples.
Claude-Specific Triggers
| Trigger | Best For |
|---|---|
| "Let's think step by step" | Sequential reasoning |
| "Walk me through your reasoning" | Explanatory responses |
| "Show your work" | Mathematical/technical problems |
| "Think through this carefully" | Complex analysis |
Examples
A company has 100 employees. If 20% work in engineering, 15% in sales, and the rest in operations, how many work in operations?
Let's think step by step.I need to decide between these two software architectures. Here are the requirements...
Walk me through your analysis of each approach.---
5. Prompt Chaining
What It Is
Breaking complex tasks into sequential prompts.
Claude-Specific Approach
Use XML tags to pass outputs between chain steps.
Example: Document Analysis Chain
Step 1: Extract Quotes
<task>
Extract all quotes relevant to "artificial intelligence" from the following document.
</task>
<document>
[paste long document]
</document>
<output_format>
<quotes>
<quote>[quote 1]</quote>
<quote>[quote 2]</quote>
</quotes>
</output_format>Step 2: Summarize
<task>
Summarize the extracted quotes and identify key themes.
</task>
<quotes>
[from step 1 output]
</quotes>
<output_format>
<summary>[executive summary]</summary>
<themes>
<theme>[theme 1]</theme>
<theme>[theme 2]</theme>
</themes>
</output_format>Step 3: Synthesize
<task>
Create a final report combining the document content with your analysis.
</task>
<document>
[original document]
</document>
<analysis>
[from step 2]
</analysis>
<output_format>
<report>
<introduction>...</introduction>
<key_findings>...</key_findings>
<conclusion>...</conclusion>
</report>
</output_format>Benefits
- Each step is verifiable
- Can adjust based on intermediate results
- Reduces complexity of individual prompts
- More transparent process
---
6. ReAct Prompting
What It Is
Interleaving reasoning with actions (tool use).
Claude's Strength
Excellent tool use and function calling capabilities.
Pattern
<question>
[research question]
</question>
<thought_1>
[initial analysis of what's needed]
</thought_1>
<action_1>
<tool_name>[search_tool]</tool_name>
<parameters>
<query>[search query]</query>
</parameters>
</action_1>
<observation_1>
[tool results]
</observation_1>
<thought_2>
[analysis of results and next step]
</thought_2>
<action_2>
[additional tool use if needed]
</action_2>
<final_answer>
[conclusion based on gathered information]
</final_answer>Example: Research Task
<question>
What are the current regulations around AI in healthcare in the EU?
</question>
<thought_1>
I need to search for current EU AI regulations, specifically related to healthcare applications.
</thought_1>
<action_1>
<tool>search</tool>
<query>EU AI Act healthcare regulations 2025</query>
</action_1>
<observation_1>
[search results about EU AI Act]
</observation_1>
<thought_2>
The results mention the EU AI Act. I should search for more specific information about healthcare classification and requirements.
</thought_2>
<action_2>
<tool>search</tool>
<query>EU AI Act high-risk AI healthcare classification requirements</query>
</action_2>
<observation_2>
[detailed requirements]
</observation_2>
<final_answer>
Based on my research, the EU AI Act classifies healthcare AI as "high-risk" and requires...
</final_answer>---
7. Tree of Thoughts (ToT)
What It Is
Exploring multiple reasoning paths before concluding.
Claude-Specific Approach
Use XML to structure thought branches.
Example: Strategic Decision
<problem>
Our startup needs to choose a pricing strategy. Options: freemium, free trial, or paid-only.
</problem>
<thought_paths>
<path_1>
<strategy>Freemium</strategy>
<analysis>
Pros:
- Largest user base potential
- Network effects
- Data collection for product improvement
Cons:
- High conversion costs
- Free users don't pay
- Support burden for non-paying users
</analysis>
<expected_outcome>
Large user base but potentially low revenue per user
</expected_outcome>
</path_1>
<path_2>
<strategy>Free Trial</strategy>
<analysis>
Pros:
- Users can experience full value
- Conversion rates typically higher than freemium
- Clear upgrade path
Cons:
- Smaller top of funnel
- Users may not sign up without free tier
- Churn after trial period
</analysis>
<expected_outcome>
Smaller but more qualified user base, better revenue per user
</expected_outcome>
</path_2>
<path_3>
<strategy>Paid-Only</strategy>
<analysis>
Pros:
- Revenue from day one
- Serious, committed users
- Lower support costs
Cons:
- Highest barrier to entry
- Smallest total addressable market
- Harder to prove value before purchase
</analysis>
<expected_outcome>
Smallest but highest-quality user base, maximum revenue per user
</expected_outcome>
</path_3>
</thought_paths>
<recommendation>
For an early-stage B2B SaaS, I recommend [choice] because...
[synthesized reasoning]
</recommendation>---
Technique Selection Guide for Claude
| Scenario | Best Technique | Why |
|---|---|---|
| Simple extraction | Zero-shot | Claude's strong instruction following |
| Format-sensitive tasks | Few-shot | Shows exact output structure |
| Complex reasoning | CoT + Extended Thinking | Shows reasoning process |
| Multi-step workflows | Prompt chaining | Verifiable intermediate steps |
| Research with tools | ReAct | Excellent tool use |
| Strategic exploration | Tree of Thoughts | Structures multiple paths |
| Long document analysis | Zero-shot with XML tags | 200K context handles it |
---
Advanced: Combining Techniques
Example: Comprehensive Analysis
<task>
Analyze this competitive landscape and provide strategic recommendations.
</task>
<context>
We are a [company type] entering the [market] market.
</context>
<competitors>
[competitor data]
</competitors>
<examples>
<example>
<analysis>[brief example of desired analysis style]</analysis>
</example>
</examples>
<reasoning_approach>
Let's think through this systematically by analyzing:
1. Each competitor's strengths
2. Each competitor's weaknesses
3. Market gaps
4. Our positioning opportunities
</reasoning_approach>
<output_format>
<analysis>
[competitor analysis]
</analysis>
<opportunities>
[opportunity 1]
[opportunity 2]
</opportunities>
<recommendations>
[priority recommendations]
</recommendations>
</output_format>This combines:
- Few-shot (examples)
- CoT (reasoning approach)
- XML structure (output format)
- Clear context setting
Claude XML-Style Formatting Guide
Official XML tag patterns from Anthropic's documentation and courses.
---
Why XML Tags for Claude?
Claude's official documentation and training materials extensively use XML-style tags because they:
- Provide clear structure and separation
- Help Claude understand prompt organization
- Enable effective long-context prompting
- Match Anthropic's recommended best practices
---
Core XML Tags
<task> or <instruction>
Purpose: Define what Claude should do
<task>
Extract all email addresses from the following text.
</task><instruction>
Summarize this document in 3-5 bullet points.
</instruction><context>
Purpose: Provide background information
<context>
You are a technical writer specializing in API documentation for developers.
</context>
<task>
Write documentation for this endpoint...
</task><input> or <input_text>
Purpose: The actual data to process
<task>
Classify the sentiment of this review.
</task>
<input_text>
I've been waiting months for this feature! Absolutely love it!
</input_text><output> or <output_format>
Purpose: Specify expected output structure
<output_format>
JSON with keys: "sentiment", "confidence", "keywords"
</output_format><output>
{
"sentiment": "[positive/negative/neutral]",
"confidence": [1-10],
"keywords": ["keyword1", "keyword2"]
}
</output>---
Complex Structures
<examples>
Purpose: Few-shot learning demonstrations
<examples>
<example>
<input>
The conference is March 15, 2025 in San Francisco.
</input>
<output>
{"date": "2025-03-15", "event": "conference", "location": "San Francisco"}
</output>
</example>
<example>
<input>
Meeting on June 22nd at the main office.
</input>
<output>
{"date": "2025-06-22", "event": "meeting", "location": "main office"}
</output>
</example>
</examples><document>
Purpose: Long-form content (Claude's 200K context shines here)
<task>
Summarize the key findings from this research paper.
</task>
<document>
[entire paper - up to 200K tokens]
</document>
<output_format>
<summary>
[executive summary]
</summary>
<key_findings>
<finding>[finding 1]</finding>
<finding>[finding 2]</finding>
</key_findings>
</output_format><thinking>
Purpose: Show Claude's reasoning (works with Extended Thinking or naturally)
<thinking>
Let me break this down:
1. First, I need to identify the core issue...
2. Then consider the available options...
3. Evaluate each option against the criteria...
4. Make a recommendation...
The key factors are...
</thinking>
<answer>
[final response]
</answer>---
Hierarchical Prompt Structure
From Anthropic's official courses:
<!-- 1. Task Context - Overall setting -->
<task_context>
You are analyzing customer feedback for a SaaS product to identify common pain points and feature requests.
</task_context>
<!-- 2. Tone Context - How to approach -->
<tone_context>
Be analytical but empathetic to user frustrations. Look for patterns, not isolated incidents.
</tone_context>
<!-- 3. Input Data - The actual data -->
<input_data>
<feedback_list>
<feedback>
User: "I can't figure out how to export my data. This should be easier."
Date: 2025-01-10
</feedback>
<feedback>
User: "Love the product but the dark mode hurts my eyes. Need better contrast."
Date: 2025-01-09
</feedback>
<!-- more feedback... -->
</feedback_list>
</input_data>
<!-- 4. Examples - Few-shot demonstrations -->
<examples>
<example>
<input>User: "Can't find the settings button anywhere."</input>
<analysis>
Category: UX/Navigation
Severity: Medium
Pattern: UI discoverability issue
</analysis>
</example>
</examples>
<!-- 5. Task Description - Specific instructions -->
<task_description>
Categorize each piece of feedback and identify recurring themes. Group related issues together.
</task_description>
<!-- 6. Immediate Task - What to do now -->
<immediate_task>
Analyze the feedback and produce a summary report.
</immediate_task>
<!-- 7. Output Formatting - Expected structure -->
<output_formatting>
<report>
<summary>[brief overview]</summary>
<themes>
<theme>
<name>[theme name]</name>
<count>[how many mentions]</count>
<examples>[example quotes]</examples>
</theme>
</themes>
<priorities>
<priority>
<issue>[description]</priority>
<severity>[high/medium/low]</severity>
<suggested_action>[recommendation]</suggested_action>
</priority>
</priorities>
</report>
</output_formatting>---
Special Purpose Tags
<constraints>
Purpose: Limit what Claude should do
<constraints>
- Output must be under 500 words
- Use only provided information (no external knowledge)
- Maintain neutral, objective tone
- Do not include speculative statements
</constraints><role> or <persona>
Purpose: Define Claude's role/persona
<role>
You are a senior software engineer conducting a code review. You are:
- Thorough but constructive
- Focused on correctness and maintainability
- Aware of performance implications
</role><rules> or <guidelines>
Purpose: Behavioral guidelines
<guidelines>
1. Always cite sources when making claims
2. Indicate confidence levels for uncertain information
3. Offer alternative viewpoints when appropriate
4. Flag potential ethical concerns
</guidelines><formatting>
Purpose: Style guidelines
<formatting>
- Use Markdown for structure
- Include headers for major sections
- Use code blocks for technical content
- Include tables for comparison data
</formatting>---
Working with Data
<data> or <dataset>
Purpose: Structured data input
<task>
Find the top 3 products by revenue.
</task>
<data>
<products>
<product>
<name>Widget A</name>
<revenue>125000</revenue>
<units_sold>500</units_sold>
</product>
<product>
<name>Gadget B</name>
<revenue>89000</revenue>
<units_sold>445</units_sold>
</product>
<!-- more products -->
</products>
</data><schema>
Purpose: Define output schema
<schema>
{
"type": "object",
"properties": {
"summary": {"type": "string"},
"findings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"category": {"type": "string"},
"description": {"type": "string"},
"priority": {"type": "string"}
}
}
}
}
}
</schema>---
Prefilling Claude's Response
Start the output tag to guide format:
<task>
Analyze this user's request and categorize it.
</task>
<user_message>
I've been trying to reset my password but I'm not receiving the email. I've checked spam and tried multiple times.
</user_message>
<output>
<analysis>
Category: Account & Authentication
Subcategory: Password Reset
Severity: High (user cannot access account)
Details:
- User not receiving password reset email
- Has checked spam folder
- Multiple attempts failed
</analysis>
<suggested_response>
[Claude continues from here]---
Cache Control with XML
Optimize repeated prompts:
<cached_content cache_control='{"type": "ephemeral", "ttl": "1h"}'>
<system_prompt>
You are a customer support agent for [company]. You are:
- Friendly and empathetic
- Solution-oriented
- Knowledgeable about our products
</system_prompt>
<product_information>
[large product catalog that doesn't change]
</product_information>
<support_policies>
[support policies and procedures]
</support_policies>
</cached_content>
<task>
Handle this customer inquiry:
</task>
<customer_message>
[specific customer message - varies each time]
</customer_message>---
Common Patterns
Document Analysis Pattern
<task>[analysis task]</task>
<document>[content]</document>
<output_format>[format]</output_format>Extraction Pattern
<task>[what to extract]</task>
<input_text>[source text]</input_text>
<output_format>[desired format]</output_format>Classification Pattern
<task>[classification task]</task>
<item>[item to classify]</item>
<categories>[valid categories]</categories>
<output_format>[format]</output_format>Generation Pattern
<task>[what to generate]</task>
<requirements>[specific requirements]</requirements>
<constraints>[limitations]</constraints>
<output_format>[format]</output_format>---
Tag Reference Table
| Tag | Purpose | When to Use |
|---|---|---|
<task> | Define what to do | Almost every prompt |
<context> | Provide background | Setting, persona, scenario |
<input> | Data to process | Extraction, analysis tasks |
<output> | Specify format | Format-sensitive tasks |
<examples> | Few-shot learning | When format/examples matter |
<document> | Long content | Doc analysis, summarization |
<thinking> | Show reasoning | Complex problems, Extended Thinking |
<constraints> | Limit behavior | Need to restrict output |
<role> | Define persona | When Claude has a specific role |
<data> | Structured input | Working with datasets |
<schema> | Output structure | Complex output requirements |
---
Best Practices
1. Be Consistent: Use the same tag names throughout your prompts 2. Nest Appropriately: Put related content in parent tags 3. Close All Tags: Always close tags properly 4. Use Descriptive Names: <user_feedback> vs <data> 5. Keep Readable: Proper indentation for complex structures 6. Escape Content: Use <![CDATA[...]]> for content with XML characters