Agentic Architecture Pattern: Chain Prompting

Written by

in


    """
Pattern 194: Chain Prompting Pattern

Breaks complex tasks into a sequence of simpler prompts where each
prompt builds on previous outputs. Creates dependency chain of prompts.
"""

from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
from datetime import datetime
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI


@dataclass
class PromptStep:
    """Single step in prompt chain."""
    name: str
    prompt_template: str
    depends_on: List[str] = field(default_factory=list)
    output: Optional[str] = None
    timestamp: Optional[datetime] = None


@dataclass
class ChainExecution:
    """Execution trace of prompt chain."""
    steps: List[PromptStep]
    inputs: Dict[str, Any]
    outputs: Dict[str, str]
    execution_order: List[str]
    total_time: float = 0.0


class ChainPromptingAgent:
    """Agent that executes prompt chains."""
    
    def __init__(self, name: str, model_name: str = "gpt-4"):
        self.name = name
        self.llm = ChatOpenAI(model=model_name, temperature=0.7)
        self.steps: Dict[str, PromptStep] = {}
        self.executions: List[ChainExecution] = []
    
    def add_step(self, step: PromptStep):
        """Add step to chain."""
        self.steps[step.name] = step
        print(f"  Added step: {step.name}")
    
    def _resolve_dependencies(self) -> List[str]:
        """Resolve execution order based on dependencies."""
        executed = set()
        execution_order = []
        
        def can_execute(step_name: str) -> bool:
            step = self.steps[step_name]
            return all(dep in executed for dep in step.depends_on)
        
        while len(executed)  ChainExecution:
        """Execute the prompt chain."""
        print(f"\n  {self.name}: Executing prompt chain...")
        start_time = datetime.now()
        
        # Resolve execution order
        execution_order = self._resolve_dependencies()
        print(f"  Execution order: {' → '.join(execution_order)}")
        
        # Execute steps in order
        outputs = {}
        executed_steps = []
        
        for step_name in execution_order:
            step = self.steps[step_name]
            print(f"\n  Executing: {step_name}")
            
            # Prepare input by gathering dependencies
            step_input = initial_input.copy()
            for dep in step.depends_on:
                if dep in outputs:
                    step_input[dep] = outputs[dep]
            
            # Execute step
            prompt = ChatPromptTemplate.from_messages([
                ("system", "You are part of a multi-step reasoning chain."),
                ("human", step.prompt_template)
            ])
            
            chain = prompt | self.llm
            response = chain.invoke(step_input)
            
            output = response.content
            outputs[step_name] = output
            
            step.output = output
            step.timestamp = datetime.now()
            executed_steps.append(step)
            
            print(f"  Output: {output[:100]}...")
        
        end_time = datetime.now()
        execution = ChainExecution(
            steps=executed_steps,
            inputs=initial_input,
            outputs=outputs,
            execution_order=execution_order,
            total_time=(end_time - start_time).total_seconds()
        )
        
        self.executions.append(execution)
        return execution


class ChainPromptingPattern:
    """
    Chain Prompting Pattern - Sequential prompt dependencies.
    
    Breaks complex tasks into dependent steps where each step
    uses outputs from previous steps.
    """
    
    def __init__(self):
        self.agents: Dict[str, ChainPromptingAgent] = {}
    
    def register_agent(self, agent: ChainPromptingAgent):
        """Register chain prompting agent."""
        self.agents[agent.name] = agent
    
    def run(self, initial_inputs: Dict[str, Any]) -> Dict[str, Any]:
        """Execute prompt chains."""
        print("=== Chain Prompting Pattern ===\n")
        
        results = {}
        for agent in self.agents.values():
            execution = agent.execute_chain(initial_inputs)
            results[agent.name] = execution.outputs
        
        return {
            "pattern": "ChainPrompting",
            "agents": len(self.agents),
            "results": results,
            "total_steps": sum(len(a.steps) for a in self.agents.values())
        }


# Example usage
if __name__ == "__main__":
    print("=== Chain Prompting Pattern Demo ===\n")
    
    # Create pattern and agent
    pattern = ChainPromptingPattern()
    agent = ChainPromptingAgent("ArticleWriter")
    
    # Build prompt chain for article writing
    print("1. Building prompt chain...\n")
    
    # Step 1: Research (no dependencies)
    agent.add_step(PromptStep(
        name="research",
        prompt_template="Research key facts about: {topic}. List 5 important facts.",
        depends_on=[]
    ))
    
    # Step 2: Outline (depends on research)
    agent.add_step(PromptStep(
        name="outline",
        prompt_template="Create an article outline about {topic} using these facts:\n{research}",
        depends_on=["research"]
    ))
    
    # Step 3: Introduction (depends on outline)
    agent.add_step(PromptStep(
        name="introduction",
        prompt_template="Write an engaging introduction for this article:\nTopic: {topic}\nOutline: {outline}",
        depends_on=["outline"]
    ))
    
    # Step 4: Body (depends on outline and research)
    agent.add_step(PromptStep(
        name="body",
        prompt_template="Write the main body using:\nOutline: {outline}\nFacts: {research}",
        depends_on=["outline", "research"]
    ))
    
    # Step 5: Conclusion (depends on all previous)
    agent.add_step(PromptStep(
        name="conclusion",
        prompt_template="Write a conclusion that ties together:\nIntro: {introduction}\nBody: {body}",
        depends_on=["introduction", "body"]
    ))
    
    pattern.register_agent(agent)
    
    # Execute chain
    print("\n2. Executing chain...\n")
    summary = pattern.run({"topic": "Artificial Intelligence in Healthcare"})
    
    print(f"\n3. Summary:")
    print(f"   Total steps: {summary['total_steps']}")
    print(f"   Steps executed: {len(agent.executions[0].execution_order)}")
    
    print(f"\n4. Chain Outputs:")
    for step_name, output in agent.executions[0].outputs.items():
        print(f"\n   {step_name}:")
        print(f"   {output[:150]}...")
    
    print(f"\n   Total execution time: {agent.executions[0].total_time:.2f}s")
    
    print("\nāœ“ Chain prompting: sequential dependent prompts!")

    

Agentic Architecture Pattern: Chain Prompting

Pattern 194: 194 Chain Prompting Pattern – Line-by-Line Explanation

Overview

Pattern 194: Chain Prompting Pattern

Breaks complex tasks into a sequence of simpler prompts where each prompt builds on previous outputs. Creates dependency chain of prompts.


Code Structure Analysis

File Information

  • Pattern Number: 194
  • Pattern Name: 194 Chain Prompting Pattern
  • File Path: patterns\llm_specific\194_chain_prompting_pattern.py
  • Total Lines: 221

Detailed Code Explanation

Module Docstring

"""
Pattern 194: Chain Prompting Pattern

Breaks complex tasks into a sequence of simpler prompts where each
prompt builds on previous outputs. Creates dependency chain of prompts.
"""

Explanation: This module docstring describes the purpose and key features of the 194 Chain Prompting Pattern pattern.


Imports Section

from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
from datetime import datetime
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI  # First 20 imports shown

Explanation: The module imports necessary dependencies: – from typing import Dict, Any, List, Optional: Type hints for better code documentation – from dataclasses import dataclass, field: Data class decorators for clean data structures – from datetime import datetime: Date and time utilities – from langchain_core.prompts import ChatPromptTemplate: LangChain framework integration – from langchain_openai import ChatOpenAI: LangChain framework integration


Classes

PromptStep (Line 16)

Description: Single step in prompt chain.

ChainExecution (Line 26)

Description: Execution trace of prompt chain.

ChainPromptingAgent (Line 35)

Description: Agent that executes prompt chains.

Methods:

__init__ (Line 38)
def __init__(self, name, model_name):
    """No method docstring."""

Purpose: No method docstring.

Parameters: – self: Instance reference – name: Identifier or label – model_name: LLM model to use (e.g., “gpt-4”)

add_step (Line 44)
def add_step(self, step):
    """Add step to chain."""

Purpose: Add step to chain.

Parameters: – self: Instance reference – step: Parameter for step

_resolve_dependencies (Line 49)
def _resolve_dependencies(self):
    """Resolve execution order based on dependencies."""

Purpose: Resolve execution order based on dependencies.

Parameters: – self: Instance reference

execute_chain (Line 71)
def execute_chain(self, initial_input):
    """Execute the prompt chain."""

Purpose: Execute the prompt chain.

Parameters: – self: Instance reference – initial_input: Parameter for initial_input

ChainPromptingPattern (Line 125)

Description: Chain Prompting Pattern – Sequential prompt dependencies.

Breaks complex tasks into dependent steps where each step uses outputs from previous steps.

Methods:

__init__ (Line 133)
def __init__(self):
    """No method docstring."""

Purpose: No method docstring.

Parameters: – self: Instance reference

register_agent (Line 136)
def register_agent(self, agent):
    """Register chain prompting agent."""

Purpose: Register chain prompting agent.

Parameters: – self: Instance reference – agent: Parameter for agent

run (Line 140)
def run(self, initial_inputs):
    """Execute prompt chains."""

Purpose: Execute prompt chains.

Parameters: – self: Instance reference – initial_inputs: Parameter for initial_inputs


Design Patterns Used

  • Strategy Pattern: Different execution strategies for various scenarios
  • State Pattern: Managing different states in the workflow
  • Chain of Responsibility: Sequential processing through workflow nodes
  • Observer Pattern: Tracking and monitoring pattern execution
  • Factory Pattern: Creating instances with proper configuration

Usage Example

# Initialize the pattern
pattern = PromptStep(name="example", model_name="gpt-4")

# Configure and execute
result = pattern.execute(data={"key": "value"})

# Check results
print(result)

Key Concepts

  • LLM Integration: Uses LangChain/OpenAI for intelligent decision-making
  • Workflow Orchestration: LangGraph manages execution flow through nodes
  • State Management: TypedDict defines workflow state structure
  • Error Handling: Comprehensive error handling and fallback mechanisms
  • Extensibility: Designed for easy customization and extension

Extension Points

This pattern can be extended by: 1. Adding custom workflow nodes 2. Implementing additional validation logic 3. Integrating with external services 4. Customizing LLM prompts and responses 5. Adding monitoring and logging capabilities

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *