Tag: llm

  • Agentic Orchestration Pattern: Peer Review Pattern

    
        """
    Pattern 05.03: Peer Review
    Agents review each other's work
    """
    from typing import TypedDict
    from langgraph.graph import StateGraph, END
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage
    
    
    class PeerReviewState(TypedDict):
        """State for Peer Review pattern."""
        input: str
        output: str
    
    
    def agent_function(state: PeerReviewState) -> PeerReviewState:
        """Peer Review agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Peer Review pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_peer_review():
        """Create Peer Review workflow."""
        workflow = StateGraph(PeerReviewState)
        workflow.add_node("agent", agent_function)
        workflow.set_entry_point("agent")
        workflow.add_edge("agent", END)
        return workflow.compile()
    
    
    if __name__ == "__main__":
        workflow = create_peer_review()
        result = workflow.invoke({"input": "Test Peer Review", "output": ""})
        print(f"\n=== Peer Review Pattern ===\nOutput: {result['output'][:200]}...")
    
        

    Agentic Orchestration Pattern: Peer Review Pattern

    03 Peer Review Pattern – Detailed Documentation

    Overview

    File: 05_collaborative/03_peer_review.py
    Pattern Category: 05 Collaborative
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 05.03: Peer Review Agents review each other’s work


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

    PeerReviewState: State for Peer Review pattern.

    State Fields: – input: Stores input – output: Stores output – def agent_function(state: Stores def agent function(state – prompt = f"Process this using Peer Review pattern: Stores prompt = f”Process this using Peer Review pattern – def create_peer_review(): Stores def create peer review()


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Peer Review agent implementation.

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

    create_peer_review()

    Line: 26
    Arguments: “

    Create Peer Review workflow.

    def create_peer_review():
        """Create Peer Review workflow."""
        workflow = StateGraph(PeerReviewState)
        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 PeerReviewState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Peer Review pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: PeerReviewState) -> PeerReviewState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Peer Review agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_peer_review definition

    def create_peer_review():
    

    Defines the create_peer_review function that processes the workflow state.

    Line 27: Module docstring

        """Create Peer Review workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

    if __name__ == "__main__":
        workflow = create_peer_review()
        result = workflow.invoke({"input": "Test Peer Review", "output": ""})
        print(f"\n=== Peer Review 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: Ensemble Pattern

    
        """
    Pattern 05.02: Ensemble
    Multiple agents solve same problem, vote on results
    """
    from typing import TypedDict
    from langgraph.graph import StateGraph, END
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage
    
    
    class EnsembleState(TypedDict):
        """State for Ensemble pattern."""
        input: str
        output: str
    
    
    def agent_function(state: EnsembleState) -> EnsembleState:
        """Ensemble agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Ensemble pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_ensemble():
        """Create Ensemble workflow."""
        workflow = StateGraph(EnsembleState)
        workflow.add_node("agent", agent_function)
        workflow.set_entry_point("agent")
        workflow.add_edge("agent", END)
        return workflow.compile()
    
    
    if __name__ == "__main__":
        workflow = create_ensemble()
        result = workflow.invoke({"input": "Test Ensemble", "output": ""})
        print(f"\n=== Ensemble Pattern ===\nOutput: {result['output'][:200]}...")
    
        

    Agentic Orchestration Pattern: Ensemble Pattern

    02 Ensemble Pattern – Detailed Documentation

    Overview

    File: 05_collaborative/02_ensemble.py
    Pattern Category: 05 Collaborative
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 05.02: Ensemble Multiple agents solve same problem, vote on 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 EnsembleState(TypedDict):
        """State for Ensemble pattern."""
        input: str
        output: str
    
    
    def agent_function(state: EnsembleState) -> EnsembleState:
    

    EnsembleState: State for Ensemble pattern.

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


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Ensemble agent implementation.

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

    create_ensemble()

    Line: 26
    Arguments: “

    Create Ensemble workflow.

    def create_ensemble():
        """Create Ensemble workflow."""
        workflow = StateGraph(EnsembleState)
        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 EnsembleState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Ensemble pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: EnsembleState) -> EnsembleState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Ensemble agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_ensemble definition

    def create_ensemble():
    

    Defines the create_ensemble function that processes the workflow state.

    Line 27: Module docstring

        """Create Ensemble workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

    if __name__ == "__main__":
        workflow = create_ensemble()
        result = workflow.invoke({"input": "Test Ensemble", "output": ""})
        print(f"\n=== Ensemble 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: Debate Pattern (CrewAI)

    
        """
    Pattern 5.1: Debate Pattern (CrewAI Implementation)
    Multiple agents argue different perspectives and synthesize views.
    """
    from crewai import Agent, Task, Crew, Process
    from langchain_openai import ChatOpenAI
    import os
    
    
    def create_debate_crew(topic: str):
        """Create a debate crew with multiple perspectives."""
        
        # Initialize LLM
        llm = ChatOpenAI(model="gpt-4")
        
        # Create agents with different perspectives
        optimist = Agent(
            role="Optimistic Analyst",
            goal=f"Argue the positive aspects and opportunities of {topic}",
            backstory="You are an optimistic analyst who always sees the bright side and potential benefits.",
            verbose=True,
            llm=llm
        )
        
        pessimist = Agent(
            role="Critical Analyst",
            goal=f"Identify risks, challenges, and potential problems with {topic}",
            backstory="You are a critical thinker who identifies risks and challenges to ensure thorough analysis.",
            verbose=True,
            llm=llm
        )
        
        realist = Agent(
            role="Pragmatic Analyst",
            goal=f"Provide a balanced, practical perspective on {topic}",
            backstory="You are a pragmatic analyst who balances optimism with realism and provides actionable insights.",
            verbose=True,
            llm=llm
        )
        
        synthesizer = Agent(
            role="Synthesis Expert",
            goal="Synthesize different perspectives into a comprehensive analysis",
            backstory="You are an expert at combining different viewpoints into coherent, balanced conclusions.",
            verbose=True,
            llm=llm
        )
        
        # Create tasks
        optimistic_task = Task(
            description=f"Present the optimistic case for {topic}. Focus on benefits, opportunities, and positive outcomes.",
            agent=optimist,
            expected_output="Detailed optimistic analysis with specific benefits and opportunities"
        )
        
        critical_task = Task(
            description=f"Present the critical analysis of {topic}. Focus on risks, challenges, and potential problems.",
            agent=pessimist,
            expected_output="Detailed critical analysis with specific risks and challenges"
        )
        
        realistic_task = Task(
            description=f"Present the pragmatic view of {topic}. Balance pros and cons with practical recommendations.",
            agent=realist,
            expected_output="Balanced pragmatic analysis with actionable recommendations"
        )
        
        synthesis_task = Task(
            description="""Synthesize the optimistic, critical, and pragmatic perspectives into a comprehensive final analysis.
            Include: 1) Summary of each perspective, 2) Key insights, 3) Balanced recommendations""",
            agent=synthesizer,
            expected_output="Comprehensive synthesis with balanced recommendations",
            context=[optimistic_task, critical_task, realistic_task]
        )
        
        # Create crew
        crew = Crew(
            agents=[optimist, pessimist, realist, synthesizer],
            tasks=[optimistic_task, critical_task, realistic_task, synthesis_task],
            process=Process.sequential,
            verbose=True
        )
        
        return crew
    
    
    def run_debate(topic: str):
        """Run the debate pattern."""
        print(f"\n{'='*60}")
        print(f"Debate Pattern: {topic}")
        print(f"{'='*60}\n")
        
        crew = create_debate_crew(topic)
        result = crew.kickoff()
        
        return result
    
    
    if __name__ == "__main__":
        # Example usage
        topic = "Implementing AI in healthcare diagnostics"
        result = run_debate(topic)
        
        print(f"\n\n{'='*60}")
        print("FINAL SYNTHESIS")
        print(f"{'='*60}")
        print(result)
    
        

    Agentic Orchestration Pattern: Debate Pattern (CrewAI)

    01 Debate Crewai Pattern – Detailed Documentation

    Overview

    File: 05_collaborative/01_debate_crewai.py
    Pattern Category: 05 Collaborative
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 5.1: Debate Pattern (CrewAI Implementation) Multiple agents argue different perspectives and synthesize views.


    Code Structure

    Imports

    from crewai import Agent, Task, Crew, Process
    from langchain_openai import ChatOpenAI
    import os
    

    Purpose of imports: – ChatOpenAI: OpenAI LLM integration – crewai: Multi-agent collaboration framework

    State Definition


    Functions

    create_debate_crew()

    Line: 10
    Arguments: topic

    Create a debate crew with multiple perspectives.

    def create_debate_crew(topic: str):
        """Create a debate crew with multiple perspectives."""
    
        # Initialize LLM
        llm = ChatOpenAI(model="gpt-4")
    
        # Create agents with different perspectives
        optimist = Agent(
            role="Optimistic Analyst",
            goal=f"Argue the positive aspects and opportunities of {topic}",
            backstory="You are an optimistic analyst who always sees the bright side and potential benefits.",
            verbose=True,
            llm=llm
        )
    
        pessimist = Agent(
            role="Critical Analyst",
            goal=f"Identify risks, challenges, and potential problems with {topic}",
            backstory="You are a critical thinker who identifies risks and challenges to ensure thorough analysis.",
            verbose=True,
            llm=llm
        )
    
        realist = Agent(
            role="Pragmatic Analyst",
            goal=f"Provide a balanced, practical perspective on {topic}",
            backstory="You are a pragmatic analyst who balances optimism with realism and provides actionable insights.",
            verbose=True,
            llm=llm
        )
    

    run_debate()

    Line: 87
    Arguments: topic

    Run the debate pattern.

    def run_debate(topic: str):
        """Run the debate pattern."""
        print(f"\n{'='*60}")
        print(f"Debate Pattern: {topic}")
        print(f"{'='*60}\n")
    
        crew = create_debate_crew(topic)
        result = crew.kickoff()
    
        return result
    
    
    if __name__ == "__main__":
    

    Line-by-Line Explanation

    Line 5: Import statement

    from crewai import Agent, Task, Crew, Process
    

    Required import for the pattern implementation.

    Line 6: Import statement

    from langchain_openai import ChatOpenAI
    

    Imports ChatOpenAI for LLM interactions.

    Line 7: Import statement

    import os
    

    Required import for the pattern implementation.

    Line 10: Function create_debate_crew definition

    def create_debate_crew(topic: str):
    

    Defines the create_debate_crew function that processes the workflow state.

    Line 11: Module docstring

        """Create a debate crew with multiple perspectives."""
    

    Describes the pattern and its purpose.

    Line 87: Function run_debate definition

    def run_debate(topic: str):
    

    Defines the run_debate function that processes the workflow state.

    Line 88: Module docstring

        """Run the debate pattern."""
    

    Describes the pattern and its purpose.


    Usage Example

    if __name__ == "__main__":
        # Example usage
        topic = "Implementing AI in healthcare diagnostics"
        result = run_debate(topic)
    
        print(f"\n\n{'='*60}")
        print("FINAL SYNTHESIS")
        print(f"{'='*60}")
        print(result)
    

    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: Debate Pattern

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

    Agentic Orchestration Pattern: Debate Pattern

    01 Debate Pattern – Detailed Documentation

    Overview

    File: 05_collaborative/01_debate.py
    Pattern Category: 05 Collaborative
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 05.01: Debate Multiple agents argue different perspectives


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

    DebateState: State for Debate pattern.

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


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Debate agent implementation.

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

    create_debate()

    Line: 26
    Arguments: “

    Create Debate workflow.

    def create_debate():
        """Create Debate workflow."""
        workflow = StateGraph(DebateState)
        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 DebateState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Debate pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: DebateState) -> DebateState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Debate agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_debate definition

    def create_debate():
    

    Defines the create_debate function that processes the workflow state.

    Line 27: Module docstring

        """Create Debate workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

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

    
        """
    Pattern 04.04: Tree Orchestration
    Multi-level hierarchy with parent-child relationships
    """
    from typing import TypedDict
    from langgraph.graph import StateGraph, END
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage
    
    
    class TreeOrchestrationState(TypedDict):
        """State for Tree Orchestration pattern."""
        input: str
        output: str
    
    
    def agent_function(state: TreeOrchestrationState) -> TreeOrchestrationState:
        """Tree Orchestration agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Tree Orchestration pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_tree_orchestration():
        """Create Tree Orchestration workflow."""
        workflow = StateGraph(TreeOrchestrationState)
        workflow.add_node("agent", agent_function)
        workflow.set_entry_point("agent")
        workflow.add_edge("agent", END)
        return workflow.compile()
    
    
    if __name__ == "__main__":
        workflow = create_tree_orchestration()
        result = workflow.invoke({"input": "Test Tree Orchestration", "output": ""})
        print(f"\n=== Tree Orchestration Pattern ===\nOutput: {result['output'][:200]}...")
    
        

    Agentic Orchestration Pattern: Tree Orchestration

    04 Tree Orchestration Pattern – Detailed Documentation

    Overview

    File: 04_hierarchical/04_tree_orchestration.py
    Pattern Category: 04 Hierarchical
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 04.04: Tree Orchestration Multi-level hierarchy with parent-child relationships


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

    TreeOrchestrationState: State for Tree Orchestration pattern.

    State Fields: – input: Stores input – output: Stores output – def agent_function(state: Stores def agent function(state – prompt = f"Process this using Tree Orchestration pattern: Stores prompt = f”Process this using Tree Orchestration pattern – def create_tree_orchestration(): Stores def create tree orchestration()


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Tree Orchestration agent implementation.

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

    create_tree_orchestration()

    Line: 26
    Arguments: “

    Create Tree Orchestration workflow.

    def create_tree_orchestration():
        """Create Tree Orchestration workflow."""
        workflow = StateGraph(TreeOrchestrationState)
        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 TreeOrchestrationState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Tree Orchestration pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: TreeOrchestrationState) -> TreeOrchestrationState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Tree Orchestration agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_tree_orchestration definition

    def create_tree_orchestration():
    

    Defines the create_tree_orchestration function that processes the workflow state.

    Line 27: Module docstring

        """Create Tree Orchestration workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

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

    
        """
    Pattern 04.03: Delegation
    High-level agent delegates to specialized agents
    """
    from typing import TypedDict
    from langgraph.graph import StateGraph, END
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage
    
    
    class DelegationState(TypedDict):
        """State for Delegation pattern."""
        input: str
        output: str
    
    
    def agent_function(state: DelegationState) -> DelegationState:
        """Delegation agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Delegation pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_delegation():
        """Create Delegation workflow."""
        workflow = StateGraph(DelegationState)
        workflow.add_node("agent", agent_function)
        workflow.set_entry_point("agent")
        workflow.add_edge("agent", END)
        return workflow.compile()
    
    
    if __name__ == "__main__":
        workflow = create_delegation()
        result = workflow.invoke({"input": "Test Delegation", "output": ""})
        print(f"\n=== Delegation Pattern ===\nOutput: {result['output'][:200]}...")
    
        

    Agentic Orchestration Pattern: Delegation Pattern

    03 Delegation Pattern – Detailed Documentation

    Overview

    File: 04_hierarchical/03_delegation.py
    Pattern Category: 04 Hierarchical
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 04.03: Delegation High-level agent delegates to specialized 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 DelegationState(TypedDict):
        """State for Delegation pattern."""
        input: str
        output: str
    
    
    def agent_function(state: DelegationState) -> DelegationState:
    

    DelegationState: State for Delegation pattern.

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


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Delegation agent implementation.

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

    create_delegation()

    Line: 26
    Arguments: “

    Create Delegation workflow.

    def create_delegation():
        """Create Delegation workflow."""
        workflow = StateGraph(DelegationState)
        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 DelegationState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Delegation pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: DelegationState) -> DelegationState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Delegation agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_delegation definition

    def create_delegation():
    

    Defines the create_delegation function that processes the workflow state.

    Line 27: Module docstring

        """Create Delegation workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

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

    
        """
    Pattern 04.02: Supervisor-Subordinate
    Hierarchical command structure with escalation
    """
    from typing import TypedDict
    from langgraph.graph import StateGraph, END
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage
    
    
    class SupervisorSubordinateState(TypedDict):
        """State for Supervisor-Subordinate pattern."""
        input: str
        output: str
    
    
    def agent_function(state: SupervisorSubordinateState) -> SupervisorSubordinateState:
        """Supervisor-Subordinate agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Supervisor-Subordinate pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_supervisor_subordinate():
        """Create Supervisor-Subordinate workflow."""
        workflow = StateGraph(SupervisorSubordinateState)
        workflow.add_node("agent", agent_function)
        workflow.set_entry_point("agent")
        workflow.add_edge("agent", END)
        return workflow.compile()
    
    
    if __name__ == "__main__":
        workflow = create_supervisor_subordinate()
        result = workflow.invoke({"input": "Test Supervisor-Subordinate", "output": ""})
        print(f"\n=== Supervisor-Subordinate Pattern ===\nOutput: {result['output'][:200]}...")
    
        

    Agentic Orchestration Pattern: Supervisor-Subordinate

    02 Supervisor Subordinate Pattern – Detailed Documentation

    Overview

    File: 04_hierarchical/02_supervisor_subordinate.py
    Pattern Category: 04 Hierarchical
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 04.02: Supervisor-Subordinate Hierarchical command structure with escalation


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

    SupervisorSubordinateState: State for Supervisor-Subordinate pattern.

    State Fields: – input: Stores input – output: Stores output – def agent_function(state: Stores def agent function(state – prompt = f"Process this using Supervisor-Subordinate pattern: Stores prompt = f”Process this using Supervisor-Subordinate pattern – def create_supervisor_subordinate(): Stores def create supervisor subordinate()


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Supervisor-Subordinate agent implementation.

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

    create_supervisor_subordinate()

    Line: 26
    Arguments: “

    Create Supervisor-Subordinate workflow.

    def create_supervisor_subordinate():
        """Create Supervisor-Subordinate workflow."""
        workflow = StateGraph(SupervisorSubordinateState)
        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 SupervisorSubordinateState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Supervisor-Subordinate pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: SupervisorSubordinateState) -> SupervisorSubordinateState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Supervisor-Subordinate agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_supervisor_subordinate definition

    def create_supervisor_subordinate():
    

    Defines the create_supervisor_subordinate function that processes the workflow state.

    Line 27: Module docstring

        """Create Supervisor-Subordinate workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

    if __name__ == "__main__":
        workflow = create_supervisor_subordinate()
        result = workflow.invoke({"input": "Test Supervisor-Subordinate", "output": ""})
        print(f"\n=== Supervisor-Subordinate 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: Master-Worker Pattern

    
        """
    Pattern 04.01: Master-Worker
    Central coordinator delegates to workers
    """
    from typing import TypedDict
    from langgraph.graph import StateGraph, END
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage
    
    
    class MasterWorkerState(TypedDict):
        """State for Master-Worker pattern."""
        input: str
        output: str
    
    
    def agent_function(state: MasterWorkerState) -> MasterWorkerState:
        """Master-Worker agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Master-Worker pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_master_worker():
        """Create Master-Worker workflow."""
        workflow = StateGraph(MasterWorkerState)
        workflow.add_node("agent", agent_function)
        workflow.set_entry_point("agent")
        workflow.add_edge("agent", END)
        return workflow.compile()
    
    
    if __name__ == "__main__":
        workflow = create_master_worker()
        result = workflow.invoke({"input": "Test Master-Worker", "output": ""})
        print(f"\n=== Master-Worker Pattern ===\nOutput: {result['output'][:200]}...")
    
        

    Agentic Orchestration Pattern: Master-Worker Pattern

    01 Master Worker Pattern – Detailed Documentation

    Overview

    File: 04_hierarchical/01_master_worker.py
    Pattern Category: 04 Hierarchical
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 04.01: Master-Worker Central coordinator delegates to workers


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

    MasterWorkerState: State for Master-Worker pattern.

    State Fields: – input: Stores input – output: Stores output – def agent_function(state: Stores def agent function(state – prompt = f"Process this using Master-Worker pattern: Stores prompt = f”Process this using Master-Worker pattern – def create_master_worker(): Stores def create master worker()


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Master-Worker agent implementation.

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

    create_master_worker()

    Line: 26
    Arguments: “

    Create Master-Worker workflow.

    def create_master_worker():
        """Create Master-Worker workflow."""
        workflow = StateGraph(MasterWorkerState)
        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 MasterWorkerState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Master-Worker pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: MasterWorkerState) -> MasterWorkerState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Master-Worker agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_master_worker definition

    def create_master_worker():
    

    Defines the create_master_worker function that processes the workflow state.

    Line 27: Module docstring

        """Create Master-Worker workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

    if __name__ == "__main__":
        workflow = create_master_worker()
        result = workflow.invoke({"input": "Test Master-Worker", "output": ""})
        print(f"\n=== Master-Worker 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: Refinement Loop

    
        """
    Pattern 03.04: Refinement Loop
    Iterative improvement of results with quality assessment
    """
    from typing import TypedDict
    from langgraph.graph import StateGraph, END
    from langchain_openai import ChatOpenAI
    from langchain_core.messages import HumanMessage
    
    
    class RefinementLoopState(TypedDict):
        """State for Refinement Loop pattern."""
        input: str
        output: str
    
    
    def agent_function(state: RefinementLoopState) -> RefinementLoopState:
        """Refinement Loop agent implementation."""
        llm = ChatOpenAI()
        prompt = f"Process this using Refinement Loop pattern: {state['input']}"
        response = llm.invoke([HumanMessage(content=prompt)])
        state["output"] = str(response.content)
        return state
    
    
    def create_refinement_loop():
        """Create Refinement Loop workflow."""
        workflow = StateGraph(RefinementLoopState)
        workflow.add_node("agent", agent_function)
        workflow.set_entry_point("agent")
        workflow.add_edge("agent", END)
        return workflow.compile()
    
    
    if __name__ == "__main__":
        workflow = create_refinement_loop()
        result = workflow.invoke({"input": "Test Refinement Loop", "output": ""})
        print(f"\n=== Refinement Loop Pattern ===\nOutput: {result['output'][:200]}...")
    
        

    Agentic Orchestration Pattern: Refinement Loop

    04 Refinement Loop Pattern – Detailed Documentation

    Overview

    File: 03_iterative/04_refinement_loop.py
    Pattern Category: 03 Iterative
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 03.04: Refinement Loop Iterative improvement of results with quality assessment


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

    RefinementLoopState: State for Refinement Loop pattern.

    State Fields: – input: Stores input – output: Stores output – def agent_function(state: Stores def agent function(state – prompt = f"Process this using Refinement Loop pattern: Stores prompt = f”Process this using Refinement Loop pattern – def create_refinement_loop(): Stores def create refinement loop()


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Refinement Loop agent implementation.

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

    create_refinement_loop()

    Line: 26
    Arguments: “

    Create Refinement Loop workflow.

    def create_refinement_loop():
        """Create Refinement Loop workflow."""
        workflow = StateGraph(RefinementLoopState)
        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 RefinementLoopState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Refinement Loop pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: RefinementLoopState) -> RefinementLoopState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Refinement Loop agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_refinement_loop definition

    def create_refinement_loop():
    

    Defines the create_refinement_loop function that processes the workflow state.

    Line 27: Module docstring

        """Create Refinement Loop workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

    if __name__ == "__main__":
        workflow = create_refinement_loop()
        result = workflow.invoke({"input": "Test Refinement Loop", "output": ""})
        print(f"\n=== Refinement Loop 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: Retry Pattern

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

    Agentic Orchestration Pattern: Retry Pattern

    03 Retry Pattern – Detailed Documentation

    Overview

    File: 03_iterative/03_retry.py
    Pattern Category: 03 Iterative
    Implementation: LangGraph/CrewAI

    Pattern Description

    Pattern 03.03: Retry Automatic retry on failure with exponential backoff


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

    RetryState: State for Retry pattern.

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


    Functions

    agent_function()

    Line: 17
    Arguments: state

    Retry agent implementation.

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

    create_retry()

    Line: 26
    Arguments: “

    Create Retry workflow.

    def create_retry():
        """Create Retry workflow."""
        workflow = StateGraph(RetryState)
        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 RetryState(TypedDict):
    

    Defines the state structure using TypedDict for type safety.

    Line 12: Module docstring

        """State for Retry pattern."""
    

    Describes the pattern and its purpose.

    Line 17: Function agent_function definition

    def agent_function(state: RetryState) -> RetryState:
    

    Defines the agent_function function that processes the workflow state.

    Line 18: Module docstring

        """Retry agent implementation."""
    

    Describes the pattern and its purpose.

    Line 26: Function create_retry definition

    def create_retry():
    

    Defines the create_retry function that processes the workflow state.

    Line 27: Module docstring

        """Create Retry workflow."""
    

    Describes the pattern and its purpose.


    Usage Example

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