The HierarchicalSwarm is a sophisticated multi-agent orchestration system that implements a hierarchical workflow pattern. It consists of a director agent that coordinates and distributes tasks to specialized worker agents, creating a structured approach to complex problem-solving.
graph TD
A[Task] --> B[Director]
B --> C[Plan & Orders]
C --> D[Agents]
D --> E[Results]
E --> F{More Loops?}
F -->|Yes| B
F -->|No| G[Output]
The Hierarchical Swarm follows a clear workflow pattern:
Task Reception: User provides a task to the swarm
Planning: Director creates a comprehensive plan and distributes orders to agents
Displays a visual tree representation of the hierarchical swarm structure, showing the Director at the top level and all worker agents as children branches. This method uses Rich formatting to create an aesthetically pleasing console output that helps visualize the organizational structure of the swarm.
fromswarmsimportAgentfromswarms.structs.hiearchical_swarmimportHierarchicalSwarm# Create specialized agentsresearch_agent=Agent(agent_name="Research-Analyst",agent_description="Specialized in comprehensive research and data gathering",model_name="gpt-4o-mini",)analysis_agent=Agent(agent_name="Data-Analyst",agent_description="Expert in data analysis and pattern recognition",model_name="gpt-4o-mini",)strategy_agent=Agent(agent_name="Strategy-Consultant",agent_description="Specialized in strategic planning and recommendations",model_name="gpt-4o-mini",)# Create hierarchical swarmswarm=HierarchicalSwarm(name="Swarms Corporation Operations",description="Enterprise-grade hierarchical swarm for complex task execution",agents=[research_agent,analysis_agent,strategy_agent],max_loops=1,director_model_name="claude-haiku-4-5",)# Display the hierarchy visualizationswarm.display_hierarchy()
The output will show a visual tree structure like:
Executes the hierarchical swarm for a specified number of feedback loops, processing the task through multiple iterations for refinement and improvement.
fromswarmsimportAgentfromswarms.structs.hiearchical_swarmimportHierarchicalSwarm# Create specialized agentsresearch_agent=Agent(agent_name="Research-Specialist",agent_description="Expert in market research and analysis",model_name="gpt-4.1",)financial_agent=Agent(agent_name="Financial-Analyst",agent_description="Specialist in financial analysis and valuation",model_name="gpt-4.1",)# Initialize the hierarchical swarmswarm=HierarchicalSwarm(name="Financial-Analysis-Swarm",description="A hierarchical swarm for comprehensive financial analysis",agents=[research_agent,financial_agent],max_loops=2,verbose=True,)# Execute a complex tasktask="Analyze the market potential for Tesla (TSLA) stock"result=swarm.run(task=task)print(result)
fromswarmsimportAgentfromswarms.structs.hiearchical_swarmimportHierarchicalSwarmdefstreaming_callback(agent_name:str,chunk:str,is_final:bool):"""Callback function for real-time streaming of agent outputs."""ifnothasattr(streaming_callback,'buffers'):streaming_callback.buffers={}streaming_callback.paragraph_count={}ifagent_namenotinstreaming_callback.buffers:streaming_callback.buffers[agent_name]=""streaming_callback.paragraph_count[agent_name]=1print(f"\n🎬 {agent_name} starting...")ifchunk.strip():tokens=chunk.replace('\n',' \n ').split()fortokenintokens:iftoken=='\n':ifstreaming_callback.buffers[agent_name].strip():print(f"\n📄 {agent_name} - Paragraph {streaming_callback.paragraph_count[agent_name]} Complete:")print(f"{streaming_callback.buffers[agent_name].strip()}")streaming_callback.paragraph_count[agent_name]+=1streaming_callback.buffers[agent_name]=""else:streaming_callback.buffers[agent_name]+=token+" "print(f"\r{agent_name} | {streaming_callback.buffers[agent_name].strip()}",end="",flush=True)ifis_final:print(f"\n✅ {agent_name} completed!")# Create agentsagents=[Agent(agent_name="Researcher",model_name="gpt-4o-mini"),Agent(agent_name="Analyst",model_name="gpt-4o-mini"),]# Initialize swarmswarm=HierarchicalSwarm(name="Streaming-Analysis-Swarm",agents=agents,max_loops=1,verbose=True,)# Execute with streamingtask="Analyze the impact of AI on the job market"result=swarm.run(task=task,streaming_callback=streaming_callback)
Execute the hierarchical swarm for multiple tasks in sequence. Processes a list of tasks sequentially, running the complete swarm workflow for each task independently.
fromswarmsimportAgentfromswarms.structs.hiearchical_swarmimportHierarchicalSwarm# Create analysis agentsmarket_agent=Agent(agent_name="Market-Analyst",agent_description="Expert in market analysis and trends",model_name="gpt-4.1",)technical_agent=Agent(agent_name="Technical-Analyst",agent_description="Specialist in technical analysis and patterns",model_name="gpt-4.1",)# Initialize the swarmswarm=HierarchicalSwarm(name="Analysis-Swarm",description="A hierarchical swarm for comprehensive analysis",agents=[market_agent,technical_agent],max_loops=2,verbose=True,)# Execute multiple taskstasks=["Analyze Apple (AAPL) stock performance","Evaluate Microsoft (MSFT) market position","Assess Google (GOOGL) competitive landscape"]results=swarm.batched_run(tasks=tasks)fori,resultinenumerate(results):print(f"Task {i+1} Result:",result)
fromswarmsimportAgentfromswarms.structs.hiearchical_swarmimportHierarchicalSwarm# Create specialized financial agentsmarket_research_agent=Agent(agent_name="Market-Research-Specialist",agent_description="Expert in market research, trend analysis, and competitive intelligence",system_prompt="""You are a senior market research specialist with expertise in: - Market trend analysis and forecasting - Competitive landscape assessment - Consumer behavior analysis - Industry report generation - Market opportunity identification - Risk assessment and mitigation strategies""",model_name="claude-3-sonnet-20240229",)financial_analyst_agent=Agent(agent_name="Financial-Analysis-Expert",agent_description="Specialist in financial statement analysis, valuation, and investment research",system_prompt="""You are a senior financial analyst with deep expertise in: - Financial statement analysis (income statement, balance sheet, cash flow) - Valuation methodologies (DCF, comparable company analysis, precedent transactions) - Investment research and due diligence - Financial modeling and forecasting - Risk assessment and portfolio analysis - ESG (Environmental, Social, Governance) analysis""",model_name="claude-3-sonnet-20240229",)# Initialize the hierarchical swarmfinancial_analysis_swarm=HierarchicalSwarm(name="Financial-Analysis-Hierarchical-Swarm",description="A hierarchical swarm for comprehensive financial analysis with specialized agents",agents=[market_research_agent,financial_analyst_agent],max_loops=2,verbose=True,)# Execute financial analysistask="Conduct a comprehensive analysis of Tesla (TSLA) stock including market position, financial health, and investment potential"result=financial_analysis_swarm.run(task=task)print(result)
fromswarmsimportAgentfromswarms.structs.hiearchical_swarmimportHierarchicalSwarm# Create specialized development agentsfrontend_developer_agent=Agent(agent_name="Frontend-Developer",agent_description="Senior frontend developer expert in modern web technologies and user experience",system_prompt="""You are a senior frontend developer with expertise in: - Modern JavaScript frameworks (React, Vue, Angular) - TypeScript and modern ES6+ features - CSS frameworks and responsive design - State management (Redux, Zustand, Context API) - Web performance optimization - Accessibility (WCAG) and SEO best practices""",model_name="claude-3-sonnet-20240229",)backend_developer_agent=Agent(agent_name="Backend-Developer",agent_description="Senior backend developer specializing in server-side development and API design",system_prompt="""You are a senior backend developer with expertise in: - Server-side programming languages (Python, Node.js, Java, Go) - Web frameworks (Django, Flask, Express, Spring Boot) - Database design and optimization (SQL, NoSQL) - API design and REST/GraphQL implementation - Authentication and authorization systems - Microservices architecture and containerization""",model_name="claude-3-sonnet-20240229",)# Initialize the development swarmdevelopment_department_swarm=HierarchicalSwarm(name="Autonomous-Development-Department",description="A fully autonomous development department with specialized agents",agents=[frontend_developer_agent,backend_developer_agent],max_loops=3,verbose=True,)# Execute development projecttask="Create a simple web app that allows users to upload a file and then download it. The app should be built with React and Node.js."result=development_department_swarm.run(task=task)print(result)
The HierarchicalSwarm supports real-time streaming of agent outputs through optional callback functions. This feature allows you to monitor the text generation process as it happens, token by token.
defstreaming_callback(agent_name:str,chunk:str,is_final:bool)->None:""" Callback function for real-time streaming of agent outputs. Args: agent_name (str): The name of the agent producing the output chunk (str): The chunk of text generated (empty if is_final=True) is_final (bool): True when the agent has completed its task """pass