Prompt chaining breaks complex tasks into sequences of simpler prompts, where each step's output feeds into the next. This technique dramatically improves reliability and enables sophisticated workflows that would be impossible with a single prompt.

<Callout type="tip" title="Think Assembly Lines">
Just like a factory assembly line breaks manufacturing into specialized stations, prompt chaining breaks AI tasks into specialized steps. Each step does one thing well, and the combined output is far better than trying to do everything at once.
</Callout>

## Why Chain Prompts?

Single prompts struggle with complex tasks because they try to do too much at once. The AI has to simultaneously understand, analyze, plan, and generate, which leads to errors and inconsistencies.

<div className="my-6 grid md:grid-cols-2 gap-4">
  <div className="border rounded-lg bg-red-50/50 dark:bg-red-950/20 border-red-200 dark:border-red-900">
    <p className="text-sm font-semibold text-red-700 dark:text-red-400 px-4 pt-3 flex items-center gap-2 m-0!"><IconX className="h-4 w-4" /> Single Prompt Struggles</p>
    <div className="text-sm p-4 pt-2 space-y-1">
      <p className="m-0!">Multi-step reasoning gets confused</p>
      <p className="m-0!">Different "modes" of thinking clash</p>
      <p className="m-0!">Complex outputs lack consistency</p>
      <p className="m-0!">No opportunity for quality control</p>
    </div>
  </div>
  <div className="border rounded-lg bg-green-50/50 dark:bg-green-950/20 border-green-200 dark:border-green-900">
    <p className="text-sm font-semibold text-green-700 dark:text-green-400 px-4 pt-3 flex items-center gap-2 m-0!"><IconCheck className="h-4 w-4" /> Chaining Solves This</p>
    <div className="text-sm p-4 pt-2 space-y-1">
      <p className="m-0!">Each step focuses on one task</p>
      <p className="m-0!">Specialized prompts for each mode</p>
      <p className="m-0!">Validate between steps</p>
      <p className="m-0!">Debug and improve individual steps</p>
    </div>
  </div>
</div>

## Basic Chaining Pattern

The simplest chain passes output from one prompt directly to the next. Each step has a clear, focused purpose.

<div className="my-6 flex items-center justify-center gap-3 p-6 bg-muted/30 rounded-lg overflow-x-auto">
  <div className="flex flex-col items-center">
    <div className="px-4 py-3 bg-blue-100 dark:bg-blue-900/50 border border-blue-200 dark:border-blue-800 rounded-lg text-center">
      <p className="text-sm font-medium text-blue-700 dark:text-blue-300 m-0!">Prompt 1</p>
      <p className="text-xs text-blue-600 dark:text-blue-400 m-0!">(Extract)</p>
    </div>
    <p className="text-xs text-muted-foreground mt-1 m-0!">Input</p>
  </div>
  <div className="text-blue-400 dark:text-blue-500">→</div>
  <div className="flex flex-col items-center">
    <div className="px-4 py-3 bg-purple-100 dark:bg-purple-900/50 border border-purple-200 dark:border-purple-800 rounded-lg text-center">
      <p className="text-sm font-medium text-purple-700 dark:text-purple-300 m-0!">Prompt 2</p>
      <p className="text-xs text-purple-600 dark:text-purple-400 m-0!">(Analyze)</p>
    </div>
    <p className="text-xs text-muted-foreground mt-1 m-0!">Intermediate</p>
  </div>
  <div className="text-purple-400 dark:text-purple-500">→</div>
  <div className="flex flex-col items-center">
    <div className="px-4 py-3 bg-green-100 dark:bg-green-900/50 border border-green-200 dark:border-green-800 rounded-lg text-center">
      <p className="text-sm font-medium text-green-700 dark:text-green-300 m-0!">Prompt 3</p>
      <p className="text-xs text-green-600 dark:text-green-400 m-0!">(Generate)</p>
    </div>
    <p className="text-xs text-muted-foreground mt-1 m-0!">Output</p>
  </div>
</div>

<Callout type="info" title="The ETG Pattern">
The most common chain pattern is **Extract → Transform → Generate**. First extract raw data, then reshape it for your purpose, then generate the final output. This pattern works for almost any content task.
</Callout>

## Chain Types

Different tasks require different chain architectures. Choose the pattern that matches your workflow.

<ChainFlowDemo />

### Sequential Chain

The most straightforward pattern: each step depends on the previous. Think of it as a relay race where each runner passes the baton to the next.

<ChainExample 
  type="sequential"
  steps={[
    { step: "Step 1: Extract", prompt: "Extract all dates, names, and numbers from: [text]", output: '{ dates: ["2024-01-15", "2024-02-20"], names: ["John Smith", "Acme Corp"], numbers: [15000, 42] }' },
    { step: "Step 2: Analyze", prompt: "Given this extracted data: [step1_output], identify relationships and patterns.", output: '{ patterns: ["Monthly meetings scheduled"], relationships: ["John Smith works at Acme Corp"] }' },
    { step: "Step 3: Generate", prompt: "Using these patterns: [step2_output], write a summary report highlighting the most significant findings.", output: "Summary Report: Analysis of the document reveals a business relationship between John Smith and Acme Corp, with scheduled monthly meetings..." }
  ]}
/>

### Parallel Chain

When you need multiple perspectives on the same input, run prompts in parallel and merge results. This is faster than sequential chains and provides richer analysis.

<ChainExample 
  type="parallel"
  steps={[
    { step: "Input", prompt: "Product review text", output: '"I love these earbuds! The battery lasts forever and the display on the case is so convenient. Perfect for my daily commute."' },
    { step: "Branch A: Sentiment", prompt: "Analyze sentiment: [text]", output: '{ sentiment: "positive", score: 0.85 }' },
    { step: "Branch B: Features", prompt: "Extract features mentioned: [text]", output: '{ features: ["battery", "display"] }' },
    { step: "Branch C: Persona", prompt: "Identify user persona: [text]", output: '{ persona: "commuter" }' },
    { step: "Merge", prompt: "Combine analyses into unified report", output: "Unified Report: Positive review from a commuter highlighting battery and display." }
  ]}
/>

### Conditional Chain

Route inputs through different paths based on classification. This is like a decision tree where the AI first categorizes the input, then handles each category differently.

<ChainExample 
  type="conditional"
  steps={[
    { step: "Classify Input", prompt: "Classify this customer message as: complaint, question, feedback, or other.\n\nMessage: [text]", output: '{ classification: "complaint", confidence: 0.92 }' },
    { step: "Route: Question (skipped)", prompt: "Identify what information is needed", output: "Skipped - input classified as complaint" },
    { step: "Route: Complaint", prompt: "Identify the issue and severity: [text]", output: '{ issue: "delayed shipping", severity: "medium" }' },
    { step: "Generate Response", prompt: "Generate empathetic response with resolution: [analysis]", output: "Dear Customer, We sincerely apologize for the delay. Your order has been expedited..." }
  ]}
/>

### Iterative Chain

Keep refining output until it meets quality standards. The AI generates, evaluates, and improves in a loop until satisfied or max iterations reached.

<Callout type="warning" title="Set Iteration Limits">
Always set a maximum number of iterations (typically 3-5) to prevent infinite loops and control costs. The law of diminishing returns applies: most improvement happens in the first 2-3 iterations.
</Callout>

<ChainExample 
  type="iterative"
  steps={[
    { step: "Generate Draft", prompt: "Write a product description for: [wireless earbuds]", output: "These wireless earbuds offer good sound quality and comfortable fit for everyday use." },
    { step: "Evaluate (Score: 5)", prompt: "Rate this description 1-10 on: clarity, persuasiveness, accuracy.\n\nDescription: [current_draft]", output: '{ score: 5, improvements: ["Add specific features", "Include emotional benefits", "Mention battery life", "Add call-to-action"] }' },
    { step: "Improve Draft", prompt: "Improve this description based on this feedback:\n\nCurrent: [current_draft]\nFeedback: [improvements]", output: "Experience crystal-clear audio with our premium wireless earbuds. Featuring 30-hour battery life, active noise cancellation, and an ergonomic design that stays comfortable all day. Perfect for music lovers and professionals alike. Order now and transform your listening experience." },
    { step: "Evaluate (Score: 8)", prompt: "Rate this description 1-10 on: clarity, persuasiveness, accuracy.\n\nDescription: [improved_draft]", output: '{ score: 8, improvements: ["Minor: Could add warranty info"] }\n\n✓ Score >= 8: EXIT LOOP' }
  ]}
/>

## Common Chain Patterns

These battle-tested patterns solve common problems. Use them as starting points and adapt to your needs.

### Extract → Transform → Generate

The workhorse of content processing. Pull data out, reshape it, then create something new.

<div className="mb-4 p-3 rounded-lg bg-blue-50/50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800">
  <p className="text-xs font-semibold text-blue-700 dark:text-blue-300 mb-1 m-0!">Best For</p>
  <p className="text-sm text-blue-600 dark:text-blue-400 m-0!">Document summarization, report generation, content repurposing, data-to-narrative conversion</p>
</div>

<ChainExample 
  type="sequential"
  steps={[
    { step: "Extract", prompt: "From this document, extract:\n- Main topic\n- Key arguments (list)\n- Supporting evidence (list)\n- Conclusions\nReturn as JSON.", output: '{ "topic": "Climate change impacts", "arguments": ["Rising temperatures", "Sea level rise"], "evidence": ["NASA data", "IPCC reports"], "conclusions": ["Urgent action needed"] }' },
    { step: "Transform", prompt: "Reorganize this information for [business executives]:\n[extracted_data]\nFocus on: economic implications\nRemove: technical jargon", output: '{ "summary": "Climate risks to business", "key_points": ["Supply chain disruption", "Insurance costs rising"], "action_items": ["Assess vulnerabilities", "Plan adaptations"] }' },
    { step: "Generate", prompt: "Using this restructured information, write a [executive brief]:\n[transformed_data]\nTone: professional\nLength: 200 words", output: "Executive Brief: Climate change presents significant operational risks to our business. Key concerns include supply chain disruptions from extreme weather events and rising insurance premiums. We recommend immediate assessment of facility vulnerabilities and development of adaptation strategies..." }
  ]}
/>

### Analyze → Plan → Execute

Perfect for code refactoring, project planning, or any task where you need to understand before acting.

<div className="mb-4 p-3 rounded-lg bg-purple-50/50 dark:bg-purple-950/20 border border-purple-200 dark:border-purple-800">
  <p className="text-xs font-semibold text-purple-700 dark:text-purple-300 mb-1 m-0!">Best For</p>
  <p className="text-sm text-purple-600 dark:text-purple-400 m-0!">Code refactoring, project planning, troubleshooting, strategic decision-making, complex problem solving</p>
</div>

<ChainExample 
  type="sequential"
  steps={[
    { step: "Analyze", prompt: "Analyze this codebase structure and identify:\n- Architecture pattern\n- Main components\n- Dependencies\n- Potential issues\n[code]", output: '{ "pattern": "MVC", "components": ["UserController", "AuthService", "Database"], "dependencies": ["express", "mongoose"], "issues": ["No input validation", "Hardcoded secrets"] }' },
    { step: "Plan", prompt: "Based on this analysis, create a refactoring plan:\n[analysis_output]\nGoal: improve security\nConstraints: no breaking changes", output: '{ "steps": ["1. Add input validation middleware", "2. Move secrets to env vars", "3. Add rate limiting"], "priority": "high", "estimated_time": "4 hours" }' },
    { step: "Execute", prompt: "Implement step 1 of this plan:\n[plan_output]\nShow the refactored code with explanations.", output: "// Added validation middleware\nconst validateInput = (req, res, next) => {\n  const { email, password } = req.body;\n  if (!email || !isValidEmail(email)) {\n    return res.status(400).json({ error: 'Invalid email' });\n  }\n  next();\n};" }
  ]}
/>

### Generate → Critique → Refine

The self-improvement loop. Generate content, have the AI evaluate it critically, then improve based on that feedback. This mimics how professional writers and editors work together.

<div className="mb-4 p-3 rounded-lg bg-green-50/50 dark:bg-green-950/20 border border-green-200 dark:border-green-800">
  <p className="text-xs font-semibold text-green-700 dark:text-green-300 mb-1 m-0!">Best For</p>
  <p className="text-sm text-green-600 dark:text-green-400 m-0!">Marketing copy, creative writing, email drafts, presentations, any content that benefits from revision</p>
</div>

<ChainExample 
  type="iterative"
  steps={[
    { step: "Generate", prompt: "Write a marketing email for [fitness app] targeting [busy professionals].", output: "Subject: Get Fit Fast!\n\nHey there! Our app helps you exercise. Download it today and start your fitness journey. Thanks!" },
    { step: "Critique", prompt: "As a marketing expert, critique this email:\n[generated_email]\nEvaluate: subject line, hook, value proposition, CTA, tone\nScore each 1-10.", output: '{ "subject_line": 4, "hook": 3, "value_proposition": 2, "cta": 5, "tone": 4, "feedback": "Too generic, no specific benefits, weak urgency" }' },
    { step: "Refine", prompt: "Rewrite the email addressing this feedback:\nOriginal: [generated_email]\nCritique: [critique_output]\nFocus on the lowest-scored elements.", output: "Subject: 15-Min Workouts for Your Lunch Break\n\nBusy schedule? We get it. Our app delivers science-backed workouts designed for professionals who have zero time to waste. Join 50,000+ executives who transformed their health in just 15 minutes a day. Start your free trial now—your future self will thank you." },
    { step: "Final Score", prompt: "Re-evaluate the refined email.", output: '{ "subject_line": 8, "hook": 8, "value_proposition": 9, "cta": 8, "tone": 9, "improvement": "+23 points total" }' }
  ]}
/>

## Implementing Chains

You can implement chains manually for experimentation, or programmatically for production systems. Start simple and add complexity as needed.

### Manual Chaining

The copy-paste approach is perfect for prototyping and experimentation. Run each prompt manually, examine the output, and paste it into the next prompt.

<CodeEditor 
  language="python"
  filename="manual_chain.py"
  code={`# Pseudocode for manual chaining
step1_output = call_ai("Extract entities from: " + input_text)
step2_output = call_ai("Analyze relationships: " + step1_output)
final_output = call_ai("Generate report: " + step2_output)`}
/>

### Programmatic Chaining

For production systems, automate the chain with code. This enables error handling, logging, and integration with your application.

<CodeEditor 
  language="python"
  filename="chain.py"
  code={`def analysis_chain(document):
    # Step 1: Summarize
    summary = call_ai(f"""
        Summarize the key points of this document in 5 bullets:
        {document}
    """)
    
    # Step 2: Extract entities
    entities = call_ai(f"""
        Extract named entities (people, organizations, locations) 
        from this summary. Return as JSON.
        {summary}
    """)
    
    # Step 3: Generate insights
    insights = call_ai(f"""
        Based on this summary and entities, generate 3 actionable 
        insights for a business analyst.
        Summary: {summary}
        Entities: {entities}
    """)
    
    return {
        "summary": summary,
        "entities": json.loads(entities),
        "insights": insights
    }`}
/>

### Using Chain Templates

Define chains as configuration files for reusability and easy modification. This separates prompt logic from application code.

<CodeEditor 
  language="yaml"
  filename="chain_template.yaml"
  code={`name: "Document Analysis Chain"
steps:
  - name: "extract"
    prompt: |
      Extract key information from this document:
      {input}
      Return JSON with: topics, entities, dates, numbers
    
  - name: "analyze"
    prompt: |
      Analyze this extracted data for patterns:
      {extract.output}
      Identify: trends, anomalies, relationships
    
  - name: "report"
    prompt: |
      Generate an executive summary based on:
      Data: {extract.output}
      Analysis: {analyze.output}
      Format: 3 paragraphs, business tone`}
/>

## Error Handling in Chains

Chains can fail at any step. Build in validation, retries, and fallbacks to make your chains robust.

<ChainErrorDemo />

<Callout type="warning" title="Garbage In, Garbage Out">
If one step produces bad output, every following step will be affected. Always validate critical intermediate results before passing them forward.
</Callout>

### Validation Between Steps

Add a validation step after any step that produces structured data. This catches errors early before they cascade.

<ValidationDemo />

### Fallback Chains

When your primary approach fails, have a simpler backup ready. Trade capability for reliability.

<FallbackDemo />

## Chain Optimization

Once your chain works, optimize for speed, cost, and reliability. These often trade off against each other.

<div className="my-6 grid md:grid-cols-3 gap-4">
  <div className="border rounded-lg bg-blue-50/50 dark:bg-blue-950/20 border-blue-200 dark:border-blue-900 p-4">
    <p className="text-sm font-semibold text-blue-700 dark:text-blue-400 mb-2 m-0!">Reducing Latency</p>
    <div className="text-sm space-y-1">
      <p className="m-0!">Parallelize independent steps</p>
      <p className="m-0!">Cache intermediate results</p>
      <p className="m-0!">Use smaller models for simple steps</p>
      <p className="m-0!">Batch similar operations</p>
    </div>
  </div>
  <div className="border rounded-lg bg-green-50/50 dark:bg-green-950/20 border-green-200 dark:border-green-900 p-4">
    <p className="text-sm font-semibold text-green-700 dark:text-green-400 mb-2 m-0!">Reducing Cost</p>
    <div className="text-sm space-y-1">
      <p className="m-0!">Use cheaper models for classification</p>
      <p className="m-0!">Limit iterations in loops</p>
      <p className="m-0!">Short-circuit when possible</p>
      <p className="m-0!">Cache repeated queries</p>
    </div>
  </div>
  <div className="border rounded-lg bg-purple-50/50 dark:bg-purple-950/20 border-purple-200 dark:border-purple-900 p-4">
    <p className="text-sm font-semibold text-purple-700 dark:text-purple-400 mb-2 m-0!">Improving Reliability</p>
    <div className="text-sm space-y-1">
      <p className="m-0!">Add validation between steps</p>
      <p className="m-0!">Include retry logic</p>
      <p className="m-0!">Log intermediate results</p>
      <p className="m-0!">Implement fallback paths</p>
    </div>
  </div>
</div>

## Real-World Chain Example

Let's walk through a complete production chain. This content pipeline transforms a raw idea into a polished article package.

### Content Pipeline Chain

<ContentPipelineDemo />

## Summary

Prompt chaining transforms what AI can accomplish by breaking impossible tasks into achievable steps.

<div className="my-6 grid md:grid-cols-2 gap-4">
  <div className="border rounded-lg bg-amber-50/50 dark:bg-amber-950/20 border-amber-200 dark:border-amber-900 p-4">
    <p className="text-sm font-semibold text-amber-700 dark:text-amber-400 mb-2 m-0!">Chaining Enables</p>
    <div className="text-sm space-y-1">
      <p className="m-0!">Complex multi-step workflows</p>
      <p className="m-0!">Higher quality through specialization</p>
      <p className="m-0!">Better error handling and validation</p>
      <p className="m-0!">Modular, reusable prompt components</p>
    </div>
  </div>
  <div className="border rounded-lg bg-cyan-50/50 dark:bg-cyan-950/20 border-cyan-200 dark:border-cyan-900 p-4">
    <p className="text-sm font-semibold text-cyan-700 dark:text-cyan-400 mb-2 m-0!">Key Principles</p>
    <div className="text-sm space-y-1">
      <p className="m-0!">Break complex tasks into simple steps</p>
      <p className="m-0!">Design clear interfaces between steps</p>
      <p className="m-0!">Validate intermediate outputs</p>
      <p className="m-0!">Build in error handling and fallbacks</p>
      <p className="m-0!">Optimize for your constraints</p>
    </div>
  </div>
</div>

<Callout type="tip" title="Start Simple">
Begin with a 2-3 step sequential chain. Get it working reliably before adding complexity. Most tasks don't need elaborate chain architectures.
</Callout>

<Quiz 
  question="What is the main advantage of prompt chaining over a single complex prompt?"
  options={[
    "It uses fewer tokens overall",
    "It's faster to execute",
    "Each step can specialize, improving quality and enabling error handling",
    "It requires less planning"
  ]}
  correctIndex={2}
  explanation="Prompt chaining breaks complex tasks into specialized steps. Each step can focus on one thing well, intermediate results can be validated, errors can be caught and retried, and the overall quality improves through specialization."
/>

In the next chapter, we'll explore multimodal prompting: working with images, audio, and other non-text content.
