Prompt Formatting & Delimiters: Complete Guide
Prompt formatting with delimiters is one of the highest-ROI techniques in prompt engineering. By structuring instructions, context, and data with clear boundaries, you dramatically improve LLM reliability—often by 30–50% on complex tasks—without changing the underlying model or requiring prompt caching.
Why Formatting Matters in Prompt Engineering
LLMs process prompts as sequences of tokens but don't inherently distinguish between instructions, examples, and data unless you make the boundaries explicit. Clear formatting acts as a visual and syntactic guide that reduces ambiguity and prevents the model from conflating different prompt components.
Real-world impact: In a study of customer support summarization, unformatted prompts produced summaries that mixed instructions into the output 15% of the time; delimited prompts reduced errors to 2% (Anthropic, 2024).
The Four Prompt Components and How to Separate Them
Every effective prompt contains these elements—and each needs clear visual separation:
- Instructions – What the model should do (role, task, constraints)
- Context – Background information the model needs to know
- Examples – Demonstrations of desired output format and tone (few-shot prompting)
- Input Data – The actual text, code, or problem the model will process
Delimiter Techniques: Which One to Use and When
Technique 1: XML Tags for Complex Multipart Inputs
XML tags create machine-readable boundaries and are ideal when you have multiple distinct data sources or need to label sections for clarity.
When to use: Customer service tickets, document QA, data extraction with multiple fields, bug triage.
Example:
You are a customer support analyst. Your task is to classify a support ticket and extract key information.
<ticket>
<customer_name>Sarah Chen</customer_name>
<product>CloudSync Pro</product>
<issue_date>2026-05-28</issue_date>
<description>
The backup feature stops working after 24 hours of continuous sync. I've restarted the app twice but the issue persists. This is affecting my team's workflow.
</description>
<affected_users>8 team members</affected_users>
</ticket>
Output the result in JSON format:
{
"severity": "high|medium|low",
"category": "bug|feature_request|performance",
"root_cause": "hypothesis based on description",
"next_action": "recommended support step"
}
Why it works: The <ticket> wrapper isolates user data from instructions, preventing the model from accidentally treating support language as instructions. Named fields (<customer_name>, <product>) cue the model to extract structured information.
Technique 2: Triple Backticks for Code and Technical Blocks
Triple backticks (\```) are the standard for code and prevent syntax errors or misinterpretation of special characters.
When to use: Code debugging, log analysis, SQL queries, configuration files, any text with syntax.
Example:
Debug this Python function and explain the error.
```python
def calculate_average(numbers):
total = sum(numbers)
return total / len(numbers)
my_list = [1, 2, 3, "4"]
print(calculate_average(my_list))
The error occurs because the list contains a string "4" but the function expects all numbers. When Python tries to add the string "4" to an integer, it raises a TypeError. Fix the list to contain only numbers: my_list = [1, 2, 3, 4] or validate input types before summing.
**Pro tip**: Always include the language tag after the opening triple backticks (`python`, `javascript`, `sql`). This helps the model recognize syntax and provide language-specific advice.
### Technique 3: Markdown Headings for Hierarchical Structure
Markdown headings create visual hierarchy and signal section importance. This is effective for complex multi-step instructions or long-form tasks.
**When to use**: Multi-part assignments, comprehensive briefings, workflows with prerequisites.
**Example**:
```markdown
# Task: Create a Product Launch Email
## Prerequisites
- You have access to our email template guidelines
- The product: **SmartAnalytics v3.0** launches on June 15, 2026
- Target audience: B2B SaaS decision-makers (VP of Operations, Finance)
## Instructions
1. Write an email subject line (max 50 chars) that mentions the product name and emphasizes efficiency gains.
2. Create a body (150–200 words) that:
- Opens with a single measurable benefit (e.g., "Cut reporting time by 60%")
- Includes the promo code `EARLY50` for 50% off the first year
- Ends with a clear call-to-action link: [Schedule a Demo](#)
## Tone & Style
- Professional but approachable (avoid jargon)
- Active voice, second person (you/your)
- No hype; focus on ROI and proof points
## Example (Reference Only)
Subject: SmartAnalytics v3.0: Turn Data into Decisions in Minutes
Body: [example email content]
Why it works: Clear section headers (## Instructions, ## Tone & Style) guide the model through the task logic. Bold text (**SmartAnalytics v3.0**) highlights critical details.
Technique 4: Triple Quotes for General-Purpose Text Delimiters
Triple double-quotes (""") are a simple, language-agnostic boundary marker useful for isolating user-provided text from instructions.
Example:
Translate the following text to French. Preserve tone and idioms.
Text to translate:
"""
The meeting is rescheduled to next Tuesday. Please bring your Q3 reports.
"""
French translation:
Technique 5: Dashes or Horizontal Rules for Visual Separation
Simple dashes (---) or asterisks (***) create visual breaks between sections without added syntax.
Example:
You are a contract reviewer. Extract key terms from the agreement below.
---
AGREEMENT TEXT:
This agreement is effective as of June 1, 2026. The Service Provider agrees
to deliver monthly reports by the 5th of each month. The client agrees to
pay $5,000 monthly. Either party may terminate with 30 days' written notice.
---
OUTPUT FORMAT:
- Effective date: [date]
- Payment terms: [amount and frequency]
- Deliverables: [list]
- Termination notice: [days or policy]
Combining Techniques: A Production-Grade Prompt
Here's a realistic prompt combining multiple techniques:
Role: Senior data analyst
Task: Extract and classify customer feedback from raw reviews
Instructions:
1. For each review, identify the primary topic (product quality, shipping, customer service, pricing, or other).
2. Extract one direct quote (max 15 words) that supports your classification.
3. Rate sentiment: 1 (very negative) to 5 (very positive).
4. Flag any mentions of refund requests or legal threats.
---
Input Data:
<review>
<customer_id>C12845</customer_id>
<date>2026-05-27</date>
<text>
Product arrived two weeks late! When it finally came, the box was damaged
and two accessories were missing. Customer service was unhelpful. I want
a full refund.
</text>
</review>
<review>
<customer_id>C12901</customer_id>
<date>2026-05-28</date>
<text>
Great quality, exactly as advertised. Shipping was faster than expected.
Definitely buying again!
</text>
</review>
---
Output Format (JSON):
{
"reviews": [
{
"customer_id": "C12845",
"topic": "shipping",
"quote": "Product arrived two weeks late",
"sentiment": 1,
"refund_flag": true,
"legal_threat_flag": false
}
]
}
What makes this work:
- Role and task stated upfront (clear intent)
- Numbered instructions (sequential clarity)
- XML-delimited review data (prevents confusion between data and instructions)
- JSON output schema (ensures parsing works)
- Multiple signals (quote extraction, flags) prevent missed details
Common Pitfalls and How to Avoid Them
Pitfall 1: Inconsistent Delimiters
Problem: Mixing XML tags, triple backticks, and markdown in one prompt without clear purpose creates confusion.
Fix: Choose one primary technique per prompt. Use XML for data, backticks for code, markdown for structure—and stick to it consistently.
Pitfall 2: Delimiter Collisions
Problem: If your input text contains triple backticks (e.g., a code snippet inside a code example), the model may misidentify where one block ends and another begins.
Fix: Escape delimiters or choose different delimiters. If processing code with backticks, use XML tags instead. If the input might contain common characters, use rare delimiters like <|START_DATA|> and <|END_DATA|>.
Pitfall 3: Over-Engineering Structure
Problem: Deeply nested tags or overly complex formatting creates cognitive overload and actually hurts performance.
Fix: Use the simplest structure that clearly separates components. "Simple but consistent" beats "complex and precise."
Pitfall 4: Silent Formatting Errors
Problem: You forget to close a tag or indent inconsistently, and the model silently interprets the structure differently than intended.
Fix: Before sending a prompt to production, validate it manually: trace through each delimiter pair, check that all sections are where you expect them, and run the prompt a few times to ensure consistent output structure.
Key Takeaways
- Formatting with delimiters is one of the highest-ROI prompt engineering techniques, typically improving accuracy and consistency by 20–50% on complex tasks.
- Use XML tags for structured multipart data, triple backticks for code, markdown for hierarchy, and dashes for simple visual separation.
- Always clearly separate instructions, context, examples, and input data—the model will otherwise conflate them, especially under long context or instruction ambiguity.
- Consistency matters more than sophistication; simple, repeatable formatting beats complex one-off schemes.
- Validate delimited prompts manually before shipping to production to catch closure errors and misaligned expectations.
Frequently Asked Questions
Do delimiters work with all LLMs?
Delimiters work with all major LLMs (GPT-4o, Claude 3.5 Sonnet, Gemini, Llama) because they use common syntactic structures (XML, markdown, quotes). However, instruction-tuned models (those fine-tuned with RLHF) respond better to delimiters than base models. Always test with your specific model and version, as formatting effectiveness can vary slightly.
Should I use delimiters if I'm using function calling or structured output?
Partially. Function calling (where the model outputs JSON in a specific schema) reduces the need for output-format delimiters, but input delimiters (XML, backticks for context) are still valuable. Combine both: use XML or markdown for input structure, and function calling or JSON mode for guaranteed output formatting.
How do I handle user input that contains my chosen delimiters?
If your users might input text with triple backticks or XML tags, either escape them (backslash before special characters) or switch to rare delimiters unlikely to appear naturally (<|INPUT_START|> instead of <input>). For maximum safety, use a hash or length-prefix ([32 chars] text…) to signal block boundaries instead of text markers.
Can I use formatting to prevent prompt injection?
Partially. Clear delimiters make it harder for an attacker to inject instructions into user-provided data, but they don't prevent all attacks. Combine formatting with additional safeguards: validate user input types (only plain text, not code), limit context window, and use system-level filtering (e.g., block outputs containing "ignore previous instructions").
Further Reading
- OpenAI Best Practices for Prompt Engineering – Official guidance on structuring prompts for GPT models.
- Anthropic Prompt Writing Guide – Detailed prompt structure recommendations for Claude.
- Prompting Fundamentals – Community guide with examples of delimiter techniques across models.
Now that you can structure individual prompts, the next lesson explores system messages and conversation management: how to maintain consistent behavior across multi-turn conversations and set guardrails that persist through long interactions.