diff --git a/.github/workflows/RELEASE.yml b/.github/workflows/RELEASE.yml index 2f20cb89..4ce68db3 100644 --- a/.github/workflows/RELEASE.yml +++ b/.github/workflows/RELEASE.yml @@ -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 diff --git a/.github/workflows/codacy.yml b/.github/workflows/codacy.yml index 632d9e03..9473405b 100644 --- a/.github/workflows/codacy.yml +++ b/.github/workflows/codacy.yml @@ -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 diff --git a/.github/workflows/code-quality-and-tests.yml b/.github/workflows/code-quality-and-tests.yml index 935b0448..025ee93b 100644 --- a/.github/workflows/code-quality-and-tests.yml +++ b/.github/workflows/code-quality-and-tests.yml @@ -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 }} diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 17ff6bb3..7bf20661 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -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: diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml index 507a2882..c71cc45e 100644 --- a/.github/workflows/dependency-review.yml +++ b/.github/workflows/dependency-review.yml @@ -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. diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index b933fd6e..7a4a8e5b 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -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 diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 2128be8a..9a6a5409 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -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 diff --git a/.github/workflows/pyre.yml b/.github/workflows/pyre.yml index 336569b5..bf5d085b 100644 --- a/.github/workflows/pyre.yml +++ b/.github/workflows/pyre.yml @@ -33,7 +33,7 @@ jobs: security-events: write runs-on: ubuntu-latest steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 with: submodules: true diff --git a/.github/workflows/pysa.yml b/.github/workflows/pysa.yml index 5f913465..590a6432 100644 --- a/.github/workflows/pysa.yml +++ b/.github/workflows/pysa.yml @@ -35,7 +35,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 with: submodules: true diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml index 1fb79863..4adb50b3 100644 --- a/.github/workflows/python-package.yml +++ b/.github/workflows/python-package.yml @@ -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: diff --git a/.github/workflows/test-main-features.yml b/.github/workflows/test-main-features.yml index 1ff92794..23b920ec 100644 --- a/.github/workflows/test-main-features.yml +++ b/.github/workflows/test-main-features.yml @@ -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 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 88a9430e..0223eb67 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -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 diff --git a/.github/workflows/trivy.yml b/.github/workflows/trivy.yml index b71ef7d4..3f72ed12 100644 --- a/.github/workflows/trivy.yml +++ b/.github/workflows/trivy.yml @@ -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: | diff --git a/docs/examples/llm_council_examples.md b/docs/examples/llm_council_examples.md index ab607dbc..eadebe9c 100644 --- a/docs/examples/llm_council_examples.md +++ b/docs/examples/llm_council_examples.md @@ -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 diff --git a/docs/requirements.txt b/docs/requirements.txt index 4e9c01f7..3746a2a8 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -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 diff --git a/docs/swarms/cli/cli_reference.md b/docs/swarms/cli/cli_reference.md index 7c1ad2e5..b96e8adc 100644 --- a/docs/swarms/cli/cli_reference.md +++ b/docs/swarms/cli/cli_reference.md @@ -5,20 +5,28 @@ The Swarms CLI is a comprehensive command-line interface for managing and execut ## Table of Contents - [Installation](#installation) - - [Basic Usage](#basic-usage) - - [Commands Reference](#commands-reference) - - [Global Arguments](#global-arguments) - - [Command-Specific Arguments](#command-specific-arguments) - + - [run-agents Command](#run-agents-command) + - [load-markdown Command](#load-markdown-command) + - [agent Command](#agent-command) + - [autoswarm Command](#autoswarm-command) + - [setup-check Command](#setup-check-command) + - [llm-council Command](#llm-council-command) + - [heavy-swarm Command](#heavy-swarm-command) + - [features Command](#features-command) - [Error Handling](#error-handling) - - [Examples](#examples) - - [Configuration](#configuration) +- [Advanced Features](#advanced-features) +- [Troubleshooting](#troubleshooting) +- [Integration](#integration) +- [Performance Considerations](#performance-considerations) +- [Security](#security) +- [Command Quick Reference](#command-quick-reference) +- [Support](#support) ## Installation @@ -43,6 +51,7 @@ swarms [options] |---------|-------------|-------------------| | `onboarding` | Start interactive onboarding process | None | | `help` | Display help message | None | +| `features` | Display all available features and actions in a comprehensive table | None | | `get-api-key` | Open API key portal in browser | None | | `check-login` | Verify login status and initialize cache | None | | `run-agents` | Execute agents from YAML configuration | `--yaml-file` | @@ -52,6 +61,8 @@ swarms [options] | `book-call` | Schedule strategy session | None | | `autoswarm` | Generate and execute autonomous swarm | `--task`, `--model` | | `setup-check` | Run comprehensive environment setup check | None | +| `llm-council` | Run LLM Council with multiple agents collaborating on a task | `--task` | +| `heavy-swarm` | Run HeavySwarm with specialized agents for complex task analysis | `--task` | ## Global Arguments @@ -221,6 +232,148 @@ swarms setup-check --verbose └─────────────────────────────────────────────────────────────────────────────┘ ``` +### `llm-council` Command + +Run the LLM Council with multiple specialized agents that collaborate, evaluate, and synthesize responses. + +The LLM Council follows a structured workflow: +1. **Independent Responses**: Each council member (GPT-5.1, Gemini 3 Pro, Claude Sonnet 4.5, Grok-4) independently responds to the query +2. **Peer Review**: All members review and rank each other's anonymized responses +3. **Synthesis**: A Chairman agent synthesizes all responses and rankings into a final comprehensive answer + +```bash +swarms llm-council [options] +``` + +#### Required Arguments + +| Argument | Type | Description | +|----------|------|-------------| +| `--task` | `str` | The query or question for the LLM Council to process | + +#### Optional Arguments + +| Argument | Type | Default | Description | +|----------|------|---------|-------------| +| `--verbose` | `bool` | `True` | Enable verbose output showing progress and intermediate results | + +**Example:** +```bash +# Basic usage +swarms llm-council --task "What are the best energy ETFs right now?" + +# With verbose output +swarms llm-council --task "What is the best approach to solve this problem?" --verbose +``` + +**How It Works:** + +The LLM Council creates a collaborative environment where: +- **Default Council Members**: GPT-5.1 (analytical), Gemini 3 Pro (concise), Claude Sonnet 4.5 (balanced), Grok-4 (creative) +- **Anonymized Evaluation**: Responses are anonymized before evaluation to ensure honest ranking +- **Cross-Model Evaluation**: Each model evaluates all responses, often selecting other models' responses as superior +- **Final Synthesis**: The Chairman (GPT-5.1 by default) synthesizes the best elements from all responses + +**Use Cases:** +- Complex problem-solving requiring multiple perspectives +- Research questions needing comprehensive analysis +- Decision-making scenarios requiring thorough evaluation +- Content generation with quality assurance + +### `heavy-swarm` Command + +Run HeavySwarm with specialized agents for complex task analysis and decomposition. + +HeavySwarm follows a structured workflow: +1. **Task Decomposition**: Breaks down tasks into specialized questions +2. **Parallel Execution**: Executes specialized agents in parallel +3. **Result Synthesis**: Integrates and synthesizes results +4. **Comprehensive Reporting**: Generates detailed final reports +5. **Iterative Refinement**: Optional multi-loop execution for iterative improvement + +```bash +swarms heavy-swarm [options] +``` + +#### Required Arguments + +| Argument | Type | Description | +|----------|------|-------------| +| `--task` | `str` | The task for HeavySwarm to analyze and process | + +#### Optional Arguments + +| Argument | Type | Default | Description | +|----------|------|---------|-------------| +| `--loops-per-agent` | `int` | `1` | Number of execution loops each agent should perform | +| `--question-agent-model-name` | `str` | `"gpt-4o-mini"` | Model name for the question generation agent | +| `--worker-model-name` | `str` | `"gpt-4o-mini"` | Model name for specialized worker agents | +| `--random-loops-per-agent` | `bool` | `False` | Enable random number of loops per agent (1-10 range) | +| `--verbose` | `bool` | `False` | Enable verbose output showing detailed progress | + +**Example:** +```bash +# Basic usage +swarms heavy-swarm --task "Analyze the current market trends for renewable energy" + +# With custom configuration +swarms heavy-swarm \ + --task "Research the best investment strategies for 2024" \ + --loops-per-agent 3 \ + --question-agent-model-name "gpt-4" \ + --worker-model-name "gpt-4" \ + --random-loops-per-agent \ + --verbose +``` + +**Specialized Agent Roles:** + +HeavySwarm includes specialized agents for different aspects of analysis: +- **Research Agent**: Fast, trustworthy, and reproducible research +- **Analysis Agent**: Statistical analysis and validated insights +- **Writing Agent**: Clear, structured documentation +- **Question Agent**: Task decomposition and question generation + +**Use Cases:** +- Complex research tasks requiring multiple perspectives +- Market analysis and financial research +- Technical analysis and evaluation +- Comprehensive report generation +- Multi-faceted problem solving + +### `features` Command + +Display all available CLI features and actions in a comprehensive, formatted table. + +This command provides a quick reference to all available features, their categories, descriptions, command syntax, and key parameters. + +```bash +swarms features +``` + +**No arguments required.** + +**Example:** +```bash +swarms features +``` + +**Output Includes:** +- **Main Features Table**: Complete list of all features with: + - Feature name + - Category (Setup, Auth, Execution, Creation, etc.) + - Description + - Command syntax + - Key parameters +- **Category Summary**: Overview of features grouped by category with counts +- **Usage Tips**: Quick tips for using the CLI effectively + +**Use Cases:** +- Quick reference when exploring CLI capabilities +- Discovering available features +- Understanding command syntax and parameters +- Learning about feature categories + ## Error Handling The CLI provides comprehensive error handling with formatted error messages: @@ -289,6 +442,34 @@ swarms autoswarm \ --model "gpt-4" ``` +### LLM Council Collaboration + +```bash +# Run LLM Council for collaborative problem solving +swarms llm-council \ + --task "What are the best strategies for reducing carbon emissions in manufacturing?" \ + --verbose +``` + +### HeavySwarm Complex Analysis + +```bash +# Run HeavySwarm for comprehensive task analysis +swarms heavy-swarm \ + --task "Analyze the impact of AI on the job market in 2024" \ + --loops-per-agent 2 \ + --question-agent-model-name "gpt-4" \ + --worker-model-name "gpt-4" \ + --verbose +``` + +### Viewing All Features + +```bash +# Display all available features +swarms features +``` + ## Configuration ### YAML Configuration Format @@ -386,6 +567,54 @@ Guided setup process including: - Usage examples +### Multi-Agent Collaboration + +The CLI supports advanced multi-agent architectures: + +#### LLM Council + +Collaborative problem-solving with multiple specialized models: + +```bash +swarms llm-council --task "Your question here" +``` + +**Features:** +- Multiple model perspectives (GPT-5.1, Gemini, Claude, Grok) +- Anonymous peer review and ranking +- Synthesized final responses +- Cross-model evaluation + +#### HeavySwarm + +Complex task analysis with specialized agent roles: + +```bash +swarms heavy-swarm --task "Your complex task here" +``` + +**Features:** +- Task decomposition into specialized questions +- Parallel agent execution +- Result synthesis and integration +- Iterative refinement with multiple loops +- Specialized agent roles (Research, Analysis, Writing, Question) + +### Feature Discovery + +Quickly discover all available features: + +```bash +swarms features +``` + +Displays comprehensive tables showing: +- All available commands +- Feature categories +- Command syntax +- Key parameters +- Usage examples + ## Troubleshooting @@ -451,6 +680,8 @@ swarms run-agents --yaml-file agents2.yaml | Model Selection | Choose appropriate models for task complexity | | Context Length | Monitor and optimize input sizes | | Rate Limiting | Respect API provider limits | +| Multi-Agent Execution | LLM Council and HeavySwarm execute agents in parallel for efficiency | +| Loop Configuration | Adjust `--loops-per-agent` based on task complexity and time constraints | ## Security @@ -461,6 +692,48 @@ swarms run-agents --yaml-file agents2.yaml | Input Validation | CLI validates all inputs before execution | | Error Sanitization | Sensitive information is not exposed in errors | +## Command Quick Reference + +### Quick Start Commands + +```bash +# Environment setup +swarms setup-check --verbose +swarms onboarding + +# View all features +swarms features + +# Get help +swarms help +``` + +### Agent Commands + +```bash +# Create custom agent +swarms agent --name "Agent" --task "Task" --system-prompt "Prompt" + +# Run agents from YAML +swarms run-agents --yaml-file agents.yaml + +# Load from markdown +swarms load-markdown --markdown-path ./agents/ +``` + +### Multi-Agent Commands + +```bash +# LLM Council +swarms llm-council --task "Your question" + +# HeavySwarm +swarms heavy-swarm --task "Your complex task" --loops-per-agent 2 --verbose + +# Auto-generate swarm +swarms autoswarm --task "Task description" --model "gpt-4" +``` + ## Support For additional support: @@ -470,3 +743,4 @@ For additional support: | **Community** | [Discord](https://discord.gg/EamjgSaEQf) | | **Issues** | [GitHub Issues](https://github.com/kyegomez/swarms/issues) | | **Strategy Sessions**| [Book a Call](https://cal.com/swarms/swarms-strategy-session) | +| **Documentation** | [Full Documentation](https://docs.swarms.world) | diff --git a/docs/swarms/concept/swarm_architectures.md b/docs/swarms/concept/swarm_architectures.md index 63bc3da8..90357636 100644 --- a/docs/swarms/concept/swarm_architectures.md +++ b/docs/swarms/concept/swarm_architectures.md @@ -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 diff --git a/docs/swarms/examples/hierarchical_swarm_example.md b/docs/swarms/examples/hierarchical_swarm_example.md index 86a5b85f..1f1b10c9 100644 --- a/docs/swarms/examples/hierarchical_swarm_example.md +++ b/docs/swarms/examples/hierarchical_swarm_example.md @@ -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). \ No newline at end of file diff --git a/docs/swarms/structs/hierarchical_swarm.md b/docs/swarms/structs/hierarchical_swarm.md index f458ac40..fe689e9e 100644 --- a/docs/swarms/structs/hierarchical_swarm.md +++ b/docs/swarms/structs/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. diff --git a/example.py b/example.py index 386b6597..203d4b4b 100644 --- a/example.py +++ b/example.py @@ -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) diff --git a/examples/README.md b/examples/README.md index 34259fd4..499b9349 100644 --- a/examples/README.md +++ b/examples/README.md @@ -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 @@ -79,16 +114,26 @@ This directory contains comprehensive examples demonstrating various capabilitie - [README.md](ui/README.md) - UI examples documentation - [chat.py](ui/chat.py) - Chat interface example +### Command Line Interface + +- **[cli/](cli/)** - CLI command examples demonstrating all available Swarms CLI features including setup, agent management, multi-agent architectures, and utilities. + - [README.md](cli/README.md) - CLI examples documentation + - [01_setup_check.sh](cli/01_setup_check.sh) - Environment setup verification + - [05_create_agent.sh](cli/05_create_agent.sh) - Create custom agents + - [08_llm_council.sh](cli/08_llm_council.sh) - LLM Council collaboration + - [09_heavy_swarm.sh](cli/09_heavy_swarm.sh) - HeavySwarm complex analysis + ## Quick Start 1. **New to Swarms?** Start with [single_agent/simple_agent.py](single_agent/simple_agent.py) for basic concepts -2. **Want multi-agent workflows?** Check out [multi_agent/duo_agent.py](multi_agent/duo_agent.py) -3. **Need tool integration?** Explore [tools/agent_as_tools.py](tools/agent_as_tools.py) -4. **Interested in AOP?** Try [aop_examples/client/example_new_agent_tools.py](aop_examples/client/example_new_agent_tools.py) for agent discovery -5. **Want to see social algorithms?** Check out [multi_agent/social_algorithms_examples/](multi_agent/social_algorithms_examples/) -6. **Looking for guides?** Visit [guides/](guides/) for comprehensive tutorials -7. **Need RAG?** Try [rag/qdrant_rag_example.py](rag/qdrant_rag_example.py) -8. **Want reasoning agents?** Check out [reasoning_agents/example_o3.py](reasoning_agents/example_o3.py) +2. **Want to use the CLI?** Check out [cli/](cli/) for all CLI command examples +3. **Want multi-agent workflows?** Check out [multi_agent/duo_agent.py](multi_agent/duo_agent.py) +4. **Need tool integration?** Explore [tools/agent_as_tools.py](tools/agent_as_tools.py) +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 [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 @@ -105,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 @@ -122,6 +167,14 @@ This directory contains comprehensive examples demonstrating various capabilitie - [Azure](single_agent/llms/azure_agent.py) - Azure OpenAI - [Ollama](models/simple_example_ollama.py) - Local Ollama models +### CLI Examples + +- [Setup Check](cli/01_setup_check.sh) - Verify environment setup +- [Create Agent](cli/05_create_agent.sh) - Create custom agents via CLI +- [LLM Council](cli/08_llm_council.sh) - Run LLM Council collaboration +- [HeavySwarm](cli/09_heavy_swarm.sh) - Run HeavySwarm for complex tasks +- [All CLI Examples](cli/) - Complete CLI examples directory + ## Documentation Each subdirectory contains its own README.md file with detailed descriptions and links to all available examples. Click on any folder above to explore its specific examples and use cases. diff --git a/examples/cli/01_setup_check.sh b/examples/cli/01_setup_check.sh new file mode 100644 index 00000000..523c806a --- /dev/null +++ b/examples/cli/01_setup_check.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +# Swarms CLI - Setup Check Example +# Verify your Swarms environment setup + +swarms setup-check + diff --git a/examples/cli/02_onboarding.sh b/examples/cli/02_onboarding.sh new file mode 100644 index 00000000..973a5630 --- /dev/null +++ b/examples/cli/02_onboarding.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +# Swarms CLI - Onboarding Example +# Start the interactive onboarding process + +swarms onboarding + diff --git a/examples/cli/03_get_api_key.sh b/examples/cli/03_get_api_key.sh new file mode 100644 index 00000000..f9775413 --- /dev/null +++ b/examples/cli/03_get_api_key.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +# Swarms CLI - Get API Key Example +# Open API key portal in browser + +swarms get-api-key + diff --git a/examples/cli/04_check_login.sh b/examples/cli/04_check_login.sh new file mode 100644 index 00000000..41479137 --- /dev/null +++ b/examples/cli/04_check_login.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +# Swarms CLI - Check Login Example +# Verify authentication status + +swarms check-login + diff --git a/examples/cli/05_create_agent.sh b/examples/cli/05_create_agent.sh new file mode 100644 index 00000000..eb4ed597 --- /dev/null +++ b/examples/cli/05_create_agent.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +# Swarms CLI - Create Agent Example +# Create and run a custom agent + +swarms agent \ + --name "Research Agent" \ + --description "AI research specialist" \ + --system-prompt "You are an expert research agent." \ + --task "Analyze current trends in renewable energy" \ + --model-name "gpt-4o-mini" + diff --git a/examples/cli/06_run_agents_yaml.sh b/examples/cli/06_run_agents_yaml.sh new file mode 100644 index 00000000..1856c54f --- /dev/null +++ b/examples/cli/06_run_agents_yaml.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +# Swarms CLI - Run Agents from YAML Example +# Execute agents from YAML configuration file + +swarms run-agents --yaml-file agents.yaml + diff --git a/examples/cli/07_load_markdown.sh b/examples/cli/07_load_markdown.sh new file mode 100644 index 00000000..b1ba6e56 --- /dev/null +++ b/examples/cli/07_load_markdown.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +# Swarms CLI - Load Markdown Agents Example +# Load agents from markdown files + +swarms load-markdown --markdown-path ./agents/ + diff --git a/examples/cli/08_llm_council.sh b/examples/cli/08_llm_council.sh new file mode 100644 index 00000000..eb29b726 --- /dev/null +++ b/examples/cli/08_llm_council.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +# Swarms CLI - LLM Council Example +# Run LLM Council for collaborative problem-solving + +swarms llm-council --task "What are the best energy ETFs to invest in right now?" + diff --git a/examples/cli/09_heavy_swarm.sh b/examples/cli/09_heavy_swarm.sh new file mode 100644 index 00000000..6dfadc00 --- /dev/null +++ b/examples/cli/09_heavy_swarm.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +# Swarms CLI - HeavySwarm Example +# Run HeavySwarm for complex task analysis + +swarms heavy-swarm --task "Analyze current market trends for renewable energy investments" + diff --git a/examples/cli/10_autoswarm.sh b/examples/cli/10_autoswarm.sh new file mode 100644 index 00000000..b94192f0 --- /dev/null +++ b/examples/cli/10_autoswarm.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +# Swarms CLI - Autoswarm Example +# Auto-generate swarm configuration + +swarms autoswarm --task "Analyze quarterly sales data" --model "gpt-4" + diff --git a/examples/cli/11_features.sh b/examples/cli/11_features.sh new file mode 100644 index 00000000..687200a4 --- /dev/null +++ b/examples/cli/11_features.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +# Swarms CLI - Features Example +# Display all available CLI features + +swarms features + diff --git a/examples/cli/12_help.sh b/examples/cli/12_help.sh new file mode 100644 index 00000000..09b6780c --- /dev/null +++ b/examples/cli/12_help.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +# Swarms CLI - Help Example +# Display comprehensive help documentation + +swarms help + diff --git a/examples/cli/13_auto_upgrade.sh b/examples/cli/13_auto_upgrade.sh new file mode 100644 index 00000000..6827f995 --- /dev/null +++ b/examples/cli/13_auto_upgrade.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +# Swarms CLI - Auto Upgrade Example +# Update Swarms to the latest version + +swarms auto-upgrade + diff --git a/examples/cli/14_book_call.sh b/examples/cli/14_book_call.sh new file mode 100644 index 00000000..e0108d9e --- /dev/null +++ b/examples/cli/14_book_call.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +# Swarms CLI - Book Call Example +# Schedule a strategy session + +swarms book-call + diff --git a/examples/cli/README.md b/examples/cli/README.md new file mode 100644 index 00000000..a002cd96 --- /dev/null +++ b/examples/cli/README.md @@ -0,0 +1,197 @@ +# Swarms CLI Examples + +This directory contains shell script examples demonstrating all available Swarms CLI commands and features. Each script is simple, focused, and demonstrates a single CLI command. + +## Quick Start + +All scripts are executable. Run them directly: + +```bash +chmod +x *.sh +./01_setup_check.sh +``` + +Or execute with bash: + +```bash +bash 01_setup_check.sh +``` + +## Available Examples + +### Setup & Configuration + +- **[01_setup_check.sh](examples/cli/01_setup_check.sh)** - Environment setup verification + ```bash + swarms setup-check + ``` + +- **[02_onboarding.sh](examples/cli/02_onboarding.sh)** - Interactive onboarding process + ```bash + swarms onboarding + ``` + +- **[03_get_api_key.sh](examples/cli/03_get_api_key.sh)** - Retrieve API keys + ```bash + swarms get-api-key + ``` + +- **[04_check_login.sh](examples/cli/04_check_login.sh)** - Verify authentication + ```bash + swarms check-login + ``` + +### Agent Management + +- **[05_create_agent.sh](examples/cli/05_create_agent.sh)** - Create and run custom agents + ```bash + swarms agent --name "Agent" --description "Description" --system-prompt "Prompt" --task "Task" + ``` + +- **[06_run_agents_yaml.sh](examples/cli/06_run_agents_yaml.sh)** - Execute agents from YAML + ```bash + swarms run-agents --yaml-file agents.yaml + ``` + +- **[07_load_markdown.sh](examples/cli/07_load_markdown.sh)** - Load agents from markdown files + ```bash + swarms load-markdown --markdown-path ./agents/ + ``` + +### Multi-Agent Architectures + +- **[08_llm_council.sh](examples/cli/08_llm_council.sh)** - Run LLM Council collaboration + ```bash + swarms llm-council --task "Your question here" + ``` + +- **[09_heavy_swarm.sh](examples/cli/09_heavy_swarm.sh)** - Run HeavySwarm for complex tasks + ```bash + swarms heavy-swarm --task "Your complex task here" + ``` + +- **[10_autoswarm.sh](examples/cli/10_autoswarm.sh)** - Auto-generate swarm configurations + ```bash + swarms autoswarm --task "Task description" --model "gpt-4" + ``` + +### Utilities + +- **[11_features.sh](examples/cli/11_features.sh)** - Display all available features + ```bash + swarms features + ``` + +- **[12_help.sh](examples/cli/12_help.sh)** - Display help documentation + ```bash + swarms help + ``` + +- **[13_auto_upgrade.sh](examples/cli/13_auto_upgrade.sh)** - Update Swarms package + ```bash + swarms auto-upgrade + ``` + +- **[14_book_call.sh](examples/cli/14_book_call.sh)** - Schedule strategy session + ```bash + swarms book-call + ``` + +### Run All Examples + +- **[run_all_examples.sh](examples/cli/run_all_examples.sh)** - Run multiple examples in sequence + ```bash + bash run_all_examples.sh + ``` + +## Script Structure + +Each script follows a simple pattern: + +1. **Shebang** - `#!/bin/bash` +2. **Comment** - Brief description of what the script does +3. **Single Command** - One CLI command execution + +Example: +```bash +#!/bin/bash + +# Swarms CLI - Setup Check Example +# Verify your Swarms environment setup + +swarms setup-check +``` + +## Usage Patterns + +### Basic Command Execution + +```bash +swarms [options] +``` + +### With Verbose Output + +```bash +swarms --verbose +``` + +### Environment Variables + +Set API keys before running scripts that require them: + +```bash +export OPENAI_API_KEY="your-key-here" +export ANTHROPIC_API_KEY="your-key-here" +export GOOGLE_API_KEY="your-key-here" +``` + +## Examples by Category + +### Setup & Diagnostics +- Environment setup verification +- Onboarding workflow +- API key management +- Authentication verification + +### Single Agent Operations +- Custom agent creation +- Agent configuration from YAML +- Agent loading from markdown + +### Multi-Agent Operations +- LLM Council for collaborative problem-solving +- HeavySwarm for complex analysis +- Auto-generated swarm configurations + +### Information & Help +- Feature discovery +- Help documentation +- Package management + +## File Paths + +All scripts are located in `examples/cli/`: + +- `examples/cli/01_setup_check.sh` +- `examples/cli/02_onboarding.sh` +- `examples/cli/03_get_api_key.sh` +- `examples/cli/04_check_login.sh` +- `examples/cli/05_create_agent.sh` +- `examples/cli/06_run_agents_yaml.sh` +- `examples/cli/07_load_markdown.sh` +- `examples/cli/08_llm_council.sh` +- `examples/cli/09_heavy_swarm.sh` +- `examples/cli/10_autoswarm.sh` +- `examples/cli/11_features.sh` +- `examples/cli/12_help.sh` +- `examples/cli/13_auto_upgrade.sh` +- `examples/cli/14_book_call.sh` +- `examples/cli/run_all_examples.sh` + +## Related Documentation + +- [CLI Reference](../../docs/swarms/cli/cli_reference.md) - Complete CLI documentation +- [Main Examples README](../README.md) - Other Swarms examples +- [Swarms Documentation](../../docs/) - Full Swarms documentation + diff --git a/examples/cli/run_all_examples.sh b/examples/cli/run_all_examples.sh new file mode 100644 index 00000000..ffd948e8 --- /dev/null +++ b/examples/cli/run_all_examples.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +# Swarms CLI - Run All Examples +# Run all CLI examples in sequence + +chmod +x *.sh + +swarms setup-check +swarms features +swarms help + diff --git a/examples/multi_agent/hiearchical_swarm/README.md b/examples/multi_agent/hiearchical_swarm/README.md index ca67f345..3ff9c1da 100644 --- a/examples/multi_agent/hiearchical_swarm/README.md +++ b/examples/multi_agent/hiearchical_swarm/README.md @@ -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 diff --git a/examples/multi_agent/hiearchical_swarm/display_hierarchy_example.py b/examples/multi_agent/hiearchical_swarm/display_hierarchy_example.py new file mode 100644 index 00000000..b470596d --- /dev/null +++ b/examples/multi_agent/hiearchical_swarm/display_hierarchy_example.py @@ -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) diff --git a/examples/multi_agent/llm_council_examples/llm_council_example.py b/examples/multi_agent/llm_council_examples/llm_council_example.py new file mode 100644 index 00000000..8dc1334a --- /dev/null +++ b/examples/multi_agent/llm_council_examples/llm_council_example.py @@ -0,0 +1,12 @@ +from swarms.structs.llm_council import LLMCouncil + +# Create the council +council = LLMCouncil(verbose=True, output_type="final") + +# Example query +query = "What are the top five best energy stocks across nuclear, solar, gas, and other energy sources?" + +# Run the council +result = council.run(query) + +print(result) diff --git a/examples/swarms_api_examples/README.md b/examples/swarms_api/README.md similarity index 100% rename from examples/swarms_api_examples/README.md rename to examples/swarms_api/README.md diff --git a/examples/swarms_api_examples/agent_overview.py b/examples/swarms_api/agent_overview.py similarity index 100% rename from examples/swarms_api_examples/agent_overview.py rename to examples/swarms_api/agent_overview.py diff --git a/examples/swarms_api_examples/batch_example.py b/examples/swarms_api/batch_example.py similarity index 100% rename from examples/swarms_api_examples/batch_example.py rename to examples/swarms_api/batch_example.py diff --git a/examples/swarms_api_examples/client_example.py b/examples/swarms_api/client_example.py similarity index 100% rename from examples/swarms_api_examples/client_example.py rename to examples/swarms_api/client_example.py diff --git a/examples/swarms_api_examples/hospital_team.py b/examples/swarms_api/hospital_team.py similarity index 100% rename from examples/swarms_api_examples/hospital_team.py rename to examples/swarms_api/hospital_team.py diff --git a/examples/swarms_api_examples/icd_ten_analysis.py b/examples/swarms_api/icd_ten_analysis.py similarity index 100% rename from examples/swarms_api_examples/icd_ten_analysis.py rename to examples/swarms_api/icd_ten_analysis.py diff --git a/examples/swarms_api_examples/legal_team.py b/examples/swarms_api/legal_team.py similarity index 100% rename from examples/swarms_api_examples/legal_team.py rename to examples/swarms_api/legal_team.py diff --git a/examples/swarms_api_examples/rate_limits.py b/examples/swarms_api/rate_limits.py similarity index 100% rename from examples/swarms_api_examples/rate_limits.py rename to examples/swarms_api/rate_limits.py diff --git a/hiearchical_swarm_example.py b/hiearchical_swarm_example.py index a5ed0633..b470596d 100644 --- a/hiearchical_swarm_example.py +++ b/hiearchical_swarm_example.py @@ -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) diff --git a/llm_council_example.py b/llm_council_example.py deleted file mode 100644 index 1cc415d0..00000000 --- a/llm_council_example.py +++ /dev/null @@ -1,22 +0,0 @@ -from swarms.structs.llm_council import LLMCouncil - -# Create the council -council = LLMCouncil(verbose=True) - -# Example query -query = "What are the top five best energy stocks across nuclear, solar, gas, and other energy sources?" - -# Run the council -result = council.run(query) - -# Print final response -print(result["final_response"]) - -# Optionally print evaluations -for name, evaluation in result["evaluations"].items(): - print(f"\n{name}:") - print( - evaluation[:500] + "..." - if len(evaluation) > 500 - else evaluation - ) diff --git a/pyproject.toml b/pyproject.toml index 0336f41f..d947301a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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" diff --git a/swarms/cli/main.py b/swarms/cli/main.py index e4458726..661dd578 100644 --- a/swarms/cli/main.py +++ b/swarms/cli/main.py @@ -22,6 +22,8 @@ from swarms.agents.create_agents_from_yaml import ( from swarms.structs.agent import Agent from swarms.structs.agent_loader import AgentLoader +from swarms.structs.llm_council import LLMCouncil +from swarms.structs.heavy_swarm import HeavySwarm from swarms.utils.formatter import formatter load_dotenv() @@ -625,6 +627,18 @@ def create_command_table() -> Table: "setup-check", "Run a comprehensive environment setup check", ), + ( + "llm-council", + "Run the LLM Council with multiple agents collaborating on a task", + ), + ( + "heavy-swarm", + "Run HeavySwarm with specialized agents for complex task analysis", + ), + ( + "features", + "Display all available features and actions in a comprehensive table", + ), ] for cmd, desc in commands: @@ -639,7 +653,7 @@ def create_detailed_command_table() -> Table: show_header=True, header_style=f"bold {COLORS['primary']}", border_style=COLORS["secondary"], - title="🚀 Swarms CLI - Complete Command Reference", + title="🚀Swarms CLI - Complete Command Reference", title_style=f"bold {COLORS['primary']}", padding=(0, 1), show_lines=True, @@ -744,6 +758,27 @@ def create_detailed_command_table() -> Table: "usage": "swarms setup-check [--verbose]", "args": "--verbose", }, + { + "cmd": "llm-council", + "category": "Collaboration", + "desc": "Run LLM Council with multiple agents", + "usage": "swarms llm-council --task 'Your question here' [--verbose]", + "args": "--task, --verbose", + }, + { + "cmd": "heavy-swarm", + "category": "Execution", + "desc": "Run HeavySwarm with specialized agents", + "usage": "swarms heavy-swarm --task 'Your task here' [--loops-per-agent 1] [--question-agent-model-name gpt-4o-mini] [--worker-model-name gpt-4o-mini] [--random-loops-per-agent] [--verbose]", + "args": "--task, --loops-per-agent, --question-agent-model-name, --worker-model-name, --random-loops-per-agent, --verbose", + }, + { + "cmd": "features", + "category": "Info", + "desc": "Display all available features and actions", + "usage": "swarms features", + "args": "None", + }, ] for cmd_info in commands: @@ -758,6 +793,225 @@ def create_detailed_command_table() -> Table: return table +def show_features(): + """ + Display all available CLI features and actions in a comprehensive table. + """ + console.print( + "\n[bold]🚀 Swarms CLI - All Available Features[/bold]\n", + style=COLORS["primary"], + ) + + # Create main features table + features_table = Table( + show_header=True, + header_style=f"bold {COLORS['primary']}", + border_style=COLORS["secondary"], + title="✨ Complete Feature Reference", + title_style=f"bold {COLORS['primary']}", + padding=(0, 1), + show_lines=True, + expand=True, + ) + + # Add columns + features_table.add_column( + "Feature", + style=f"bold {COLORS['accent']}", + width=20, + no_wrap=True, + ) + features_table.add_column( + "Category", + style="bold cyan", + width=15, + justify="center", + ) + features_table.add_column( + "Description", + style="white", + width=50, + no_wrap=False, + ) + features_table.add_column( + "Command", + style="dim yellow", + width=35, + no_wrap=False, + ) + features_table.add_column( + "Key Parameters", + style="dim magenta", + width=30, + no_wrap=False, + ) + + # Define all features + features = [ + { + "feature": "Environment Setup", + "category": "Setup", + "desc": "Check and verify your Swarms environment configuration", + "command": "swarms setup-check [--verbose]", + "params": "--verbose", + }, + { + "feature": "Onboarding", + "category": "Setup", + "desc": "Run environment setup check (alias for setup-check)", + "command": "swarms onboarding [--verbose]", + "params": "--verbose", + }, + { + "feature": "API Key Management", + "category": "Setup", + "desc": "Retrieve API keys from the Swarms platform", + "command": "swarms get-api-key", + "params": "None", + }, + { + "feature": "Authentication", + "category": "Auth", + "desc": "Verify login status and initialize authentication cache", + "command": "swarms check-login", + "params": "None", + }, + { + "feature": "YAML Agent Execution", + "category": "Execution", + "desc": "Execute agents from YAML configuration files", + "command": "swarms run-agents --yaml-file agents.yaml", + "params": "--yaml-file", + }, + { + "feature": "Markdown Agent Loading", + "category": "Loading", + "desc": "Load agents from markdown files with YAML frontmatter", + "command": "swarms load-markdown --markdown-path ./agents/", + "params": "--markdown-path, --concurrent", + }, + { + "feature": "Custom Agent Creation", + "category": "Creation", + "desc": "Create and run a custom agent with specified parameters", + "command": "swarms agent --name 'Agent' --task 'Task' --system-prompt 'Prompt'", + "params": "--name, --task, --system-prompt, --model-name, --temperature, --max-loops, --verbose", + }, + { + "feature": "Auto Swarm Generation", + "category": "AI Generation", + "desc": "Automatically generate and execute an autonomous swarm configuration", + "command": "swarms autoswarm --task 'analyze data' --model gpt-4", + "params": "--task, --model", + }, + { + "feature": "LLM Council", + "category": "Collaboration", + "desc": "Run LLM Council with multiple agents collaborating and evaluating responses", + "command": "swarms llm-council --task 'Your question' [--verbose]", + "params": "--task, --verbose", + }, + { + "feature": "HeavySwarm", + "category": "Execution", + "desc": "Run HeavySwarm with specialized agents for complex task analysis", + "command": "swarms heavy-swarm --task 'Your task' [options]", + "params": "--task, --loops-per-agent, --question-agent-model-name, --worker-model-name, --random-loops-per-agent, --verbose", + }, + { + "feature": "Package Upgrade", + "category": "Maintenance", + "desc": "Update Swarms to the latest version", + "command": "swarms auto-upgrade", + "params": "None", + }, + { + "feature": "Support Booking", + "category": "Support", + "desc": "Schedule a strategy session with the Swarms team", + "command": "swarms book-call", + "params": "None", + }, + { + "feature": "Help Documentation", + "category": "Info", + "desc": "Display comprehensive help message with all commands", + "command": "swarms help", + "params": "None", + }, + { + "feature": "Features List", + "category": "Info", + "desc": "Display all available features and actions in a table", + "command": "swarms features", + "params": "None", + }, + ] + + # Add rows to table + for feat in features: + features_table.add_row( + feat["feature"], + feat["category"], + feat["desc"], + feat["command"], + feat["params"], + ) + + console.print(features_table) + + # Add category summary + console.print("\n[bold cyan]📊 Feature Categories:[/bold cyan]\n") + + category_table = Table( + show_header=True, + header_style=f"bold {COLORS['primary']}", + border_style=COLORS["secondary"], + padding=(0, 2), + ) + + 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("Features", style="dim white", width=60) + + # Count features by category + categories = {} + for feat in features: + cat = feat["category"] + if cat not in categories: + categories[cat] = [] + categories[cat].append(feat["feature"]) + + for category, feature_list in sorted(categories.items()): + category_table.add_row( + category, + str(len(feature_list)), + ", ".join(feature_list), + ) + + console.print(category_table) + + # Add usage tips + tips_panel = Panel( + "[bold cyan]💡 Quick Tips:[/bold cyan]\n" + "• Use [yellow]swarms features[/yellow] to see this table anytime\n" + "• Use [yellow]swarms help[/yellow] for detailed command documentation\n" + "• Use [yellow]swarms setup-check --verbose[/yellow] for detailed diagnostics\n" + "• Most commands support [yellow]--verbose[/yellow] for detailed output\n" + "• Use [yellow]swarms --help[/yellow] for command-specific help", + title="📚 Usage Tips", + border_style=COLORS["success"], + padding=(1, 2), + ) + console.print(tips_panel) + + console.print( + "\n[dim]For more information, visit: https://docs.swarms.world[/dim]" + ) + + def show_help(): """Display a beautifully formatted help message with comprehensive command reference.""" console.print( @@ -771,7 +1025,10 @@ def show_help(): "• [yellow]swarms onboarding[/yellow] - Environment setup check\n" "• [yellow]swarms setup-check[/yellow] - Check your environment\n" "• [yellow]swarms agent --name 'MyAgent' --task 'Hello World'[/yellow] - Create agent\n" - "• [yellow]swarms autoswarm --task 'analyze data' --model gpt-4[/yellow] - Auto-generate swarm", + "• [yellow]swarms autoswarm --task 'analyze data' --model gpt-4[/yellow] - Auto-generate swarm\n" + "• [yellow]swarms llm-council --task 'Your question'[/yellow] - Run LLM Council\n" + "• [yellow]swarms heavy-swarm --task 'Your task'[/yellow] - Run HeavySwarm\n" + "• [yellow]swarms features[/yellow] - View all available features", title="⚡ Quick Usage Guide", border_style=COLORS["secondary"], padding=(1, 2), @@ -1028,6 +1285,189 @@ def load_markdown_agents( return [] +def run_heavy_swarm( + task: str, + loops_per_agent: int = 1, + question_agent_model_name: str = "gpt-4o-mini", + worker_model_name: str = "gpt-4o-mini", + random_loops_per_agent: bool = False, + verbose: bool = False, +): + """ + Run the HeavySwarm with a given task. + + Args: + task: The task/query for the HeavySwarm to process + loops_per_agent: Number of execution loops each agent should perform + question_agent_model_name: Model name for question generation + worker_model_name: Model name for specialized worker agents + random_loops_per_agent: Enable random number of loops per agent (1-10 range) + verbose: Whether to show verbose output + """ + try: + console.print( + "[yellow]🚀 Initializing HeavySwarm...[/yellow]" + ) + + # Create progress display + progress = Progress( + SpinnerColumn(), + TextColumn("[progress.description]{task.description}"), + console=console, + ) + + with progress: + # Add initial task + init_task = progress.add_task( + "Initializing swarm...", total=None + ) + + # Create HeavySwarm + progress.update( + init_task, + description="Creating HeavySwarm with specialized agents...", + ) + swarm = HeavySwarm( + loops_per_agent=loops_per_agent, + question_agent_model_name=question_agent_model_name, + worker_model_name=worker_model_name, + random_loops_per_agent=random_loops_per_agent, + verbose=verbose, + ) + + # Update progress + progress.update( + init_task, + description="Swarm initialized! Processing task...", + ) + + # Run the swarm + result = swarm.run(task=task) + + # Update progress on completion + progress.update( + init_task, + description="Task completed!", + completed=True, + ) + + # Display results + if result: + console.print( + "\n[bold green]✓ HeavySwarm completed successfully![/bold green]" + ) + + # Display result in a panel + result_panel = Panel( + str(result), + title="HeavySwarm Final Response", + border_style="green", + padding=(1, 2), + ) + console.print(result_panel) + + return result + else: + console.print( + "[yellow]⚠ HeavySwarm completed but returned no results.[/yellow]" + ) + return None + + except Exception as e: + show_error( + "HeavySwarm Error", + f"Failed to run HeavySwarm: {str(e)}\n\n" + "Please check:\n" + "1. Your API keys are set correctly\n" + "2. You have network connectivity\n" + "3. The task is properly formatted", + ) + return None + + +def run_llm_council(task: str, verbose: bool = True): + """ + Run the LLM Council with a given task. + + Args: + task: The task/query for the LLM Council to process + verbose: Whether to show verbose output + """ + try: + console.print( + "[yellow]🏛️ Initializing LLM Council...[/yellow]" + ) + + # Create progress display + progress = Progress( + SpinnerColumn(), + TextColumn("[progress.description]{task.description}"), + console=console, + ) + + with progress: + # Add initial task + init_task = progress.add_task( + "Initializing council...", total=None + ) + + # Create LLM Council + progress.update( + init_task, + description="Creating LLM Council with default members...", + ) + council = LLMCouncil(verbose=verbose) + + # Update progress + progress.update( + init_task, + description="Council initialized! Processing task...", + ) + + # Run the council + result = council.run(query=task) + + # Update progress on completion + progress.update( + init_task, + description="Task completed!", + completed=True, + ) + + # Display results + if result: + console.print( + "\n[bold green]✓ LLM Council completed successfully![/bold green]" + ) + + # Display result in a panel + result_panel = Panel( + str(result), + title="LLM Council Final Response", + border_style="green", + padding=(1, 2), + ) + console.print(result_panel) + + return result + else: + console.print( + "[yellow]⚠ LLM Council completed but returned no results.[/yellow]" + ) + return None + + except Exception as e: + show_error( + "LLM Council Error", + f"Failed to run LLM Council: {str(e)}\n\n" + "Please check:\n" + "1. Your API keys are set correctly\n" + "2. You have network connectivity\n" + "3. The task is properly formatted", + ) + return None + + def create_swarm_agent( name: str, description: str, @@ -1158,6 +1598,9 @@ def main(): "book-call", "autoswarm", "setup-check", + "llm-council", + "heavy-swarm", + "features", ], help="Command to execute", ) @@ -1285,6 +1728,30 @@ def main(): type=str, help="MCP URL for the agent", ) + # HeavySwarm specific arguments + parser.add_argument( + "--loops-per-agent", + type=int, + default=1, + help="Number of execution loops each agent should perform (default: 1)", + ) + parser.add_argument( + "--question-agent-model-name", + type=str, + default="gpt-4o-mini", + help="Model name for question generation agent (default: gpt-4o-mini)", + ) + parser.add_argument( + "--worker-model-name", + type=str, + default="gpt-4o-mini", + help="Model name for specialized worker agents (default: gpt-4o-mini)", + ) + parser.add_argument( + "--random-loops-per-agent", + action="store_true", + help="Enable random number of loops per agent (1-10 range)", + ) args = parser.parse_args() @@ -1297,6 +1764,8 @@ def main(): run_setup_check(verbose=args.verbose) elif args.command == "help": show_help() + elif args.command == "features": + show_features() elif args.command == "get-api-key": get_api_key() elif args.command == "check-login": @@ -1517,6 +1986,29 @@ def main(): run_autoswarm(args.task, args.model) elif args.command == "setup-check": run_setup_check(verbose=args.verbose) + elif args.command == "llm-council": + if not args.task: + show_error( + "Missing required argument: --task", + "Example usage: swarms llm-council --task 'What is the best approach to solve this problem?'", + ) + exit(1) + run_llm_council(task=args.task, verbose=args.verbose) + elif args.command == "heavy-swarm": + if not args.task: + show_error( + "Missing required argument: --task", + "Example usage: swarms heavy-swarm --task 'Analyze the current market trends'", + ) + exit(1) + run_heavy_swarm( + task=args.task, + loops_per_agent=args.loops_per_agent, + question_agent_model_name=args.question_agent_model_name, + worker_model_name=args.worker_model_name, + random_loops_per_agent=args.random_loops_per_agent, + verbose=args.verbose, + ) except Exception as e: console.print( f"[{COLORS['error']}]Error: {str(e)}[/{COLORS['error']}]" diff --git a/swarms/structs/__init__.py b/swarms/structs/__init__.py index 6952d2b0..ec292632 100644 --- a/swarms/structs/__init__.py +++ b/swarms/structs/__init__.py @@ -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, diff --git a/swarms/structs/auto_swarm_builder.py b/swarms/structs/auto_swarm_builder.py index 514cb79c..08c75164 100644 --- a/swarms/structs/auto_swarm_builder.py +++ b/swarms/structs/auto_swarm_builder.py @@ -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)) diff --git a/swarms/structs/hiearchical_swarm.py b/swarms/structs/hiearchical_swarm.py index 49b63595..8b8f8fdf 100644 --- a/swarms/structs/hiearchical_swarm.py +++ b/swarms/structs/hiearchical_swarm.py @@ -34,6 +34,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, @@ -748,6 +749,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 = ( diff --git a/swarms/structs/llm_council.py b/swarms/structs/llm_council.py index a303fa12..c732f058 100644 --- a/swarms/structs/llm_council.py +++ b/swarms/structs/llm_council.py @@ -17,10 +17,14 @@ from swarms.structs.multi_agent_exec import ( run_agents_concurrently, batched_grid_agent_execution, ) -from swarms.utils.history_output_formatter import HistoryOutputType, history_output_formatter +from swarms.utils.history_output_formatter import ( + HistoryOutputType, + history_output_formatter, +) from swarms.structs.conversation import Conversation from swarms.structs.swarm_id import swarm_id + def get_gpt_councilor_prompt() -> str: """ Get system prompt for GPT-5.1 councilor. @@ -272,7 +276,7 @@ class LLMCouncil: council_members: Optional[List[Agent]] = None, chairman_model: str = "gpt-5.1", verbose: bool = True, - output_type: HistoryOutputType = "dict", + output_type: HistoryOutputType = "dict-all-except-first", ): """ Initialize the LLM Council. @@ -306,8 +310,10 @@ class LLMCouncil: verbose=verbose, temperature=0.7, ) - - self.conversation = Conversation(name=f"[LLM Council] [Conversation][{name}]") + + self.conversation = Conversation( + name=f"[LLM Council] [Conversation][{name}]" + ) if self.verbose: print( @@ -365,7 +371,7 @@ class LLMCouncil: agent_name="Grok-4-Councilor", agent_description="Creative and innovative AI councilor specializing in unique perspectives and creative solutions", system_prompt=get_grok_councilor_prompt(), - model_name="x-ai/grok-4", # Using available model as proxy for Grok-4 + model_name="xai/grok-4-1-fast-reasoning", # Using available model as proxy for Grok-4 max_loops=1, verbose=False, temperature=0.8, @@ -513,4 +519,4 @@ class LLMCouncil: Returns: List of formatted outputs based on output_type """ - return [self.run(task) for task in tasks] \ No newline at end of file + return [self.run(task) for task in tasks] diff --git a/swarms/structs/swarm_router.py b/swarms/structs/swarm_router.py index dd13ee08..57a67a12 100644 --- a/swarms/structs/swarm_router.py +++ b/swarms/structs/swarm_router.py @@ -256,7 +256,7 @@ class SwarmRouter: heavy_swarm_swarm_show_output ) self.chairman_model = chairman_model - + # Initialize swarm factory for O(1) lookup performance self._swarm_factory = self._initialize_swarm_factory() self._swarm_cache = {} # Cache for created swarms @@ -446,7 +446,7 @@ class SwarmRouter: aggregation_strategy=self.aggregation_strategy, show_dashboard=False, ) - + def _create_llm_council(self, *args, **kwargs): """Factory function for LLMCouncil.""" return LLMCouncil( diff --git a/tests/structs/test_auto_swarms_builder.py b/tests/structs/test_auto_swarms_builder.py index 1d6e8762..3952a794 100644 --- a/tests/structs/test_auto_swarms_builder.py +++ b/tests/structs/test_auto_swarms_builder.py @@ -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(