Generative AI & LLM

Module 4 of 16

Module 04: Prompt Chaining and Orchestration

5 min read828 words
What you'll learn
Decompose complex tasks into multi-step prompt chainsImplement sequential, parallel, and conditional chaining patternsBuild map-reduce workflows for processing large datasets with LLMsApply self-consistency techniques for more reliable outputsDesign robust multi-step workflows with error handling

Duration: 3 hours | Difficulty: Intermediate | Prerequisites: Modules 01–03

Learning Objectives

By the end of this module, you will be able to:

  • Decompose complex tasks into multi-step prompt chains
  • Implement sequential, parallel, and conditional chaining patterns
  • Build map-reduce workflows for processing large datasets with LLMs
  • Apply self-consistency techniques for more reliable outputs
  • Design robust multi-step workflows with error handling

1. Why Prompt Chaining?

The Single-Prompt Trap

One giant prompt is like asking someone to research, outline, write, edit, and fact-check in a single breath. Chains give each step a narrow job—higher quality, easier debugging.

One-shotChained
“Do everything”Extract → check → summarize → translate
Hard to testEach step inspectable
Errors entangledFailure localized

Concept: Chaining trades latency and cost for control—usually a good trade for anything customer-facing.

Try This! Take a task you do today in one prompt; break it into three prompts on paper before you open the IDE.

2. Sequential Chains

Output of step n becomes input (or context) for step n+1.

Step archetypeExample prompt role
ExtractPull claims, entities, numbers
ReasonCritique, score evidence
SynthesizeMerge into memo voice
FormatMarkdown table, JSON, slides outline

Key Example: Four-stage doc pipeline—each stage is a focused LLM call. In production you’d log intermediates.

python
[object Object], openai ,[object Object], OpenAI

client = OpenAI(api_key=,[object Object],)

,[object Object], ,[object Object],(,[object Object],) -> ,[object Object],:
    r = client.chat.completions.create(
        model=,[object Object],,
        messages=[
            {,[object Object],: ,[object Object],, ,[object Object],: system},
            {,[object Object],: ,[object Object],, ,[object Object],: prompt},
        ],
        temperature=,[object Object],,
    )
    ,[object Object], r.choices[,[object Object],].message.content


,[object Object], ,[object Object],(,[object Object],) -> ,[object Object],:
    extracted = llm(
        ,[object Object],,
        ,[object Object],,
    )
    analysis = llm(
        ,[object Object],,
        ,[object Object],,
    )
    recs = llm(
        ,[object Object],,
        ,[object Object],,
    )
    summary = llm(
        ,[object Object],,
        ,[object Object],,
    )
    ,[object Object], {
        ,[object Object],: extracted,
        ,[object Object],: analysis,
        ,[object Object],: recs,
        ,[object Object],: summary,
    }


doc = ,[object Object],
,[object Object],(sequential_chain(doc)[,[object Object],])

Key Takeaway

If a step’s output is messy, fix that step before adding new ones—downstream prompts amplify garbage.

3. Parallel Chains

When analyses don’t depend on each other, run them concurrently—wall-clock time drops.

Parallel-friendlyUsually sequential
Sentiment + entities + summary“Translate then summarize” if target lang affects summary
Per-chunk map phaseReduce that needs all chunks

Sketch: asyncio.gather around three async LLM calls, each with its own system prompt, then merge results in Python.

Fun Fact: Parallelism multiplies throughput; it also multiplies rate-limit pressure—add semaphores in prod.

4. Conditional Routing

Classify first, then dispatch to a specialist prompt pack.

StagePurpose
RouterCheap model + tight schema → intent label
SpecialistDomain system prompt + policies
Fallback“General” handler when confidence low
PatternBenefit
Intent → template IDStable analytics (“% billing tickets”)
Confidence thresholdEscalate to human or to stronger model

Try This! Write five user utterances that should collide in keywords but belong to different intents—test your router.

5. Map-Reduce Pattern

Map: run the same prompt on many chunks (summaries, extractions).
Reduce: one prompt merges partial outputs into a coherent whole.

PhaseFailure modeMitigation
MapLost numbers“Preserve all dollar amounts verbatim”
ReduceContradictionsAsk model to list conflicts explicitly

Concept: Map-reduce is how you stay inside context windows for book-scale inputs.

6. Self-Consistency

Sample multiple answers (higher temperature), then vote on the final short answer line. Great for riddles and fragile arithmetic; expensive for prose.

ProsCons
Boosts reliability on small output spacesNot automatic for open-ended essays

7. Building Reliable Multi-Step Workflows

HabitWhy
Structured logs per stepReplay and debug
Idempotency keysSafe retries
Timeouts per stepOne stall doesn’t wedge the queue
Human checkpointApprove before send/email/post

You can implement a tiny Chain class with depends_on (DAG) later—start with functions + dict context until you feel pain.

Key Takeaway

Reliability features (retries, timeouts, fallbacks) are part of the chain, not an afterthought.

Practice Exercises

Exercise 1: Translation Pipeline (Beginner)

Build a chain that: translates text to French → back-translates to English → compares the original with the back-translation to identify potential translation issues.

Exercise 2: Research Synthesizer (Intermediate)

Create a map-reduce chain that takes 5 article snippets on the same topic, extracts claims from each, identifies agreements/contradictions, and produces a balanced synthesis.

Exercise 3: Self-Consistency Calculator (Intermediate)

Implement self-consistency for math word problems. Test with 10 problems. Compare accuracy with and without self-consistency (use 1 sample vs. 5 samples with majority vote).

Exercise 4: Conditional Content Generator (Advanced)

Build a content pipeline that detects the input type (email, report, social post) and routes to specialized formatting chains. Each chain should have 3+ steps.

Exercise 5: Fault-Tolerant Pipeline (Advanced)

Extend a chain design to support: fallback steps (if step A fails, try step B), timeout per step, and a final “recovery” step that summarizes partial results if the chain doesn't fully complete.

Mini-Project: Automated Report Generator

Ingest CSV/JSON → parallel stats narratives → final Markdown report section → optional “consistency check” pass. Reuse your sequential pattern from section 2.

Key Takeaways

Key Takeaway

  • Decompose before you prompt; one job per call.
  • Parallelize independent analyses; sequence true dependencies.
  • Route by intent so specialists stay narrow.
  • Map-reduce scales RAG-ish workloads across chunks.
  • Self-consistency trades cost for stability on small structured answers.

Resources for Further Learning

← Previous: LLM APIs | Next: Embeddings & Vector Databases →