---
name: Prompt Chain Patterns
description: |
  Patterns for chaining prompts together: minimalist chainable, fusion chains,
  and multi-model orchestration for complex tasks.

  WHEN TO USE:
  - "Chain these prompts together"
  - "Build a prompt pipeline"
  - "Use fusion chain pattern"
  - "Multi-step LLM workflow"
  - Task too complex for single prompt
  - Need multiple model perspectives
  - Subsequent prompts depend on previous outputs

  CAPABILITIES:
  - Sequential prompt chaining
  - Fusion chains (multi-model)
  - Back-reference patterns
  - Evaluator-based selection

allowed-tools:
  - Read
---

# Prompt Chain Patterns

## Purpose

When a single prompt isn't enough, chain them together. More tokens to reason = better results. Prompt chains are a critical abstraction that won't disappear even as models improve.

## When to Use Chains vs Single Prompt

### Four Questions to Decide

1. **Is task too complex for single prompt?**
   - 2+ distantly related tasks → Use chain
   - Single focused task → Single prompt

2. **Need maximum performance?**
   - More tokens to reason = use chain
   - Speed over quality = single prompt

3. **Do subsequent prompts rely on previous outputs?**
   - Output dependencies → Definitely use chain
   - Independent outputs → Parallel or single

4. **Need adaptive workflow?**
   - Flow control needed → Use chain
   - Fixed output → Single prompt

## Pattern 1: Minimalist Chainable

Zero-library sequential chain with back-references:

```python
from minimal_chainable import run

results, context_filled = run(
    context={"topic": "AI agents"},
    model=claude_sonnet,
    callable=prompt_call,
    prompts=[
        "Generate blog title about {{topic}}. Return JSON: {title: string}",
        "Generate hook for: {{output[-1].title}}. Return JSON: {hook: string}",
        "Write intro using {{output[-2].title}} and {{output[-1].hook}}"
    ]
)
```

**Key Features:**
- `output[-1]` = previous prompt result
- `output[-2]` = two prompts back
- Context available to all prompts
- Single class, solves 80% of use cases

## Pattern 2: Fusion Chain

Multiply chains across multiple models, pick best:

```python
from fusion_chain import run_fusion

results = run_fusion(
    models=["claude-sonnet", "gpt-4o", "gemini-pro"],
    prompts=["Analyze this code...", "Suggest improvements..."],
    evaluator=rank_best_response  # Returns 0-1 score
)
```

**Architecture:**
```
Input → [Chain A (Claude)]  ─┐
      → [Chain B (GPT)]     ─┼→ Evaluator → Best Output
      → [Chain C (Gemini)]  ─┘
```

**Key Insight**: GPT-5 chain will STILL beat single GPT-5 prompt.

## Pattern 3: Architect-Editor Chain

Two-step chain for code generation:

```bash
aider --architect --editor-model claude-sonnet
```

**Flow:**
1. **Architect**: First model drafts the changes (planning)
2. **Editor**: Second model executes the draft (implementation)

**Variants:**
- Architect → Editor → Reviewer (3-step)
- 2 Architects → Lead Engineer (merger) → Editor
- o1 as Architect → Fast model as Editor

## Pattern 4: CEO and Board

Multiple models provide perspectives, CEO synthesizes:

```python
def ceo_and_board(prompt, board_models, ceo_model):
    board_responses = []
    for model in board_models:
        response = call_model(model, prompt)
        board_responses.append({"model": model, "response": response})

    ceo_prompt = f"""
    You are the CEO. Synthesize these board member responses:
    {json.dumps(board_responses)}

    Provide final recommendation considering all perspectives.
    """
    return call_model(ceo_model, ceo_prompt)
```

**Use Cases:** High-stakes decisions, architectural reviews, security audits.

## Chain Design Principles

1. **Each prompt = one focused task**
   - Don't overload a single prompt
   - Clear input/output contract

2. **Enable back-references**
   - `{{output[-1]}}` for previous result
   - Build context progressively

3. **Add evaluators for quality**
   - Define what "great result" means
   - Score outputs, pick best

4. **Consider parallel vs sequential**
   - Independent steps → Parallel
   - Dependencies → Sequential

## Example: Blog Writing Chain

```python
chain = [
    {
        "prompt": "Research keywords for: {{topic}}",
        "output": "keywords"
    },
    {
        "prompt": "Create outline using {{keywords}}",
        "output": "outline"
    },
    {
        "prompt": "Write intro based on {{outline}}",
        "output": "intro"
    },
    {
        "prompt": "Write body sections from {{outline}}",
        "output": "body"
    },
    {
        "prompt": "Write conclusion summarizing {{body}}",
        "output": "conclusion"
    },
    {
        "prompt": "Combine {{intro}}, {{body}}, {{conclusion}} into final post",
        "output": "final"
    }
]
```

## Cost/Performance Matrix

| Pattern | Cost | Speed | Quality |
|---------|------|-------|---------|
| Single prompt | Low | Fast | Variable |
| Sequential chain | Medium | Medium | High |
| Fusion chain | High | Slow | Highest |
| Architect-Editor | Medium | Medium | High |

## References

See `references/` for implementation examples.
