Advanced

Prompt Chaining

Connecting multiple prompts

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.

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.

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.

Single Prompt Struggles

Multi-step reasoning gets confused

Different "modes" of thinking clash

Complex outputs lack consistency

No opportunity for quality control

Chaining Solves This

Each step focuses on one task

Specialized prompts for each mode

Validate between steps

Debug and improve individual steps

Basic Chaining Pattern

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

Prompt 1

(Extract)

Input

Prompt 2

(Analyze)

Intermediate

Prompt 3

(Generate)

Output

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.

Chain Types

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

Each step depends on the previous, like a relay race.

Extract

Pull data from input

Analyze

Find patterns

Generate

Create output

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.

sequential chain
1

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] }

2

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"] }

3

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.

parallel chain
1

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."

2

Branch A: Sentiment

Prompt:

Analyze sentiment: [text]

Output:

{ sentiment: "positive", score: 0.85 }

3

Branch B: Features

Prompt:

Extract features mentioned: [text]

Output:

{ features: ["battery", "display"] }

4

Branch C: Persona

Prompt:

Identify user persona: [text]

Output:

{ persona: "commuter" }

5

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.

conditional chain
1

Classify Input

Prompt:

Classify this customer message as: complaint, question, feedback, or other. Message: [text]

Output:

{ classification: "complaint", confidence: 0.92 }

2

Route: Question (skipped)

3

Route: Complaint

Prompt:

Identify the issue and severity: [text]

Output:

{ issue: "delayed shipping", severity: "medium" }

4

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.

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.

iterative chain
1

Generate Draft

Prompt:

Write a product description for: [wireless earbuds]

Output:

These wireless earbuds offer good sound quality and comfortable fit for everyday use.

2

Evaluate (Score: 5)

Prompt:

Rate this description 1-10 on: clarity, persuasiveness, accuracy. Description: [current_draft]

Output:

{ score: 5, improvements: ["Add specific features", "Include emotional benefits", "Mention battery life", "Add call-to-action"] }

3

Improve Draft

Prompt:

Improve this description based on this feedback: Current: [current_draft] Feedback: [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.

4

Evaluate (Score: 8)

Prompt:

Rate this description 1-10 on: clarity, persuasiveness, accuracy. Description: [improved_draft]

Output:

{ score: 8, improvements: ["Minor: Could add warranty info"] } ✓ Score >= 8: EXIT LOOP

Loop until quality threshold met

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.

Best For

Document summarization, report generation, content repurposing, data-to-narrative conversion

sequential chain
1

Extract

Prompt:

From this document, extract: - Main topic - Key arguments (list) - Supporting evidence (list) - Conclusions Return as JSON.

Output:

{ "topic": "Climate change impacts", "arguments": ["Rising temperatures", "Sea level rise"], "evidence": ["NASA data", "IPCC reports"], "conclusions": ["Urgent action needed"] }

2

Transform

Prompt:

Reorganize this information for [business executives]: [extracted_data] Focus on: economic implications Remove: technical jargon

Output:

{ "summary": "Climate risks to business", "key_points": ["Supply chain disruption", "Insurance costs rising"], "action_items": ["Assess vulnerabilities", "Plan adaptations"] }

3

Generate

Prompt:

Using this restructured information, write a [executive brief]: [transformed_data] Tone: professional Length: 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.

Best For

Code refactoring, project planning, troubleshooting, strategic decision-making, complex problem solving

sequential chain
1

Analyze

Prompt:

Analyze this codebase structure and identify: - Architecture pattern - Main components - Dependencies - Potential issues [code]

Output:

{ "pattern": "MVC", "components": ["UserController", "AuthService", "Database"], "dependencies": ["express", "mongoose"], "issues": ["No input validation", "Hardcoded secrets"] }

2

Plan

Prompt:

Based on this analysis, create a refactoring plan: [analysis_output] Goal: improve security Constraints: 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" }

3

Execute

Prompt:

Implement step 1 of this plan: [plan_output] Show the refactored code with explanations.

Output:

// Added validation middleware const validateInput = (req, res, next) => { const { email, password } = req.body; if (!email || !isValidEmail(email)) { return res.status(400).json({ error: 'Invalid email' }); } next(); };

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.

Best For

Marketing copy, creative writing, email drafts, presentations, any content that benefits from revision

iterative chain
1

Generate

Prompt:

Write a marketing email for [fitness app] targeting [busy professionals].

Output:

Subject: Get Fit Fast! Hey there! Our app helps you exercise. Download it today and start your fitness journey. Thanks!

2

Critique

Prompt:

As a marketing expert, critique this email: [generated_email] Evaluate: subject line, hook, value proposition, CTA, tone Score each 1-10.

Output:

{ "subject_line": 4, "hook": 3, "value_proposition": 2, "cta": 5, "tone": 4, "feedback": "Too generic, no specific benefits, weak urgency" }

3

Refine

Prompt:

Rewrite the email addressing this feedback: Original: [generated_email] Critique: [critique_output] Focus on the lowest-scored elements.

Output:

Subject: 15-Min Workouts for Your Lunch Break Busy 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.

4

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" }

Loop until quality threshold met

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.

manual_chain.py
python
Loading...

Programmatic Chaining

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

chain.py
python
Loading...

Using Chain Templates

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

chain_template.yaml
yaml
Loading...

Error Handling in Chains

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

Chain Error Handling Demo
Extract Data
Validate Output
Transform Data
Final Output
Success
Failed
Retry
Fallback
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.

Validation Between Steps

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

Validation Between Steps
Step 1
Generate Data
Step 2
Validate Output

Checks output schema & types

Step 3
Process Data

Uses validated data

Fallback Chains

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

Fallback Chain Demo
Primary
Complex Analysis
Fallback
Simple Extraction

Standby if primary fails

Output
Final Result

Chain Optimization

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

Reducing Latency

Parallelize independent steps

Cache intermediate results

Use smaller models for simple steps

Batch similar operations

Reducing Cost

Use cheaper models for classification

Limit iterations in loops

Short-circuit when possible

Cache repeated queries

Improving Reliability

Add validation between steps

Include retry logic

Log intermediate results

Implement fallback paths

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

Content Pipeline Chain

Summary

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

Chaining Enables

Complex multi-step workflows

Higher quality through specialization

Better error handling and validation

Modular, reusable prompt components

Key Principles

Break complex tasks into simple steps

Design clear interfaces between steps

Validate intermediate outputs

Build in error handling and fallbacks

Optimize for your constraints

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.

What is the main advantage of prompt chaining over a single complex prompt?

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