Skip to content

1.5 The Power of Prompt Chaining

Prompt Chaining as an Architectural Pattern

Figure 6. Prompt chaining.

Figure 6. Prompt chaining.

When a task becomes complicated, there is a natural temptation to write one big prompt that solves everything. This works poorly. The model gets lost in details, starts forgetting the beginning of the instructions by the end, and answer quality drops. Here an idea comes to the rescue that has long been known in traditional software development: divide and conquer.

Prompt chaining is the sequential execution of several requests to the model (Fig. 6), where the result of one step becomes the input for the next. Each step solves a narrow, specialized task and has a clear contract: a defined data structure comes in, and the model returns a predictable result. The chain as a whole performs a complex task that would be difficult or even impossible to solve with a single request.

A basic implementation looks roughly like this:

class PromptChain:
    def __init__(self, client):
        self.client = client
        self.steps = []
        self.intermediate_results = {}

    def add_step(self, name, prompt_template, output_parser=None):
        self.steps.append({
            "name": name,
            "prompt_template": prompt_template,
            "output_parser": output_parser or (lambda x: x)
        })
        return self

    def run(self, initial_input):
        current_input = initial_input

        for step in self.steps:
            prompt = step["prompt_template"].format(**current_input)

            response = self.client.responses.create(
                model="gpt-5-mini",
                input=[{"role": "user", "content": prompt}],
                temperature=0
            )

            raw_output = response.output_text
            parsed_output = step["output_parser"](raw_output)

            self.intermediate_results[step["name"]] = {
                "input": current_input,
                "raw_output": raw_output,
                "parsed_output": parsed_output
            }

            if isinstance(parsed_output, dict):
                current_input = {**current_input, **parsed_output}
            else:
                current_input = {**current_input, step["name"]: parsed_output}

        return current_input

Here each step has a name (for debugging and logging), a prompt template with placeholders such as {customer_name} (filled with data from the current context), and an optional parser to structure the output. Importantly, the intermediate results are saved. You can trace how the data was transformed at each step.

The reliability of the whole chain depends on how clearly the contracts between steps are defined. Each step must know: what data it receives as input, in what format it arrives, and in what format it must return the result. If the contracts are vague, a change in one step will sooner or later break the next one.

The best approach is to use JSON as the data format between steps. This gives several advantages at once. First, JSON is easy to parse and structure. Second, you can validate the schema (check that the response contains the expected fields). Third, it is convenient to log and analyze. And finally, it is a standard that everyone knows. Alternatives such as free text require more complex parsing and are less predictable.

Here is how typed data passing can look using Pydantic:

from pydantic import BaseModel, Field
from typing import List, Optional

class ExtractedFacts(BaseModel):
    customer_name: Optional[str] = None
    contact_info: Optional[str] = None
    problem_description: str
    mentioned_services: List[str] = Field(default_factory=list)
    urgency_indicators: List[str] = Field(default_factory=list)

class Categorization(BaseModel):
    category: str
    priority: str
    reasoning: str

def parse_json_response(response_text, model_class):
    json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
    if not json_match:
        raise ValueError("JSON not found in response")

    data = json.loads(json_match.group())
    return model_class(**data)

Pydantic models provide validation at the boundaries between steps. If the model returns a response that does not match the expected schema, the error surfaces immediately instead of propagating down the chain and causing a problem in some later step.

Flow Control and Branching

Figure 7. Flow control and branching.

Figure 7. Flow control and branching.

Applications often need conditional logic. The result of one step can determine which step should run next. Imagine a system for handling customer requests. If the analysis shows that this is a complaint (COMPLAINT), an additional check and possibly an escalation are needed. If it is simply an information request (INFORMATION), it may be enough to search the knowledge base and return a ready answer (Fig. 7). Why generate an answer if the knowledge base already has a suitable one?

Such an architecture requires a conditional chain with routing:

class ConditionalChain:
    def __init__(self, client):
        self.client = client
        self.steps = {}
        self.routing_rules = {}

    def add_step(self, name, prompt_template, output_parser=None):
        self.steps[name] = {
            "prompt_template": prompt_template,
            "output_parser": output_parser or (lambda x: x)
        }
        return self

    def add_route(self, from_step, condition_fn, to_step):
        if from_step not in self.routing_rules:
            self.routing_rules[from_step] = []
        self.routing_rules[from_step].append((condition_fn, to_step))
        return self

    def run(self, start_step, initial_input):
        current_step = start_step
        current_input = initial_input
        execution_path = []

        while current_step:
            step_config = self.steps[current_step]
            prompt = step_config["prompt_template"].format(**current_input)

            response = self.call_model(prompt)
            parsed = step_config["output_parser"](response)

            execution_path.append({
                "step": current_step,
                "input": current_input,
                "output": parsed
            })

            if isinstance(parsed, dict):
                current_input = {**current_input, **parsed}
            else:
                current_input = {**current_input, current_step: parsed}

            next_step = None
            for condition_fn, to_step in self.routing_rules.get(current_step, []):
                if condition_fn(current_input):
                    next_step = to_step
                    break

            current_step = next_step

        return current_input, execution_path

This architecture makes it possible to build complex workflows while keeping each step simple and easy to test. The condition function (condition_fn) can be a simple check on the category or more complex logic based on many fields.

Saving Resources Through Conditional Execution

Another important point: chains let you save resources by skipping unnecessary steps. If your application serves customers and the first step determines that a request needs a minimal reply from a template, why generate a full response? Skip the generation and return to the user right away.

Here is what this can look like in code:

def process_inquiry(message):
    facts = extract_facts(message)
    category = categorize(facts)

    if category["category"] == "INFORMATION" and is_faq_question(facts):
        return get_faq_response(facts["problem_description"])

    if category["priority"] == "LOW" and category["category"] == "OTHER":
        return get_generic_acknowledgment(facts.get("customer_name"))

    draft = generate_response(facts, category)
    final = validate_response(draft, category)

    return final

The logic is simple: first we extract the facts and categorize the request. If it is just a FAQ question, we return a prepared answer. If it is a low-priority request for another reason, we return a standard confirmation. Only for complex cases do we run full generation and validation. This not only saves tokens and money but also improves latency for simple cases.

Error Handling in Chains

When a chain consists of several steps, it is logical that it can break at any one of them. For example, the API may be unavailable, the model may decide to return invalid JSON, or the data may not match the expected format. A reliable system needs a good recovery strategy.

There are several approaches. The first: retry with the same input. This works for temporary API errors or random generation failures. If a step did not return valid JSON, a repeated request often produces a correct result. The second approach: fallback to a simplified version. If the main step systematically fails on a certain type of input, you can switch to a simpler prompt or a different model. And the third: graceful degradation, when the system returns a partial result instead of a complete failure. For requests, this may mean returning the extracted facts without a generated answer, so that an operator can handle the request manually.

Here is an implementation with recovery:

def run_chain_with_recovery(chain, initial_input):
    results = {"input": initial_input, "completed_steps": [], "errors": []}
    current_input = initial_input

    for step in chain.steps:
        try:
            output = run_step_with_retry(step, current_input, max_retries=2)
            results["completed_steps"].append(step["name"])

            if isinstance(output, dict):
                current_input = {**current_input, **output}
            else:
                current_input = {**current_input, step["name"]: output}

        except StepExecutionError as e:
            results["errors"].append({
                "step": step["name"],
                "error": str(e),
                "input": current_input
            })

            if step.get("required", True):
                results["status"] = "PARTIAL"
                break

    if not results["errors"]:
        results["status"] = "COMPLETE"

    results["final_output"] = current_input
    return results

Here each step is checked for the required flag. If a required step fails, the chain stops. If the step is optional, execution continues. The result status (COMPLETE or PARTIAL) helps the higher-level logic decide what to do next.

Questions for Reflection and Practice

Theoretical questions

  1. Explain the concept of prompt chaining and its connection to traditional data-processing pipelines (pipes, the Unix philosophy).

  2. What role do the contracts between chain steps play, and what are the consequences of defining them vaguely?

  3. Why is JSON the preferred format for passing data between steps, and what alternatives exist?

  4. How does branching in chains enable adaptive workflows, and what criteria determine the choice of the next step?

  5. Describe strategies for saving resources through conditional execution of steps, and give examples of situations where this applies.

  6. What approaches to error handling in chains do you know (retry, fallback, graceful degradation), and how do you choose the right one for a given situation?

  7. How do you organize logging and auditing of chain execution for later debugging and problem analysis?

  8. In which cases does splitting a task into a chain of prompts have advantages over one complex prompt?

  9. How do you test individual chain steps in isolation, and how do you test the chain as a whole?

  10. Which design patterns from traditional software development (Strategy, Chain of Responsibility, State Machine) apply to prompt chaining?

  11. How do you manage prompt versioning in a chain during iterative development?

  12. Describe the trade-offs between chain depth and the overall execution latency.

Practical exercises

  1. Implement the base class PromptChain with methods for adding steps and running them sequentially.

  2. Create a function that extracts structured entities from text, validated with a Pydantic model.

  3. Build a minimal product database and implement a chain for processing requests: intent extraction, product search, response generation.

  4. Implement a parser for JSON responses that handles different output formats from the model (with backticks, without them, with Markdown).

  5. Create a response formatting system with templates for different request categories (complaint, information, question).

  6. Build an end-to-end customer service scenario: from an incoming message to a finished response, with logging of all intermediate steps.