"""
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
- State Management: Uses TypedDict to maintain workflow state
- Graph-Based Flow: LangGraph orchestrates execution flow
- Agent Functions: Each node processes and updates state
- 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