Tag: llm

  • Agentic Orchestration Pattern: Fan-Out/Fan-In Pattern

    
        """
    Pattern 10.02: Fan-Out-Fan-In
    Distribute work to multiple agents and collect results
    """
    from typing import TypedDict
    from langgraph.graph import StateGraph, END
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage
    
    
    class FanOutFanInState(TypedDict):
        """State for Fan-Out-Fan-In pattern."""
        input: str
        output: str
    
    
    def agent_function(state: FanOutFanInState) -> FanOutFanInState:
        """Fan-Out-Fan-In agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Fan-Out-Fan-In pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_fan_out_fan_in():
        """Create Fan-Out-Fan-In workflow."""
        workflow = StateGraph(FanOutFanInState)
        workflow.add_node("agent", agent_function)
        workflow.set_entry_point("agent")
        workflow.add_edge("agent", END)
        return workflow.compile()
    
    
    if __name__ == "__main__":
        workflow = create_fan_out_fan_in()
        result = workflow.invoke({"input": "Test Fan-Out-Fan-In", "output": ""})
        print(f"\n=== Fan-Out-Fan-In Pattern ===\nOutput: {result['output'][:200]}...")
    
        

    Agentic Orchestration Pattern: Fan-Out/Fan-In Pattern

    02 Fan Out Fan In Pattern – Detailed Documentation

    Overview

    File: 10_optimization/02_fan_out_fan_in.py
    Pattern Category: 10 Optimization
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 10.02: Fan-Out-Fan-In Distribute work to multiple agents and collect results


    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 FanOutFanInState(TypedDict):
        """State for Fan-Out-Fan-In pattern."""
        input: str
        output: str
    
    
    def agent_function(state: FanOutFanInState) -> FanOutFanInState:
    

    FanOutFanInState: State for Fan-Out-Fan-In pattern.

    State Fields: – input: Stores input – output: Stores output – def agent_function(state: Stores def agent function(state – prompt = f"Process this using Fan-Out-Fan-In pattern: Stores prompt = f”Process this using Fan-Out-Fan-In pattern – def create_fan_out_fan_in(): Stores def create fan out fan in()


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Fan-Out-Fan-In agent implementation.

    def agent_function(state: FanOutFanInState) -> FanOutFanInState:
        """Fan-Out-Fan-In agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Fan-Out-Fan-In pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_fan_out_fan_in():
    

    create_fan_out_fan_in()

    Line: 26
    Arguments: “

    Create Fan-Out-Fan-In workflow.

    def create_fan_out_fan_in():
        """Create Fan-Out-Fan-In workflow."""
        workflow = StateGraph(FanOutFanInState)
        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 FanOutFanInState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Fan-Out-Fan-In pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: FanOutFanInState) -> FanOutFanInState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Fan-Out-Fan-In agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_fan_out_fan_in definition

    def create_fan_out_fan_in():
    

    Defines the create_fan_out_fan_in function that processes the workflow state.

    Line 27: Module docstring

        """Create Fan-Out-Fan-In workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

    if __name__ == "__main__":
        workflow = create_fan_out_fan_in()
        result = workflow.invoke({"input": "Test Fan-Out-Fan-In", "output": ""})
        print(f"\n=== Fan-Out-Fan-In 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
  • Agentic Orchestration Pattern: Map-Reduce Pattern

    
        """
    Pattern 10.01: Map-Reduce
    Parallel processing of data chunks with aggregation
    """
    from typing import TypedDict
    from langgraph.graph import StateGraph, END
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage
    
    
    class MapReduceState(TypedDict):
        """State for Map-Reduce pattern."""
        input: str
        output: str
    
    
    def agent_function(state: MapReduceState) -> MapReduceState:
        """Map-Reduce agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Map-Reduce pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_map_reduce():
        """Create Map-Reduce workflow."""
        workflow = StateGraph(MapReduceState)
        workflow.add_node("agent", agent_function)
        workflow.set_entry_point("agent")
        workflow.add_edge("agent", END)
        return workflow.compile()
    
    
    if __name__ == "__main__":
        workflow = create_map_reduce()
        result = workflow.invoke({"input": "Test Map-Reduce", "output": ""})
        print(f"\n=== Map-Reduce Pattern ===\nOutput: {result['output'][:200]}...")
    
        

    Agentic Orchestration Pattern: Map-Reduce Pattern

    01 Map Reduce Pattern – Detailed Documentation

    Overview

    File: 10_optimization/01_map_reduce.py
    Pattern Category: 10 Optimization
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 10.01: Map-Reduce Parallel processing of data chunks with aggregation


    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 MapReduceState(TypedDict):
        """State for Map-Reduce pattern."""
        input: str
        output: str
    
    
    def agent_function(state: MapReduceState) -> MapReduceState:
    

    MapReduceState: State for Map-Reduce pattern.

    State Fields: – input: Stores input – output: Stores output – def agent_function(state: Stores def agent function(state – prompt = f"Process this using Map-Reduce pattern: Stores prompt = f”Process this using Map-Reduce pattern – def create_map_reduce(): Stores def create map reduce()


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Map-Reduce agent implementation.

    def agent_function(state: MapReduceState) -> MapReduceState:
        """Map-Reduce agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Map-Reduce pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_map_reduce():
    

    create_map_reduce()

    Line: 26
    Arguments: “

    Create Map-Reduce workflow.

    def create_map_reduce():
        """Create Map-Reduce workflow."""
        workflow = StateGraph(MapReduceState)
        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 MapReduceState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Map-Reduce pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: MapReduceState) -> MapReduceState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Map-Reduce agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_map_reduce definition

    def create_map_reduce():
    

    Defines the create_map_reduce function that processes the workflow state.

    Line 27: Module docstring

        """Create Map-Reduce workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

    if __name__ == "__main__":
        workflow = create_map_reduce()
        result = workflow.invoke({"input": "Test Map-Reduce", "output": ""})
        print(f"\n=== Map-Reduce 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
  • Agentic Orchestration Pattern: Compensation Pattern

    
        """
    Pattern 09.04: Compensation
    Rollback on failure with compensating transactions
    """
    from typing import TypedDict
    from langgraph.graph import StateGraph, END
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage
    
    
    class CompensationState(TypedDict):
        """State for Compensation pattern."""
        input: str
        output: str
    
    
    def agent_function(state: CompensationState) -> CompensationState:
        """Compensation agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Compensation pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_compensation():
        """Create Compensation workflow."""
        workflow = StateGraph(CompensationState)
        workflow.add_node("agent", agent_function)
        workflow.set_entry_point("agent")
        workflow.add_edge("agent", END)
        return workflow.compile()
    
    
    if __name__ == "__main__":
        workflow = create_compensation()
        result = workflow.invoke({"input": "Test Compensation", "output": ""})
        print(f"\n=== Compensation Pattern ===\nOutput: {result['output'][:200]}...")
    
        

    Agentic Orchestration Pattern: Compensation Pattern

    04 Compensation Pattern – Detailed Documentation

    Overview

    File: 09_error_handling/04_compensation.py
    Pattern Category: 09 Error Handling
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 09.04: Compensation Rollback on failure with compensating transactions


    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 CompensationState(TypedDict):
        """State for Compensation pattern."""
        input: str
        output: str
    
    
    def agent_function(state: CompensationState) -> CompensationState:
    

    CompensationState: State for Compensation pattern.

    State Fields: – input: Stores input – output: Stores output – def agent_function(state: Stores def agent function(state – prompt = f"Process this using Compensation pattern: Stores prompt = f”Process this using Compensation pattern – def create_compensation(): Stores def create compensation()


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Compensation agent implementation.

    def agent_function(state: CompensationState) -> CompensationState:
        """Compensation agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Compensation pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_compensation():
    

    create_compensation()

    Line: 26
    Arguments: “

    Create Compensation workflow.

    def create_compensation():
        """Create Compensation workflow."""
        workflow = StateGraph(CompensationState)
        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 CompensationState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Compensation pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: CompensationState) -> CompensationState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Compensation agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_compensation definition

    def create_compensation():
    

    Defines the create_compensation function that processes the workflow state.

    Line 27: Module docstring

        """Create Compensation workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

    if __name__ == "__main__":
        workflow = create_compensation()
        result = workflow.invoke({"input": "Test Compensation", "output": ""})
        print(f"\n=== Compensation 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
  • Agentic Orchestration Pattern: Bulkhead Pattern

    
        """
    Pattern 09.03: Bulkhead
    Isolate failures through resource partitioning
    """
    from typing import TypedDict
    from langgraph.graph import StateGraph, END
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage
    
    
    class BulkheadState(TypedDict):
        """State for Bulkhead pattern."""
        input: str
        output: str
    
    
    def agent_function(state: BulkheadState) -> BulkheadState:
        """Bulkhead agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Bulkhead pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_bulkhead():
        """Create Bulkhead workflow."""
        workflow = StateGraph(BulkheadState)
        workflow.add_node("agent", agent_function)
        workflow.set_entry_point("agent")
        workflow.add_edge("agent", END)
        return workflow.compile()
    
    
    if __name__ == "__main__":
        workflow = create_bulkhead()
        result = workflow.invoke({"input": "Test Bulkhead", "output": ""})
        print(f"\n=== Bulkhead Pattern ===\nOutput: {result['output'][:200]}...")
    
        

    Agentic Orchestration Pattern: Bulkhead Pattern

    03 Bulkhead Pattern – Detailed Documentation

    Overview

    File: 09_error_handling/03_bulkhead.py
    Pattern Category: 09 Error Handling
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 09.03: Bulkhead Isolate failures through resource partitioning


    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 BulkheadState(TypedDict):
        """State for Bulkhead pattern."""
        input: str
        output: str
    
    
    def agent_function(state: BulkheadState) -> BulkheadState:
    

    BulkheadState: State for Bulkhead pattern.

    State Fields: – input: Stores input – output: Stores output – def agent_function(state: Stores def agent function(state – prompt = f"Process this using Bulkhead pattern: Stores prompt = f”Process this using Bulkhead pattern – def create_bulkhead(): Stores def create bulkhead()


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Bulkhead agent implementation.

    def agent_function(state: BulkheadState) -> BulkheadState:
        """Bulkhead agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Bulkhead pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_bulkhead():
    

    create_bulkhead()

    Line: 26
    Arguments: “

    Create Bulkhead workflow.

    def create_bulkhead():
        """Create Bulkhead workflow."""
        workflow = StateGraph(BulkheadState)
        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 BulkheadState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Bulkhead pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: BulkheadState) -> BulkheadState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Bulkhead agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_bulkhead definition

    def create_bulkhead():
    

    Defines the create_bulkhead function that processes the workflow state.

    Line 27: Module docstring

        """Create Bulkhead workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

    if __name__ == "__main__":
        workflow = create_bulkhead()
        result = workflow.invoke({"input": "Test Bulkhead", "output": ""})
        print(f"\n=== Bulkhead 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
  • Agentic Orchestration Pattern: Circuit Breaker Pattern

    
        """
    Pattern 09.02: Circuit Breaker
    Prevent cascade failures
    """
    from typing import TypedDict
    from langgraph.graph import StateGraph, END
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage
    
    
    class CircuitBreakerState(TypedDict):
        """State for Circuit Breaker pattern."""
        input: str
        output: str
    
    
    def agent_function(state: CircuitBreakerState) -> CircuitBreakerState:
        """Circuit Breaker agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Circuit Breaker pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_circuit_breaker():
        """Create Circuit Breaker workflow."""
        workflow = StateGraph(CircuitBreakerState)
        workflow.add_node("agent", agent_function)
        workflow.set_entry_point("agent")
        workflow.add_edge("agent", END)
        return workflow.compile()
    
    
    if __name__ == "__main__":
        workflow = create_circuit_breaker()
        result = workflow.invoke({"input": "Test Circuit Breaker", "output": ""})
        print(f"\n=== Circuit Breaker Pattern ===\nOutput: {result['output'][:200]}...")
    
        

    Agentic Orchestration Pattern: Circuit Breaker Pattern

    02 Circuit Breaker Pattern – Detailed Documentation

    Overview

    File: 09_error_handling/02_circuit_breaker.py
    Pattern Category: 09 Error Handling
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 09.02: Circuit Breaker Prevent cascade failures


    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 CircuitBreakerState(TypedDict):
        """State for Circuit Breaker pattern."""
        input: str
        output: str
    
    
    def agent_function(state: CircuitBreakerState) -> CircuitBreakerState:
    

    CircuitBreakerState: State for Circuit Breaker pattern.

    State Fields: – input: Stores input – output: Stores output – def agent_function(state: Stores def agent function(state – prompt = f"Process this using Circuit Breaker pattern: Stores prompt = f”Process this using Circuit Breaker pattern – def create_circuit_breaker(): Stores def create circuit breaker()


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Circuit Breaker agent implementation.

    def agent_function(state: CircuitBreakerState) -> CircuitBreakerState:
        """Circuit Breaker agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Circuit Breaker pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_circuit_breaker():
    

    create_circuit_breaker()

    Line: 26
    Arguments: “

    Create Circuit Breaker workflow.

    def create_circuit_breaker():
        """Create Circuit Breaker workflow."""
        workflow = StateGraph(CircuitBreakerState)
        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 CircuitBreakerState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Circuit Breaker pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: CircuitBreakerState) -> CircuitBreakerState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Circuit Breaker agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_circuit_breaker definition

    def create_circuit_breaker():
    

    Defines the create_circuit_breaker function that processes the workflow state.

    Line 27: Module docstring

        """Create Circuit Breaker workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

    if __name__ == "__main__":
        workflow = create_circuit_breaker()
        result = workflow.invoke({"input": "Test Circuit Breaker", "output": ""})
        print(f"\n=== Circuit Breaker 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
  • Agentic Orchestration Pattern: Try-Catch Pattern

    
        """
    Pattern 09.01: Try-Catch
    Error detection and handling with recovery
    """
    from typing import TypedDict
    from langgraph.graph import StateGraph, END
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage
    
    
    class TryCatchState(TypedDict):
        """State for Try-Catch pattern."""
        input: str
        output: str
    
    
    def agent_function(state: TryCatchState) -> TryCatchState:
        """Try-Catch agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Try-Catch pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_try_catch():
        """Create Try-Catch workflow."""
        workflow = StateGraph(TryCatchState)
        workflow.add_node("agent", agent_function)
        workflow.set_entry_point("agent")
        workflow.add_edge("agent", END)
        return workflow.compile()
    
    
    if __name__ == "__main__":
        workflow = create_try_catch()
        result = workflow.invoke({"input": "Test Try-Catch", "output": ""})
        print(f"\n=== Try-Catch Pattern ===\nOutput: {result['output'][:200]}...")
    
        

    Agentic Orchestration Pattern: Try-Catch Pattern

    01 Try Catch Pattern – Detailed Documentation

    Overview

    File: 09_error_handling/01_try_catch.py
    Pattern Category: 09 Error Handling
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 09.01: Try-Catch Error detection and handling with recovery


    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 TryCatchState(TypedDict):
        """State for Try-Catch pattern."""
        input: str
        output: str
    
    
    def agent_function(state: TryCatchState) -> TryCatchState:
    

    TryCatchState: State for Try-Catch pattern.

    State Fields: – input: Stores input – output: Stores output – def agent_function(state: Stores def agent function(state – prompt = f"Process this using Try-Catch pattern: Stores prompt = f”Process this using Try-Catch pattern – def create_try_catch(): Stores def create try catch()


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Try-Catch agent implementation.

    def agent_function(state: TryCatchState) -> TryCatchState:
        """Try-Catch agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Try-Catch pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_try_catch():
    

    create_try_catch()

    Line: 26
    Arguments: “

    Create Try-Catch workflow.

    def create_try_catch():
        """Create Try-Catch workflow."""
        workflow = StateGraph(TryCatchState)
        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 TryCatchState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Try-Catch pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: TryCatchState) -> TryCatchState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Try-Catch agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_try_catch definition

    def create_try_catch():
    

    Defines the create_try_catch function that processes the workflow state.

    Line 27: Module docstring

        """Create Try-Catch workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

    if __name__ == "__main__":
        workflow = create_try_catch()
        result = workflow.invoke({"input": "Test Try-Catch", "output": ""})
        print(f"\n=== Try-Catch 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
  • Agentic Orchestration Pattern: Blackboard Pattern

    
        """
    Pattern 08.04: Blackboard
    Shared knowledge space for collaborative problem solving
    """
    from typing import TypedDict
    from langgraph.graph import StateGraph, END
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage
    
    
    class BlackboardState(TypedDict):
        """State for Blackboard pattern."""
        input: str
        output: str
    
    
    def agent_function(state: BlackboardState) -> BlackboardState:
        """Blackboard agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Blackboard pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_blackboard():
        """Create Blackboard workflow."""
        workflow = StateGraph(BlackboardState)
        workflow.add_node("agent", agent_function)
        workflow.set_entry_point("agent")
        workflow.add_edge("agent", END)
        return workflow.compile()
    
    
    if __name__ == "__main__":
        workflow = create_blackboard()
        result = workflow.invoke({"input": "Test Blackboard", "output": ""})
        print(f"\n=== Blackboard Pattern ===\nOutput: {result['output'][:200]}...")
    
        

    Agentic Orchestration Pattern: Blackboard Pattern

    04 Blackboard Pattern – Detailed Documentation

    Overview

    File: 08_state_management/04_blackboard.py
    Pattern Category: 08 State Management
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 08.04: Blackboard Shared knowledge space for collaborative problem solving


    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 BlackboardState(TypedDict):
        """State for Blackboard pattern."""
        input: str
        output: str
    
    
    def agent_function(state: BlackboardState) -> BlackboardState:
    

    BlackboardState: State for Blackboard pattern.

    State Fields: – input: Stores input – output: Stores output – def agent_function(state: Stores def agent function(state – prompt = f"Process this using Blackboard pattern: Stores prompt = f”Process this using Blackboard pattern – def create_blackboard(): Stores def create blackboard()


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Blackboard agent implementation.

    def agent_function(state: BlackboardState) -> BlackboardState:
        """Blackboard agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Blackboard pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_blackboard():
    

    create_blackboard()

    Line: 26
    Arguments: “

    Create Blackboard workflow.

    def create_blackboard():
        """Create Blackboard workflow."""
        workflow = StateGraph(BlackboardState)
        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 BlackboardState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Blackboard pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: BlackboardState) -> BlackboardState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Blackboard agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_blackboard definition

    def create_blackboard():
    

    Defines the create_blackboard function that processes the workflow state.

    Line 27: Module docstring

        """Create Blackboard workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

    if __name__ == "__main__":
        workflow = create_blackboard()
        result = workflow.invoke({"input": "Test Blackboard", "output": ""})
        print(f"\n=== Blackboard 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
  • Agentic Orchestration Pattern: Memory Pattern

    
        """
    Pattern 08.03: Memory
    Persistent memory across interactions
    """
    from typing import TypedDict
    from langgraph.graph import StateGraph, END
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage
    
    
    class MemoryState(TypedDict):
        """State for Memory pattern."""
        input: str
        output: str
    
    
    def agent_function(state: MemoryState) -> MemoryState:
        """Memory agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Memory pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_memory():
        """Create Memory workflow."""
        workflow = StateGraph(MemoryState)
        workflow.add_node("agent", agent_function)
        workflow.set_entry_point("agent")
        workflow.add_edge("agent", END)
        return workflow.compile()
    
    
    if __name__ == "__main__":
        workflow = create_memory()
        result = workflow.invoke({"input": "Test Memory", "output": ""})
        print(f"\n=== Memory Pattern ===\nOutput: {result['output'][:200]}...")
    
        

    Agentic Orchestration Pattern: Memory Pattern

    03 Memory Pattern – Detailed Documentation

    Overview

    File: 08_state_management/03_memory.py
    Pattern Category: 08 State Management
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 08.03: Memory Persistent memory across interactions


    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 MemoryState(TypedDict):
        """State for Memory pattern."""
        input: str
        output: str
    
    
    def agent_function(state: MemoryState) -> MemoryState:
    

    MemoryState: State for Memory pattern.

    State Fields: – input: Stores input – output: Stores output – def agent_function(state: Stores def agent function(state – prompt = f"Process this using Memory pattern: Stores prompt = f”Process this using Memory pattern – def create_memory(): Stores def create memory()


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Memory agent implementation.

    def agent_function(state: MemoryState) -> MemoryState:
        """Memory agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Memory pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_memory():
    

    create_memory()

    Line: 26
    Arguments: “

    Create Memory workflow.

    def create_memory():
        """Create Memory workflow."""
        workflow = StateGraph(MemoryState)
        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 MemoryState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Memory pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: MemoryState) -> MemoryState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Memory agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_memory definition

    def create_memory():
    

    Defines the create_memory function that processes the workflow state.

    Line 27: Module docstring

        """Create Memory workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

    if __name__ == "__main__":
        workflow = create_memory()
        result = workflow.invoke({"input": "Test Memory", "output": ""})
        print(f"\n=== Memory 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
  • Agentic Orchestration Pattern: Context Passing Pattern

    
        """
    Pattern 08.02: Context Passing
    Shared context between agents
    """
    from typing import TypedDict
    from langgraph.graph import StateGraph, END
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage
    
    
    class ContextPassingState(TypedDict):
        """State for Context Passing pattern."""
        input: str
        output: str
    
    
    def agent_function(state: ContextPassingState) -> ContextPassingState:
        """Context Passing agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Context Passing pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_context_passing():
        """Create Context Passing workflow."""
        workflow = StateGraph(ContextPassingState)
        workflow.add_node("agent", agent_function)
        workflow.set_entry_point("agent")
        workflow.add_edge("agent", END)
        return workflow.compile()
    
    
    if __name__ == "__main__":
        workflow = create_context_passing()
        result = workflow.invoke({"input": "Test Context Passing", "output": ""})
        print(f"\n=== Context Passing Pattern ===\nOutput: {result['output'][:200]}...")
    
        

    Agentic Orchestration Pattern: Context Passing Pattern

    02 Context Passing Pattern – Detailed Documentation

    Overview

    File: 08_state_management/02_context_passing.py
    Pattern Category: 08 State Management
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 08.02: Context Passing Shared context between agents


    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 ContextPassingState(TypedDict):
        """State for Context Passing pattern."""
        input: str
        output: str
    
    
    def agent_function(state: ContextPassingState) -> ContextPassingState:
    

    ContextPassingState: State for Context Passing pattern.

    State Fields: – input: Stores input – output: Stores output – def agent_function(state: Stores def agent function(state – prompt = f"Process this using Context Passing pattern: Stores prompt = f”Process this using Context Passing pattern – def create_context_passing(): Stores def create context passing()


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Context Passing agent implementation.

    def agent_function(state: ContextPassingState) -> ContextPassingState:
        """Context Passing agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Context Passing pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_context_passing():
    

    create_context_passing()

    Line: 26
    Arguments: “

    Create Context Passing workflow.

    def create_context_passing():
        """Create Context Passing workflow."""
        workflow = StateGraph(ContextPassingState)
        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 ContextPassingState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Context Passing pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: ContextPassingState) -> ContextPassingState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Context Passing agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_context_passing definition

    def create_context_passing():
    

    Defines the create_context_passing function that processes the workflow state.

    Line 27: Module docstring

        """Create Context Passing workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

    if __name__ == "__main__":
        workflow = create_context_passing()
        result = workflow.invoke({"input": "Test Context Passing", "output": ""})
        print(f"\n=== Context Passing 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
  • Agentic Orchestration Pattern: State Machine Pattern

    
        """
    Pattern 08.01: State Machine
    Explicit states and transitions
    """
    from typing import TypedDict
    from langgraph.graph import StateGraph, END
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage
    
    
    class StateMachineState(TypedDict):
        """State for State Machine pattern."""
        input: str
        output: str
    
    
    def agent_function(state: StateMachineState) -> StateMachineState:
        """State Machine agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using State Machine pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_state_machine():
        """Create State Machine workflow."""
        workflow = StateGraph(StateMachineState)
        workflow.add_node("agent", agent_function)
        workflow.set_entry_point("agent")
        workflow.add_edge("agent", END)
        return workflow.compile()
    
    
    if __name__ == "__main__":
        workflow = create_state_machine()
        result = workflow.invoke({"input": "Test State Machine", "output": ""})
        print(f"\n=== State Machine Pattern ===\nOutput: {result['output'][:200]}...")
    
        

    Agentic Orchestration Pattern: State Machine Pattern

    01 State Machine Pattern – Detailed Documentation

    Overview

    File: 08_state_management/01_state_machine.py
    Pattern Category: 08 State Management
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 08.01: State Machine Explicit states and transitions


    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 StateMachineState(TypedDict):
        """State for State Machine pattern."""
        input: str
        output: str
    
    
    def agent_function(state: StateMachineState) -> StateMachineState:
    

    StateMachineState: State for State Machine pattern.

    State Fields: – input: Stores input – output: Stores output – def agent_function(state: Stores def agent function(state – prompt = f"Process this using State Machine pattern: Stores prompt = f”Process this using State Machine pattern – def create_state_machine(): Stores def create state machine()


    Functions

    agent_function()

    Line: 17
    Arguments: state

    State Machine agent implementation.

    def agent_function(state: StateMachineState) -> StateMachineState:
        """State Machine agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using State Machine pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_state_machine():
    

    create_state_machine()

    Line: 26
    Arguments: “

    Create State Machine workflow.

    def create_state_machine():
        """Create State Machine workflow."""
        workflow = StateGraph(StateMachineState)
        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 StateMachineState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for State Machine pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: StateMachineState) -> StateMachineState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """State Machine agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_state_machine definition

    def create_state_machine():
    

    Defines the create_state_machine function that processes the workflow state.

    Line 27: Module docstring

        """Create State Machine workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

    if __name__ == "__main__":
        workflow = create_state_machine()
        result = workflow.invoke({"input": "Test State Machine", "output": ""})
        print(f"\n=== State Machine 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