How to use XML tags in Claude prompts
Quick answer
Use XML tags directly in
Claude prompts by embedding them as plain text within the user message. Claude treats XML tags as part of the prompt text, enabling structured input or markup for better context parsing. Wrap your content in XML tags inside the prompt string to guide Claude's response.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 set environment variable on Windows.
pip install anthropic>=0.20 Step by step
Send a prompt containing XML tags as plain text in the messages parameter. Claude will interpret the tags as part of the input, allowing you to structure data or instructions.
import os
from anthropic import Anthropic
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
system_prompt = "You are a helpful assistant that understands XML tags in prompts."
user_prompt = '''<request>
<task>Summarize the following text</task>
<text>Artificial intelligence is transforming industries worldwide.</text>
</request>'''
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=200,
system=system_prompt,
messages=[{"role": "user", "content": user_prompt}]
)
print(response.content[0].text) output
Artificial intelligence is revolutionizing various industries globally by enhancing efficiency, enabling new capabilities, and driving innovation.
Common variations
You can use different XML structures to organize data or instructions. Also, you can switch models or use async calls with the anthropic SDK.
import asyncio
import os
from anthropic import Anthropic
async def async_prompt():
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
system_prompt = "You are an assistant that parses XML tags."
user_prompt = '''<command>
<action>Translate</action>
<content>Hello, world!</content>
<language>Spanish</language>
</command>'''
response = await client.messages.acreate(
model="claude-3-5-sonnet-20241022",
max_tokens=100,
system=system_prompt,
messages=[{"role": "user", "content": user_prompt}]
)
print(response.content[0].text)
asyncio.run(async_prompt()) output
Hola, mundo!
Troubleshooting
If Claude does not respond as expected, ensure your XML tags are well-formed and properly escaped if needed. Avoid mixing XML with conflicting prompt instructions. Use clear system instructions to guide interpretation.
Key Takeaways
- Embed XML tags as plain text inside the user prompt to structure input for Claude.
- Use clear system instructions to help Claude interpret XML-tagged content correctly.
- The
anthropicSDK supports both sync and async calls with XML-tagged prompts. - Ensure XML is well-formed to avoid parsing confusion in the AI response.
- Switch models or prompt styles to optimize XML tag handling for your use case.