Merge branch 'master' into thingymabober

pull/1231/head
CI-DEV 4 weeks ago committed by GitHub
commit 17cb8fbd53
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -17,7 +17,7 @@ jobs:
&& ${{ contains(github.event.pull_request.labels.*.name, 'release') }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v6
- name: Install poetry
run: pipx install poetry==$POETRY_VERSION
- name: Set up Python 3.9

@ -21,7 +21,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v5
uses: actions/checkout@v6
# Execute Codacy Analysis CLI and generate a SARIF output with the security issues identified during the analysis
- name: Run Codacy Analysis CLI
uses: codacy/codacy-analysis-cli-action@562ee3e92b8e92df8b67e0a5ff8aa8e261919c08

@ -16,7 +16,7 @@ jobs:
steps:
# Step 1: Check out the repository
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v6
# Step 2: Set up Python
- name: Set up Python ${{ matrix.python-version }}

@ -28,7 +28,7 @@ jobs:
language: ["python"]
steps:
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v6
- name: Initialize CodeQL
uses: github/codeql-action/init@v4
with:

@ -28,7 +28,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: 'Checkout repository'
uses: actions/checkout@v5
uses: actions/checkout@v6
- name: 'Dependency Review'
uses: actions/dependency-review-action@v4
# Commonly enabled options, see https://github.com/actions/dependency-review-action#configuration-options for all available options.

@ -9,7 +9,7 @@ jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
with:
python-version: 3.11

@ -6,7 +6,7 @@ jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v6
- name: Set up Python
uses: actions/setup-python@v6

@ -33,7 +33,7 @@ jobs:
security-events: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v6
with:
submodules: true

@ -35,7 +35,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v6
with:
submodules: true

@ -21,7 +21,7 @@ jobs:
python-version: ["3.10", "3.11", "3.12"]
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v6
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v6
with:

@ -24,7 +24,7 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v5
uses: actions/checkout@v6
- name: Set up Python 3.10
uses: actions/setup-python@v6
@ -121,7 +121,7 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v5
uses: actions/checkout@v6
- name: Set up Python 3.10
uses: actions/setup-python@v6

@ -11,7 +11,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v6
- name: Set up Python 3.10
uses: actions/setup-python@v6

@ -27,7 +27,7 @@ jobs:
runs-on: "ubuntu-20.04"
steps:
- name: Checkout code
uses: actions/checkout@v5
uses: actions/checkout@v6
- name: Build an image from Dockerfile
run: |

@ -65,18 +65,24 @@ python examples/multi_agent/llm_council_examples/medical_diagnosis_council.py
## Key Features
- **Multiple Perspectives**: Each council member (GPT-5.1, Gemini, Claude, Grok) provides unique insights
- **Peer Review**: Members evaluate and rank each other's responses anonymously
- **Synthesis**: Chairman combines the best elements from all responses
- **Transparency**: See both individual responses and evaluation rankings
| Feature | Description |
|----------------------|---------------------------------------------------------------------------------------------------------|
| **Multiple Perspectives** | Each council member (GPT-5.1, Gemini, Claude, Grok) provides unique insights |
| **Peer Review** | Members evaluate and rank each other's responses anonymously |
| **Synthesis** | Chairman combines the best elements from all responses |
| **Transparency** | See both individual responses and evaluation rankings |
## Council Members
The default council consists of:
- **GPT-5.1-Councilor**: Analytical and comprehensive
- **Gemini-3-Pro-Councilor**: Concise and well-processed
- **Claude-Sonnet-4.5-Councilor**: Thoughtful and balanced
- **Grok-4-Councilor**: Creative and innovative
| Council Member | Description |
|-------------------------------|-------------------------------|
| **GPT-5.1-Councilor** | Analytical and comprehensive |
| **Gemini-3-Pro-Councilor** | Concise and well-processed |
| **Claude-Sonnet-4.5-Councilor** | Thoughtful and balanced |
| **Grok-4-Councilor** | Creative and innovative |
## Customization

@ -27,7 +27,7 @@ jinja2~=3.1
markdown~=3.10
mkdocs-material-extensions~=1.3
pygments~=2.19
pymdown-extensions~=10.16
pymdown-extensions~=10.17
# Requirements for plugins
colorama~=0.4

@ -32,21 +32,20 @@ Multi-agent architectures leverage these communication patterns to ensure that a
| Graph Workflow | Agents collaborate in a directed acyclic graph (DAG) format to manage dependencies and parallel tasks. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/graph_workflow/) | AI-driven software development pipelines, complex project management |
| Group Chat | Agents engage in a chat-like interaction to reach decisions collaboratively. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/group_chat/) | Real-time collaborative decision-making, contract negotiations |
| Interactive Group Chat | Enhanced group chat with dynamic speaker selection and interaction patterns. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/interactive_groupchat/) | Advanced collaborative decision-making, dynamic team coordination |
| Agent Registry | A centralized registry where agents are stored, retrieved, and invoked dynamically. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/agent_registry/) | Dynamic agent management, evolving recommendation engines |
| SpreadSheet | Manages tasks at scale, tracking agent outputs in a structured format like CSV files. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/spreadsheet_swarm/) | Large-scale marketing analytics, financial audits |
| Router | Routes and chooses the architecture based on the task requirements and available agents. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/swarm_router/) | Dynamic task routing, adaptive architecture selection, optimized agent allocation |
| Heavy | High-performance architecture for handling intensive computational tasks with multiple agents. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/heavy_swarm/) | Large-scale data processing, intensive computational workflows |
| Deep Research | Specialized architecture for conducting in-depth research tasks across multiple domains. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/deep_research_swarm/) | Academic research, market analysis, comprehensive data investigation |
| De-Hallucination | Architecture designed to reduce and eliminate hallucinations in AI outputs through consensus. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/de_hallucination_swarm/) | Fact-checking, content verification, reliable information generation |
| Council as Judge | Multiple agents act as a council to evaluate and judge outputs or decisions. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/council_of_judges/) | Quality assessment, decision validation, peer review processes |
| MALT | Specialized architecture for complex language processing tasks across multiple agents. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/malt/) | Natural language processing, translation, content generation |
| Majority Voting | Agents vote on decisions with the majority determining the final outcome. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/majorityvoting/) | Democratic decision-making, consensus building, error reduction |
| Round Robin | Tasks are distributed cyclically among agents in a rotating order. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/round_robin_swarm/) | Load balancing, fair task distribution, resource optimization |
| Auto-Builder | Automatically constructs and configures multi-agent systems based on requirements. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/auto_swarm_builder/) | Dynamic system creation, adaptive architectures, rapid prototyping |
| Hybrid Hierarchical Cluster | Combines hierarchical and peer-to-peer communication patterns for complex workflows. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/hhcs/) | Complex enterprise workflows, multi-department coordination |
| Election | Agents participate in democratic voting processes to select leaders or make collective decisions. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/election_swarm/) | Democratic governance, consensus building, leadership selection |
| Dynamic Conversational | Adaptive conversation management with dynamic agent selection and interaction patterns. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/dynamic_conversational_swarm/) | Adaptive chatbots, dynamic customer service, contextual conversations |
| Tree | Hierarchical tree structure for organizing agents in parent-child relationships. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/tree_swarm/) | Organizational hierarchies, decision trees, taxonomic classification |
| Batched Grid Workflow | Executes tasks in a batched grid format, where each agent processes a different task simultaneously in parallel. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/batched_grid_workflow/) | Parallel task processing, batch operations, grid-based task distribution |
| LLM Council | Orchestrates multiple specialized LLM agents to collaboratively answer queries through structured peer review and synthesis. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/llm_council/) | Multi-model evaluation, peer review systems, collaborative AI decision-making |
| Debate with Judge | A debate architecture where two agents (Pro and Con) debate a topic, with a Judge agent evaluating arguments and providing refined synthesis over multiple rounds. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/debate_with_judge/) | Argument analysis, decision refinement, structured debates, iterative improvement |
| Self MoA Seq | Sequential self-mixture of agents that generates multiple candidate responses and synthesizes them sequentially using a sliding window approach. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/self_moa_seq/) | High-quality response generation, ensemble methods, sequential synthesis |
| Swarm Rearrange | Orchestrates multiple swarms in sequential or parallel flow patterns, providing thread-safe operations for managing swarm execution. | [Learn More](https://docs.swarms.world/en/latest/swarms/structs/swarm_rearrange/) | Multi-swarm coordination, complex workflow orchestration, swarm composition |
---
@ -84,6 +83,7 @@ graph TD
A dynamic architecture where agents rearrange themselves based on task requirements and environmental conditions. Agents can adapt their roles, positions, and relationships to optimize performance for different scenarios.
**Use Cases:**
- Adaptive manufacturing lines that reconfigure based on product requirements
- Dynamic sales territory realignment based on market conditions
@ -123,6 +123,7 @@ graph TD
Multiple agents operate independently and simultaneously on different tasks. Each agent works on its own task without dependencies on the others.
**Use Cases:**
- Tasks that can be processed independently, such as parallel data analysis
- Large-scale simulations where multiple scenarios are run simultaneously
@ -204,6 +205,7 @@ graph TD
Makes it easy to manage thousands of agents in one place: a CSV file. Initialize any number of agents and run loops of agents on tasks.
**Use Cases:**
- Multi-threaded execution: Execute agents on multiple threads
- Save agent outputs into CSV file
@ -242,12 +244,52 @@ graph TD
---
### Batched Grid Workflow
**Overview:**
Multi-agent orchestration pattern that executes tasks in a batched grid format, where each agent processes different tasks simultaneously. Provides structured parallel processing with conversation state management.
**Use Cases:**
- Parallel task processing
- Grid-based agent execution
- Batch operations
- Multi-task multi-agent coordination
**[Learn More](https://docs.swarms.world/en/latest/swarms/structs/batched_grid_workflow/)**
```mermaid
graph TD
A[Task Batch] --> B[BatchedGridWorkflow]
B --> C[Initialize Agents]
C --> D[Create Grid]
D --> E[Agent 1: Task 1]
D --> F[Agent 2: Task 2]
D --> G[Agent N: Task N]
E --> H[Collect Results]
F --> H
G --> H
H --> I[Update Conversation]
I --> J[Next Iteration]
J --> D
```
---
### Mixture of Agents
**Overview:**
Combines multiple agents with different capabilities and expertise to solve complex problems that require diverse skill sets.
**Use Cases:**
- Financial forecasting requiring different analytical approaches
- Complex problem-solving needing diverse expertise
@ -282,6 +324,7 @@ graph TD
Organizes agents in a directed acyclic graph (DAG) format, enabling complex dependencies and parallel execution paths.
**Use Cases:**
- AI-driven software development pipelines
- Complex project management with dependencies
@ -311,6 +354,7 @@ graph TD
Enables agents to engage in chat-like interactions to reach decisions collaboratively through discussion and consensus building.
**Use Cases:**
- Real-time collaborative decision-making
- Contract negotiations
@ -345,6 +389,7 @@ graph TD
Enhanced version of Group Chat with dynamic speaker selection, priority-based communication, and advanced interaction patterns.
**Use Cases:**
- Advanced collaborative decision-making
- Dynamic team coordination
@ -378,49 +423,13 @@ graph TD
---
### Agent Registry
**Overview:**
A centralized registry system where agents are stored, retrieved, and invoked dynamically. The registry maintains metadata about agent capabilities, availability, and performance metrics, enabling intelligent agent selection and management.
**Use Cases:**
- Dynamic agent management in large-scale systems
- Evolving recommendation engines that adapt agent selection
- Service discovery in distributed agent systems
**[Learn More](https://docs.swarms.world/en/latest/swarms/structs/agent_registry/)**
```mermaid
graph TD
A[Agent Registration] --> B[Registry Database]
B --> C[Agent Metadata]
C --> D[Capabilities]
C --> E[Performance Metrics]
C --> F[Availability Status]
G[Task Request] --> H[Registry Query Engine]
H --> I[Agent Discovery]
I --> J[Capability Matching]
J --> K[Agent Selection]
K --> L[Agent Invocation]
L --> M[Task Execution]
M --> N[Performance Tracking]
N --> O[Registry Update]
O --> B
```
---
### Router Architecture
**Overview:**
Intelligently routes tasks to the most appropriate agents or architectures based on task requirements and agent capabilities.
**Use Cases:**
- Dynamic task routing
- Adaptive architecture selection
@ -458,6 +467,7 @@ graph TD
High-performance architecture designed for handling intensive computational tasks with multiple agents working on resource-heavy operations.
**Use Cases:**
- Large-scale data processing
- Intensive computational workflows
@ -493,6 +503,7 @@ graph TD
Specialized architecture for conducting comprehensive research tasks across multiple domains with iterative refinement and cross-validation.
**Use Cases:**
- Academic research projects
- Market analysis and intelligence
@ -528,6 +539,7 @@ graph TD
Architecture specifically designed to reduce and eliminate hallucinations in AI outputs through consensus mechanisms and fact-checking protocols.
**Use Cases:**
- Fact-checking and verification
- Content validation
@ -558,12 +570,52 @@ graph TD
---
### Self MoA Seq
**Overview:**
Ensemble method that generates multiple candidate responses from a single high-performing model and synthesizes them sequentially using a sliding window approach. Keeps context within bounds while leveraging diversity across samples.
**Use Cases:**
- Response synthesis
- Ensemble methods
- Sequential aggregation
- Quality improvement through diversity
**[Learn More](https://docs.swarms.world/en/latest/swarms/structs/self_moa_seq/)**
```mermaid
graph TD
A[Task] --> B[Proposer Agent]
B --> C[Generate Samples]
C --> D[Sample 1]
C --> E[Sample 2]
C --> F[Sample N]
D --> G[Sliding Window]
E --> G
F --> G
G --> H[Aggregator Agent]
H --> I[Biased Synthesis]
I --> J{More Iterations?}
J -->|Yes| G
J -->|No| K[Final Output]
```
---
### Council as Judge
**Overview:**
Multiple agents act as a council to evaluate, judge, and validate outputs or decisions through collaborative assessment.
**Use Cases:**
- Quality assessment and validation
- Decision validation processes
@ -594,12 +646,91 @@ graph TD
---
### LLM Council
**Overview:**
Orchestrates multiple specialized LLM agents to collaboratively answer queries through structured peer review and synthesis. Different models evaluate and rank each other's work, often selecting responses from other models as superior.
**Use Cases:**
- Multi-model collaboration
- Peer review processes
- Model evaluation and synthesis
- Cross-model consensus building
**[Learn More](https://docs.swarms.world/en/latest/swarms/structs/llm_council/)**
```mermaid
graph TD
A[User Query] --> B[Council Members]
B --> C[GPT Councilor]
B --> D[Gemini Councilor]
B --> E[Claude Councilor]
B --> F[Grok Councilor]
C --> G[Responses]
D --> G
E --> G
F --> G
G --> H[Anonymize & Evaluate]
H --> I[Chairman Synthesis]
I --> J[Final Response]
```
---
### Debate with Judge
**Overview:**
Debate architecture with self-refinement through a judge agent, enabling Pro and Con agents to debate a topic with iterative refinement. The judge evaluates arguments and provides synthesis for progressive improvement.
**Use Cases:**
- Structured debates
- Argument evaluation
- Iterative refinement of positions
- Multi-perspective analysis
**[Learn More](https://docs.swarms.world/en/latest/swarms/structs/debate_with_judge/)**
```mermaid
graph TD
A[Topic] --> B[DebateWithJudge]
B --> C[Pro Agent]
B --> D[Con Agent]
B --> E[Judge Agent]
C --> F[Pro Argument]
D --> G[Con Argument]
F --> H[Judge Evaluation]
G --> H
H --> I[Judge Synthesis]
I --> J{More Rounds?}
J -->|Yes| C
J -->|No| K[Final Output]
```
---
### MALT Architecture
**Overview:**
Specialized architecture for complex language processing tasks that require coordination between multiple language-focused agents.
**Use Cases:**
- Natural language processing pipelines
- Translation and localization
@ -637,6 +768,7 @@ graph TD
Agents vote on decisions with the majority determining the final outcome, providing democratic decision-making and error reduction through consensus.
**Use Cases:**
- Democratic decision-making processes
- Consensus building
@ -675,6 +807,7 @@ graph TD
Automatically constructs and configures multi-agent systems based on requirements, enabling dynamic system creation and adaptation.
**Use Cases:**
- Dynamic system creation
- Adaptive architectures
@ -706,12 +839,55 @@ graph TD
---
### Swarm Rearrange
**Overview:**
Orchestrates multiple swarms in sequential or parallel flow patterns with thread-safe operations and flow validation. Provides comprehensive swarm management and coordination capabilities.
**Use Cases:**
- Multi-swarm orchestration
- Flow pattern management
- Swarm coordination
- Sequential and parallel swarm execution
**[Learn More](https://docs.swarms.world/en/latest/swarms/structs/swarm_rearrange/)**
```mermaid
graph TD
A[Swarm Pool] --> B[SwarmRearrange]
B --> C[Flow Pattern]
C --> D[Sequential Flow]
C --> E[Parallel Flow]
D --> F[Swarm 1]
F --> G[Swarm 2]
G --> H[Swarm N]
E --> I[Swarm 1]
E --> J[Swarm 2]
E --> K[Swarm N]
H --> L[Result Aggregation]
I --> L
J --> L
K --> L
```
---
### Hybrid Hierarchical Cluster
**Overview:**
Combines hierarchical and peer-to-peer communication patterns for complex workflows that require both centralized coordination and distributed collaboration.
**Use Cases:**
- Complex enterprise workflows
- Multi-department coordination
@ -753,6 +929,7 @@ graph TD
Agents participate in democratic voting processes to select leaders or make collective decisions.
**Use Cases:**
- Democratic governance
- Consensus building
@ -794,6 +971,7 @@ graph TD
Adaptive conversation management with dynamic agent selection and interaction patterns.
**Use Cases:**
- Adaptive chatbots
- Dynamic customer service
@ -833,6 +1011,7 @@ graph TD
Hierarchical tree structure for organizing agents in parent-child relationships.
**Use Cases:**
- Organizational hierarchies
- Decision trees

@ -215,6 +215,48 @@ result = research_swarm.run(task=task)
print(result)
```
## Visualizing Swarm Hierarchy
You can visualize the hierarchical structure of your swarm before executing tasks using the `display_hierarchy()` method:
```python
from swarms import Agent
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
# Create specialized agents
research_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 swarm
swarm = 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 visualization
swarm.display_hierarchy()
```
This will output a visual tree structure showing the Director and all worker agents, making it easy to understand the swarm's organizational structure before executing tasks.
## Key Takeaways
1. **Agent Specialization**: Create agents with specific, well-defined expertise areas
@ -222,5 +264,6 @@ print(result)
3. **Appropriate Loop Count**: Set `max_loops` based on task complexity (1-3 for most tasks)
4. **Verbose Logging**: Enable verbose mode during development for debugging
5. **Context Preservation**: The swarm maintains full conversation history automatically
6. **Hierarchy Visualization**: Use `display_hierarchy()` to visualize swarm structure before execution
For more detailed information about the `HierarchicalSwarm` API and advanced usage patterns, see the [main documentation](hierarchical_swarm.md).

@ -35,6 +35,7 @@ The Hierarchical Swarm follows a clear workflow pattern:
| **Comprehensive Logging** | Detailed logging for debugging and monitoring |
| **Live Streaming** | Real-time streaming callbacks for monitoring agent outputs |
| **Token-by-Token Updates** | Watch text formation in real-time as agents generate responses |
| **Hierarchy Visualization** | Visual tree representation of swarm structure with `display_hierarchy()` |
## Constructor
@ -70,6 +71,65 @@ Initializes a new HierarchicalSwarm instance.
## Core Methods
### `display_hierarchy()`
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.
#### Returns
| Type | Description |
|------|-------------|
| `None` | Prints the hierarchy visualization to the console |
#### Example
```python
from swarms import Agent
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
# Create specialized agents
research_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 swarm
swarm = 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 visualization
swarm.display_hierarchy()
```
The output will show a visual tree structure like:
```
┌─ HierarchicalSwarm Hierarchy: Swarms Corporation Operations ─┐
│ │
│ 🎯 Director [claude-haiku-4-5] │
│ ├─ 🤖 Research-Analyst [gpt-4o-mini] - Specialized in... │
│ ├─ 🤖 Data-Analyst [gpt-4o-mini] - Expert in data... │
│ └─ 🤖 Strategy-Consultant [gpt-4o-mini] - Specialized... │
└───────────────────────────────────────────────────────────────┘
```
### `run()`
Executes the hierarchical swarm for a specified number of feedback loops, processing the task through multiple iterations for refinement and improvement.

@ -12,9 +12,6 @@ agent = Agent(
top_p=None,
)
out = agent.run(
task="What are the top five best energy stocks across nuclear, solar, gas, and other energy sources?",
n=1,
)
out = agent.run(task="What are the top five best energy stocks across nuclear, solar, gas, and other energy sources?",)
print(out)

@ -6,60 +6,90 @@ This directory contains comprehensive examples demonstrating various capabilitie
### Multi-Agent Systems
- **[multi_agent/](multi_agent/)** - Advanced multi-agent patterns including agent rearrangement, auto swarm builder (ASB), batched workflows, board of directors, caching, concurrent processing, councils, debates, elections, forest swarms, graph workflows, group chats, heavy swarms, hierarchical swarms, majority voting, orchestration examples, social algorithms, simulations, spreadsheet examples, and swarm routing.
- **[multi_agent/](multi_agent/)** - Advanced multi-agent patterns including agent rearrangement, auto swarm builder (ASB), batched workflows, board of directors, caching, concurrent processing, councils, debates, elections, forest swarms, graph workflows, group chats, heavy swarms, hierarchical swarms, LLM council, majority voting, orchestration examples, paper implementations, sequential workflows, social algorithms, simulations, spreadsheet examples, swarm routing, and utilities.
- [README.md](multi_agent/README.md) - Complete multi-agent examples documentation
- [duo_agent.py](multi_agent/duo_agent.py) - Two-agent collaboration example
- [llm_council_examples/](multi_agent/llm_council_examples/) - LLM Council collaboration patterns
- [caching_examples/](multi_agent/caching_examples/) - Agent caching examples
### Single Agent Systems
- **[single_agent/](single_agent/)** - Single agent implementations including demos, external agent integrations, LLM integrations (Azure, Claude, DeepSeek, Mistral, OpenAI, Qwen), onboarding, RAG, reasoning agents, tools integration, utils, and vision capabilities.
- **[single_agent/](single_agent/)** - Single agent implementations including demos, external agent integrations, LLM integrations (Azure, Claude, DeepSeek, Mistral, OpenAI, Qwen), onboarding, RAG, reasoning agents, tools integration, utils, vision capabilities, and MCP integration.
- [README.md](single_agent/README.md) - Complete single agent examples documentation
- [simple_agent.py](single_agent/simple_agent.py) - Basic single agent example
- [agent_mcp.py](single_agent/agent_mcp.py) - MCP integration example
- [rag/](single_agent/rag/) - Retrieval Augmented Generation (RAG) implementations with vector database integrations
### Tools & Integrations
- **[tools/](tools/)** - Tool integration examples including agent-as-tools, base tool implementations, browser automation, Claude integration, Exa search, Firecrawl, multi-tool usage, and Stagehand integration.
- [README.md](tools/README.md) - Complete tools examples documentation
- [agent_as_tools.py](tools/agent_as_tools.py) - Using agents as tools
- [browser_use_as_tool.py](tools/browser_use_as_tool.py) - Browser automation tool
- [exa_search_agent.py](tools/exa_search_agent.py) - Exa search integration
- [firecrawl_agents_example.py](tools/firecrawl_agents_example.py) - Firecrawl integration
- [base_tool_examples/](tools/base_tool_examples/) - Base tool implementation examples
- [multii_tool_use/](tools/multii_tool_use/) - Multi-tool usage examples
- [stagehand/](tools/stagehand/) - Stagehand UI automation
### Model Integrations
- **[models/](models/)** - Various model integrations including Cerebras, GPT-5, GPT-OSS, Llama 4, Lumo, and Ollama implementations with concurrent processing examples and provider-specific configurations.
- **[models/](models/)** - Various model integrations including Cerebras, GPT-5, GPT-OSS, Llama 4, Lumo, O3, Ollama, and vLLM implementations with concurrent processing examples and provider-specific configurations.
- [README.md](models/README.md) - Model integration documentation
- [simple_example_ollama.py](models/simple_example_ollama.py) - Ollama integration example
- [cerebas_example.py](models/cerebas_example.py) - Cerebras model example
- [lumo_example.py](models/lumo_example.py) - Lumo model example
- [example_o3.py](models/example_o3.py) - O3 model example
- [gpt_5/](models/gpt_5/) - GPT-5 model examples
- [gpt_oss_examples/](models/gpt_oss_examples/) - GPT-OSS examples
- [llama4_examples/](models/llama4_examples/) - Llama 4 examples
- [main_providers/](models/main_providers/) - Main provider configurations
- [vllm/](models/vllm/) - vLLM integration examples
### API & Protocols
- **[swarms_api_examples/](swarms_api_examples/)** - Swarms API usage examples including agent overview, batch processing, client integration, team examples, analysis, and rate limiting.
- [README.md](swarms_api_examples/README.md) - API examples documentation
- [client_example.py](swarms_api_examples/client_example.py) - API client example
- [batch_example.py](swarms_api_examples/batch_example.py) - Batch processing example
- **[swarms_api/](swarms_api/)** - Swarms API usage examples including agent overview, batch processing, client integration, team examples, analysis, and rate limiting.
- [README.md](swarms_api/README.md) - API examples documentation
- [client_example.py](swarms_api/client_example.py) - API client example
- [batch_example.py](swarms_api/batch_example.py) - Batch processing example
- [hospital_team.py](swarms_api/hospital_team.py) - Hospital management team simulation
- [legal_team.py](swarms_api/legal_team.py) - Legal team collaboration example
- [icd_ten_analysis.py](swarms_api/icd_ten_analysis.py) - ICD-10 medical code analysis
- [rate_limits.py](swarms_api/rate_limits.py) - Rate limiting and throttling examples
- **[mcp/](mcp/)** - Model Context Protocol (MCP) integration examples including agent implementations, multi-connection setups, server configurations, and utility functions.
- **[mcp/](mcp/)** - Model Context Protocol (MCP) integration examples including agent implementations, multi-connection setups, server configurations, utility functions, and multi-MCP guides.
- [README.md](mcp/README.md) - MCP examples documentation
- [multi_mcp_example.py](mcp/multi_mcp_example.py) - Multi-MCP connection example
- [agent_examples/](mcp/agent_examples/) - Agent-based MCP examples
- [servers/](mcp/servers/) - MCP server implementations
- [mcp_utils/](mcp/mcp_utils/) - MCP utility functions
- [multi_mcp_guide/](mcp/multi_mcp_guide/) - Multi-MCP setup guides
- **[aop_examples/](aop_examples/)** - Agents over Protocol (AOP) examples demonstrating MCP server setup, agent discovery, client interactions, queue-based task submission, and medical AOP implementations.
- **[aop_examples/](aop_examples/)** - Agents over Protocol (AOP) examples demonstrating MCP server setup, agent discovery, client interactions, queue-based task submission, medical AOP implementations, and utility functions.
- [README.md](aop_examples/README.md) - AOP examples documentation
- [server.py](aop_examples/server.py) - AOP server implementation
- [client/](aop_examples/client/) - AOP client examples and agent discovery
- [discovery/](aop_examples/discovery/) - Agent discovery examples
- [medical_aop/](aop_examples/medical_aop/) - Medical AOP implementations
- [utils/](aop_examples/utils/) - AOP utility functions
### Advanced Capabilities
- **[reasoning_agents/](reasoning_agents/)** - Advanced reasoning capabilities including agent judge evaluation systems, O3 model integration, and mixture of agents (MOA) sequential examples.
- **[reasoning_agents/](reasoning_agents/)** - Advanced reasoning capabilities including agent judge evaluation systems, O3 model integration, mixture of agents (MOA) sequential examples, and reasoning agent router examples.
- [README.md](reasoning_agents/README.md) - Reasoning agents documentation
- [example_o3.py](reasoning_agents/example_o3.py) - O3 model example
- [moa_seq_example.py](reasoning_agents/moa_seq_example.py) - MOA sequential example
- **[rag/](rag/)** - Retrieval Augmented Generation (RAG) implementations with vector database integrations including Qdrant examples.
- [README.md](rag/README.md) - RAG documentation
- [qdrant_rag_example.py](rag/qdrant_rag_example.py) - Qdrant RAG example
- [agent_judge_examples/](reasoning_agents/agent_judge_examples/) - Agent judge evaluation systems
- [reasoning_agent_router_examples/](reasoning_agents/reasoning_agent_router_examples/) - Reasoning agent router examples
### Guides & Tutorials
- **[guides/](guides/)** - Comprehensive guides and tutorials including generation length blog, geo guesser agent, graph workflow guide, hierarchical marketing team, nano banana Jarvis agent, smart database, web scraper agents, and workshop examples (840_update, 850_workshop).
- **[guides/](guides/)** - Comprehensive guides and tutorials including demos, generation length blog, geo guesser agent, graph workflow guide, hackathon examples, hierarchical marketing team, nano banana Jarvis agent, smart database, web scraper agents, workshops, x402 examples, and workshop examples (840_update, 850_workshop).
- [README.md](guides/README.md) - Guides documentation
- [hiearchical_marketing_team.py](guides/hiearchical_marketing_team.py) - Hierarchical marketing team example
- [demos/](guides/demos/) - Various demonstration examples
- [hackathons/](guides/hackathons/) - Hackathon project examples
- [workshops/](guides/workshops/) - Workshop examples
- [x402_examples/](guides/x402_examples/) - X402 protocol examples
### Deployment
@ -72,6 +102,11 @@ This directory contains comprehensive examples demonstrating various capabilitie
- **[utils/](utils/)** - Utility functions and helper implementations including agent loader, communication examples, concurrent wrappers, miscellaneous utilities, and telemetry.
- [README.md](utils/README.md) - Utils documentation
- [agent_loader/](utils/agent_loader/) - Agent loading utilities
- [communication_examples/](utils/communication_examples/) - Agent communication patterns
- [concurrent_wrapper_examples.py](utils/concurrent_wrapper_examples.py) - Concurrent processing wrappers
- [misc/](utils/misc/) - Miscellaneous utility functions
- [telemetry/](utils/telemetry/) - Telemetry and monitoring utilities
### User Interface
@ -97,8 +132,8 @@ This directory contains comprehensive examples demonstrating various capabilitie
5. **Interested in AOP?** Try [aop_examples/client/example_new_agent_tools.py](aop_examples/client/example_new_agent_tools.py) for agent discovery
6. **Want to see social algorithms?** Check out [multi_agent/social_algorithms_examples/](multi_agent/social_algorithms_examples/)
7. **Looking for guides?** Visit [guides/](guides/) for comprehensive tutorials
8. **Need RAG?** Try [rag/qdrant_rag_example.py](rag/qdrant_rag_example.py)
9. **Want reasoning agents?** Check out [reasoning_agents/example_o3.py](reasoning_agents/example_o3.py)
8. **Need RAG?** Try [single_agent/rag/](single_agent/rag/) for RAG examples
9. **Want reasoning agents?** Check out [reasoning_agents/](reasoning_agents/) for reasoning agent examples
## Key Examples by Category
@ -115,7 +150,7 @@ This directory contains comprehensive examples demonstrating various capabilitie
- [Simple Agent](single_agent/simple_agent.py) - Basic agent setup
- [Reasoning Agents](single_agent/reasoning_agent_examples/) - Advanced reasoning patterns
- [Vision Agents](single_agent/vision/multimodal_example.py) - Vision and multimodal capabilities
- [RAG Agents](single_agent/rag/qdrant_rag_example.py) - Retrieval augmented generation
- [RAG Agents](single_agent/rag/) - Retrieval augmented generation
### Tool Integrations

@ -14,6 +14,7 @@ This directory contains examples demonstrating hierarchical swarm patterns for m
- [hs_stock_team.py](hs_stock_team.py) - Stock trading team
- [hybrid_hiearchical_swarm.py](hybrid_hiearchical_swarm.py) - Hybrid approach
- [sector_analysis_hiearchical_swarm.py](sector_analysis_hiearchical_swarm.py) - Sector analysis
- [display_hierarchy_example.py](display_hierarchy_example.py) - Visualize swarm hierarchy structure
## Subdirectories

@ -0,0 +1,47 @@
from swarms import Agent, HierarchicalSwarm
# Create specialized agents
research_agent = Agent(
agent_name="Research-Analyst",
agent_description="Specialized in comprehensive research and data gathering",
model_name="gpt-4o-mini",
max_loops=1,
verbose=False,
)
analysis_agent = Agent(
agent_name="Data-Analyst",
agent_description="Expert in data analysis and pattern recognition",
model_name="gpt-4o-mini",
max_loops=1,
verbose=False,
)
strategy_agent = Agent(
agent_name="Strategy-Consultant",
agent_description="Specialized in strategic planning and recommendations",
model_name="gpt-4o-mini",
max_loops=1,
verbose=False,
)
# Create hierarchical swarm with interactive dashboard
swarm = HierarchicalSwarm(
name="Swarms Corporation Operations",
description="Enterprise-grade hierarchical swarm for complex task execution",
agents=[research_agent, analysis_agent, strategy_agent],
max_loops=1,
interactive=False, # Enable the Arasaka dashboard
director_model_name="claude-haiku-4-5",
director_temperature=0.7,
director_top_p=None,
planning_enabled=True,
)
print(swarm.display_hierarchy())
# out = swarm.run(
# "Conduct a research analysis on water stocks and etfs"
# )
# print(out)

@ -38,7 +38,10 @@ swarm = HierarchicalSwarm(
planning_enabled=True,
)
out = swarm.run(
"Conduct a research analysis on water stocks and etfs"
)
print(out)
print(swarm.display_hierarchy())
# out = swarm.run(
# "Conduct a research analysis on water stocks and etfs"
# )
# print(out)

@ -85,7 +85,7 @@ swarms = "swarms.cli.main:main"
[tool.poetry.group.lint.dependencies]
black = ">=23.1,<26.0"
ruff = ">=0.5.1,<0.14.5"
ruff = ">=0.5.1,<0.14.7"
types-toml = "^0.10.8.1"
types-pytz = ">=2023.3,<2026.0"
types-chardet = "^5.0.4.6"

@ -971,7 +971,9 @@ def show_features():
)
category_table.add_column("Category", style="bold cyan", width=20)
category_table.add_column("Count", style="bold white", justify="center", width=10)
category_table.add_column(
"Count", style="bold white", justify="center", width=10
)
category_table.add_column("Features", style="dim white", width=60)
# Count features by category

@ -11,7 +11,6 @@ from swarms.structs.concurrent_workflow import ConcurrentWorkflow
from swarms.structs.conversation import Conversation
from swarms.structs.council_as_judge import CouncilAsAJudge
from swarms.structs.cron_job import CronJob
from swarms.structs.llm_council import LLMCouncil
from swarms.structs.debate_with_judge import DebateWithJudge
from swarms.structs.graph_workflow import (
Edge,
@ -35,6 +34,7 @@ from swarms.structs.interactive_groupchat import (
random_speaker,
round_robin_speaker,
)
from swarms.structs.llm_council import LLMCouncil
from swarms.structs.ma_blocks import (
aggregate,
find_agent_by_name,

@ -407,6 +407,8 @@ class AutoSwarmBuilder:
agents_dictionary = model.run(task)
agents_dictionary = json.loads(agents_dictionary)
return agents_dictionary
except Exception as e:
@ -437,6 +439,8 @@ class AutoSwarmBuilder:
f"Create the swarm spec for the following task: {task}"
)
swarm_spec = json.loads(swarm_spec)
print(swarm_spec)
print(type(swarm_spec))

@ -40,6 +40,7 @@ from rich.live import Live
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from rich.tree import Tree
from swarms.prompts.hiearchical_system_prompt import (
HIEARCHICAL_SWARM_SYSTEM_PROMPT,
@ -777,6 +778,77 @@ class HierarchicalSwarm:
add_to_conversation=False,
)
def display_hierarchy(self) -> None:
"""
Display the hierarchical structure of the swarm using Rich Tree.
This method creates a visual tree representation showing the Director
at the top level and all worker agents as children branches. The tree
is printed to the console with rich formatting.
The hierarchy visualization helps understand the organizational structure
of the swarm, with the Director coordinating all worker agents.
"""
console = Console()
# Create the root tree with Director
director_label = Text()
director_label.append("🎯 ", style="bold red")
director_label.append(self.director_name, style="bold white")
director_label.append(
f" [{self.director_model_name}]", style="dim cyan"
)
tree = Tree(director_label, guide_style="bold red")
# Add each worker agent as a branch
for agent in self.agents:
agent_label = Text()
# Get agent name
if hasattr(agent, "agent_name"):
agent_name = agent.agent_name
elif hasattr(agent, "name"):
agent_name = agent.name
else:
agent_name = f"Agent_{self.agents.index(agent)}"
# Get agent model if available
model_info = ""
if hasattr(agent, "model_name"):
model_info = f" [{agent.model_name}]"
elif hasattr(agent, "llm") and hasattr(
agent.llm, "model"
):
model_info = f" [{agent.llm.model}]"
# Get agent description if available
description = ""
if hasattr(agent, "agent_description"):
description = f" - {agent.agent_description[:50]}"
elif hasattr(agent, "description"):
description = f" - {agent.description[:50]}"
agent_label.append("🤖 ", style="bold cyan")
agent_label.append(agent_name, style="bold cyan")
if model_info:
agent_label.append(model_info, style="dim cyan")
if description:
agent_label.append(description, style="dim white")
# Add agent as a branch
tree.add(agent_label)
# Create a panel with the tree
panel = Panel(
tree,
title=f"[bold white]HierarchicalSwarm Hierarchy: {self.name}[/bold white]",
border_style="red",
padding=(1, 2),
)
console.print(panel)
def prepare_worker_agents(self):
for agent in self.agents:
prompt = (

@ -59,6 +59,12 @@ def test_agent_building():
agents = swarm.create_agents_from_specs(specs)
agent = agents[0]
# Create agent from spec
agents = swarm.create_agents_from_specs(
{"agents": [agent_spec]}
)
agent = agents[0]
print("✓ Built agent with configuration:")
print(f" - Name: {agent.agent_name}")
print(f" - Description: {agent.agent_description}")
@ -116,7 +122,7 @@ def test_swarm_routing():
task = "Analyze the impact of AI on healthcare"
print("Starting task routing...")
result = swarm.swarm_router(agents, task)
result = swarm.initialize_swarm_router(agents, task)
print("✓ Task routed successfully")
print(

Loading…
Cancel
Save