How to use Claude XML tags effectively
Claude XML tags to structure prompts by wrapping instructions or content in tags like <quote> or <code> to guide the model's behavior precisely. These tags help clarify intent, separate content types, and improve output formatting when using claude-3-5-sonnet-20241022 or similar models.PREREQUISITES
Python 3.8+Anthropic API keypip install anthropic>=0.20
Setup
Install the anthropic Python SDK and set your API key as an environment variable.
- Run
pip install anthropic>=0.20 - Set
export ANTHROPIC_API_KEY='your_api_key'on Linux/macOS or use environment variables on Windows.
pip install anthropic>=0.20 Step by step
Use XML tags in your prompt to clearly define sections or content types. For example, wrap a quote in <quote> tags or code in <code> tags to instruct Claude to treat them differently.
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
prompt = '''
Please summarize the following text.
<quote>
To be, or not to be, that is the question.
</quote>
'''
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=200,
system="You are a helpful assistant.",
messages=[{"role": "user", "content": prompt}]
)
print(response.content[0].text) Summary: The quote reflects on the dilemma of existence and the nature of life and death.
Common variations
You can combine multiple XML tags to structure complex prompts, such as <instruction>, <example>, and <code>. Also, use different Claude models like claude-3-5-haiku-20241022 for poetic outputs or claude-3-opus-20240229 for more concise responses.
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
prompt = '''
<instruction>Explain the following code snippet.</instruction>
<code>
def add(a, b):
return a + b
</code>
'''
response = client.messages.create(
model="claude-3-opus-20240229",
max_tokens=150,
system="You are a helpful assistant.",
messages=[{"role": "user", "content": prompt}]
)
print(response.content[0].text) This function named 'add' takes two arguments, 'a' and 'b', and returns their sum.
Troubleshooting
If Claude ignores your XML tags or outputs raw tags, ensure your prompt clearly instructs the model to interpret tags semantically. Avoid mixing incompatible tags or overly complex nesting. Also, verify you are using a Claude model version that supports XML tag parsing.
Key Takeaways
- Use XML tags like
and
to clearly separate content types in prompts. - Combine multiple tags to structure complex instructions and examples effectively.
- Always instruct Claude explicitly to interpret XML tags semantically for best results.