A modular implementation of a hierarchical multi-agent system using LangGraph and LangChain, featuring CEO-led coordination of specialized research and writing teams for comprehensive task analysis and report generation.
- Overview
- Architecture
- Features
- Project Structure
- Getting Started
- Usage
- Agent Hierarchy
- Workflow Stages
- Configuration
- Development Guide
- Testing
- Contributing
This project implements a sophisticated hierarchical multi-agent system where a CEO agent coordinates specialized teams to complete complex tasks. The system demonstrates:
- Hierarchical Decision Making: CEO orchestrates high-level workflow and delegates to team leaders
- Team-Based Specialization: Dedicated research and writing teams with specialized agents
- State Management: Centralized state tracking using LangGraph's MessagesState
- Dynamic Routing: Intelligent workflow routing based on task completion status
- Modular Architecture: Clean separation of concerns with extensible design
- Comprehensive market research and analysis
- Technical documentation generation
- Strategic business reports
- Industry trend analysis
- Multi-perspective content creation
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CEO AGENT β
β (Orchestration & Decision Making) β
ββββββββββββββββββ¬ββββββββββββββββββ¬βββββββββββββββββββββββ
β β
ββββββββββββΌββββββββββ βββΌβββββββββββββββββββ
β Research Team β β Writing Team β
β Leader β β Leader β
ββββ¬ββββββββββββββ¬ββββ ββββ¬βββββββββββββ¬βββββ
β β β β
ββββββΌββββ ββββββΌβββββ βββββΌββββββ ββββββΌβββββββββ
β Data β β Market β β Summary β β Technical β
βResearchβ βResearch β β Writer β β Writer β
ββββββββββ βββββββββββ βββββββββββ βββββββββββββββ
β
ββββββΌββββββββββββββ
β Consolidation β
β Agent β
ββββββββββββββββββββ
- Planning - CEO receives task and initiates workflow
- Research Phase - Research team gathers data and market insights
- Writing Phase - Writing team creates summary and technical content
- Consolidation - Final report generation combining all outputs
- Hierarchical Agent Architecture: Three-tier hierarchy (CEO β Team Leaders β Specialists)
- Modular Design: Each agent is independently implemented and testable
- State Management: Robust state tracking with
HierarchicalStateTypedDict - Dynamic Routing: Conditional edge routing based on completion status
- Team Coordination: Parallel team operations with synchronized reporting
- LLM Integration: Configurable LLM support (Groq, OpenAI, etc.)
- Web UI: Streamlit interface for interactive task execution
- Extensible Framework: Easy to add new agents, teams, or workflow stages
- Data Researcher: Gathers factual information, statistics, and quantitative data
- Market Researcher: Analyzes market trends, competition, and opportunities
- Summary Writer: Creates executive summaries and high-level overviews
- Technical Writer: Develops detailed technical documentation and analysis
hierarchical_agent_system/
βββ main.py # Entry point with CLI interface
βββ requirements.txt # Python dependencies
βββ README.md # Project documentation
βββ .gitignore # Git ignore rules
βββ raw_agent_book.ipynb # Development notebook
β
βββ src/ # Source code directory
β βββ __init__.py
β β
β βββ core/ # Core system components
β β βββ __init__.py
β β βββ state.py # HierarchicalState definition
β β βββ router.py # Conditional routing logic
β β βββ workflow.py # LangGraph workflow builder
β β βββ llm_config.py # LLM configuration and chains
β β
β βββ agents/ # Individual agent implementations
β β βββ __init__.py
β β βββ ceo.py # CEO orchestration agent
β β βββ data_researcher.py # Data research specialist
β β βββ market_researcher.py # Market analysis specialist
β β βββ summary_writer.py # Executive summary specialist
β β βββ technical_writer.py # Technical documentation specialist
β β βββ consolidation.py # Final report consolidation
β β
β βββ teams/ # Team leader implementations
β β βββ __init__.py
β β βββ research_team.py # Research team coordinator
β β βββ writing_team.py # Writing team coordinator
β β
β βββ ui/ # User interface components
β βββ __init__.py
β βββ streamlit_app.py # Streamlit web interface
β βββ components.py # Reusable UI components
β
βββ config/ # Configuration files
β βββ settings.py # Application settings
β βββ .env.example # Environment template
β
βββ tests/ # Test files
βββ __init__.py
βββ test_ceo.py # CEO agent tests
βββ test_research_team.py # Research team tests
βββ test_writing_team.py # Writing team tests
βββ test_workflow.py # Integration tests
- Python 3.8 or higher
- pip package manager
- API key for LLM provider (Groq, OpenAI, etc.)
-
Clone the repository:
git clone https://github.com/Arshp-svg/hierarchical-agent-system.git cd hierarchical-agent-system -
Install dependencies:
pip install -r requirements.txt
-
Set up environment variables:
cp config/.env.example config/.env
Edit
config/.envand add your API keys:GROQ_API_KEY=your_groq_api_key_here # or OPENAI_API_KEY=your_openai_api_key_here
Run the default example:
python main.pyThis will execute the system with the default task: "Analyze the impact of AI on healthcare industry"
Run with default task:
python main.pyRun with custom task (modify main.py):
from main import run_custom_task
response = run_custom_task("Analyze the electric vehicle market in 2024")
print(response["final_report"])Launch the interactive web UI:
streamlit run src/ui/streamlit_app.pyFeatures:
- Task input interface
- Real-time workflow visualization
- Agent message tracking
- Final report display
- Export functionality
from langchain_core.messages import HumanMessage
from src.core.workflow import create_hierarchical_workflow
# Create workflow
workflow = create_hierarchical_workflow()
# Define task
task = "Your custom analysis task here"
# Execute workflow
response = workflow.invoke(
{"messages": [HumanMessage(content=task)]},
config={"recursion_limit": 50}
)
# Access results
final_report = response.get("final_report", "")
research_data = response.get("research_team_report", "")
writing_data = response.get("writing_team_report", "")Responsibilities:
- Receives initial task
- Monitors team completion status
- Routes workflow between research and writing phases
- Initiates consolidation when all teams complete
Decision Logic:
if research_completed and writing_completed:
β consolidation
elif not research_completed:
β research_team_leader
elif research_completed and not writing_completed:
β writing_team_leaderResponsibilities:
- Coordinates data and market researchers
- Tracks research task completion
- Compiles research reports
- Reports back to CEO
Workflow:
- Assigns data research task
- Assigns market research task
- Compiles combined report
- Updates
team_completed["research_team"] = True
Responsibilities:
- Coordinates summary and technical writers
- Manages writing task distribution
- Compiles writing outputs
- Reports back to CEO
Workflow:
- Assigns summary writing task
- Assigns technical writing task
- Compiles combined document
- Updates
team_completed["writing_team"] = True
- Gathers statistics and quantitative data
- Provides historical trends
- Delivers factual background information
- Analyzes market size and growth
- Performs competitive analysis
- Identifies opportunities and challenges
- Creates executive overviews
- Highlights key findings
- Provides strategic recommendations
- Develops detailed technical content
- Provides implementation specifics
- Creates comprehensive documentation
Responsibilities:
- Combines all team outputs
- Generates final comprehensive report
- Sets
task_completed = True - Triggers workflow termination
User Input β CEO Agent β Task Analysis β Team Assignment
CEO β Research Team Leader β {Data Researcher, Market Researcher}
β Compile Research Report β CEO
CEO β Writing Team Leader β {Summary Writer, Technical Writer}
β Compile Writing Report β CEO
CEO β Consolidation Agent β Final Report Generation β END
Configure your preferred LLM provider:
from langchain_groq import ChatGroq
llm = ChatGroq(
model="mixtral-8x7b-32768",
temperature=0.7,
groq_api_key="your_api_key"
)The HierarchicalState TypedDict manages all workflow data:
class HierarchicalState(MessagesState):
current_level: str # Current hierarchy level
active_teams: List[str] # Active team identifiers
next_agent: str # Next agent to execute
main_task: str # Original user task
research_team_data: Dict # Research outputs
writing_team_data: Dict # Writing outputs
team_completed: Dict # Completion tracking
final_report: str # Consolidated output
# ... and more- Create agent file in
src/agents/:
# src/agents/my_new_agent.py
from typing import Dict
from langchain_core.messages import AIMessage
from ..core.state import HierarchicalState
from ..core.llm_config import llm
def my_new_agent(state: HierarchicalState) -> Dict:
"""Your agent description"""
task = state.get("current_task", "")
# Your agent logic here
result = llm.invoke([HumanMessage(content=f"Process: {task}")])
return {
"messages": [AIMessage(content=f"Completed: {task}")],
"next_agent": "appropriate_next_agent"
}- Register in workflow (
workflow.py):
from ..agents.my_new_agent import my_new_agent
hierarchical_wflow.add_node("my_new_agent", my_new_agent)- Update router (
router.py):
def hierarchical_router(state: HierarchicalState) -> Literal[..., "my_new_agent", ...]:
# Add routing logic- Create team leader in
src/teams/ - Add team-specific state fields in
state.py - Update CEO decision logic in
ceo.py - Register team leader in workflow
- Single Responsibility: Each agent has one clear purpose
- Dependency Injection: LLM and state passed as parameters
- Type Safety: Use TypedDict for state management
- Error Handling: Graceful fallbacks in routing logic
- Testability: Pure functions for easy unit testing
pytest tests/# Test CEO agent
pytest tests/test_ceo.py
# Test research team
pytest tests/test_research_team.py
# Test complete workflow
pytest tests/test_workflow.pypytest --cov=src tests/π Starting Hierarchical Multi-Agent System...
π Task: Analyze the impact of AI on healthcare industry
============================================================
CEO - Research: False, Writing: False, Stage: planning
CEO Decision: start research
π CEO: Starting research phase.
Research Leader - Data: False, Market: False
π Research Team Leader: Assigning data research task.
Data Researcher: Completed data analysis for 'Analyze the impact of AI on healthcare industry'.
Key data points:
The healthcare AI market is projected to reach $187.95 billion by 2030...
[... workflow continues ...]
β
CEO: Both teams completed. Moving to consolidation.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
FINAL COMPREHENSIVE REPORT
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
[Final consolidated report appears here]
Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
# Install development dependencies
pip install -r requirements-dev.txt
# Run linting
flake8 src/
# Run type checking
mypy src/
# Format code
black src/This project is licensed under the MIT License - see the LICENSE file for details.
- LangChain for LLM orchestration
- LangGraph for stateful workflow management
- Streamlit for the web interface
- Groq for fast LLM inference
For questions or feedback, please open an issue on GitHub.
Built with β€οΈ using LangGraph and LangChain