XML Tags in Claude Prompts
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
XML tags are the closest thing prompts have to punctuation for structure. They let you say "this part is instructions, this part is a customer email, and this part is where I want your answer" without the model having to work it out. They're easy to use badly, mostly by overthinking them, so this lesson sticks to what's useful.
What you'll learn
- Why tags help, and what a good tag looks like.
- How to refer to tags in your instructions.
- How to ask for answers inside tags and pull them out in code.
- Where tags stop helping.
Before you start
Why tags help
A long prompt often mixes instructions, background, examples and the actual input. Without markers the model has to infer where one ends and the next begins, and sometimes it infers wrong. Anthropic's guidance is to wrap each type of content in its own tag, such as <instructions>, <context> and <input>, noting that this reduces misinterpretation when a prompt mixes several kinds of content.
Two points that surprise people. First, these aren't "real" XML. There's no schema and nothing validates them. They're just consistent, readable markers. Second, there's no list of approved tag names. Use names that say what's inside.
Good tag habits
- Descriptive names.
<customer_email> beats <data>. Tag names are part of the instruction.
- The same names every time. If your prompts say
<email> in one place and <message> in another, you're making the model do extra work.
- Nesting for hierarchy. Several documents go inside
<documents>, each in a <document index="n"> with <source> and <document_content>.
- Refer to them by name. "Summarise the text in the
<email> tags in two sentences" is clearer than "summarise the following".
Asking for answers in tags
Tags work in both directions. You can tell the model to put its answer, or parts of it, inside tags you choose. Anthropic lists this as an effective way to steer formatting too, for example asking it to write prose sections inside <smoothly_flowing_prose_paragraphs> tags. The practical payoff for developers is parsing: instead of guessing where the answer is in a paragraph, you pull it from a tag.
A common pattern is to let the model think first and answer second, each in its own tag:
import re
def tagged(name: str, content: str) -> str:
return f"<{name}>\n{content}\n</{name}>"
def extract_tag(text: str, name: str) -> str | None:
"""Return the text inside the LAST <name>...</name> pair, or None if the model did not use the tag.
The last pair is usually the final answer if the model wrote its reasoning in earlier tags."""
matches = re.findall(rf"<{re.escape(name)}>(.*?)</{re.escape(name)}>", text, flags=re.DOTALL)
return matches[-1].strip() if matches else None
def extract_all(text: str, name: str) -> list[str]:
return [m.strip() for m in re.findall(rf"<{re.escape(name)}>(.*?)</{re.escape(name)}>", text, flags=re.DOTALL)]
PROMPT = """You review a customer email and decide how urgent it is.
<email>
{email}
</email>
First write your reasoning inside <analysis> tags. Then give your final answer inside <urgency> tags:
exactly one of low, medium, high."""
def urgency_from_reply(reply: str) -> str:
value = extract_tag(reply, "urgency")
if value not in {"low", "medium", "high"}:
raise ValueError(f"Unusable reply, no valid <urgency> tag: {reply[:80]!r}")
return value
The prompt asks for reasoning inside <analysis> and the final answer inside <urgency>. In code, extract_tag takes the last matching pair, which is usually the final answer if the model mentions the tag name earlier while thinking. urgency_from_reply then refuses anything that isn't low, medium or high, so a stray "whenever" or a missing tag fails loudly instead of flowing into your database.
We tested the parsing helpers with a normal reply, a reply with no tags, a multi-line value, two matching tags (the last one wins), and a bad value. They behave as described.
One honest caveat: for strictly formatted data you can get stronger guarantees from the structured outputs feature (lesson 2.8). Tag parsing is a good fit for mixed content, where you want some free text and one or two extracted values.
Match the style you want back
This one is subtle and documented. Anthropic notes that the formatting style of your prompt can influence the style of the response, and suggests that if you want less markdown in the output you try removing markdown from the prompt. If your prompt is full of bullet points and bold text, expect a lot of them in the answer. Write the prompt in the style you'd like to read.
Where tags stop helping
- Short, simple prompts. A one-line question doesn't need tags.
- As a security device. Tags clarify structure. They don't stop a determined injection, and untrusted text can contain tag-like strings, which is why lesson 3.3 neutralises your wrapper tags first.
- When the structure is the product. If you need guaranteed JSON, use the schema-based feature instead of asking for tags.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A helpdesk tool reads incoming emails and decides how urgent each one is. The first version asked "how urgent is this?" and parsed the reply with a regex that broke whenever the model added a sentence. The second version wrapped the email in <email> tags and asked for the answer in <urgency> tags. Parsing became one function call, and a missing tag was easy to detect and send for review instead of silently becoming the wrong label.
Mistakes to avoid
- Inventing a different tag name for the same thing in each prompt.
- Forgetting to close a tag, which makes both you and the model unsure where content ends.
- Parsing the first match when the model may have mentioned the tag earlier.
- Trusting extracted values without validating them.
- Putting user text inside your tags without neutralising any tags it contains.
Security notes
User-supplied text inside a tag can include its own closing tag. Neutralise the tags you use before inserting untrusted content (see the function in lesson 3.3). And never run extracted text as code, SQL or HTML. Validate it first.
Cost and speed
Tags cost a few tokens each, which is negligible. Asking the model to write reasoning in an <analysis> tag adds output tokens, and output is the expensive side. If you don't need the reasoning, ask for the answer tag only, or rely on the model's built-in adaptive thinking instead.
Key takeaways
- Wrap each kind of content in a descriptive tag and use the same names everywhere.
- Refer to tags by name in your instructions, and nest them for hierarchy.
- Ask for answers in tags and extract them with a small, strict parser.
- Tags clarify structure but aren't a security measure, and the style of your prompt influences the style of the reply.
Lesson recap: tags work in both directions, with strict parsing on the way back.
Quick quiz
- Does a tag name have to come from an approved list?
- Why does
extract_tag return the last matching pair?
- What happens in the example if the model replies with no
<urgency> tag?
- If you want fewer bullet points in the answer, what should you look at in your prompt?
- When is structured output a better choice than tags?
Answers and explanations
- No. They aren't validated XML. Use descriptive, consistent names.
- If the model mentions the tag name while reasoning, the final answer is normally the last pair.
urgency_from_reply raises an error, so the problem is caught instead of passing a wrong value along.
- The formatting style of the prompt itself. Anthropic notes that removing markdown from the prompt can reduce markdown in the output.
- When you need strictly valid data that matches a schema, for example JSON going straight into a database.
Official references and further reading
Related tutorials