Agentic Orchestration Pattern: Chain of Responsibility

Written by

in


    """
Pattern 17.04: Chain of Responsibility
Request passed through processing chain
"""
from typing import TypedDict
from langgraph.graph import StateGraph, END
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage


class ChainOfResponsibilityState(TypedDict):
    """State for Chain of Responsibility pattern."""
    input: str
    output: str
    metadata: dict


def agent_function(state: ChainOfResponsibilityState) -> ChainOfResponsibilityState:
    """Chain of Responsibility agent implementation."""
    llm = ChatOpenAI()
    prompt = f"Process using Chain of Responsibility: {state['input']}"
    response = llm.invoke([HumanMessage(content=prompt)])
    state["output"] = str(response.content)
    state["metadata"] = {"pattern": "Chain of Responsibility", "status": "completed"}
    return state


def create_chain_of_responsibility():
    """Create Chain of Responsibility workflow."""
    workflow = StateGraph(ChainOfResponsibilityState)
    workflow.add_node("agent", agent_function)
    workflow.set_entry_point("agent")
    workflow.add_edge("agent", END)
    return workflow.compile()


if __name__ == "__main__":
    workflow = create_chain_of_responsibility()
    result = workflow.invoke({"input": "Test Chain of Responsibility", "output": "", "metadata": {}})
    print(f"\n=== Chain of Responsibility Pattern ===\nOutput: {result['output'][:200]}...")

    

Agentic Orchestration Pattern: Chain of Responsibility

04 Chain Of Responsibility Pattern – Detailed Documentation

Overview

File: 17_composition/04_chain_of_responsibility.py
Pattern Category: 17 Composition
Implementation: LangGraph/CrewAI

Pattern Description

Pattern 17.04: Chain of Responsibility Request passed through processing chain


Code Structure

Imports

from typing import TypedDict
from langgraph.graph import StateGraph, END
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage

Purpose of imports: – TypedDict: For type-safe state definitions – StateGraph: LangGraph’s graph-based workflow orchestration – ChatOpenAI: OpenAI LLM integration – HumanMessage: LangChain message formatting

State Definition

class ChainOfResponsibilityState(TypedDict):
    """State for Chain of Responsibility pattern."""
    input: str
    output: str
    metadata: dict


def agent_function(state: ChainOfResponsibilityState) -> ChainOfResponsibilityState:

ChainOfResponsibilityState: State for Chain of Responsibility pattern.

State Fields: – input: Stores input – output: Stores output – metadata: Stores metadata – def agent_function(state: Stores def agent function(state – prompt = f"Process using Chain of Responsibility: Stores prompt = f”Process using Chain of Responsibility – state["metadata"] = {"pattern": Stores state[“metadata”] = {“pattern”


Functions

agent_function()

Line: 18
Arguments: state

Chain of Responsibility agent implementation.

def agent_function(state: ChainOfResponsibilityState) -> ChainOfResponsibilityState:
    """Chain of Responsibility agent implementation."""
    llm = ChatOpenAI()
    prompt = f"Process using Chain of Responsibility: {state['input']}"
    response = llm.invoke([HumanMessage(content=prompt)])
    state["output"] = str(response.content)
    state["metadata"] = {"pattern": "Chain of Responsibility", "status": "completed"}
    return state


def create_chain_of_responsibility():

create_chain_of_responsibility()

Line: 28
Arguments: “

Create Chain of Responsibility workflow.

def create_chain_of_responsibility():
    """Create Chain of Responsibility workflow."""
    workflow = StateGraph(ChainOfResponsibilityState)
    workflow.add_node("agent", agent_function)
    workflow.set_entry_point("agent")
    workflow.add_edge("agent", END)
    return workflow.compile()


if __name__ == "__main__":

Line-by-Line Explanation

Line 5: Import statement

from typing import TypedDict

Imports TypedDict for creating type-safe state dictionaries.

Line 6: Import statement

from langgraph.graph import StateGraph, END

Imports StateGraph – the core LangGraph class for building workflows.

Line 7: Import statement

from langchain_openai import ChatOpenAI

Imports ChatOpenAI for LLM interactions.

Line 8: Import statement

from langchain_core.messages import HumanMessage

Imports HumanMessage for formatting prompts to the LLM.

Line 11: Class definition

class ChainOfResponsibilityState(TypedDict):

Defines the state structure using TypedDict for type safety.

Line 12: Module docstring

    """State for Chain of Responsibility pattern."""

Describes the pattern and its purpose.

Line 18: Function agent_function definition

def agent_function(state: ChainOfResponsibilityState) -> ChainOfResponsibilityState:

Defines the agent_function function that processes the workflow state.

Line 19: Module docstring

    """Chain of Responsibility agent implementation."""

Describes the pattern and its purpose.

Line 28: Function create_chain_of_responsibility definition

def create_chain_of_responsibility():

Defines the create_chain_of_responsibility function that processes the workflow state.

Line 29: Module docstring

    """Create Chain of Responsibility workflow."""

Describes the pattern and its purpose.


Usage Example

if __name__ == "__main__":
    workflow = create_chain_of_responsibility()
    result = workflow.invoke({"input": "Test Chain of Responsibility", "output": "", "metadata": {}})
    print(f"\n=== Chain of Responsibility Pattern ===\nOutput: {result['output'][:200]}...")

Key Concepts

  1. State Management: Uses TypedDict to maintain workflow state
  2. Graph-Based Flow: LangGraph orchestrates execution flow
  3. Agent Functions: Each node processes and updates state
  4. LLM Integration: Uses ChatOpenAI for intelligent processing

Pattern Benefits

  • ✅ Type-safe state management
  • ✅ Clear workflow visualization
  • ✅ Modular and reusable components
  • ✅ Easy to test and debug
  • ✅ Scalable architecture

Related Patterns

  • See other patterns in the same category
  • Explore combination possibilities
  • Check the main documentation for pattern relationships

Comments

Leave a Reply

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