What is Prompt Engineering?
Prompt engineering is the practice of designing and refining prompts to get better, more accurate responses from Claude. Small changes in how you phrase a question can lead to dramatically different results. By understanding Claude's capabilities and limitations, you can craft prompts that consistently produce high-quality outputs.
System Prompts
A system prompt sets the context and behavior for the entire conversation. It's processed before your actual query and acts as invisible instructions that guide Claude's responses.
Using System Prompts
System Prompt:
You are a technical writing expert specializing in software documentation.
Always structure responses with clear headings and concise explanations.
Use examples to illustrate complex concepts.
Avoid jargon without first defining it.
System prompts are particularly effective for:
- Establishing a professional tone or personality
- Defining the assistant's role or expertise
- Specifying output format requirements
- Setting constraints or guidelines
In Claude.ai, you can set system prompts in the project settings. In the API, use the system parameter in your request.
Few-Shot Examples (In-Context Learning)
Few-shot examples teach Claude how to respond by demonstrating the desired pattern before asking it to solve your actual problem. This technique is more effective than lengthy explanations.
Example: Text Classification
Here are examples of sentiment classification:
Input: "This product is amazing! I love it."
Classification: POSITIVE
Input: "It broke after one week. Very disappointed."
Classification: NEGATIVE
Input: "It's okay, nothing special but it works."
Classification: NEUTRAL
Now classify this: "The customer service was unhelpful and rude."
Classification:
Few-shot prompting works because Claude learns patterns from concrete examples. It's especially useful when:
- Your task has specific formatting requirements
- You need consistent categorization across many items
- You want to define custom categories or labels
- Standard instructions aren't producing the desired format
Chain-of-Thought Reasoning
Chain-of-thought prompting asks Claude to explain its reasoning step-by-step before providing a final answer. This technique improves accuracy, especially for complex problem-solving and reasoning tasks.
Without Chain-of-Thought
Q: A train travels 120 miles at 40 mph. How long is the trip?
A: 3 hours
With Chain-of-Thought
Q: A train travels 120 miles at 40 mph. How long is the trip?
Think through this step by step:
1. Identify what we know
2. Write the relevant formula
3. Perform the calculation
4. State your answer
A:
Claude will naturally explain each step, leading to more accurate and verifiable results. This is invaluable for:
- Complex calculations and reasoning
- Decision-making processes
- Debugging and troubleshooting
- Academic or technical problems
XML Tags for Structure
XML tags help you organize complex prompts and clearly separate different parts of your request. They act as visual delimiters that make the prompt easier to understand and parse.
Structured Request with XML Tags
<task>
Write a product description for a wireless headphone.
</task>
<requirements>
- Maximum 150 words
- Target audience: professionals
- Emphasize battery life and sound quality
- Include one key technical specification
</requirements>
<tone>
Professional but approachable
</tone>
<format>
Start with a headline, followed by two paragraphs.
</format>
XML tags are effective because:
- They clearly separate different types of information
- Claude can easily identify the structure of your request
- They work particularly well for complex or multi-part requests
- They improve consistency when used across multiple prompts
Output Formatting Specifications
Being explicit about your desired output format significantly improves result quality. Instead of hoping Claude guesses the right format, tell it exactly what you want.
Specifying JSON Output
Generate 5 creative business name ideas for a tech startup.
Return as JSON with this structure:
{
"names": [
{
"name": "string",
"reasoning": "string"
}
]
}
Specifying Markdown Tables
Compare Python, JavaScript, and Go across 5 dimensions.
Format as a markdown table with languages as columns and dimensions as rows.
Specifying Lists and Bullet Points
List the top 10 productivity tips for remote workers.
Format as a numbered list with brief one-line descriptions.
Each item should have a practical action step.
Combining Techniques: A Complete Example
You are an expert Python code reviewer. Your role is to identify bugs,
suggest optimizations, and explain improvements clearly.
Here's how you should review code:
1. Identify any bugs or logical errors
2. Suggest performance improvements
3. Recommend best practices
4. Explain each suggestion in simple terms
Format your review as:
- **Bugs Found:** [list any issues]
- **Performance:** [optimization suggestions]
- **Best Practices:** [recommendations]
Review this code:
[code snippet here]
Think through potential issues step by step before providing your review.
This example combines:
- System prompt (role definition)
- Few-shot examples (format demonstration)
- Output specification (structured format)
- Chain-of-thought (step-by-step thinking)
Testing and Iteration
Prompt engineering is not a one-shot process. The best prompts are refined through testing:
- Start simple — Begin with a clear, basic request
- Test variations — Try different phrasings and structures
- Evaluate quality — Does the output meet your needs?
- Iterate — Refine based on results
- Document — Save your best prompts for reuse
Keep a collection of prompts that work well for your common tasks. Over time, you'll develop an intuition for what works with Claude.
Common Pitfalls to Avoid
- Being too vague: "Write something about AI" is less effective than "Write a 300-word beginner's guide to prompt engineering"
- Overcomplicating: Lengthy prompts aren't always better. Clarity beats verbosity
- Assuming context: Don't assume Claude knows your specific terminology or background
- Inconsistent formatting: When asking for structured output, be precise about format
- Neglecting tone: Tone matters. Specify "formal," "friendly," "technical," etc.
Next Steps
- Experiment with system prompts in your Claude.ai projects
- Try few-shot examples for repetitive categorization tasks
- Use chain-of-thought for complex reasoning
- Build a personal library of effective prompts for your workflows
Want to study prompt engineering more systematically? Check out our recommended books for learning AI & LLMs, including titles focused on prompt engineering techniques.
Structured Prompts: The Foundation of Quality Output
When asking Claude to handle complex tasks, structuring your prompt with clear sections makes a significant difference. The XML tag pattern works particularly well with Claude.
<context>
You are a senior frontend engineer specializing in TypeScript and React.
You are conducting a code review.
</context>
<task>
Review the following React component and identify areas for improvement.
</task>
<requirements>
- Check for performance issues
- Include accessibility improvement suggestions
- Verify TypeScript type safety
- Provide concrete code examples for each improvement
</requirements>
<code>
function UserList({ users }) {
return (
<div>
{users.map(user => (
<div onClick={() => window.location.href = `/user/${user.id}`}>
{user.name}
</div>
))}
</div>
);
}
</code>By clearly separating context, task, requirements, and input data, Claude can accurately understand the role of each section and generate well-structured, high-quality responses.
Tips for Using XML Tags Effectively
Claude recognizes <tag> format XML tags and treats them as section boundaries. You can use any tag name that makes sense for your use case — <instructions>, <example>, <output_format> — making your prompts both machine-readable and human-readable.
Chain of Thought: Boosting Reasoning Accuracy
For complex problems, asking Claude to think step-by-step produces significantly better results than requesting an immediate final answer. This is known as Chain of Thought (CoT) prompting.
Analyze the following revenue data.
<data>
2025 Q1: $95,000
2025 Q2: $120,000
2025 Q3: $108,000
2025 Q4: $143,000
2026 Q1: $122,000
</data>
Please analyze this step by step:
1. First, calculate the quarter-over-quarter growth rate
2. Next, identify the annual trend
3. Examine whether there are seasonal patterns
4. Finally, provide a Q2 2026 revenue forecast with your reasoningBy explicitly instructing Claude to follow a thought process, each step is handled carefully, leading to more accurate and well-reasoned final analysis.
Leveraging Extended Thinking
With Claude 3.5 Sonnet and later models, you can enable the thinking API parameter to observe the model's internal reasoning process.
import anthropic
client = anthropic.Anthropic()
# Request with Extended Thinking enabled
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=8000,
thinking={
"type": "enabled",
"budget_tokens": 5000 # Token budget for thinking
},
messages=[{
"role": "user",
"content": "Implement an efficient LRU cache in Python. Analyze the time and space complexity, and compare it with the standard library implementation."
}]
)
# Display thinking process and final answer
for block in response.content:
if block.type == "thinking":
print("[Thinking Process]")
print(block.thinking)
elif block.type == "text":
print("[Answer]")
print(block.text)Extended Thinking lets you see exactly how Claude arrives at its answer, which is invaluable for refining your prompts.
Few-Shot Learning for Consistent Output Formats
When you need Claude to produce output in a specific format, providing a few examples — known as few-shot learning — is remarkably effective.
<task>
Generate an SEO-optimized meta description for the following article title.
</task>
<examples>
<example>
<input>How to Master App Router in Next.js 15</input>
<output>Master Next.js 15 App Router from fundamentals to production. Learn Server Components, layout design, and data fetching best practices with hands-on code examples. Suitable for beginners to intermediate developers.</output>
</example>
<example>
<input>Practical Guide to Setting Up Dev Environments with Docker Compose</input>
<output>Complete guide to building development environments with Docker Compose. From MySQL, Redis, and Nginx configuration to hot-reload support, with ready-to-use templates for team development.</output>
</example>
</examples>
<input>Building a Real-Time Streaming Chat with the Claude API</input>Just two or three examples are enough for Claude to learn the pattern — tone, length, keyword density — and produce consistently formatted output.
Role Setting and Persona Design
Assigning Claude a specific role produces more focused, domain-specific responses. The most effective approach is defining the role in the System Prompt.
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=4096,
system="""You are a security engineer with 10+ years of experience.
You are well-versed in the OWASP Top 10 and have extensive hands-on penetration testing experience.
In code reviews, you identify specific vulnerabilities and provide remediation guidance.
Structure your response as follows:
1. Vulnerability summary (with CWE number)
2. Severity (High/Medium/Low)
3. Specific attack scenario
4. Fixed code""",
messages=[{
"role": "user",
"content": "Please review this Node.js code for security issues.\n\napp.get('/user', (req, res) => {\n const query = `SELECT * FROM users WHERE id = ${req.query.id}`;\n db.query(query, (err, result) => res.json(result));\n});"
}]
)
print(response.content[0].text)
# Expected output:
# 1. SQL Injection (CWE-89)
# 2. Severity: High
# 3. Attack scenario: /user?id=1 OR 1=1 leaks all user data
# 4. Fix: Use parameterized queriesWrapping Up
Prompt engineering is an essential skill for unlocking Claude AI's full potential. By combining the techniques covered in this article — structured prompts, Chain of Thought reasoning, few-shot learning, and role-based prompting — you can dramatically improve the quality of your AI-generated output.
Start by adding XML-based structure to your everyday prompts. These small improvements compound over time and will meaningfully enhance how you collaborate with Claude AI.