Introduction
Welcome back! In our last lesson, we focused on improving the reliability of a single problem-solving step using self-consistency, where we generated multiple reasoning paths and used a majority vote to find the most robust answer. This was about adding depth and resilience to one action.
Today, we shift our focus from a single step to orchestrating an entire workflow. This lesson addresses the learning outcome: Apply prompt chaining to decompose complex tasks into a sequence of simpler, interconnected subtasks. Instead of asking an LLM to solve a complex problem in one go, we'll break it down into a logical sequence, where the output of one prompt becomes the input for the next. This is a fundamental software engineering pattern for building sophisticated and reliable LLM applications, moving you from writing prompts to designing intelligent pipelines. Mastering this is a crucial stepping stone toward the agentic systems you aim to build.
1. From a Single Prompt to a Multi-Step Workflow
A single, large prompt asking for a complex output can often fail. The model might miss instructions, lose context ("lost in the middle"), or hallucinate. Prompt chaining solves this by mimicking how a human expert would tackle a complex task: by breaking it down into manageable stages.

At its core, prompt chaining is the simple idea that the output of one LLM call is used as the input for a subsequent call.
How to Master the Art of Chain Prompting
For a clear conceptual overview, let's watch a short segment from the video 'How to Master the Art of Chain Prompting' by Mark Kashef.
Watch from the beginning to 01:39 and then from 03:14 to 05:45. Pay attention to the three primary scenarios where chaining is particularly useful: handling 'bloated' prompts, creating 'piecemeal pipelines,' and enabling 'progressive improvement.'
As the video explains, prompt chaining is not just a theoretical concept; it's a practical solution to common engineering challenges:
- Decomposition: Breaking down a large task, like writing a research report, into an outline, followed by drafting each section, and finally writing a conclusion.
- Progressive Refinement: Taking an initial output and iteratively improving it. For example, a first prompt generates a story, a second adjusts its tone, and a third makes it sound more human.
- Modularity and Maintenance: By splitting logic into smaller, focused prompts, you create a system that is easier to debug, test, and maintain. If one step is failing, you only need to fix that specific prompt, not a monolithic one.
2. A Practical Implementation: Sequential Chaining in Python
Let's move from concept to code. The most fundamental type of chain is a sequential chain, where prompts are executed in a linear order.
Given your experience, you'll appreciate that understanding the underlying logic without framework abstractions is the best starting point.
Prompt Chaining Tutorial: What Is Prompt Chaining and How to Use It?
The article 'Prompt Chaining Tutorial' from DataCamp provides an excellent, step-by-step guide to implementing prompt chaining in pure Python. We'll focus on the core implementation.
Please read the sections 'How to Implement Prompt Chaining' and the Python implementation steps that follow. Focus on how the prompt_chain function is constructed to pass the output of one get_completion call as part of the input to the next.
The approach detailed in the article is a clear and robust pattern. Let's analyze the Python code provided:
-
Task Identification: The complex task ("write a report on climate change") is broken down into four distinct subtasks:
- Summarize temperature trends.
- List relevant studies based on the trends.
- Summarize the findings of those studies.
- Propose mitigation strategies based on the findings.
-
Prompt Design: Each subtask gets its own focused prompt.
-
Chain Execution: The core logic resides in the
prompt_chainfunction.def prompt_chain(initial_prompt, follow_up_prompts): # 1. Execute the first prompt result = get_completion(initial_prompt) if result is None: return "Initial prompt failed." # 2. Loop through the subsequent prompts for i, prompt in enumerate(follow_up_prompts, 1): # 3. The magic: append the previous output to the new prompt full_prompt = f"{prompt}\n\nPrevious output: {result}" result = get_completion(full_prompt) # The result is updated if result is None: return f"Prompt {i} failed." return resultThis simple loop embodies the essence of chaining. The
resultvariable is continuously updated, carrying the context from one step to the next, building a progressively more detailed and comprehensive final output.
3. Advanced Chaining Patterns for Sophisticated Workflows
While sequential chains are powerful, real-world applications often require more complex logic. By introducing control flow, you can create dynamic and responsive systems.

Let's explore some of these advanced patterns.
Prompt Chaining Tutorial: What Is Prompt Chaining and How to Use It?
The DataCamp article also provides excellent code examples for more advanced techniques. These patterns are the building blocks for agentic behavior.
Read the section 'Prompt Chaining Techniques'. Pay close attention to the Python examples for 'Conditional Chaining' and 'Looping Chaining'.
Here is a summary of key chaining patterns:
| Pattern | Description | Use Case Example |
|---|---|---|
| Sequential | Prompts are executed in a fixed, linear order. | Generating a report: Outline -> Section 1 -> Section 2 -> Conclusion. |
| Conditional | The chain branches based on the output of a previous step. if-then logic. |
A chatbot analyzing sentiment: If the sentiment is negative, the next prompt asks about solutions; if positive, it asks about opportunities. |
| Looping/Iterative | A prompt or series of prompts is executed repeatedly to refine an output until a condition is met. | A code generation chain that generates code, runs a test, and if the test fails, loops back to a debugging prompt to fix the code. |
| Parallel | Multiple independent prompts are executed simultaneously to reduce latency. | A financial analysis tool that concurrently fetches market data, analyzes company fundamentals, and assesses risk before synthesizing the results. |
| Mix-and-Match | Using different LLMs for different steps in the chain based on their strengths. | Using a powerful, creative model like GPT-4 for brainstorming initial ideas, and a faster, cheaper model like Llama 3 8B for summarizing the final text. |
This "Mix-and-Match" strategy, in particular, is a hallmark of an elite AI engineer. It demonstrates a deep understanding of the cost-performance trade-offs between different models and is a key optimization technique for building efficient, production-grade systems.
Test your understanding!
You are tasked with building a system that takes a customer complaint email, analyzes it, and drafts a reply. Design a prompt chain to accomplish this. Which patterns would you use?
Show answer
A robust solution would use a combination of patterns:
- Step 1 (Sequential): A prompt to summarize the key issue from the email.
- Step 2 (Sequential): A prompt to categorize the issue (e.g., "Billing," "Technical," "Shipping").
- Step 3 (Conditional): Based on the category from Step 2, the chain branches.
- If "Billing," use a prompt template designed to address billing issues.
- If "Technical," use a prompt to look up relevant troubleshooting steps from a knowledge base.
- Step 4 (Sequential): A final prompt to draft a polite, empathetic email to the customer, incorporating the information from the previous steps.
This design uses both sequential and conditional chaining to create a dynamic and appropriate response.
4. Frameworks vs. Native Python: An Engineering Trade-off
As chains become more complex, managing them with simple Python functions can become cumbersome. This is where orchestration frameworks like LangChain come in. They provide high-level abstractions for building, executing, and debugging chains.
Prompt Engineering for LLMs, PDL, & LangChain in Action
The IBM Technology video 'Prompt Engineering for LLMs, PDL, & LangChain in Action' gives a great justification for why frameworks are useful in a professional software engineering context.
Watch from 03:17 to 06:45. Focus on how LangChain's 'runnables' are used to create a pipeline for processing a bug report. Notice how it incorporates steps for validation, retry/repair logic, and fallbacks—all crucial for production systems.
Frameworks like LangChain offer convenience, pre-built components, and integrations. However, this comes at a cost. As an experienced engineer, you must weigh the pros and cons:
- Pro-Framework: Faster development, built-in observability, standardized components, and a large ecosystem of tools and integrations.
- Pro-Native Python: Full control, no framework-specific abstractions to learn, easier debugging of underlying logic, avoidance of "framework lock-in," and often better performance due to less overhead.
The article "LLM Chaining - Techniques and Best Practices" by Mirascope makes a strong case for using native Python constructs, arguing that some framework abstractions (like LangChain Expression Language) can become "unmanageable and difficult to debug" for complex chains.
This is a key architectural decision you will face. The right choice depends on the project's complexity, the team's familiarity with the tools, and the required level of control and performance. A good practice is to start simple with native Python to fully understand the logic, and only introduce a framework when the complexity genuinely warrants it.
Conclusion
You have now learned how to apply prompt chaining, a technique that transforms you from a prompt writer into a workflow architect. By decomposing complex problems into a series of interconnected, manageable subtasks, you can build LLM applications that are more reliable, accurate, and maintainable.
Key Takeaways:
- Prompt chaining is a core engineering pattern where the output of one LLM call serves as the input for the next.
- It is used to decompose complexity, progressively refine outputs, and build modular, debuggable systems.
- Beyond simple sequential chains, advanced patterns like conditional, looping, and parallel chains enable dynamic and efficient workflows.
- A key optimization strategy is mix-and-match chaining, using the right model for the right subtask to balance performance and cost.
- There is an engineering trade-off between using orchestration frameworks like LangChain for convenience and using native Python for maximum control and transparency.
What's Next?
So far, our chains have operated on context generated within the chain itself. But what if a step in our chain needs access to external, up-to-date information or specific examples relevant to the user's query?
In the next lesson, we will tackle this by learning how to implement dynamic few-shot example selection using semantic similarity search. This is the first major step toward building Retrieval-Augmented Generation (RAG) systems, where you'll learn to dynamically fetch and inject relevant data into your prompts at runtime.