Advanced

Advanced Prompt Patterns

Explore meta-prompting, structured output formats, prompt templates with variables, multi-modal prompting, retrieval-augmented prompting, and prompt compression.

Meta-Prompting

Meta-prompting is the technique of using AI to generate prompts. Instead of writing a prompt yourself, you ask the AI to design the optimal prompt for your task. This is especially useful for complex tasks where you are not sure how to structure the prompt.

Meta-Prompt Example
Prompt:
I need to use an AI to analyze customer support
tickets and categorize them by urgency, topic,
and sentiment. The AI should also suggest a
response template.

Design the optimal prompt for this task. Include:
- A clear role assignment
- Specific instructions with edge cases
- Output format specification
- 2-3 few-shot examples
- Error handling instructions

The AI will generate a complete, optimized prompt
that you can then use directly for your task.
Meta-prompting workflow: (1) Describe your task and requirements to the AI. (2) Ask it to generate an optimal prompt. (3) Test the generated prompt. (4) Ask the AI to refine based on results. This iterative approach often produces prompts better than what you would write manually.

Constitutional AI Prompting

Inspired by Anthropic's Constitutional AI approach, this technique involves giving the model a set of principles to follow, then asking it to self-evaluate and revise its responses against those principles.

Constitutional Prompting
Prompt:
Generate a response to the user's question below.
Then evaluate your response against these principles:

Principles:
1. Accuracy: All facts must be verifiable
2. Completeness: Address all parts of the question
3. Clarity: Use simple language, avoid jargon
4. Balance: Present multiple perspectives if relevant
5. Safety: Do not include harmful or misleading info

After generating your response, score it 1-5 on each
principle. If any score is below 4, revise the
response to improve that aspect. Show both the
original and revised response.

User Question: "What are the pros and cons of
nuclear energy?"

Structured Output Formats

Requesting specific output formats is essential for building AI-powered applications. Here are the main formats and when to use each:

JSON Output

JSON Output
Prompt:
Extract the following information from this job
posting and return it as a JSON object:

Fields: title, company, location, salary_range,
required_skills (array), experience_years,
remote_policy (onsite/hybrid/remote)

Job Posting: """
Senior React Developer at TechCorp in Austin, TX.
$130K-$160K. Hybrid (3 days office). 5+ years
experience required. Must know React, TypeScript,
Node.js, PostgreSQL, and AWS.
"""

Response:
{
  "title": "Senior React Developer",
  "company": "TechCorp",
  "location": "Austin, TX",
  "salary_range": "$130K-$160K",
  "required_skills": ["React", "TypeScript",
    "Node.js", "PostgreSQL", "AWS"],
  "experience_years": 5,
  "remote_policy": "hybrid"
}

XML Output

XML Output
Prompt:
Analyze this text and return the results in XML
format with tags for: <summary>, <key_points>,
<sentiment>, and <action_items>.

Response:
<analysis>
  <summary>The Q3 report shows 15% revenue
  growth but rising customer churn.</summary>
  <key_points>
    <point>Revenue up 15% YoY</point>
    <point>Churn rate increased to 8%</point>
  </key_points>
  <sentiment>mixed</sentiment>
  <action_items>
    <item>Investigate churn causes</item>
    <item>Launch retention campaign</item>
  </action_items>
</analysis>

YAML and CSV

YAML and CSV Formats
# YAML - great for configuration-like output
Prompt: "Generate a deployment config in YAML format"

Response:
app:
  name: my-service
  version: 2.1.0
  replicas: 3
  resources:
    cpu: "500m"
    memory: "256Mi"

# CSV - great for tabular data
Prompt: "List top 5 programming languages with their
use cases. Format as CSV with headers."

Response:
language,primary_use,popularity_rank
Python,Data Science/AI,1
JavaScript,Web Development,2
TypeScript,Full-Stack Apps,3
Java,Enterprise/Android,4
Rust,Systems Programming,5

Prompt Templates and Variables

Prompt templates allow you to create reusable prompt structures with placeholders that get filled in dynamically. This is essential for production AI applications.

Python Prompt Template
def create_review_prompt(product, review_text, aspects):
    """Generate a product review analysis prompt."""
    return f"""
Analyze the following {product} review.

Review: "{review_text}"

For each of these aspects, provide a rating (1-5)
and a brief explanation:
{chr(10).join(f'- {a}' for a in aspects)}

Format your response as JSON with this structure:
{{
  "overall_sentiment": "positive/negative/neutral",
  "aspects": {{
    "aspect_name": {{
      "rating": 1-5,
      "explanation": "brief explanation"
    }}
  }},
  "summary": "one-sentence summary"
}}
"""

# Usage
prompt = create_review_prompt(
    product="laptop",
    review_text="Great performance but battery life
    is disappointing. The keyboard feels premium.",
    aspects=["performance", "battery", "build_quality"]
)

Dynamic Prompting

Dynamic prompting adjusts the prompt based on runtime conditions such as user profile, previous interactions, or external data. This enables personalized AI experiences.

Dynamic Prompt Construction
def build_dynamic_prompt(user):
    # Adjust complexity based on user expertise
    if user.level == "beginner":
        style = "Use simple language, avoid jargon,
        include analogies"
    elif user.level == "intermediate":
        style = "Use technical terms with brief
        explanations"
    else:
        style = "Use precise technical language,
        assume deep domain knowledge"

    # Add context from previous interactions
    history = get_relevant_history(user.id, limit=3)

    return f"""
{style}

Previous context from this user:
{history}

User's current question: {user.query}
"""

Multi-Modal Prompting

Multi-modal prompting involves combining text with other data types like images. Models such as Claude, GPT-4V, and Gemini can process both text and images simultaneously.

Multi-Modal Prompt with Image
# Using Claude's API with an image
import anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "image",
                "source": {
                    "type": "url",
                    "url": "https://example.com/chart.png"
                }
            },
            {
                "type": "text",
                "text": "Analyze this sales chart.
                Identify: (1) overall trend, (2) seasonal
                patterns, (3) anomalies, (4) forecast
                for next quarter. Format as JSON."
            }
        ]
    }]
)

Retrieval-Augmented Prompting

Retrieval-augmented prompting combines prompt engineering with retrieved context. You fetch relevant documents and include them in your prompt to ground the model's responses in specific data.

RAG Prompt Pattern
Prompt:
Answer the user's question using ONLY the provided
context documents. If the answer is not in the
documents, say "I don't have enough information to
answer this question."

Context Documents:
---
Document 1 (Company Policy - Updated Jan 2026):
[retrieved content here]
---
Document 2 (Employee Handbook Section 4.2):
[retrieved content here]
---

User Question: "What is the company's policy on
remote work for new employees?"

Instructions:
- Cite the specific document and section
- Quote relevant passages
- If documents conflict, note the discrepancy
- Do not use knowledge outside these documents

Prompt Compression Techniques

When dealing with large contexts or limited token budgets, prompt compression helps you convey maximum information in minimum tokens:

Abbreviation

Use standard abbreviations and remove filler words. "Please provide a detailed analysis of" becomes "Analyze:"

Structured Shorthand

Use lists, bullets, and key-value pairs instead of prose. Saves 40-60% of tokens with the same information.

Summarized Context

Summarize long documents before including them. Use a first pass to extract key points, then include only those.

Schema References

Define a schema once, then reference it. "Follow the JSON schema above" instead of repeating the full schema.

Compression tradeoff: Compressing prompts saves tokens and cost, but over-compression can reduce output quality. Always test compressed prompts against their full versions to ensure you are not losing important context or nuance.

Ready to Go Deeper?

Live instructor-led courses from our partners. Affiliate disclosure.