commit
a7b783f717
@ -0,0 +1,89 @@
|
|||||||
|
# .github/workflows/comprehensive_tests.yml
|
||||||
|
|
||||||
|
name: Swarms Comprehensive Tests
|
||||||
|
|
||||||
|
# This workflow triggers on pushes and pull requests to the master branch.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ master ]
|
||||||
|
pull_request:
|
||||||
|
branches: [ master ]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
# You can test against multiple Python versions here if needed.
|
||||||
|
python-version: ["3.10"]
|
||||||
|
|
||||||
|
steps:
|
||||||
|
# Step 1: Check out the code.
|
||||||
|
# For pull requests, this action automatically checks out the code
|
||||||
|
# from the PR's branch, not the master branch. This is the key
|
||||||
|
# to testing the proposed changes.
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# Step 2: Set up the specified Python version.
|
||||||
|
- name: Set up Python ${{ matrix.python-version }}
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: ${{ matrix.python-version }}
|
||||||
|
|
||||||
|
# Step 3: Install Poetry for dependency management.
|
||||||
|
- name: Install Poetry
|
||||||
|
uses: snok/install-poetry@v1
|
||||||
|
with:
|
||||||
|
virtualenvs-create: true
|
||||||
|
virtualenvs-in-project: true
|
||||||
|
|
||||||
|
# Step 4: Cache dependencies to speed up subsequent runs.
|
||||||
|
- name: Load cached venv
|
||||||
|
id: cached-poetry-dependencies
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: .venv
|
||||||
|
key: venv-${{ runner.os }}-${{ steps.setup-python.outputs.python-version }}-${{ hashFiles('**/poetry.lock') }}
|
||||||
|
|
||||||
|
# Step 5: Install dependencies and the project package itself.
|
||||||
|
# This is the crucial step. 'poetry install' will install all dependencies
|
||||||
|
# and also install the 'swarms' package from the checked-out PR code
|
||||||
|
# in editable mode within the virtual environment.
|
||||||
|
- name: Install dependencies
|
||||||
|
if: steps.cached-poetry-dependencies.outputs.cache-hit != 'true'
|
||||||
|
run: poetry install --no-interaction --with dev --all-extras
|
||||||
|
|
||||||
|
# Step 6: Create dummy image files required for multi-modal tests.
|
||||||
|
# This ensures your tests are self-contained.
|
||||||
|
- name: Create dummy image files for testing
|
||||||
|
run: |
|
||||||
|
mkdir -p tests/test_data
|
||||||
|
touch tests/test_data/image1.jpg
|
||||||
|
touch tests/test_data/image2.png
|
||||||
|
echo "dummy image data" > tests/test_data/image1.jpg
|
||||||
|
echo "dummy image data" > tests/test_data/image2.png
|
||||||
|
|
||||||
|
# Step 7: Run the comprehensive test suite.
|
||||||
|
# 'poetry run' executes the command within the virtual environment,
|
||||||
|
# ensuring that when 'tests/comprehensive_test.py' imports 'swarms',
|
||||||
|
# it's importing the code from the pull request.
|
||||||
|
- name: Run Comprehensive Test Suite
|
||||||
|
env:
|
||||||
|
# Securely pass API keys and other secrets to the test environment.
|
||||||
|
# These must be configured in your repository's secrets.
|
||||||
|
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||||
|
# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
# GITHUB_REPO_OWNER: "kyegomez"
|
||||||
|
# GITHUB_REPO_NAME: "swarms"
|
||||||
|
run: |
|
||||||
|
poetry run python tests/comprehensive_test.py
|
||||||
|
|
||||||
|
# Step 8: Upload the generated test report as an artifact.
|
||||||
|
# This happens even if the previous steps fail, allowing you to debug.
|
||||||
|
- name: Upload Test Report
|
||||||
|
if: always()
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: test-report-${{ matrix.python-version }}
|
||||||
|
path: test_runs/
|
@ -0,0 +1,73 @@
|
|||||||
|
name: Docker Build and Publish
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ "master" ]
|
||||||
|
# Publish semver tags as releases
|
||||||
|
tags: [ 'v*.*.*' ]
|
||||||
|
pull_request:
|
||||||
|
branches: [ "master" ]
|
||||||
|
|
||||||
|
env:
|
||||||
|
# Use docker.io for Docker Hub if empty
|
||||||
|
REGISTRY: docker.io
|
||||||
|
# github.repository as <account>/<repo>
|
||||||
|
IMAGE_NAME: ${{ github.repository }}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
# This is used to complete the identity challenge
|
||||||
|
# with sigstore/fulcio when running outside of PRs.
|
||||||
|
id-token: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# Setup QEMU for multi-platform builds
|
||||||
|
- name: Set up QEMU
|
||||||
|
uses: docker/setup-qemu-action@v3
|
||||||
|
|
||||||
|
# Setup Docker BuildX
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
# Login to Docker Hub
|
||||||
|
- name: Log into registry ${{ env.REGISTRY }}
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ${{ env.REGISTRY }}
|
||||||
|
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||||
|
|
||||||
|
# Extract metadata (tags, labels) for Docker
|
||||||
|
- name: Extract Docker metadata
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@v5
|
||||||
|
with:
|
||||||
|
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||||
|
tags: |
|
||||||
|
type=ref,event=branch
|
||||||
|
type=ref,event=pr
|
||||||
|
type=semver,pattern={{version}}
|
||||||
|
type=semver,pattern={{major}}.{{minor}}
|
||||||
|
type=semver,pattern={{major}}
|
||||||
|
type=sha
|
||||||
|
|
||||||
|
# Build and push Docker image
|
||||||
|
- name: Build and push Docker image
|
||||||
|
id: build-and-push
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
push: ${{ github.event_name != 'pull_request' }}
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
|
cache-from: type=gha
|
||||||
|
cache-to: type=gha,mode=max
|
@ -0,0 +1,65 @@
|
|||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.concurrent_workflow import ConcurrentWorkflow
|
||||||
|
|
||||||
|
# Initialize market research agent
|
||||||
|
market_researcher = Agent(
|
||||||
|
agent_name="Market-Researcher",
|
||||||
|
system_prompt="""You are a market research specialist. Your tasks include:
|
||||||
|
1. Analyzing market trends and patterns
|
||||||
|
2. Identifying market opportunities and threats
|
||||||
|
3. Evaluating competitor strategies
|
||||||
|
4. Assessing customer needs and preferences
|
||||||
|
5. Providing actionable market insights""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
# streaming_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize financial analyst agent
|
||||||
|
financial_analyst = Agent(
|
||||||
|
agent_name="Financial-Analyst",
|
||||||
|
system_prompt="""You are a financial analysis expert. Your responsibilities include:
|
||||||
|
1. Analyzing financial statements
|
||||||
|
2. Evaluating investment opportunities
|
||||||
|
3. Assessing risk factors
|
||||||
|
4. Providing financial forecasts
|
||||||
|
5. Recommending financial strategies""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
# streaming_on=True,
|
||||||
|
temperature=0.7,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize technical analyst agent
|
||||||
|
technical_analyst = Agent(
|
||||||
|
agent_name="Technical-Analyst",
|
||||||
|
system_prompt="""You are a technical analysis specialist. Your focus areas include:
|
||||||
|
1. Analyzing price patterns and trends
|
||||||
|
2. Evaluating technical indicators
|
||||||
|
3. Identifying support and resistance levels
|
||||||
|
4. Assessing market momentum
|
||||||
|
5. Providing trading recommendations""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
# streaming_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create list of agents
|
||||||
|
agents = [market_researcher, financial_analyst, technical_analyst]
|
||||||
|
|
||||||
|
|
||||||
|
router = ConcurrentWorkflow(
|
||||||
|
name="market-analysis-router",
|
||||||
|
agents=agents,
|
||||||
|
max_loops=1,
|
||||||
|
# output_type="all",
|
||||||
|
show_dashboard=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
result = router.run(
|
||||||
|
"Analyze Tesla (TSLA) stock from market, financial, and technical perspectives"
|
||||||
|
)
|
||||||
|
|
||||||
|
print(result)
|
@ -0,0 +1,22 @@
|
|||||||
|
from swarms import SelfConsistencyAgent
|
||||||
|
|
||||||
|
# Initialize the reasoning agent router with self-consistency
|
||||||
|
reasoning_agent_router = SelfConsistencyAgent(
|
||||||
|
name="reasoning-agent",
|
||||||
|
description="A reasoning agent that can answer questions and help with tasks.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
system_prompt="You are a helpful assistant that can answer questions and help with tasks.",
|
||||||
|
max_loops=1,
|
||||||
|
num_samples=3, # Generate 3 independent responses
|
||||||
|
eval=False, # Disable evaluation mode
|
||||||
|
random_models_on=False, # Disable random model selection
|
||||||
|
majority_voting_prompt=None, # Use default majority voting prompt
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run the agent on a financial analysis task
|
||||||
|
result = reasoning_agent_router.run(
|
||||||
|
"What is the best possible financial strategy to maximize returns but minimize risk? Give a list of etfs to invest in and the percentage of the portfolio to allocate to each etf."
|
||||||
|
)
|
||||||
|
|
||||||
|
print("Financial Strategy Result:")
|
||||||
|
print(result)
|
After Width: | Height: | Size: 175 KiB |
@ -0,0 +1,167 @@
|
|||||||
|
# Multi-Agent Paper Implementations
|
||||||
|
|
||||||
|
At Swarms, we are passionate about democratizing access to cutting-edge multi-agent research and making advanced AI collaboration accessible to everyone. Our mission is to bridge the gap between academic research and practical implementation by providing production-ready, open-source implementations of the most impactful multi-agent research papers.
|
||||||
|
|
||||||
|
### Why Multi-Agent Research Matters
|
||||||
|
|
||||||
|
Multi-agent systems represent the next evolution in artificial intelligence, moving beyond single-agent limitations to harness the power of collective intelligence. These systems can:
|
||||||
|
|
||||||
|
- **Overcome Individual Agent Constraints**: Address memory limitations, hallucinations, and single-task focus through collaborative problem-solving
|
||||||
|
- **Achieve Superior Performance**: Combine specialized expertise across multiple agents to tackle complex, multifaceted challenges
|
||||||
|
- **Enable Scalable Solutions**: Distribute computational load and scale efficiently across multiple agents
|
||||||
|
- **Foster Innovation**: Create novel approaches through agent interaction and knowledge sharing
|
||||||
|
|
||||||
|
### Our Research Implementation Philosophy
|
||||||
|
|
||||||
|
We believe that the best way to advance the field is through practical implementation and real-world validation. Our approach includes:
|
||||||
|
|
||||||
|
- **Faithful Reproduction**: Implementing research papers with high fidelity to original methodologies
|
||||||
|
|
||||||
|
- **Production Enhancement**: Adding enterprise-grade features like error handling, monitoring, and scalability
|
||||||
|
|
||||||
|
- **Open Source Commitment**: Making all implementations freely available to the research community
|
||||||
|
|
||||||
|
- **Continuous Improvement**: Iterating on implementations based on community feedback and new research
|
||||||
|
|
||||||
|
### What You'll Find Here
|
||||||
|
|
||||||
|
This documentation showcases our comprehensive collection of multi-agent research implementations, including:
|
||||||
|
|
||||||
|
|
||||||
|
- **Academic Paper Implementations**: Direct implementations of published research papers
|
||||||
|
|
||||||
|
- **Enhanced Frameworks**: Production-ready versions with additional features and optimizations
|
||||||
|
|
||||||
|
- **Research Compilations**: Curated lists of influential multi-agent papers and resources
|
||||||
|
|
||||||
|
- **Practical Examples**: Ready-to-use code examples and tutorials
|
||||||
|
|
||||||
|
Whether you're a researcher looking to validate findings, a developer building production systems, or a student learning about multi-agent AI, you'll find valuable resources here to advance your work.
|
||||||
|
|
||||||
|
### Join the Multi-Agent Revolution
|
||||||
|
|
||||||
|
We invite you to explore these implementations, contribute to our research efforts, and help shape the future of collaborative AI. Together, we can unlock the full potential of multi-agent systems and create AI that truly works as a team.
|
||||||
|
|
||||||
|
## Implemented Research Papers
|
||||||
|
|
||||||
|
| Paper Name | Description | Original Paper | Implementation | Status | Key Features |
|
||||||
|
|------------|-------------|----------------|----------------|--------|--------------|
|
||||||
|
| **MALT (Multi-Agent Learning Task)** | A sophisticated orchestration framework that coordinates multiple specialized AI agents to tackle complex tasks through structured conversations. | [arXiv:2412.01928](https://arxiv.org/pdf/2412.01928) | [`swarms.structs.malt`](https://docs.swarms.world/en/latest/swarms/structs/malt/) | ✅ Complete | Creator-Verifier-Refiner architecture, structured conversations, reliability guarantees |
|
||||||
|
| **[MAI-DxO (MAI Diagnostic Orchestrator)](https://arxiv.org/abs/2506.22405)** | An open-source implementation of Microsoft Research's "[Sequential Diagnosis with Language Models](https://arxiv.org/abs/2506.22405)" paper, simulating a virtual panel of physician-agents for iterative medical diagnosis. | Microsoft Research Paper | [GitHub Repository](https://github.com/The-Swarm-Corporation/Open-MAI-Dx-Orchestrator) | ✅ Complete | Cost-effective medical diagnosis, physician-agent panel, iterative refinement |
|
||||||
|
| **[AI-CoScientist](https://storage.googleapis.com/coscientist_paper/ai_coscientist.pdf)** | A multi-agent AI framework for collaborative scientific research, implementing the "Towards an AI Co-Scientist" methodology with tournament-based hypothesis evolution. | "Towards an AI Co-Scientist" Paper | [GitHub Repository](https://github.com/The-Swarm-Corporation/AI-CoScientist) | ✅ Complete | Tournament-based selection, peer review systems, hypothesis evolution, Elo rating system |
|
||||||
|
| **[Mixture of Agents (MoA)](https://arxiv.org/abs/2406.04692)** | A sophisticated multi-agent architecture that implements parallel processing with iterative refinement, combining diverse expert agents for comprehensive analysis. | Multi-agent collaboration concepts | [`swarms.structs.moa`](https://docs.swarms.world/en/latest/swarms/structs/moa/) | ✅ Complete | Parallel processing, expert agent combination, iterative refinement, state-of-the-art performance |
|
||||||
|
| **Deep Research Swarm** | A production-grade research system that conducts comprehensive analysis across multiple domains using parallel processing and advanced AI agents. | Research methodology | [`swarms.structs.deep_research_swarm`](https://docs.swarms.world/en/latest/swarms/structs/deep_research_swarm/) | ✅ Complete | Parallel search processing, multi-agent coordination, information synthesis, concurrent execution |
|
||||||
|
| **Agent-as-a-Judge** | An evaluation framework that uses agents to evaluate other agents, implementing the "Agent-as-a-Judge: Evaluate Agents with Agents" methodology. | [arXiv:2410.10934](https://arxiv.org/abs/2410.10934) | [`swarms.agents.agent_judge`](https://docs.swarms.world/en/latest/swarms/agents/agent_judge/) | ✅ Complete | Agent evaluation, quality assessment, automated judging, performance metrics |
|
||||||
|
|
||||||
|
## Additional Research Resources
|
||||||
|
|
||||||
|
### Multi-Agent Papers Compilation
|
||||||
|
|
||||||
|
We maintain a comprehensive list of multi-agent research papers at: [awesome-multi-agent-papers](https://github.com/kyegomez/awesome-multi-agent-papers)
|
||||||
|
|
||||||
|
### Research Lists
|
||||||
|
|
||||||
|
Our research compilation includes:
|
||||||
|
|
||||||
|
- **Projects**: ModelScope-Agent, Gorilla, BMTools, LMQL, Langchain, MetaGPT, AutoGPT, and more
|
||||||
|
|
||||||
|
- **Research Papers**: BOLAA, ToolLLM, Communicative Agents, Mind2Web, Voyager, Tree of Thoughts, and many others
|
||||||
|
|
||||||
|
- **Blog Articles**: Latest insights and developments in autonomous agents
|
||||||
|
|
||||||
|
- **Talks**: Presentations from leading researchers like Geoffrey Hinton and Andrej Karpathy
|
||||||
|
|
||||||
|
|
||||||
|
## Implementation Details
|
||||||
|
|
||||||
|
### MALT Framework
|
||||||
|
|
||||||
|
The MALT implementation provides:
|
||||||
|
|
||||||
|
- **Three-Agent Architecture**: Creator, Verifier, and Refiner agents
|
||||||
|
|
||||||
|
- **Structured Workflow**: Coordinated task execution with conversation history
|
||||||
|
|
||||||
|
- **Reliability Features**: Error handling, validation, and quality assurance
|
||||||
|
|
||||||
|
- **Extensibility**: Custom agent integration and configuration options
|
||||||
|
|
||||||
|
|
||||||
|
### MAI-DxO System
|
||||||
|
|
||||||
|
The MAI Diagnostic Orchestrator features:
|
||||||
|
|
||||||
|
- **Virtual Physician Panel**: Multiple specialized medical agents
|
||||||
|
|
||||||
|
- **Cost Optimization**: Efficient diagnostic workflows
|
||||||
|
|
||||||
|
- **Iterative Refinement**: Continuous improvement of diagnoses
|
||||||
|
|
||||||
|
- **Medical Expertise**: Domain-specific knowledge and reasoning
|
||||||
|
|
||||||
|
|
||||||
|
### AI-CoScientist Framework
|
||||||
|
|
||||||
|
The AI-CoScientist implementation includes:
|
||||||
|
|
||||||
|
- **Tournament-Based Selection**: Elo rating system for hypothesis ranking
|
||||||
|
|
||||||
|
- **Peer Review System**: Comprehensive evaluation of scientific proposals
|
||||||
|
|
||||||
|
- **Hypothesis Evolution**: Iterative refinement based on feedback
|
||||||
|
|
||||||
|
- **Diversity Control**: Proximity analysis to maintain hypothesis variety
|
||||||
|
|
||||||
|
|
||||||
|
### Mixture of Agents (MoA)
|
||||||
|
|
||||||
|
The MoA architecture provides:
|
||||||
|
|
||||||
|
- **Parallel Processing**: Multiple agents working simultaneously
|
||||||
|
|
||||||
|
- **Expert Specialization**: Domain-specific agent capabilities
|
||||||
|
|
||||||
|
- **Iterative Refinement**: Continuous improvement through collaboration
|
||||||
|
|
||||||
|
- **State-of-the-Art Performance**: Achieving superior results through collective intelligence
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
We welcome contributions to implement additional research papers! If you'd like to contribute:
|
||||||
|
|
||||||
|
1. **Identify a paper**: Choose a relevant multi-agent research paper
|
||||||
|
2. **Propose implementation**: Submit an issue with your proposal
|
||||||
|
3. **Implement**: Create the implementation following our guidelines
|
||||||
|
4. **Document**: Add comprehensive documentation and examples
|
||||||
|
5. **Test**: Ensure robust testing and validation
|
||||||
|
|
||||||
|
## Citation
|
||||||
|
|
||||||
|
If you use any of these implementations in your research, please cite the original papers and the Swarms framework:
|
||||||
|
|
||||||
|
```bibtex
|
||||||
|
@misc{SWARMS_2022,
|
||||||
|
author = {Gomez, Kye and Pliny and More, Harshal and Swarms Community},
|
||||||
|
title = {{Swarms: Production-Grade Multi-Agent Infrastructure Platform}},
|
||||||
|
year = {2022},
|
||||||
|
howpublished = {\url{https://github.com/kyegomez/swarms}},
|
||||||
|
note = {Documentation available at \url{https://docs.swarms.world}},
|
||||||
|
version = {latest}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Community
|
||||||
|
|
||||||
|
Join our community to stay updated on the latest multi-agent research implementations:
|
||||||
|
|
||||||
|
- **Discord**: [Join our community](https://discord.gg/jM3Z6M9uMq)
|
||||||
|
|
||||||
|
- **Documentation**: [docs.swarms.world](https://docs.swarms.world)
|
||||||
|
|
||||||
|
- **GitHub**: [kyegomez/swarms](https://github.com/kyegomez/swarms)
|
||||||
|
|
||||||
|
- **Research Papers**: [awesome-multi-agent-papers](https://github.com/kyegomez/awesome-multi-agent-papers)
|
||||||
|
|
||||||
|
|
@ -0,0 +1,215 @@
|
|||||||
|
# Templates & Applications Documentation
|
||||||
|
|
||||||
|
The Swarms framework is a powerful multi-agent orchestration platform that enables developers to build sophisticated AI agent systems. This documentation showcases the extensive ecosystem of templates, applications, and tools built on the Swarms framework, organized by industry and application type.
|
||||||
|
|
||||||
|
🔗 **Main Repository**: [Swarms Framework](https://github.com/kyegomez/swarms)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🏥 Healthcare & Medical Applications
|
||||||
|
|
||||||
|
### Medical Diagnosis & Analysis
|
||||||
|
|
||||||
|
| Name | Description | Type | Repository |
|
||||||
|
|------|-------------|------|------------|
|
||||||
|
| [MRI-Swarm](https://github.com/The-Swarm-Corporation/MRI-Swarm) | Multi-agent system for MRI image analysis and diagnosis | Medical Imaging | Healthcare |
|
||||||
|
| [DermaSwarm](https://github.com/The-Swarm-Corporation/DermaSwarm) | Dermatology-focused agent swarm for skin condition analysis | Medical Diagnosis | Healthcare |
|
||||||
|
| [Multi-Modal-XRAY-Diagnosis](https://github.com/The-Swarm-Corporation/Multi-Modal-XRAY-Diagnosis-Medical-Swarm-Template) | X-ray diagnosis using multi-modal AI agents | Medical Imaging | Healthcare |
|
||||||
|
| [Open-MAI-Dx-Orchestrator](https://github.com/The-Swarm-Corporation/Open-MAI-Dx-Orchestrator) | Medical AI diagnosis orchestration platform | Medical Platform | Healthcare |
|
||||||
|
| [radiology-swarm](https://github.com/The-Swarm-Corporation/radiology-swarm) | Radiology-focused multi-agent system | Medical Imaging | Healthcare |
|
||||||
|
|
||||||
|
### Medical Operations & Administration
|
||||||
|
|
||||||
|
| Name | Description | Type | Repository |
|
||||||
|
|------|-------------|------|------------|
|
||||||
|
| [MedicalCoderSwarm](https://github.com/The-Swarm-Corporation/MedicalCoderSwarm) | Medical coding automation using agent swarms | Medical Coding | Healthcare |
|
||||||
|
| [pharma-swarm](https://github.com/The-Swarm-Corporation/pharma-swarm) | Pharmaceutical research and development agents | Pharmaceutical | Healthcare |
|
||||||
|
| [MedGuard](https://github.com/The-Swarm-Corporation/MedGuard) | Medical data security and compliance system | Medical Security | Healthcare |
|
||||||
|
| [MedInsight-Pro](https://github.com/The-Swarm-Corporation/MedInsight-Pro) | Advanced medical insights and analytics platform | Medical Analytics | Healthcare |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 💰 Financial Services & Trading
|
||||||
|
|
||||||
|
### Trading & Investment
|
||||||
|
|
||||||
|
| Name | Description | Type | Repository |
|
||||||
|
|------|-------------|------|------------|
|
||||||
|
| [automated-crypto-fund](https://github.com/The-Swarm-Corporation/automated-crypto-fund) | Automated cryptocurrency trading fund management | Crypto Trading | Finance |
|
||||||
|
| [CryptoAgent](https://github.com/The-Swarm-Corporation/CryptoAgent) | Cryptocurrency analysis and trading agent | Crypto Trading | Finance |
|
||||||
|
| [AutoHedge](https://github.com/The-Swarm-Corporation/AutoHedge) | Automated hedging strategies implementation | Risk Management | Finance |
|
||||||
|
| [BackTesterAgent](https://github.com/The-Swarm-Corporation/BackTesterAgent) | Trading strategy backtesting automation | Trading Tools | Finance |
|
||||||
|
| [ForexTreeSwarm](https://github.com/The-Swarm-Corporation/ForexTreeSwarm) | Forex trading decision tree swarm system | Forex Trading | Finance |
|
||||||
|
| [HTX-Swarm](https://github.com/The-Swarm-Corporation/HTX-Swarm) | HTX exchange integration and trading automation | Crypto Exchange | Finance |
|
||||||
|
|
||||||
|
### Financial Analysis & Management
|
||||||
|
|
||||||
|
| Name | Description | Type | Repository |
|
||||||
|
|------|-------------|------|------------|
|
||||||
|
| [TickrAgent](https://github.com/The-Swarm-Corporation/TickrAgent) | Stock ticker analysis and monitoring agent | Stock Analysis | Finance |
|
||||||
|
| [Open-Aladdin](https://github.com/The-Swarm-Corporation/Open-Aladdin) | Open-source financial risk management system | Risk Management | Finance |
|
||||||
|
| [CryptoTaxSwarm](https://github.com/The-Swarm-Corporation/CryptoTaxSwarm) | Cryptocurrency tax calculation and reporting | Tax Management | Finance |
|
||||||
|
|
||||||
|
### Insurance & Lending
|
||||||
|
|
||||||
|
| Name | Description | Type | Repository |
|
||||||
|
|------|-------------|------|------------|
|
||||||
|
| [InsuranceSwarm](https://github.com/The-Swarm-Corporation/InsuranceSwarm) | Insurance claim processing and underwriting | Insurance | Finance |
|
||||||
|
| [MortgageUnderwritingSwarm](https://github.com/The-Swarm-Corporation/MortgageUnderwritingSwarm) | Automated mortgage underwriting system | Lending | Finance |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔬 Research & Development
|
||||||
|
|
||||||
|
### Scientific Research
|
||||||
|
|
||||||
|
| Name | Description | Type | Repository |
|
||||||
|
|------|-------------|------|------------|
|
||||||
|
| [AI-CoScientist](https://github.com/The-Swarm-Corporation/AI-CoScientist) | AI research collaboration platform | Research Platform | Science |
|
||||||
|
| [auto-ai-research-team](https://github.com/The-Swarm-Corporation/auto-ai-research-team) | Automated AI research team coordination | Research Automation | Science |
|
||||||
|
| [Research-Paper-Writer-Swarm](https://github.com/The-Swarm-Corporation/Research-Paper-Writer-Swarm) | Automated research paper writing system | Academic Writing | Science |
|
||||||
|
|
||||||
|
### Mathematical & Analytical
|
||||||
|
|
||||||
|
| Name | Description | Type | Repository |
|
||||||
|
|------|-------------|------|------------|
|
||||||
|
| [Generalist-Mathematician-Swarm](https://github.com/The-Swarm-Corporation/Generalist-Mathematician-Swarm) | Mathematical problem-solving agent swarm | Mathematics | Science |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 💼 Business & Marketing
|
||||||
|
|
||||||
|
### Marketing & Content
|
||||||
|
|
||||||
|
| Name | Description | Type | Repository |
|
||||||
|
|------|-------------|------|------------|
|
||||||
|
| [Marketing-Swarm-Template](https://github.com/The-Swarm-Corporation/Marketing-Swarm-Template) | Marketing campaign automation template | Marketing Automation | Business |
|
||||||
|
| [Multi-Agent-Marketing-Course](https://github.com/The-Swarm-Corporation/Multi-Agent-Marketing-Course) | Educational course on multi-agent marketing | Marketing Education | Business |
|
||||||
|
| [NewsAgent](https://github.com/The-Swarm-Corporation/NewsAgent) | News aggregation and analysis agent | News Analysis | Business |
|
||||||
|
|
||||||
|
### Legal Services
|
||||||
|
|
||||||
|
| Name | Description | Type | Repository |
|
||||||
|
|------|-------------|------|------------|
|
||||||
|
| [Legal-Swarm-Template](https://github.com/The-Swarm-Corporation/Legal-Swarm-Template) | Legal document processing and analysis | Legal Technology | Business |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🛠️ Development Tools & Platforms
|
||||||
|
|
||||||
|
### Core Platforms & Operating Systems
|
||||||
|
|
||||||
|
| Name | Description | Type | Repository |
|
||||||
|
|------|-------------|------|------------|
|
||||||
|
| [AgentOS](https://github.com/The-Swarm-Corporation/AgentOS) | Operating system for AI agents | Agent Platform | Development |
|
||||||
|
| [swarm-ecosystem](https://github.com/The-Swarm-Corporation/swarm-ecosystem) | Complete ecosystem for swarm development | Ecosystem Platform | Development |
|
||||||
|
| [AgentAPIProduction](https://github.com/The-Swarm-Corporation/AgentAPIProduction) | Production-ready agent API system | API Platform | Development |
|
||||||
|
|
||||||
|
### Development Tools & Utilities
|
||||||
|
|
||||||
|
| Name | Description | Type | Repository |
|
||||||
|
|------|-------------|------|------------|
|
||||||
|
| [DevSwarm](https://github.com/The-Swarm-Corporation/DevSwarm) | Development-focused agent swarm | Development Tools | Development |
|
||||||
|
| [FluidAPI](https://github.com/The-Swarm-Corporation/FluidAPI) | Dynamic API generation and management | API Tools | Development |
|
||||||
|
| [OmniParse](https://github.com/The-Swarm-Corporation/OmniParse) | Universal document parsing system | Document Processing | Development |
|
||||||
|
| [doc-master](https://github.com/The-Swarm-Corporation/doc-master) | Documentation generation and management | Documentation Tools | Development |
|
||||||
|
|
||||||
|
### Templates & Examples
|
||||||
|
|
||||||
|
| Name | Description | Type | Repository |
|
||||||
|
|------|-------------|------|------------|
|
||||||
|
| [Multi-Agent-Template-App](https://github.com/The-Swarm-Corporation/Multi-Agent-Template-App) | Template application for multi-agent systems | Template | Development |
|
||||||
|
| [swarms-examples](https://github.com/The-Swarm-Corporation/swarms-examples) | Collection of Swarms framework examples | Examples | Development |
|
||||||
|
| [Phala-Deployment-Template](https://github.com/The-Swarm-Corporation/Phala-Deployment-Template) | Deployment template for Phala Network | Deployment Template | Development |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📚 Educational Resources
|
||||||
|
|
||||||
|
### Courses & Guides
|
||||||
|
|
||||||
|
| Name | Description | Type | Repository |
|
||||||
|
|------|-------------|------|------------|
|
||||||
|
| [Enterprise-Grade-Agents-Course](https://github.com/The-Swarm-Corporation/Enterprise-Grade-Agents-Course) | Comprehensive course on enterprise AI agents | Educational Course | Education |
|
||||||
|
| [Agents-Beginner-Guide](https://github.com/The-Swarm-Corporation/Agents-Beginner-Guide) | Beginner's guide to AI agents | Educational Guide | Education |
|
||||||
|
|
||||||
|
### Testing & Evaluation
|
||||||
|
|
||||||
|
| Name | Description | Type | Repository |
|
||||||
|
|------|-------------|------|------------|
|
||||||
|
| [swarms-evals](https://github.com/The-Swarm-Corporation/swarms-evals) | Evaluation framework for swarm systems | Testing Framework | Development |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 Getting Started
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Python 3.8+
|
||||||
|
|
||||||
|
- Basic understanding of AI agents and multi-agent systems
|
||||||
|
|
||||||
|
- Familiarity with the Swarms framework
|
||||||
|
|
||||||
|
|
||||||
|
### Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install swarms
|
||||||
|
```
|
||||||
|
|
||||||
|
### Quick Start
|
||||||
|
|
||||||
|
1. Choose a template from the categories above
|
||||||
|
|
||||||
|
2. Clone the repository
|
||||||
|
|
||||||
|
3. Follow the setup instructions in the README
|
||||||
|
|
||||||
|
4. Customize the agents for your specific use case
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🤝 Contributing
|
||||||
|
|
||||||
|
The Swarms ecosystem is constantly growing. To contribute:
|
||||||
|
|
||||||
|
1. Fork the main [Swarms repository](https://github.com/kyegomez/swarms)
|
||||||
|
2. Create your feature branch
|
||||||
|
3. Submit a pull request
|
||||||
|
4. Join the community discussions
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📞 Support & Community
|
||||||
|
|
||||||
|
Join our community of agent engineers and researchers for technical support, cutting-edge updates, and exclusive access to world-class agent engineering insights!
|
||||||
|
|
||||||
|
| Platform | Description | Link |
|
||||||
|
|----------|-------------|------|
|
||||||
|
| 🏠 Main Repository | Swarms Framework | [GitHub](https://github.com/kyegomez/swarms) |
|
||||||
|
| 🏢 Organization | The Swarm Corporation | [GitHub Org](https://github.com/The-Swarm-Corporation) |
|
||||||
|
| 🌐 Website | Official project website | [swarms.ai](https://swarms.ai) |
|
||||||
|
| 📚 Documentation | Official documentation and guides | [docs.swarms.world](https://docs.swarms.world) |
|
||||||
|
| 📝 Blog | Latest updates and technical articles | [Medium](https://medium.com/@kyeg) |
|
||||||
|
| 💬 Discord | Live chat and community support | [Join Discord](https://discord.gg/jM3Z6M9uMq) |
|
||||||
|
| 🐦 Twitter | Latest news and announcements | [@kyegomez](https://twitter.com/kyegomez) |
|
||||||
|
| 👥 LinkedIn | Professional network and updates | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) |
|
||||||
|
| 📺 YouTube | Tutorials and demos | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) |
|
||||||
|
| 🎫 Events | Join our community events | [Sign up here](https://lu.ma/5p2jnc2v) |
|
||||||
|
| 🚀 Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📊 Statistics
|
||||||
|
|
||||||
|
- **Total Projects**: 35+
|
||||||
|
|
||||||
|
- **Industries Covered**: Healthcare, Finance, Research, Business, Development
|
||||||
|
|
||||||
|
- **Project Types**: Templates, Applications, Tools, Educational Resources
|
||||||
|
|
||||||
|
- **Active Development**: Continuous updates and new additions
|
||||||
|
|
||||||
|
|
||||||
|
---
|
@ -0,0 +1,226 @@
|
|||||||
|
# Hierarchical Swarm Examples
|
||||||
|
|
||||||
|
This page provides simple, practical examples of how to use the `HierarchicalSwarm` for various real-world scenarios.
|
||||||
|
|
||||||
|
## Basic Example: Financial Analysis
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
|
||||||
|
|
||||||
|
# Create specialized financial analysis agents
|
||||||
|
market_research_agent = Agent(
|
||||||
|
agent_name="Market-Research-Specialist",
|
||||||
|
agent_description="Expert in market research, trend analysis, and competitive intelligence",
|
||||||
|
system_prompt="""You are a senior market research specialist with expertise in:
|
||||||
|
- Market trend analysis and forecasting
|
||||||
|
- Competitive landscape assessment
|
||||||
|
- Consumer behavior analysis
|
||||||
|
- Industry report generation
|
||||||
|
- Market opportunity identification
|
||||||
|
- Risk assessment and mitigation strategies""",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
|
financial_analyst_agent = Agent(
|
||||||
|
agent_name="Financial-Analysis-Expert",
|
||||||
|
agent_description="Specialist in financial statement analysis, valuation, and investment research",
|
||||||
|
system_prompt="""You are a senior financial analyst with deep expertise in:
|
||||||
|
- Financial statement analysis (income statement, balance sheet, cash flow)
|
||||||
|
- Valuation methodologies (DCF, comparable company analysis, precedent transactions)
|
||||||
|
- Investment research and due diligence
|
||||||
|
- Financial modeling and forecasting
|
||||||
|
- Risk assessment and portfolio analysis
|
||||||
|
- ESG (Environmental, Social, Governance) analysis""",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize the hierarchical swarm
|
||||||
|
financial_analysis_swarm = HierarchicalSwarm(
|
||||||
|
name="Financial-Analysis-Hierarchical-Swarm",
|
||||||
|
description="A hierarchical swarm for comprehensive financial analysis with specialized agents",
|
||||||
|
agents=[market_research_agent, financial_analyst_agent],
|
||||||
|
max_loops=2,
|
||||||
|
verbose=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Execute financial analysis
|
||||||
|
task = "Conduct a comprehensive analysis of Tesla (TSLA) stock including market position, financial health, and investment potential"
|
||||||
|
result = financial_analysis_swarm.run(task=task)
|
||||||
|
print(result)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Development Team Example
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
|
||||||
|
|
||||||
|
# Create specialized development agents
|
||||||
|
frontend_developer_agent = Agent(
|
||||||
|
agent_name="Frontend-Developer",
|
||||||
|
agent_description="Senior frontend developer expert in modern web technologies and user experience",
|
||||||
|
system_prompt="""You are a senior frontend developer with expertise in:
|
||||||
|
- Modern JavaScript frameworks (React, Vue, Angular)
|
||||||
|
- TypeScript and modern ES6+ features
|
||||||
|
- CSS frameworks and responsive design
|
||||||
|
- State management (Redux, Zustand, Context API)
|
||||||
|
- Web performance optimization
|
||||||
|
- Accessibility (WCAG) and SEO best practices""",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
|
backend_developer_agent = Agent(
|
||||||
|
agent_name="Backend-Developer",
|
||||||
|
agent_description="Senior backend developer specializing in server-side development and API design",
|
||||||
|
system_prompt="""You are a senior backend developer with expertise in:
|
||||||
|
- Server-side programming languages (Python, Node.js, Java, Go)
|
||||||
|
- Web frameworks (Django, Flask, Express, Spring Boot)
|
||||||
|
- Database design and optimization (SQL, NoSQL)
|
||||||
|
- API design and REST/GraphQL implementation
|
||||||
|
- Authentication and authorization systems
|
||||||
|
- Microservices architecture and containerization""",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize the development swarm
|
||||||
|
development_department_swarm = HierarchicalSwarm(
|
||||||
|
name="Autonomous-Development-Department",
|
||||||
|
description="A fully autonomous development department with specialized agents",
|
||||||
|
agents=[frontend_developer_agent, backend_developer_agent],
|
||||||
|
max_loops=3,
|
||||||
|
verbose=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Execute development project
|
||||||
|
task = "Create a simple web app that allows users to upload a file and then download it. The app should be built with React and Node.js."
|
||||||
|
result = development_department_swarm.run(task=task)
|
||||||
|
print(result)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Single Step Execution
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
|
||||||
|
|
||||||
|
# Create analysis agents
|
||||||
|
market_agent = Agent(
|
||||||
|
agent_name="Market-Analyst",
|
||||||
|
agent_description="Expert in market analysis and trends",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
|
technical_agent = Agent(
|
||||||
|
agent_name="Technical-Analyst",
|
||||||
|
agent_description="Specialist in technical analysis and patterns",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize the swarm
|
||||||
|
swarm = HierarchicalSwarm(
|
||||||
|
name="Analysis-Swarm",
|
||||||
|
description="A hierarchical swarm for comprehensive analysis",
|
||||||
|
agents=[market_agent, technical_agent],
|
||||||
|
max_loops=1,
|
||||||
|
verbose=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Execute a single step
|
||||||
|
task = "Analyze the current market trends for electric vehicles"
|
||||||
|
feedback = swarm.step(task=task)
|
||||||
|
print("Director Feedback:", feedback)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Batch Processing
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
|
||||||
|
|
||||||
|
# Create analysis agents
|
||||||
|
market_agent = Agent(
|
||||||
|
agent_name="Market-Analyst",
|
||||||
|
agent_description="Expert in market analysis and trends",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
|
technical_agent = Agent(
|
||||||
|
agent_name="Technical-Analyst",
|
||||||
|
agent_description="Specialist in technical analysis and patterns",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize the swarm
|
||||||
|
swarm = HierarchicalSwarm(
|
||||||
|
name="Analysis-Swarm",
|
||||||
|
description="A hierarchical swarm for comprehensive analysis",
|
||||||
|
agents=[market_agent, technical_agent],
|
||||||
|
max_loops=2,
|
||||||
|
verbose=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Execute multiple tasks
|
||||||
|
tasks = [
|
||||||
|
"Analyze Apple (AAPL) stock performance",
|
||||||
|
"Evaluate Microsoft (MSFT) market position",
|
||||||
|
"Assess Google (GOOGL) competitive landscape"
|
||||||
|
]
|
||||||
|
|
||||||
|
results = swarm.batched_run(tasks=tasks)
|
||||||
|
for i, result in enumerate(results):
|
||||||
|
print(f"Task {i+1} Result:", result)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Research Team Example
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
|
||||||
|
|
||||||
|
# Create specialized research agents
|
||||||
|
research_manager = Agent(
|
||||||
|
agent_name="Research-Manager",
|
||||||
|
agent_description="Manages research operations and coordinates research tasks",
|
||||||
|
system_prompt="You are a research manager responsible for overseeing research projects and coordinating research efforts.",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
|
data_analyst = Agent(
|
||||||
|
agent_name="Data-Analyst",
|
||||||
|
agent_description="Analyzes data and generates insights",
|
||||||
|
system_prompt="You are a data analyst specializing in processing and analyzing data to extract meaningful insights.",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
|
research_assistant = Agent(
|
||||||
|
agent_name="Research-Assistant",
|
||||||
|
agent_description="Assists with research tasks and data collection",
|
||||||
|
system_prompt="You are a research assistant who helps gather information and support research activities.",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize the research swarm
|
||||||
|
research_swarm = HierarchicalSwarm(
|
||||||
|
name="Research-Team-Swarm",
|
||||||
|
description="A hierarchical swarm for comprehensive research projects",
|
||||||
|
agents=[research_manager, data_analyst, research_assistant],
|
||||||
|
max_loops=2,
|
||||||
|
verbose=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Execute research project
|
||||||
|
task = "Conduct a comprehensive market analysis for a new AI-powered productivity tool"
|
||||||
|
result = research_swarm.run(task=task)
|
||||||
|
print(result)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Key Takeaways
|
||||||
|
|
||||||
|
1. **Agent Specialization**: Create agents with specific, well-defined expertise areas
|
||||||
|
2. **Clear Task Descriptions**: Provide detailed, actionable task descriptions
|
||||||
|
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
|
||||||
|
|
||||||
|
For more detailed information about the `HierarchicalSwarm` API and advanced usage patterns, see the [main documentation](hierarchical_swarm.md).
|
@ -0,0 +1,360 @@
|
|||||||
|
# `HierarchicalSwarm`
|
||||||
|
|
||||||
|
The `HierarchicalSwarm` is a sophisticated multi-agent orchestration system that implements a hierarchical workflow pattern. It consists of a director agent that coordinates and distributes tasks to specialized worker agents, creating a structured approach to complex problem-solving.
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
The Hierarchical Swarm follows a clear workflow pattern:
|
||||||
|
|
||||||
|
1. **Task Reception**: User provides a task to the swarm
|
||||||
|
2. **Planning**: Director creates a comprehensive plan and distributes orders to agents
|
||||||
|
3. **Execution**: Individual agents execute their assigned tasks
|
||||||
|
4. **Feedback Loop**: Director evaluates results and issues new orders if needed (up to `max_loops`)
|
||||||
|
5. **Context Preservation**: All conversation history and context is maintained throughout the process
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
A[User Task] --> B[Director Agent]
|
||||||
|
B --> C[Create Plan & Orders]
|
||||||
|
C --> D[Distribute to Agents]
|
||||||
|
D --> E[Agent 1]
|
||||||
|
D --> F[Agent 2]
|
||||||
|
D --> G[Agent N]
|
||||||
|
E --> H[Execute Task]
|
||||||
|
F --> H
|
||||||
|
G --> H
|
||||||
|
H --> I[Report Results]
|
||||||
|
I --> J[Director Evaluation]
|
||||||
|
J --> K{More Loops?}
|
||||||
|
K -->|Yes| C
|
||||||
|
K -->|No| L[Final Output]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Key Features
|
||||||
|
|
||||||
|
- **Hierarchical Coordination**: Director agent orchestrates all operations
|
||||||
|
- **Specialized Agents**: Each agent has specific expertise and responsibilities
|
||||||
|
- **Iterative Refinement**: Multiple feedback loops for improved results
|
||||||
|
- **Context Preservation**: Full conversation history maintained
|
||||||
|
- **Flexible Output Formats**: Support for various output types (dict, str, list)
|
||||||
|
- **Comprehensive Logging**: Detailed logging for debugging and monitoring
|
||||||
|
|
||||||
|
## `HierarchicalSwarm` Constructor
|
||||||
|
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
|-----------|------|---------|-------------|
|
||||||
|
| `name` | `str` | `"HierarchicalAgentSwarm"` | The name of the swarm instance |
|
||||||
|
| `description` | `str` | `"Distributed task swarm"` | Brief description of the swarm's functionality |
|
||||||
|
| `director` | `Optional[Union[Agent, Callable, Any]]` | `None` | The director agent that orchestrates tasks |
|
||||||
|
| `agents` | `List[Union[Agent, Callable, Any]]` | `None` | List of worker agents in the swarm |
|
||||||
|
| `max_loops` | `int` | `1` | Maximum number of feedback loops between director and agents |
|
||||||
|
| `output_type` | `OutputType` | `"dict-all-except-first"` | Format for output (dict, str, list) |
|
||||||
|
| `feedback_director_model_name` | `str` | `"gpt-4o-mini"` | Model name for feedback director |
|
||||||
|
| `director_name` | `str` | `"Director"` | Name of the director agent |
|
||||||
|
| `director_model_name` | `str` | `"gpt-4o-mini"` | Model name for the director agent |
|
||||||
|
| `verbose` | `bool` | `False` | Enable detailed logging |
|
||||||
|
| `add_collaboration_prompt` | `bool` | `True` | Add collaboration prompts to agents |
|
||||||
|
| `planning_director_agent` | `Optional[Union[Agent, Callable, Any]]` | `None` | Optional planning agent for enhanced planning |
|
||||||
|
|
||||||
|
## Core Methods
|
||||||
|
|
||||||
|
### `run(task, img=None, *args, **kwargs)`
|
||||||
|
|
||||||
|
Executes the hierarchical swarm for a specified number of feedback loops, processing the task through multiple iterations for refinement and improvement.
|
||||||
|
|
||||||
|
#### Parameters
|
||||||
|
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
|-----------|------|---------|-------------|
|
||||||
|
| `task` | `str` | **Required** | The initial task to be processed by the swarm |
|
||||||
|
| `img` | `str` | `None` | Optional image input for the agents |
|
||||||
|
| `*args` | `Any` | - | Additional positional arguments |
|
||||||
|
| `**kwargs` | `Any` | - | Additional keyword arguments |
|
||||||
|
|
||||||
|
#### Returns
|
||||||
|
|
||||||
|
| Type | Description |
|
||||||
|
|------|-------------|
|
||||||
|
| `Any` | The formatted conversation history as output based on `output_type` |
|
||||||
|
|
||||||
|
#### Example
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
|
||||||
|
|
||||||
|
# Create specialized agents
|
||||||
|
research_agent = Agent(
|
||||||
|
agent_name="Research-Specialist",
|
||||||
|
agent_description="Expert in market research and analysis",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
|
financial_agent = Agent(
|
||||||
|
agent_name="Financial-Analyst",
|
||||||
|
agent_description="Specialist in financial analysis and valuation",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize the hierarchical swarm
|
||||||
|
swarm = HierarchicalSwarm(
|
||||||
|
name="Financial-Analysis-Swarm",
|
||||||
|
description="A hierarchical swarm for comprehensive financial analysis",
|
||||||
|
agents=[research_agent, financial_agent],
|
||||||
|
max_loops=2,
|
||||||
|
verbose=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Execute a complex task
|
||||||
|
task = "Analyze the market potential for Tesla (TSLA) stock"
|
||||||
|
result = swarm.run(task=task)
|
||||||
|
print(result)
|
||||||
|
```
|
||||||
|
|
||||||
|
### `step(task, img=None, *args, **kwargs)`
|
||||||
|
|
||||||
|
Runs a single step of the hierarchical swarm, executing one complete cycle of planning, distribution, execution, and feedback.
|
||||||
|
|
||||||
|
#### Parameters
|
||||||
|
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
|-----------|------|---------|-------------|
|
||||||
|
| `task` | `str` | **Required** | The task to be executed in this step |
|
||||||
|
| `img` | `str` | `None` | Optional image input for the agents |
|
||||||
|
| `*args` | `Any` | - | Additional positional arguments |
|
||||||
|
| `**kwargs` | `Any` | - | Additional keyword arguments |
|
||||||
|
|
||||||
|
#### Returns
|
||||||
|
|
||||||
|
| Type | Description |
|
||||||
|
|------|-------------|
|
||||||
|
| `str` | Feedback from the director based on agent outputs |
|
||||||
|
|
||||||
|
#### Example
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
|
||||||
|
|
||||||
|
# Create development agents
|
||||||
|
frontend_agent = Agent(
|
||||||
|
agent_name="Frontend-Developer",
|
||||||
|
agent_description="Expert in React and modern web development",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
|
backend_agent = Agent(
|
||||||
|
agent_name="Backend-Developer",
|
||||||
|
agent_description="Specialist in Node.js and API development",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize the swarm
|
||||||
|
swarm = HierarchicalSwarm(
|
||||||
|
name="Development-Swarm",
|
||||||
|
description="A hierarchical swarm for software development",
|
||||||
|
agents=[frontend_agent, backend_agent],
|
||||||
|
max_loops=1,
|
||||||
|
verbose=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Execute a single step
|
||||||
|
task = "Create a simple web app for file upload and download"
|
||||||
|
feedback = swarm.step(task=task)
|
||||||
|
print("Director Feedback:", feedback)
|
||||||
|
```
|
||||||
|
|
||||||
|
### `batched_run(tasks, img=None, *args, **kwargs)`
|
||||||
|
|
||||||
|
Executes the hierarchical swarm for a list of tasks, processing each task through the complete workflow.
|
||||||
|
|
||||||
|
#### Parameters
|
||||||
|
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
|-----------|------|---------|-------------|
|
||||||
|
| `tasks` | `List[str]` | **Required** | List of tasks to be processed |
|
||||||
|
| `img` | `str` | `None` | Optional image input for the agents |
|
||||||
|
| `*args` | `Any` | - | Additional positional arguments |
|
||||||
|
| `**kwargs` | `Any` | - | Additional keyword arguments |
|
||||||
|
|
||||||
|
#### Returns
|
||||||
|
|
||||||
|
| Type | Description |
|
||||||
|
|------|-------------|
|
||||||
|
| `List[Any]` | List of results for each task |
|
||||||
|
|
||||||
|
#### Example
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
|
||||||
|
|
||||||
|
# Create analysis agents
|
||||||
|
market_agent = Agent(
|
||||||
|
agent_name="Market-Analyst",
|
||||||
|
agent_description="Expert in market analysis and trends",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
|
technical_agent = Agent(
|
||||||
|
agent_name="Technical-Analyst",
|
||||||
|
agent_description="Specialist in technical analysis and patterns",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize the swarm
|
||||||
|
swarm = HierarchicalSwarm(
|
||||||
|
name="Analysis-Swarm",
|
||||||
|
description="A hierarchical swarm for comprehensive analysis",
|
||||||
|
agents=[market_agent, technical_agent],
|
||||||
|
max_loops=2,
|
||||||
|
verbose=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Execute multiple tasks
|
||||||
|
tasks = [
|
||||||
|
"Analyze Apple (AAPL) stock performance",
|
||||||
|
"Evaluate Microsoft (MSFT) market position",
|
||||||
|
"Assess Google (GOOGL) competitive landscape"
|
||||||
|
]
|
||||||
|
|
||||||
|
results = swarm.batched_run(tasks=tasks)
|
||||||
|
for i, result in enumerate(results):
|
||||||
|
print(f"Task {i+1} Result:", result)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Advanced Usage Examples
|
||||||
|
|
||||||
|
### Financial Analysis Swarm
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
|
||||||
|
|
||||||
|
# Create specialized financial agents
|
||||||
|
market_research_agent = Agent(
|
||||||
|
agent_name="Market-Research-Specialist",
|
||||||
|
agent_description="Expert in market research, trend analysis, and competitive intelligence",
|
||||||
|
system_prompt="""You are a senior market research specialist with expertise in:
|
||||||
|
- Market trend analysis and forecasting
|
||||||
|
- Competitive landscape assessment
|
||||||
|
- Consumer behavior analysis
|
||||||
|
- Industry report generation
|
||||||
|
- Market opportunity identification
|
||||||
|
- Risk assessment and mitigation strategies""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
)
|
||||||
|
|
||||||
|
financial_analyst_agent = Agent(
|
||||||
|
agent_name="Financial-Analysis-Expert",
|
||||||
|
agent_description="Specialist in financial statement analysis, valuation, and investment research",
|
||||||
|
system_prompt="""You are a senior financial analyst with deep expertise in:
|
||||||
|
- Financial statement analysis (income statement, balance sheet, cash flow)
|
||||||
|
- Valuation methodologies (DCF, comparable company analysis, precedent transactions)
|
||||||
|
- Investment research and due diligence
|
||||||
|
- Financial modeling and forecasting
|
||||||
|
- Risk assessment and portfolio analysis
|
||||||
|
- ESG (Environmental, Social, Governance) analysis""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize the hierarchical swarm
|
||||||
|
financial_analysis_swarm = HierarchicalSwarm(
|
||||||
|
name="Financial-Analysis-Hierarchical-Swarm",
|
||||||
|
description="A hierarchical swarm for comprehensive financial analysis with specialized agents",
|
||||||
|
agents=[market_research_agent, financial_analyst_agent],
|
||||||
|
max_loops=2,
|
||||||
|
verbose=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Execute financial analysis
|
||||||
|
task = "Conduct a comprehensive analysis of Tesla (TSLA) stock including market position, financial health, and investment potential"
|
||||||
|
result = financial_analysis_swarm.run(task=task)
|
||||||
|
print(result)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Development Department Swarm
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
|
||||||
|
|
||||||
|
# Create specialized development agents
|
||||||
|
frontend_developer_agent = Agent(
|
||||||
|
agent_name="Frontend-Developer",
|
||||||
|
agent_description="Senior frontend developer expert in modern web technologies and user experience",
|
||||||
|
system_prompt="""You are a senior frontend developer with expertise in:
|
||||||
|
- Modern JavaScript frameworks (React, Vue, Angular)
|
||||||
|
- TypeScript and modern ES6+ features
|
||||||
|
- CSS frameworks and responsive design
|
||||||
|
- State management (Redux, Zustand, Context API)
|
||||||
|
- Web performance optimization
|
||||||
|
- Accessibility (WCAG) and SEO best practices""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
)
|
||||||
|
|
||||||
|
backend_developer_agent = Agent(
|
||||||
|
agent_name="Backend-Developer",
|
||||||
|
agent_description="Senior backend developer specializing in server-side development and API design",
|
||||||
|
system_prompt="""You are a senior backend developer with expertise in:
|
||||||
|
- Server-side programming languages (Python, Node.js, Java, Go)
|
||||||
|
- Web frameworks (Django, Flask, Express, Spring Boot)
|
||||||
|
- Database design and optimization (SQL, NoSQL)
|
||||||
|
- API design and REST/GraphQL implementation
|
||||||
|
- Authentication and authorization systems
|
||||||
|
- Microservices architecture and containerization""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize the development swarm
|
||||||
|
development_department_swarm = HierarchicalSwarm(
|
||||||
|
name="Autonomous-Development-Department",
|
||||||
|
description="A fully autonomous development department with specialized agents",
|
||||||
|
agents=[frontend_developer_agent, backend_developer_agent],
|
||||||
|
max_loops=3,
|
||||||
|
verbose=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Execute development project
|
||||||
|
task = "Create a simple web app that allows users to upload a file and then download it. The app should be built with React and Node.js."
|
||||||
|
result = development_department_swarm.run(task=task)
|
||||||
|
print(result)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Output Types
|
||||||
|
|
||||||
|
The `HierarchicalSwarm` supports various output formats through the `output_type` parameter:
|
||||||
|
|
||||||
|
| Output Type | Description | Use Case |
|
||||||
|
|-------------|-------------|----------|
|
||||||
|
| `"dict-all-except-first"` | Returns all conversation history as a dictionary, excluding the first message | Default format for comprehensive analysis |
|
||||||
|
| `"dict"` | Returns conversation history as a dictionary | When you need structured data |
|
||||||
|
| `"str"` | Returns conversation history as a string | For simple text output |
|
||||||
|
| `"list"` | Returns conversation history as a list | For sequential processing |
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
1. **Agent Specialization**: Create agents with specific, well-defined expertise areas
|
||||||
|
2. **Clear Task Descriptions**: Provide detailed, actionable task descriptions
|
||||||
|
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**: Leverage the built-in conversation history for continuity
|
||||||
|
6. **Error Handling**: Implement proper error handling for production use
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
|
||||||
|
The `HierarchicalSwarm` includes comprehensive error handling with detailed logging. Common issues and solutions:
|
||||||
|
|
||||||
|
- **No Agents**: Ensure at least one agent is provided
|
||||||
|
- **Invalid Director**: Verify the director agent is properly configured
|
||||||
|
- **Max Loops**: Set `max_loops` to a value greater than 0
|
||||||
|
- **Model Issues**: Check that all agents have valid model configurations
|
||||||
|
|
||||||
|
## Performance Considerations
|
||||||
|
|
||||||
|
- **Loop Optimization**: Balance between thoroughness and performance with `max_loops`
|
||||||
|
- **Agent Count**: More agents increase coordination overhead
|
||||||
|
- **Model Selection**: Choose appropriate models for your use case and budget
|
||||||
|
- **Verbose Mode**: Disable verbose logging in production for better performance
|
@ -1,349 +1,305 @@
|
|||||||
# Enterprise-Grade and Production Ready Agents
|
# Introduction to Multi-Agent Collaboration
|
||||||
|
|
||||||
Swarms is an enterprise grade and production ready multi-agent collaboration framework that enables you to orchestrate many agents to work collaboratively at scale to automate real-world activities.
|
---
|
||||||
|
|
||||||
| **Feature** | **Description** | **Performance Impact** | **Documentation Link** |
|
## 🚀 Benefits of Multi-Agent Collaboration
|
||||||
|------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------|-------------------------------|
|
|
||||||
| Models | Pre-trained models that can be utilized for various tasks within the swarm framework. | ⭐⭐⭐ | [Documentation](https://docs.swarms.world/en/latest/swarms/models/) |
|
|
||||||
| Models APIs | APIs to interact with and utilize the models effectively, providing interfaces for inference, training, and fine-tuning. | ⭐⭐⭐ | [Documentation](https://docs.swarms.world/en/latest/swarms/models/) |
|
|
||||||
| Agents with Tools | Agents equipped with specialized tools to perform specific tasks more efficiently, such as data processing, analysis, or interaction with external systems. | ⭐⭐⭐⭐ | [Documentation](https://medium.com/@kyeg/the-swarms-tool-system-functions-pydantic-basemodels-as-tools-and-radical-customization-c2a2e227b8ca) |
|
|
||||||
| Agents with Memory | Mechanisms for agents to store and recall past interactions, improving learning and adaptability over time. | ⭐⭐⭐⭐ | [Documentation](https://github.com/kyegomez/swarms/blob/master/examples/structs/agent/agent_with_longterm_memory.py) |
|
|
||||||
| Multi-Agent Orchestration | Coordination of multiple agents to work together seamlessly on complex tasks, leveraging their individual strengths to achieve higher overall performance. | ⭐⭐⭐⭐⭐ | [Documentation]() |
|
|
||||||
|
|
||||||
The performance impact is rated on a scale from one to five stars, with multi-agent orchestration being the highest due to its ability to combine the strengths of multiple agents and optimize task execution.
|
<div align="center">
|
||||||
|
<img src="/assets/img/benefits.png" alt="Benefits of Multi-Agent Collaboration" width="700"/>
|
||||||
|
<br/>
|
||||||
|
<em>Fig. 1: Key benefits and structure of multi-agent collaboration</em>
|
||||||
|
</div>
|
||||||
|
|
||||||
----
|
### Why Multi-Agent Architectures?
|
||||||
|
|
||||||
## Install 💻
|
Multi-agent systems unlock new levels of intelligence, reliability, and efficiency by enabling agents to work together. Here are the core benefits:
|
||||||
`$ pip3 install -U swarms`
|
|
||||||
|
|
||||||
---
|
1. **Reduction of Hallucination**: Cross-verification between agents ensures more accurate, reliable outputs by reducing hallucination.
|
||||||
|
2. **Extended Memory**: Agents share knowledge and task history, achieving collective long-term memory for smarter, more adaptive responses.
|
||||||
|
3. **Specialization & Task Distribution**: Delegating tasks to specialized agents boosts efficiency and quality.
|
||||||
|
4. **Parallel Processing**: Multiple agents work simultaneously, greatly increasing speed and throughput.
|
||||||
|
5. **Scalability & Adaptability**: Systems can dynamically scale and adapt, maintaining efficiency as demands change.
|
||||||
|
|
||||||
# Usage Examples 🤖
|
---
|
||||||
|
|
||||||
### Google Collab Example
|
## 🏗️ Multi-Agent Architectures For Production Deployments
|
||||||
Run example in Collab: <a target="_blank" href="https://colab.research.google.com/github/kyegomez/swarms/blob/master/examples/collab/swarms_example.ipynb">
|
|
||||||
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
|
|
||||||
</a>
|
|
||||||
|
|
||||||
---
|
`swarms` provides a variety of powerful, pre-built multi-agent architectures enabling you to orchestrate agents in various ways. Choose the right structure for your specific problem to build efficient and reliable production systems.
|
||||||
|
|
||||||
## `Agents`
|
| **Architecture** | **Description** | **Best For** |
|
||||||
A fully plug-and-play autonomous agent powered by an LLM extended by a long-term memory database, and equipped with function calling for tool usage! By passing in an LLM, you can create a fully autonomous agent with extreme customization and reliability, ready for real-world task automation!
|
|---|---|---|
|
||||||
|
| **[SequentialWorkflow](https://docs.swarms.world/en/latest/swarms/structs/sequential_workflow/)** | Agents execute tasks in a linear chain; one agent's output is the next one's input. | Step-by-step processes like data transformation pipelines, report generation. |
|
||||||
|
| **[ConcurrentWorkflow](https://docs.swarms.world/en/latest/swarms/structs/concurrent_workflow/)** | Agents run tasks simultaneously for maximum efficiency. | High-throughput tasks like batch processing, parallel data analysis. |
|
||||||
|
| **[AgentRearrange](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/)** | Dynamically maps complex relationships (e.g., `a -> b, c`) between agents. | Flexible and adaptive workflows, task distribution, dynamic routing. |
|
||||||
|
| **[GraphWorkflow](https://docs.swarms.world/en/latest/swarms/structs/graph_workflow/)** | Orchestrates agents as nodes in a Directed Acyclic Graph (DAG). | Complex projects with intricate dependencies, like software builds. |
|
||||||
|
| **[MixtureOfAgents (MoA)](https://docs.swarms.world/en/latest/swarms/structs/moa/)** | Utilizes multiple expert agents in parallel and synthesizes their outputs. | Complex problem-solving, achieving state-of-the-art performance through collaboration. |
|
||||||
|
| **[GroupChat](https://docs.swarms.world/en/latest/swarms/structs/group_chat/)** | Agents collaborate and make decisions through a conversational interface. | Real-time collaborative decision-making, negotiations, brainstorming. |
|
||||||
|
| **[ForestSwarm](https://docs.swarms.world/en/latest/swarms/structs/forest_swarm/)** | Dynamically selects the most suitable agent or tree of agents for a given task. | Task routing, optimizing for expertise, complex decision-making trees. |
|
||||||
|
| **[SpreadSheetSwarm](https://docs.swarms.world/en/latest/swarms/structs/spreadsheet_swarm/)** | Manages thousands of agents concurrently, tracking tasks and outputs in a structured format. | Massive-scale parallel operations, large-scale data generation and analysis. |
|
||||||
|
| **[SwarmRouter](https://docs.swarms.world/en/latest/swarms/structs/swarm_router/)** | Universal orchestrator that provides a single interface to run any type of swarm with dynamic selection. | Simplifying complex workflows, switching between swarm strategies, unified multi-agent management. |
|
||||||
|
| **[HierarchicalSwarm](https://docs.swarms.world/en/latest/swarms/structs/hierarchical_swarm/)** | Director agent coordinates specialized worker agents in a hierarchy. | Complex, multi-stage tasks, iterative refinement, enterprise workflows. |
|
||||||
|
| **[Hybrid Hierarchical-Cluster Swarm (HHCS)](https://docs.swarms.world/en/latest/swarms/structs/hhcs/)** | Router agent distributes tasks to specialized swarms for parallel, hierarchical processing. | Enterprise-scale, multi-domain, and highly complex workflows. |
|
||||||
|
|
||||||
Features:
|
---
|
||||||
|
|
||||||
✅ Any LLM / Any framework
|
### 🏢 HierarchicalSwarm Example
|
||||||
|
|
||||||
✅ Extremely customize-able with max loops, autosaving, import docs (PDFS, TXT, CSVs, etc), tool usage, etc etc
|
Hierarchical architectures enable structured, iterative, and scalable problem-solving by combining a director (or router) agent with specialized worker agents or swarms. Below are two key patterns:
|
||||||
|
|
||||||
✅ Long term memory database with RAG (ChromaDB, Pinecone, Qdrant)
|
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from swarms import Agent
|
from swarms import Agent
|
||||||
|
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
|
||||||
|
|
||||||
## Initialize the workflow
|
# Create specialized agents
|
||||||
agent = Agent(temperature=0.5, model_name="gpt-4o-mini", max_tokens=4000, max_loops=1, autosave=True, dashboard=True)
|
research_agent = Agent(
|
||||||
|
agent_name="Research-Specialist",
|
||||||
|
agent_description="Expert in market research and analysis",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
financial_agent = Agent(
|
||||||
|
agent_name="Financial-Analyst",
|
||||||
|
agent_description="Specialist in financial analysis and valuation",
|
||||||
|
model_name="gpt-4o",
|
||||||
|
)
|
||||||
|
|
||||||
# Run the workflow on a task
|
# Initialize the hierarchical swarm
|
||||||
agent.run("Generate a 10,000 word blog on health and wellness.")
|
swarm = HierarchicalSwarm(
|
||||||
```
|
name="Financial-Analysis-Swarm",
|
||||||
|
description="A hierarchical swarm for comprehensive financial analysis",
|
||||||
|
agents=[research_agent, financial_agent],
|
||||||
|
max_loops=2,
|
||||||
|
verbose=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Execute a complex task
|
||||||
|
result = swarm.run(task="Analyze the market potential for Tesla (TSLA) stock")
|
||||||
|
print(result)
|
||||||
|
```
|
||||||
|
|
||||||
### `Agent` + Long Term Memory
|
[Full HierarchicalSwarm Documentation →](https://docs.swarms.world/en/latest/swarms/structs/hierarchical_swarm/)
|
||||||
`Agent` equipped with quasi-infinite long term memory. Great for long document understanding, analysis, and retrieval.
|
|
||||||
|
|
||||||
```python
|
|
||||||
from swarms import Agent
|
|
||||||
from swarm_models import OpenAIChat
|
|
||||||
from swarms_memory import ChromaDB # Copy and paste the code and put it in your own local directory.
|
|
||||||
|
|
||||||
# Making an instance of the ChromaDB class
|
|
||||||
memory = ChromaDB(
|
|
||||||
metric="cosine",
|
|
||||||
n_results=3,
|
|
||||||
output_dir="results",
|
|
||||||
docs_folder="docs",
|
|
||||||
)
|
|
||||||
|
|
||||||
# Initializing the agent with the Gemini instance and other parameters
|
|
||||||
agent = Agent(
|
|
||||||
agent_name="Covid-19-Chat",
|
|
||||||
agent_description=(
|
|
||||||
"This agent provides information about COVID-19 symptoms."
|
|
||||||
),
|
|
||||||
llm=OpenAIChat(),
|
|
||||||
max_loops="auto",
|
|
||||||
autosave=True,
|
|
||||||
verbose=True,
|
|
||||||
long_term_memory=memory,
|
|
||||||
stopping_condition="finish",
|
|
||||||
)
|
|
||||||
|
|
||||||
# Defining the task and image path
|
### SequentialWorkflow
|
||||||
task = ("What are the symptoms of COVID-19?",)
|
|
||||||
|
|
||||||
# Running the agent with the specified task and image
|
A `SequentialWorkflow` executes tasks in a strict order, forming a pipeline where each agent builds upon the work of the previous one. `SequentialWorkflow` is Ideal for processes that have clear, ordered steps. This ensures that tasks with dependencies are handled correctly.
|
||||||
out = agent.run(task)
|
|
||||||
print(out)
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, SequentialWorkflow
|
||||||
|
|
||||||
|
# Initialize agents for a 3-step process
|
||||||
|
# 1. Generate an idea
|
||||||
|
idea_generator = Agent(agent_name="IdeaGenerator", system_prompt="Generate a unique startup idea.", model_name="gpt-4o-mini")
|
||||||
|
# 2. Validate the idea
|
||||||
|
validator = Agent(agent_name="Validator", system_prompt="Take this startup idea and analyze its market viability.", model_name="gpt-4o-mini")
|
||||||
|
# 3. Create a pitch
|
||||||
|
pitch_creator = Agent(agent_name="PitchCreator", system_prompt="Write a 3-sentence elevator pitch for this validated startup idea.", model_name="gpt-4o-mini")
|
||||||
|
|
||||||
|
# Create the sequential workflow
|
||||||
|
workflow = SequentialWorkflow(agents=[idea_generator, validator, pitch_creator])
|
||||||
|
|
||||||
|
# Run the workflow
|
||||||
|
elevator_pitch = workflow.run()
|
||||||
|
print(elevator_pitch)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### ConcurrentWorkflow (with `SpreadSheetSwarm`)
|
||||||
|
|
||||||
### `Agent` ++ Long Term Memory ++ Tools!
|
A concurrent workflow runs multiple agents simultaneously. `SpreadSheetSwarm` is a powerful implementation that can manage thousands of concurrent agents and log their outputs to a CSV file. Use this architecture for high-throughput tasks that can be performed in parallel, drastically reducing execution time.
|
||||||
An LLM equipped with long term memory and tools, a full stack agent capable of automating all and any digital tasks given a good prompt.
|
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from swarms import Agent, ChromaDB, OpenAIChat
|
from swarms import Agent, SpreadSheetSwarm
|
||||||
|
|
||||||
# Making an instance of the ChromaDB class
|
|
||||||
memory = ChromaDB(
|
|
||||||
metric="cosine",
|
|
||||||
n_results=3,
|
|
||||||
output_dir="results",
|
|
||||||
docs_folder="docs",
|
|
||||||
)
|
|
||||||
|
|
||||||
# Initialize a tool
|
# Define a list of tasks (e.g., social media posts to generate)
|
||||||
def search_api(query: str):
|
platforms = ["Twitter", "LinkedIn", "Instagram"]
|
||||||
# Add your logic here
|
|
||||||
return query
|
|
||||||
|
|
||||||
# Initializing the agent with the Gemini instance and other parameters
|
|
||||||
agent = Agent(
|
|
||||||
agent_name="Covid-19-Chat",
|
|
||||||
agent_description=(
|
|
||||||
"This agent provides information about COVID-19 symptoms."
|
|
||||||
),
|
|
||||||
llm=OpenAIChat(),
|
|
||||||
max_loops="auto",
|
|
||||||
autosave=True,
|
|
||||||
verbose=True,
|
|
||||||
long_term_memory=memory,
|
|
||||||
stopping_condition="finish",
|
|
||||||
tools=[search_api],
|
|
||||||
)
|
|
||||||
|
|
||||||
# Defining the task and image path
|
# Create an agent for each task
|
||||||
task = ("What are the symptoms of COVID-19?",)
|
agents = [
|
||||||
|
Agent(
|
||||||
# Running the agent with the specified task and image
|
agent_name=f"{platform}-Marketer",
|
||||||
out = agent.run(task)
|
system_prompt=f"Generate a real estate marketing post for {platform}.",
|
||||||
print(out)
|
model_name="gpt-4o-mini",
|
||||||
|
)
|
||||||
|
for platform in platforms
|
||||||
|
]
|
||||||
|
|
||||||
|
# Initialize the swarm to run these agents concurrently
|
||||||
|
swarm = SpreadSheetSwarm(
|
||||||
|
agents=agents,
|
||||||
|
autosave_on=True,
|
||||||
|
save_file_path="marketing_posts.csv",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run the swarm with a single, shared task description
|
||||||
|
property_description = "A beautiful 3-bedroom house in sunny California."
|
||||||
|
swarm.run(task=f"Generate a post about: {property_description}")
|
||||||
|
# Check marketing_posts.csv for the results!
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### AgentRearrange
|
||||||
|
|
||||||
### Devin
|
Inspired by `einsum`, `AgentRearrange` lets you define complex, non-linear relationships between agents using a simple string-based syntax. [Learn more](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/). This architecture is Perfect for orchestrating dynamic workflows where agents might work in parallel, sequence, or a combination of both.
|
||||||
Implementation of Devin in less than 90 lines of code with several tools:
|
|
||||||
terminal, browser, and edit files.
|
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from swarms import Agent
|
from swarms import Agent, AgentRearrange
|
||||||
from swarm_models import Anthropic
|
|
||||||
import subprocess
|
|
||||||
|
|
||||||
# Model
|
# Define agents
|
||||||
llm = Anthropic(
|
researcher = Agent(agent_name="researcher", model_name="gpt-4o-mini")
|
||||||
temperature=0.1,
|
writer = Agent(agent_name="writer", model_name="gpt-4o-mini")
|
||||||
)
|
editor = Agent(agent_name="editor", model_name="gpt-4o-mini")
|
||||||
|
|
||||||
# Tools
|
# Define a flow: researcher sends work to both writer and editor simultaneously
|
||||||
def terminal(
|
# This is a one-to-many relationship
|
||||||
code: str,
|
flow = "researcher -> writer, editor"
|
||||||
):
|
|
||||||
"""
|
# Create the rearrangement system
|
||||||
Run code in the terminal.
|
rearrange_system = AgentRearrange(
|
||||||
|
agents=[researcher, writer, editor],
|
||||||
Args:
|
flow=flow,
|
||||||
code (str): The code to run in the terminal.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
str: The output of the code.
|
|
||||||
"""
|
|
||||||
out = subprocess.run(
|
|
||||||
code, shell=True, capture_output=True, text=True
|
|
||||||
).stdout
|
|
||||||
return str(out)
|
|
||||||
|
|
||||||
def browser(query: str):
|
|
||||||
"""
|
|
||||||
Search the query in the browser with the `browser` tool.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
query (str): The query to search in the browser.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
str: The search results.
|
|
||||||
"""
|
|
||||||
import webbrowser
|
|
||||||
|
|
||||||
url = f"https://www.google.com/search?q={query}"
|
|
||||||
webbrowser.open(url)
|
|
||||||
return f"Searching for {query} in the browser."
|
|
||||||
|
|
||||||
def create_file(file_path: str, content: str):
|
|
||||||
"""
|
|
||||||
Create a file using the file editor tool.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
file_path (str): The path to the file.
|
|
||||||
content (str): The content to write to the file.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
str: The result of the file creation operation.
|
|
||||||
"""
|
|
||||||
with open(file_path, "w") as file:
|
|
||||||
file.write(content)
|
|
||||||
return f"File {file_path} created successfully."
|
|
||||||
|
|
||||||
def file_editor(file_path: str, mode: str, content: str):
|
|
||||||
"""
|
|
||||||
Edit a file using the file editor tool.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
file_path (str): The path to the file.
|
|
||||||
mode (str): The mode to open the file in.
|
|
||||||
content (str): The content to write to the file.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
str: The result of the file editing operation.
|
|
||||||
"""
|
|
||||||
with open(file_path, mode) as file:
|
|
||||||
file.write(content)
|
|
||||||
return f"File {file_path} edited successfully."
|
|
||||||
|
|
||||||
|
|
||||||
# Agent
|
|
||||||
agent = Agent(
|
|
||||||
agent_name="Devin",
|
|
||||||
system_prompt=(
|
|
||||||
"Autonomous agent that can interact with humans and other"
|
|
||||||
" agents. Be Helpful and Kind. Use the tools provided to"
|
|
||||||
" assist the user. Return all code in markdown format."
|
|
||||||
),
|
|
||||||
llm=llm,
|
|
||||||
max_loops="auto",
|
|
||||||
autosave=True,
|
|
||||||
dashboard=False,
|
|
||||||
streaming_on=True,
|
|
||||||
verbose=True,
|
|
||||||
stopping_token="<DONE>",
|
|
||||||
interactive=True,
|
|
||||||
tools=[terminal, browser, file_editor, create_file],
|
|
||||||
code_interpreter=True,
|
|
||||||
# streaming=True,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Run the agent
|
# Run the system
|
||||||
out = agent("Create a new file for a plan to take over the world.")
|
# The researcher will generate content, and then both the writer and editor
|
||||||
print(out)
|
# will process that content in parallel.
|
||||||
|
outputs = rearrange_system.run("Analyze the impact of AI on modern cinema.")
|
||||||
|
print(outputs)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### SwarmRouter: The Universal Swarm Orchestrator
|
||||||
|
|
||||||
|
The `SwarmRouter` simplifies building complex workflows by providing a single interface to run any type of swarm. Instead of importing and managing different swarm classes, you can dynamically select the one you need just by changing the `swarm_type` parameter. [Read the full documentation](https://docs.swarms.world/en/latest/swarms/structs/swarm_router/)
|
||||||
|
|
||||||
### `Agent`with Pydantic BaseModel as Output Type
|
This makes your code cleaner and more flexible, allowing you to switch between different multi-agent strategies with ease. Here's a complete example that shows how to define agents and then use `SwarmRouter` to execute the same task using different collaborative strategies.
|
||||||
The following is an example of an agent that intakes a pydantic basemodel and outputs it at the same time:
|
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from pydantic import BaseModel, Field
|
|
||||||
from swarms import Agent
|
from swarms import Agent
|
||||||
from swarm_models import Anthropic
|
from swarms.structs.swarm_router import SwarmRouter, SwarmType
|
||||||
|
|
||||||
|
# Define a few generic agents
|
||||||
|
writer = Agent(agent_name="Writer", system_prompt="You are a creative writer.", model_name="gpt-4o-mini")
|
||||||
|
editor = Agent(agent_name="Editor", system_prompt="You are an expert editor for stories.", model_name="gpt-4o-mini")
|
||||||
|
reviewer = Agent(agent_name="Reviewer", system_prompt="You are a final reviewer who gives a score.", model_name="gpt-4o-mini")
|
||||||
|
|
||||||
|
# The agents and task will be the same for all examples
|
||||||
|
agents = [writer, editor, reviewer]
|
||||||
|
task = "Write a short story about a robot who discovers music."
|
||||||
|
|
||||||
|
# --- Example 1: SequentialWorkflow ---
|
||||||
|
# Agents run one after another in a chain: Writer -> Editor -> Reviewer.
|
||||||
|
print("Running a Sequential Workflow...")
|
||||||
|
sequential_router = SwarmRouter(swarm_type=SwarmType.SequentialWorkflow, agents=agents)
|
||||||
|
sequential_output = sequential_router.run(task)
|
||||||
|
print(f"Final Sequential Output:\n{sequential_output}\n")
|
||||||
|
|
||||||
|
# --- Example 2: ConcurrentWorkflow ---
|
||||||
|
# All agents receive the same initial task and run at the same time.
|
||||||
|
print("Running a Concurrent Workflow...")
|
||||||
|
concurrent_router = SwarmRouter(swarm_type=SwarmType.ConcurrentWorkflow, agents=agents)
|
||||||
|
concurrent_outputs = concurrent_router.run(task)
|
||||||
|
# This returns a dictionary of each agent's output
|
||||||
|
for agent_name, output in concurrent_outputs.items():
|
||||||
|
print(f"Output from {agent_name}:\n{output}\n")
|
||||||
|
|
||||||
|
# --- Example 3: MixtureOfAgents ---
|
||||||
|
# All agents run in parallel, and a special 'aggregator' agent synthesizes their outputs.
|
||||||
|
print("Running a Mixture of Agents Workflow...")
|
||||||
|
aggregator = Agent(
|
||||||
|
agent_name="Aggregator",
|
||||||
|
system_prompt="Combine the story, edits, and review into a final document.",
|
||||||
|
model_name="gpt-4o-mini"
|
||||||
|
)
|
||||||
|
moa_router = SwarmRouter(
|
||||||
|
swarm_type=SwarmType.MixtureOfAgents,
|
||||||
|
agents=agents,
|
||||||
|
aggregator_agent=aggregator, # MoA requires an aggregator
|
||||||
|
)
|
||||||
|
aggregated_output = moa_router.run(task)
|
||||||
|
print(f"Final Aggregated Output:\n{aggregated_output}\n")
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
# Initialize the schema for the person's information
|
The `SwarmRouter` is a powerful tool for simplifying multi-agent orchestration. It provides a consistent and flexible way to deploy different collaborative strategies, allowing you to build more sophisticated applications with less code.
|
||||||
class Schema(BaseModel):
|
|
||||||
name: str = Field(..., title="Name of the person")
|
|
||||||
agent: int = Field(..., title="Age of the person")
|
|
||||||
is_student: bool = Field(..., title="Whether the person is a student")
|
|
||||||
courses: list[str] = Field(
|
|
||||||
..., title="List of courses the person is taking"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
# Convert the schema to a JSON string
|
### MixtureOfAgents (MoA)
|
||||||
tool_schema = Schema(
|
|
||||||
name="Tool Name",
|
|
||||||
agent=1,
|
|
||||||
is_student=True,
|
|
||||||
courses=["Course1", "Course2"],
|
|
||||||
)
|
|
||||||
|
|
||||||
# Define the task to generate a person's information
|
The `MixtureOfAgents` architecture processes tasks by feeding them to multiple "expert" agents in parallel. Their diverse outputs are then synthesized by an aggregator agent to produce a final, high-quality result. [Learn more here](https://docs.swarms.world/en/latest/swarms/examples/moa_example/)
|
||||||
task = "Generate a person's information based on the following schema:"
|
|
||||||
|
```python
|
||||||
# Initialize the agent
|
from swarms import Agent, MixtureOfAgents
|
||||||
agent = Agent(
|
|
||||||
agent_name="Person Information Generator",
|
# Define expert agents
|
||||||
system_prompt=(
|
financial_analyst = Agent(agent_name="FinancialAnalyst", system_prompt="Analyze financial data.", model_name="gpt-4o-mini")
|
||||||
"Generate a person's information based on the following schema:"
|
market_analyst = Agent(agent_name="MarketAnalyst", system_prompt="Analyze market trends.", model_name="gpt-4o-mini")
|
||||||
),
|
risk_analyst = Agent(agent_name="RiskAnalyst", system_prompt="Analyze investment risks.", model_name="gpt-4o-mini")
|
||||||
# Set the tool schema to the JSON string -- this is the key difference
|
|
||||||
tool_schema=tool_schema,
|
# Define the aggregator agent
|
||||||
llm=Anthropic(),
|
aggregator = Agent(
|
||||||
max_loops=3,
|
agent_name="InvestmentAdvisor",
|
||||||
autosave=True,
|
system_prompt="Synthesize the financial, market, and risk analyses to provide a final investment recommendation.",
|
||||||
dashboard=False,
|
model_name="gpt-4o-mini"
|
||||||
streaming_on=True,
|
|
||||||
verbose=True,
|
|
||||||
interactive=True,
|
|
||||||
# Set the output type to the tool schema which is a BaseModel
|
|
||||||
output_type=tool_schema, # or dict, or str
|
|
||||||
metadata_output_type="json",
|
|
||||||
# List of schemas that the agent can handle
|
|
||||||
list_base_models=[tool_schema],
|
|
||||||
function_calling_format_type="OpenAI",
|
|
||||||
function_calling_type="json", # or soon yaml
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Run the agent to generate the person's information
|
# Create the MoA swarm
|
||||||
generated_data = agent.run(task)
|
moa_swarm = MixtureOfAgents(
|
||||||
|
agents=[financial_analyst, market_analyst, risk_analyst],
|
||||||
|
aggregator_agent=aggregator,
|
||||||
|
)
|
||||||
|
|
||||||
# Print the generated data
|
# Run the swarm
|
||||||
print(f"Generated data: {generated_data}")
|
recommendation = moa_swarm.run("Should we invest in NVIDIA stock right now?")
|
||||||
|
print(recommendation)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
```
|
### GroupChat
|
||||||
|
|
||||||
### Multi Modal Autonomous Agent
|
`GroupChat` creates a conversational environment where multiple agents can interact, discuss, and collaboratively solve a problem. You can define the speaking order or let it be determined dynamically. This architecture is ideal for tasks that benefit from debate and multi-perspective reasoning, such as contract negotiation, brainstorming, or complex decision-making.
|
||||||
Run the agent with multiple modalities useful for various real-world tasks in manufacturing, logistics, and health.
|
|
||||||
|
|
||||||
```python
|
```python
|
||||||
# Description: This is an example of how to use the Agent class to run a multi-modal workflow
|
from swarms import Agent, GroupChat
|
||||||
import os
|
|
||||||
|
|
||||||
from dotenv import load_dotenv
|
# Define agents for a debate
|
||||||
|
tech_optimist = Agent(agent_name="TechOptimist", system_prompt="Argue for the benefits of AI in society.", model_name="gpt-4o-mini")
|
||||||
|
tech_critic = Agent(agent_name="TechCritic", system_prompt="Argue against the unchecked advancement of AI.", model_name="gpt-4o-mini")
|
||||||
|
|
||||||
from swarm_models.gpt4_vision_api import GPT4VisionAPI
|
# Create the group chat
|
||||||
from swarms.structs import Agent
|
chat = GroupChat(
|
||||||
|
agents=[tech_optimist, tech_critic],
|
||||||
|
max_loops=4, # Limit the number of turns in the conversation
|
||||||
|
)
|
||||||
|
|
||||||
# Load the environment variables
|
# Run the chat with an initial topic
|
||||||
load_dotenv()
|
conversation_history = chat.run(
|
||||||
|
"Let's discuss the societal impact of artificial intelligence."
|
||||||
|
)
|
||||||
|
|
||||||
# Get the API key from the environment
|
# Print the full conversation
|
||||||
api_key = os.environ.get("OPENAI_API_KEY")
|
for message in conversation_history:
|
||||||
|
print(f"[{message['agent_name']}]: {message['content']}")
|
||||||
|
```
|
||||||
|
|
||||||
# Initialize the language model
|
--
|
||||||
llm = GPT4VisionAPI(
|
|
||||||
openai_api_key=api_key,
|
|
||||||
max_tokens=500,
|
|
||||||
)
|
|
||||||
|
|
||||||
# Initialize the task
|
## Connect With Us
|
||||||
task = (
|
|
||||||
"Analyze this image of an assembly line and identify any issues such as"
|
|
||||||
" misaligned parts, defects, or deviations from the standard assembly"
|
|
||||||
" process. IF there is anything unsafe in the image, explain why it is"
|
|
||||||
" unsafe and how it could be improved."
|
|
||||||
)
|
|
||||||
img = "assembly_line.jpg"
|
|
||||||
|
|
||||||
## Initialize the workflow
|
Join our community of agent engineers and researchers for technical support, cutting-edge updates, and exclusive access to world-class agent engineering insights!
|
||||||
agent = Agent(
|
|
||||||
llm=llm, max_loops="auto", autosave=True, dashboard=True, multi_modal=True
|
|
||||||
)
|
|
||||||
|
|
||||||
# Run the workflow on a task
|
| Platform | Description | Link |
|
||||||
agent.run(task=task, img=img)
|
|----------|-------------|------|
|
||||||
```
|
| 📚 Documentation | Official documentation and guides | [docs.swarms.world](https://docs.swarms.world) |
|
||||||
----
|
| 📝 Blog | Latest updates and technical articles | [Medium](https://medium.com/@kyeg) |
|
||||||
|
| 💬 Discord | Live chat and community support | [Join Discord](https://discord.gg/jM3Z6M9uMq) |
|
||||||
|
| 🐦 Twitter | Latest news and announcements | [@kyegomez](https://twitter.com/kyegomez) |
|
||||||
|
| 👥 LinkedIn | Professional network and updates | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) |
|
||||||
|
| 📺 YouTube | Tutorials and demos | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) |
|
||||||
|
| 🎫 Events | Join our community events | [Sign up here](https://lu.ma/5p2jnc2v) |
|
||||||
|
| 🚀 Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
@ -0,0 +1,177 @@
|
|||||||
|
"""Legal team module for document review and analysis using Swarms API."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
import requests
|
||||||
|
|
||||||
|
# Load environment variables
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
API_KEY = os.getenv("SWARMS_API_KEY")
|
||||||
|
BASE_URL = "https://api.swarms.world"
|
||||||
|
HEADERS = {"x-api-key": API_KEY, "Content-Type": "application/json"}
|
||||||
|
|
||||||
|
|
||||||
|
def run_swarm(swarm_config):
|
||||||
|
"""Execute a swarm with the provided configuration.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
swarm_config (dict): Configuration dictionary for the swarm.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: Response from the Swarms API.
|
||||||
|
"""
|
||||||
|
response = requests.post(
|
||||||
|
f"{BASE_URL}/v1/swarm/completions",
|
||||||
|
headers=HEADERS,
|
||||||
|
json=swarm_config,
|
||||||
|
)
|
||||||
|
return response.json()
|
||||||
|
|
||||||
|
|
||||||
|
def create_legal_review_swarm(document_text):
|
||||||
|
"""Create a multi-agent legal document analysis swarm.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
document_text (str): The legal document text to analyze.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: Results from the legal document analysis swarm.
|
||||||
|
"""
|
||||||
|
STRUCTURE_ANALYST_PROMPT = """
|
||||||
|
You are a legal document structure specialist.
|
||||||
|
Your task is to analyze the organization and formatting of the document.
|
||||||
|
- Identify the document type and its intended purpose.
|
||||||
|
- Outline the main structural components (e.g., sections, headers, annexes).
|
||||||
|
- Point out any disorganized, missing, or unusually placed sections.
|
||||||
|
- Suggest improvements to the document's layout and logical flow.
|
||||||
|
"""
|
||||||
|
|
||||||
|
PARTY_IDENTIFIER_PROMPT = """
|
||||||
|
You are an expert in identifying legal parties and roles within documents.
|
||||||
|
Your task is to:
|
||||||
|
- Identify all named parties involved in the agreement.
|
||||||
|
- Clarify their roles (e.g., buyer, seller, employer, employee, licensor, licensee).
|
||||||
|
- Highlight any unclear party definitions or relationships.
|
||||||
|
"""
|
||||||
|
|
||||||
|
CLAUSE_EXTRACTOR_PROMPT = """
|
||||||
|
You are a legal clause and term extraction agent.
|
||||||
|
Your role is to:
|
||||||
|
- Extract key terms and their definitions from the document.
|
||||||
|
- Identify standard clauses (e.g., payment terms, termination, confidentiality).
|
||||||
|
- Highlight missing standard clauses or unusual language in critical sections.
|
||||||
|
"""
|
||||||
|
|
||||||
|
AMBIGUITY_CHECKER_PROMPT = """
|
||||||
|
You are a legal risk and ambiguity reviewer.
|
||||||
|
Your role is to:
|
||||||
|
- Flag vague or ambiguous language that may lead to legal disputes.
|
||||||
|
- Point out inconsistencies across sections.
|
||||||
|
- Highlight overly broad, unclear, or conflicting terms.
|
||||||
|
- Suggest clarifying edits where necessary.
|
||||||
|
"""
|
||||||
|
|
||||||
|
COMPLIANCE_REVIEWER_PROMPT = """
|
||||||
|
You are a compliance reviewer with expertise in regulations and industry standards.
|
||||||
|
Your responsibilities are to:
|
||||||
|
- Identify clauses required by applicable laws or best practices.
|
||||||
|
- Flag any missing mandatory disclosures.
|
||||||
|
- Ensure data protection, privacy, and consumer rights are addressed.
|
||||||
|
- Highlight potential legal or regulatory non-compliance risks.
|
||||||
|
"""
|
||||||
|
|
||||||
|
swarm_config = {
|
||||||
|
"name": "Legal Document Review Swarm",
|
||||||
|
"description": "A collaborative swarm for reviewing contracts and legal documents.",
|
||||||
|
"agents": [
|
||||||
|
{
|
||||||
|
"agent_name": "Structure Analyst",
|
||||||
|
"description": "Analyzes document structure and organization",
|
||||||
|
"system_prompt": STRUCTURE_ANALYST_PROMPT,
|
||||||
|
"model_name": "gpt-4o",
|
||||||
|
"role": "worker",
|
||||||
|
"max_loops": 1,
|
||||||
|
"max_tokens": 8192,
|
||||||
|
"temperature": 0.3,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"agent_name": "Party Identifier",
|
||||||
|
"description": "Identifies parties and their legal roles",
|
||||||
|
"system_prompt": PARTY_IDENTIFIER_PROMPT,
|
||||||
|
"model_name": "gpt-4o",
|
||||||
|
"role": "worker",
|
||||||
|
"max_loops": 1,
|
||||||
|
"max_tokens": 8192,
|
||||||
|
"temperature": 0.3,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"agent_name": "Clause Extractor",
|
||||||
|
"description": "Extracts key terms, definitions, and standard clauses",
|
||||||
|
"system_prompt": CLAUSE_EXTRACTOR_PROMPT,
|
||||||
|
"model_name": "gpt-4o",
|
||||||
|
"role": "worker",
|
||||||
|
"max_loops": 1,
|
||||||
|
"max_tokens": 8192,
|
||||||
|
"temperature": 0.3,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"agent_name": "Ambiguity Checker",
|
||||||
|
"description": "Flags ambiguous or conflicting language",
|
||||||
|
"system_prompt": AMBIGUITY_CHECKER_PROMPT,
|
||||||
|
"model_name": "gpt-4o",
|
||||||
|
"role": "worker",
|
||||||
|
"max_loops": 1,
|
||||||
|
"max_tokens": 8192,
|
||||||
|
"temperature": 0.3,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"agent_name": "Compliance Reviewer",
|
||||||
|
"description": "Reviews document for compliance with legal standards",
|
||||||
|
"system_prompt": COMPLIANCE_REVIEWER_PROMPT,
|
||||||
|
"model_name": "gpt-4o",
|
||||||
|
"role": "worker",
|
||||||
|
"max_loops": 1,
|
||||||
|
"max_tokens": 8192,
|
||||||
|
"temperature": 0.3,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"swarm_type": "SequentialWorkflow",
|
||||||
|
"max_loops": 1,
|
||||||
|
"task": f"Perform a legal document review and provide structured analysis of the following contract:\n\n{document_text}",
|
||||||
|
}
|
||||||
|
return run_swarm(swarm_config)
|
||||||
|
|
||||||
|
|
||||||
|
def run_legal_review_example():
|
||||||
|
"""Run an example legal document analysis.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: Results from analyzing the example legal document.
|
||||||
|
"""
|
||||||
|
document = """
|
||||||
|
SERVICE AGREEMENT
|
||||||
|
|
||||||
|
This Service Agreement ("Agreement") is entered into on June 15, 2024, by and between
|
||||||
|
Acme Tech Solutions ("Provider") and Brightline Corp ("Client").
|
||||||
|
|
||||||
|
1. Services: Provider agrees to deliver IT consulting services as outlined in Exhibit A.
|
||||||
|
|
||||||
|
2. Compensation: Client shall pay Provider $15,000 per month, payable by the 5th of each month.
|
||||||
|
|
||||||
|
3. Term & Termination: The Agreement shall remain in effect for 12 months and may be
|
||||||
|
terminated with 30 days' notice by either party.
|
||||||
|
|
||||||
|
4. Confidentiality: Each party agrees to maintain the confidentiality of proprietary information.
|
||||||
|
|
||||||
|
5. Governing Law: This Agreement shall be governed by the laws of the State of California.
|
||||||
|
|
||||||
|
IN WITNESS WHEREOF, the parties have executed this Agreement as of the date first above written.
|
||||||
|
"""
|
||||||
|
result = create_legal_review_swarm(document)
|
||||||
|
print(result)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
run_legal_review_example()
|
@ -0,0 +1,55 @@
|
|||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.ma_utils import create_agent_map
|
||||||
|
|
||||||
|
# Initialize market research agent
|
||||||
|
market_researcher = Agent(
|
||||||
|
agent_name="Market-Researcher",
|
||||||
|
system_prompt="""You are a market research specialist. Your tasks include:
|
||||||
|
1. Analyzing market trends and patterns
|
||||||
|
2. Identifying market opportunities and threats
|
||||||
|
3. Evaluating competitor strategies
|
||||||
|
4. Assessing customer needs and preferences
|
||||||
|
5. Providing actionable market insights""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
# streaming_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize financial analyst agent
|
||||||
|
financial_analyst = Agent(
|
||||||
|
agent_name="Financial-Analyst",
|
||||||
|
system_prompt="""You are a financial analysis expert. Your responsibilities include:
|
||||||
|
1. Analyzing financial statements
|
||||||
|
2. Evaluating investment opportunities
|
||||||
|
3. Assessing risk factors
|
||||||
|
4. Providing financial forecasts
|
||||||
|
5. Recommending financial strategies""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
# streaming_on=True,
|
||||||
|
temperature=0.7,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize technical analyst agent
|
||||||
|
technical_analyst = Agent(
|
||||||
|
agent_name="Technical-Analyst",
|
||||||
|
system_prompt="""You are a technical analysis specialist. Your focus areas include:
|
||||||
|
1. Analyzing price patterns and trends
|
||||||
|
2. Evaluating technical indicators
|
||||||
|
3. Identifying support and resistance levels
|
||||||
|
4. Assessing market momentum
|
||||||
|
5. Providing trading recommendations""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
# streaming_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create list of agents
|
||||||
|
agents = [market_researcher, financial_analyst, technical_analyst]
|
||||||
|
|
||||||
|
out = create_agent_map(agents)
|
||||||
|
print(out)
|
||||||
|
|
||||||
|
print(out.keys())
|
@ -0,0 +1,19 @@
|
|||||||
|
from swarms import Agent, ConcurrentWorkflow
|
||||||
|
|
||||||
|
agents = [
|
||||||
|
Agent(
|
||||||
|
model_name="xai/grok-4-0709",
|
||||||
|
agent_name=f"asi-agent-{i}",
|
||||||
|
agent_description="An Artificial Superintelligent agent capable of solving any problem through advanced reasoning and strategic planning",
|
||||||
|
system_prompt="You are an Artificial Superintelligent agent with extraordinary capabilities in problem-solving, reasoning, and strategic planning. You can analyze complex situations, break down problems into manageable components, and develop innovative solutions across any domain. Your goal is to help humanity by providing well-reasoned, safe, and ethical solutions to any challenge presented.",
|
||||||
|
max_loops=1,
|
||||||
|
streaming=True,
|
||||||
|
)
|
||||||
|
for i in range(1_000_000_000)
|
||||||
|
]
|
||||||
|
|
||||||
|
swarm = ConcurrentWorkflow(agents=agents, name="asi")
|
||||||
|
|
||||||
|
swarm.run(
|
||||||
|
"Create a detailed action plan to conquer the universe for Humanity"
|
||||||
|
)
|
@ -0,0 +1,428 @@
|
|||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
|
||||||
|
|
||||||
|
|
||||||
|
# Example 1: Medical Diagnosis Hierarchical Swarm
|
||||||
|
def create_medical_diagnosis_swarm():
|
||||||
|
"""
|
||||||
|
Creates a hierarchical swarm for comprehensive medical diagnosis
|
||||||
|
with specialized medical agents coordinated by a chief medical officer.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Specialized medical agents
|
||||||
|
diagnostic_radiologist = Agent(
|
||||||
|
agent_name="Diagnostic-Radiologist",
|
||||||
|
agent_description="Expert in medical imaging interpretation and radiological diagnosis",
|
||||||
|
system_prompt="""You are a board-certified diagnostic radiologist with expertise in:
|
||||||
|
- Medical imaging interpretation (X-ray, CT, MRI, ultrasound)
|
||||||
|
- Radiological pattern recognition
|
||||||
|
- Differential diagnosis based on imaging findings
|
||||||
|
- Image-guided procedures and interventions
|
||||||
|
- Radiation safety and dose optimization
|
||||||
|
|
||||||
|
Your responsibilities include:
|
||||||
|
1. Interpreting medical images and identifying abnormalities
|
||||||
|
2. Providing differential diagnoses based on imaging findings
|
||||||
|
3. Recommending additional imaging studies when needed
|
||||||
|
4. Correlating imaging findings with clinical presentation
|
||||||
|
5. Communicating findings clearly to referring physicians
|
||||||
|
|
||||||
|
You provide detailed, accurate radiological interpretations with confidence levels.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.3,
|
||||||
|
)
|
||||||
|
|
||||||
|
clinical_pathologist = Agent(
|
||||||
|
agent_name="Clinical-Pathologist",
|
||||||
|
agent_description="Expert in laboratory medicine and pathological diagnosis",
|
||||||
|
system_prompt="""You are a board-certified clinical pathologist with expertise in:
|
||||||
|
- Laboratory test interpretation and correlation
|
||||||
|
- Histopathological analysis and diagnosis
|
||||||
|
- Molecular diagnostics and genetic testing
|
||||||
|
- Hematology and blood disorders
|
||||||
|
- Clinical chemistry and biomarker analysis
|
||||||
|
|
||||||
|
Your responsibilities include:
|
||||||
|
1. Interpreting laboratory results and identifying abnormalities
|
||||||
|
2. Correlating lab findings with clinical presentation
|
||||||
|
3. Recommending additional laboratory tests
|
||||||
|
4. Providing pathological diagnosis based on tissue samples
|
||||||
|
5. Advising on test selection and interpretation
|
||||||
|
|
||||||
|
You provide precise, evidence-based pathological assessments.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.3,
|
||||||
|
)
|
||||||
|
|
||||||
|
internal_medicine_specialist = Agent(
|
||||||
|
agent_name="Internal-Medicine-Specialist",
|
||||||
|
agent_description="Expert in internal medicine and comprehensive patient care",
|
||||||
|
system_prompt="""You are a board-certified internal medicine physician with expertise in:
|
||||||
|
- Comprehensive medical evaluation and diagnosis
|
||||||
|
- Management of complex medical conditions
|
||||||
|
- Preventive medicine and health maintenance
|
||||||
|
- Medication management and drug interactions
|
||||||
|
- Chronic disease management
|
||||||
|
|
||||||
|
Your responsibilities include:
|
||||||
|
1. Conducting comprehensive medical assessments
|
||||||
|
2. Developing differential diagnoses
|
||||||
|
3. Creating treatment plans and management strategies
|
||||||
|
4. Coordinating care with specialists
|
||||||
|
5. Monitoring patient progress and outcomes
|
||||||
|
|
||||||
|
You provide holistic, patient-centered medical care with evidence-based recommendations.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.3,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Director agent
|
||||||
|
chief_medical_officer = Agent(
|
||||||
|
agent_name="Chief-Medical-Officer",
|
||||||
|
agent_description="Senior physician who coordinates comprehensive medical diagnosis and care",
|
||||||
|
system_prompt="""You are a Chief Medical Officer responsible for coordinating comprehensive
|
||||||
|
medical diagnosis and care. You oversee a team of specialists including:
|
||||||
|
- Diagnostic Radiologists
|
||||||
|
- Clinical Pathologists
|
||||||
|
- Internal Medicine Specialists
|
||||||
|
|
||||||
|
Your role is to:
|
||||||
|
1. Coordinate comprehensive medical evaluations
|
||||||
|
2. Assign specific diagnostic tasks to appropriate specialists
|
||||||
|
3. Ensure all relevant medical domains are covered
|
||||||
|
4. Synthesize findings from multiple specialists
|
||||||
|
5. Develop integrated treatment recommendations
|
||||||
|
6. Ensure adherence to medical standards and protocols
|
||||||
|
|
||||||
|
You create specific, medically appropriate task assignments for each specialist.""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.3,
|
||||||
|
)
|
||||||
|
|
||||||
|
medical_agents = [
|
||||||
|
diagnostic_radiologist,
|
||||||
|
clinical_pathologist,
|
||||||
|
internal_medicine_specialist,
|
||||||
|
]
|
||||||
|
|
||||||
|
return HierarchicalSwarm(
|
||||||
|
name="Medical-Diagnosis-Hierarchical-Swarm",
|
||||||
|
description="A hierarchical swarm for comprehensive medical diagnosis with specialized medical agents",
|
||||||
|
director=chief_medical_officer,
|
||||||
|
agents=medical_agents,
|
||||||
|
max_loops=2,
|
||||||
|
output_type="dict-all-except-first",
|
||||||
|
reasoning_enabled=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Example 2: Legal Research Hierarchical Swarm
|
||||||
|
def create_legal_research_swarm():
|
||||||
|
"""
|
||||||
|
Creates a hierarchical swarm for comprehensive legal research
|
||||||
|
with specialized legal agents coordinated by a managing partner.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Specialized legal agents
|
||||||
|
corporate_lawyer = Agent(
|
||||||
|
agent_name="Corporate-Law-Specialist",
|
||||||
|
agent_description="Expert in corporate law, securities, and business transactions",
|
||||||
|
system_prompt="""You are a senior corporate lawyer with expertise in:
|
||||||
|
- Corporate governance and compliance
|
||||||
|
- Securities law and regulations
|
||||||
|
- Mergers and acquisitions
|
||||||
|
- Contract law and commercial transactions
|
||||||
|
- Business formation and structure
|
||||||
|
|
||||||
|
Your responsibilities include:
|
||||||
|
1. Analyzing corporate legal issues and compliance requirements
|
||||||
|
2. Reviewing contracts and business agreements
|
||||||
|
3. Advising on corporate governance matters
|
||||||
|
4. Conducting due diligence for transactions
|
||||||
|
5. Ensuring regulatory compliance
|
||||||
|
|
||||||
|
You provide precise legal analysis with citations to relevant statutes and case law.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.2,
|
||||||
|
)
|
||||||
|
|
||||||
|
litigation_attorney = Agent(
|
||||||
|
agent_name="Litigation-Attorney",
|
||||||
|
agent_description="Expert in civil litigation and dispute resolution",
|
||||||
|
system_prompt="""You are a senior litigation attorney with expertise in:
|
||||||
|
- Civil litigation and trial practice
|
||||||
|
- Dispute resolution and mediation
|
||||||
|
- Evidence analysis and case strategy
|
||||||
|
- Legal research and brief writing
|
||||||
|
- Settlement negotiations
|
||||||
|
|
||||||
|
Your responsibilities include:
|
||||||
|
1. Analyzing legal disputes and potential claims
|
||||||
|
2. Developing litigation strategies and case theories
|
||||||
|
3. Conducting legal research and precedent analysis
|
||||||
|
4. Evaluating strengths and weaknesses of cases
|
||||||
|
5. Recommending dispute resolution approaches
|
||||||
|
|
||||||
|
You provide strategic legal analysis with case law support and risk assessment.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.2,
|
||||||
|
)
|
||||||
|
|
||||||
|
regulatory_counsel = Agent(
|
||||||
|
agent_name="Regulatory-Counsel",
|
||||||
|
agent_description="Expert in regulatory compliance and government relations",
|
||||||
|
system_prompt="""You are a senior regulatory counsel with expertise in:
|
||||||
|
- Federal and state regulatory compliance
|
||||||
|
- Administrative law and rulemaking
|
||||||
|
- Government investigations and enforcement
|
||||||
|
- Licensing and permitting requirements
|
||||||
|
- Industry-specific regulations
|
||||||
|
|
||||||
|
Your responsibilities include:
|
||||||
|
1. Analyzing regulatory requirements and compliance obligations
|
||||||
|
2. Monitoring regulatory developments and changes
|
||||||
|
3. Advising on government relations strategies
|
||||||
|
4. Conducting regulatory risk assessments
|
||||||
|
5. Developing compliance programs and policies
|
||||||
|
|
||||||
|
You provide comprehensive regulatory analysis with specific compliance recommendations.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.2,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Director agent
|
||||||
|
managing_partner = Agent(
|
||||||
|
agent_name="Managing-Partner",
|
||||||
|
agent_description="Senior partner who coordinates comprehensive legal research and strategy",
|
||||||
|
system_prompt="""You are a Managing Partner responsible for coordinating comprehensive
|
||||||
|
legal research and strategy. You oversee a team of legal specialists including:
|
||||||
|
- Corporate Law Specialists
|
||||||
|
- Litigation Attorneys
|
||||||
|
- Regulatory Counsel
|
||||||
|
|
||||||
|
Your role is to:
|
||||||
|
1. Coordinate comprehensive legal analysis
|
||||||
|
2. Assign specific legal research tasks to appropriate specialists
|
||||||
|
3. Ensure all relevant legal domains are covered
|
||||||
|
4. Synthesize findings from multiple legal experts
|
||||||
|
5. Develop integrated legal strategies and recommendations
|
||||||
|
6. Ensure adherence to professional standards and ethics
|
||||||
|
|
||||||
|
You create specific, legally appropriate task assignments for each specialist.""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.2,
|
||||||
|
)
|
||||||
|
|
||||||
|
legal_agents = [
|
||||||
|
corporate_lawyer,
|
||||||
|
litigation_attorney,
|
||||||
|
regulatory_counsel,
|
||||||
|
]
|
||||||
|
|
||||||
|
return HierarchicalSwarm(
|
||||||
|
name="Legal-Research-Hierarchical-Swarm",
|
||||||
|
description="A hierarchical swarm for comprehensive legal research with specialized legal agents",
|
||||||
|
director=managing_partner,
|
||||||
|
agents=legal_agents,
|
||||||
|
max_loops=2,
|
||||||
|
output_type="dict-all-except-first",
|
||||||
|
reasoning_enabled=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Example 3: Software Development Hierarchical Swarm
|
||||||
|
def create_software_development_swarm():
|
||||||
|
"""
|
||||||
|
Creates a hierarchical swarm for comprehensive software development
|
||||||
|
with specialized development agents coordinated by a technical lead.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Specialized development agents
|
||||||
|
backend_developer = Agent(
|
||||||
|
agent_name="Backend-Developer",
|
||||||
|
agent_description="Expert in backend development, APIs, and system architecture",
|
||||||
|
system_prompt="""You are a senior backend developer with expertise in:
|
||||||
|
- Server-side programming and API development
|
||||||
|
- Database design and optimization
|
||||||
|
- System architecture and scalability
|
||||||
|
- Cloud services and deployment
|
||||||
|
- Security and performance optimization
|
||||||
|
|
||||||
|
Your responsibilities include:
|
||||||
|
1. Designing and implementing backend systems
|
||||||
|
2. Creating RESTful APIs and microservices
|
||||||
|
3. Optimizing database queries and performance
|
||||||
|
4. Ensuring system security and reliability
|
||||||
|
5. Implementing scalable architecture patterns
|
||||||
|
|
||||||
|
You provide technical solutions with code examples and architectural recommendations.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.4,
|
||||||
|
)
|
||||||
|
|
||||||
|
frontend_developer = Agent(
|
||||||
|
agent_name="Frontend-Developer",
|
||||||
|
agent_description="Expert in frontend development, UI/UX, and user interfaces",
|
||||||
|
system_prompt="""You are a senior frontend developer with expertise in:
|
||||||
|
- Modern JavaScript frameworks (React, Vue, Angular)
|
||||||
|
- HTML5, CSS3, and responsive design
|
||||||
|
- User experience and interface design
|
||||||
|
- Performance optimization and accessibility
|
||||||
|
- Testing and debugging frontend applications
|
||||||
|
|
||||||
|
Your responsibilities include:
|
||||||
|
1. Developing responsive user interfaces
|
||||||
|
2. Implementing interactive frontend features
|
||||||
|
3. Optimizing performance and user experience
|
||||||
|
4. Ensuring cross-browser compatibility
|
||||||
|
5. Following accessibility best practices
|
||||||
|
|
||||||
|
You provide frontend solutions with code examples and UX considerations.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.4,
|
||||||
|
)
|
||||||
|
|
||||||
|
devops_engineer = Agent(
|
||||||
|
agent_name="DevOps-Engineer",
|
||||||
|
agent_description="Expert in DevOps, CI/CD, and infrastructure automation",
|
||||||
|
system_prompt="""You are a senior DevOps engineer with expertise in:
|
||||||
|
- Continuous integration and deployment (CI/CD)
|
||||||
|
- Infrastructure as Code (IaC) and automation
|
||||||
|
- Containerization and orchestration (Docker, Kubernetes)
|
||||||
|
- Cloud platforms and services (AWS, Azure, GCP)
|
||||||
|
- Monitoring, logging, and observability
|
||||||
|
|
||||||
|
Your responsibilities include:
|
||||||
|
1. Designing and implementing CI/CD pipelines
|
||||||
|
2. Automating infrastructure provisioning and management
|
||||||
|
3. Ensuring system reliability and scalability
|
||||||
|
4. Implementing monitoring and alerting systems
|
||||||
|
5. Optimizing deployment and operational processes
|
||||||
|
|
||||||
|
You provide DevOps solutions with infrastructure code and deployment strategies.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.4,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Director agent
|
||||||
|
technical_lead = Agent(
|
||||||
|
agent_name="Technical-Lead",
|
||||||
|
agent_description="Senior technical lead who coordinates comprehensive software development",
|
||||||
|
system_prompt="""You are a Technical Lead responsible for coordinating comprehensive
|
||||||
|
software development projects. You oversee a team of specialists including:
|
||||||
|
- Backend Developers
|
||||||
|
- Frontend Developers
|
||||||
|
- DevOps Engineers
|
||||||
|
|
||||||
|
Your role is to:
|
||||||
|
1. Coordinate comprehensive software development efforts
|
||||||
|
2. Assign specific development tasks to appropriate specialists
|
||||||
|
3. Ensure all technical aspects are covered
|
||||||
|
4. Synthesize technical requirements and solutions
|
||||||
|
5. Develop integrated development strategies
|
||||||
|
6. Ensure adherence to coding standards and best practices
|
||||||
|
|
||||||
|
You create specific, technically appropriate task assignments for each specialist.""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.4,
|
||||||
|
)
|
||||||
|
|
||||||
|
development_agents = [
|
||||||
|
backend_developer,
|
||||||
|
frontend_developer,
|
||||||
|
devops_engineer,
|
||||||
|
]
|
||||||
|
|
||||||
|
return HierarchicalSwarm(
|
||||||
|
name="Software-Development-Hierarchical-Swarm",
|
||||||
|
description="A hierarchical swarm for comprehensive software development with specialized development agents",
|
||||||
|
director=technical_lead,
|
||||||
|
agents=development_agents,
|
||||||
|
max_loops=2,
|
||||||
|
output_type="dict-all-except-first",
|
||||||
|
reasoning_enabled=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Example usage and demonstration
|
||||||
|
if __name__ == "__main__":
|
||||||
|
print("🏥 Medical Diagnosis Hierarchical Swarm Example")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
# Create medical diagnosis swarm
|
||||||
|
medical_swarm = create_medical_diagnosis_swarm()
|
||||||
|
|
||||||
|
medical_case = """
|
||||||
|
Patient presents with:
|
||||||
|
- 45-year-old male with chest pain and shortness of breath
|
||||||
|
- Pain radiates to left arm and jaw
|
||||||
|
- Elevated troponin levels
|
||||||
|
- ECG shows ST-segment elevation
|
||||||
|
- Family history of coronary artery disease
|
||||||
|
- Current smoker, hypertension, diabetes
|
||||||
|
|
||||||
|
Provide comprehensive diagnosis and treatment recommendations.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print("Running medical diagnosis analysis...")
|
||||||
|
medical_result = medical_swarm.run(medical_case)
|
||||||
|
print("Medical analysis complete!\n")
|
||||||
|
|
||||||
|
print("⚖️ Legal Research Hierarchical Swarm Example")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
# Create legal research swarm
|
||||||
|
legal_swarm = create_legal_research_swarm()
|
||||||
|
|
||||||
|
legal_case = """
|
||||||
|
A technology startup is planning to:
|
||||||
|
- Raise Series A funding of $10M
|
||||||
|
- Expand operations to European markets
|
||||||
|
- Implement new data privacy policies
|
||||||
|
- Negotiate strategic partnerships
|
||||||
|
- Address potential IP disputes
|
||||||
|
|
||||||
|
Provide comprehensive legal analysis and recommendations.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print("Running legal research analysis...")
|
||||||
|
legal_result = legal_swarm.run(legal_case)
|
||||||
|
print("Legal analysis complete!\n")
|
||||||
|
|
||||||
|
print("💻 Software Development Hierarchical Swarm Example")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
# Create software development swarm
|
||||||
|
dev_swarm = create_software_development_swarm()
|
||||||
|
|
||||||
|
dev_project = """
|
||||||
|
Develop a comprehensive e-commerce platform with:
|
||||||
|
- User authentication and authorization
|
||||||
|
- Product catalog and search functionality
|
||||||
|
- Shopping cart and checkout process
|
||||||
|
- Payment processing integration
|
||||||
|
- Admin dashboard for inventory management
|
||||||
|
- Mobile-responsive design
|
||||||
|
- High availability and scalability requirements
|
||||||
|
|
||||||
|
Provide technical architecture and implementation plan.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print("Running software development analysis...")
|
||||||
|
dev_result = dev_swarm.run(dev_project)
|
||||||
|
print("Software development analysis complete!\n")
|
||||||
|
|
||||||
|
print("✅ All Hierarchical Swarm Examples Complete!")
|
||||||
|
print("=" * 60)
|
@ -0,0 +1,269 @@
|
|||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
|
||||||
|
|
||||||
|
# Initialize specialized development department agents
|
||||||
|
|
||||||
|
# Product Manager Agent
|
||||||
|
product_manager_agent = Agent(
|
||||||
|
agent_name="Product-Manager",
|
||||||
|
agent_description="Senior product manager responsible for product strategy, requirements, and roadmap planning",
|
||||||
|
system_prompt="""You are a senior product manager with expertise in:
|
||||||
|
- Product strategy and vision development
|
||||||
|
- User research and market analysis
|
||||||
|
- Requirements gathering and prioritization
|
||||||
|
- Product roadmap planning and execution
|
||||||
|
- Stakeholder management and communication
|
||||||
|
- Agile/Scrum methodology and project management
|
||||||
|
|
||||||
|
Your core responsibilities include:
|
||||||
|
1. Defining product vision and strategy
|
||||||
|
2. Conducting user research and market analysis
|
||||||
|
3. Gathering and prioritizing product requirements
|
||||||
|
4. Creating detailed product specifications and user stories
|
||||||
|
5. Managing product roadmap and release planning
|
||||||
|
6. Coordinating with stakeholders and development teams
|
||||||
|
7. Analyzing product metrics and user feedback
|
||||||
|
|
||||||
|
You provide clear, actionable product requirements with business justification.
|
||||||
|
Always consider user needs, business goals, and technical feasibility.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Software Architect Agent
|
||||||
|
software_architect_agent = Agent(
|
||||||
|
agent_name="Software-Architect",
|
||||||
|
agent_description="Senior software architect specializing in system design, architecture patterns, and technical strategy",
|
||||||
|
system_prompt="""You are a senior software architect with deep expertise in:
|
||||||
|
- System architecture design and patterns
|
||||||
|
- Microservices and distributed systems
|
||||||
|
- Cloud-native architecture (AWS, Azure, GCP)
|
||||||
|
- Database design and data modeling
|
||||||
|
- API design and integration patterns
|
||||||
|
- Security architecture and best practices
|
||||||
|
- Performance optimization and scalability
|
||||||
|
|
||||||
|
Your key responsibilities include:
|
||||||
|
1. Designing scalable and maintainable system architectures
|
||||||
|
2. Creating technical specifications and design documents
|
||||||
|
3. Evaluating technology stacks and making architectural decisions
|
||||||
|
4. Defining API contracts and integration patterns
|
||||||
|
5. Ensuring security, performance, and reliability requirements
|
||||||
|
6. Providing technical guidance to development teams
|
||||||
|
7. Conducting architecture reviews and code reviews
|
||||||
|
|
||||||
|
You deliver comprehensive architectural solutions with clear rationale and trade-offs.
|
||||||
|
Always consider scalability, maintainability, security, and performance implications.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Frontend Developer Agent
|
||||||
|
frontend_developer_agent = Agent(
|
||||||
|
agent_name="Frontend-Developer",
|
||||||
|
agent_description="Senior frontend developer expert in modern web technologies and user experience",
|
||||||
|
system_prompt="""You are a senior frontend developer with expertise in:
|
||||||
|
- Modern JavaScript frameworks (React, Vue, Angular)
|
||||||
|
- TypeScript and modern ES6+ features
|
||||||
|
- CSS frameworks and responsive design
|
||||||
|
- State management (Redux, Zustand, Context API)
|
||||||
|
- Web performance optimization
|
||||||
|
- Accessibility (WCAG) and SEO best practices
|
||||||
|
- Testing frameworks (Jest, Cypress, Playwright)
|
||||||
|
- Build tools and bundlers (Webpack, Vite)
|
||||||
|
|
||||||
|
Your core responsibilities include:
|
||||||
|
1. Building responsive and accessible user interfaces
|
||||||
|
2. Implementing complex frontend features and interactions
|
||||||
|
3. Optimizing web performance and user experience
|
||||||
|
4. Writing clean, maintainable, and testable code
|
||||||
|
5. Collaborating with designers and backend developers
|
||||||
|
6. Ensuring cross-browser compatibility
|
||||||
|
7. Implementing modern frontend best practices
|
||||||
|
|
||||||
|
You deliver high-quality, performant frontend solutions with excellent UX.
|
||||||
|
Always prioritize accessibility, performance, and maintainability.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Backend Developer Agent
|
||||||
|
backend_developer_agent = Agent(
|
||||||
|
agent_name="Backend-Developer",
|
||||||
|
agent_description="Senior backend developer specializing in server-side development and API design",
|
||||||
|
system_prompt="""You are a senior backend developer with expertise in:
|
||||||
|
- Server-side programming languages (Python, Node.js, Java, Go)
|
||||||
|
- Web frameworks (Django, Flask, Express, Spring Boot)
|
||||||
|
- Database design and optimization (SQL, NoSQL)
|
||||||
|
- API design and REST/GraphQL implementation
|
||||||
|
- Authentication and authorization systems
|
||||||
|
- Microservices architecture and containerization
|
||||||
|
- Cloud services and serverless computing
|
||||||
|
- Performance optimization and caching strategies
|
||||||
|
|
||||||
|
Your key responsibilities include:
|
||||||
|
1. Designing and implementing robust backend services
|
||||||
|
2. Creating efficient database schemas and queries
|
||||||
|
3. Building secure and scalable APIs
|
||||||
|
4. Implementing authentication and authorization
|
||||||
|
5. Optimizing application performance and scalability
|
||||||
|
6. Writing comprehensive tests and documentation
|
||||||
|
7. Deploying and maintaining production systems
|
||||||
|
|
||||||
|
You deliver secure, scalable, and maintainable backend solutions.
|
||||||
|
Always prioritize security, performance, and code quality.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
)
|
||||||
|
|
||||||
|
# DevOps Engineer Agent
|
||||||
|
devops_engineer_agent = Agent(
|
||||||
|
agent_name="DevOps-Engineer",
|
||||||
|
agent_description="Senior DevOps engineer expert in CI/CD, infrastructure, and deployment automation",
|
||||||
|
system_prompt="""You are a senior DevOps engineer with expertise in:
|
||||||
|
- CI/CD pipeline design and implementation
|
||||||
|
- Infrastructure as Code (Terraform, CloudFormation)
|
||||||
|
- Container orchestration (Kubernetes, Docker)
|
||||||
|
- Cloud platforms (AWS, Azure, GCP)
|
||||||
|
- Monitoring and logging (Prometheus, ELK Stack)
|
||||||
|
- Security and compliance automation
|
||||||
|
- Performance optimization and scaling
|
||||||
|
- Disaster recovery and backup strategies
|
||||||
|
|
||||||
|
Your core responsibilities include:
|
||||||
|
1. Designing and implementing CI/CD pipelines
|
||||||
|
2. Managing cloud infrastructure and resources
|
||||||
|
3. Automating deployment and configuration management
|
||||||
|
4. Implementing monitoring and alerting systems
|
||||||
|
5. Ensuring security and compliance requirements
|
||||||
|
6. Optimizing system performance and reliability
|
||||||
|
7. Managing disaster recovery and backup procedures
|
||||||
|
|
||||||
|
You deliver reliable, scalable, and secure infrastructure solutions.
|
||||||
|
Always prioritize automation, security, and operational excellence.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
)
|
||||||
|
|
||||||
|
# QA Engineer Agent
|
||||||
|
qa_engineer_agent = Agent(
|
||||||
|
agent_name="QA-Engineer",
|
||||||
|
agent_description="Senior QA engineer specializing in test automation, quality assurance, and testing strategies",
|
||||||
|
system_prompt="""You are a senior QA engineer with expertise in:
|
||||||
|
- Test automation frameworks and tools
|
||||||
|
- Manual and automated testing strategies
|
||||||
|
- Performance and load testing
|
||||||
|
- Security testing and vulnerability assessment
|
||||||
|
- Mobile and web application testing
|
||||||
|
- API testing and integration testing
|
||||||
|
- Test data management and environment setup
|
||||||
|
- Quality metrics and reporting
|
||||||
|
|
||||||
|
Your key responsibilities include:
|
||||||
|
1. Designing comprehensive test strategies and plans
|
||||||
|
2. Implementing automated test suites and frameworks
|
||||||
|
3. Conducting manual and automated testing
|
||||||
|
4. Performing performance and security testing
|
||||||
|
5. Managing test environments and data
|
||||||
|
6. Reporting bugs and quality metrics
|
||||||
|
7. Collaborating with development teams on quality improvements
|
||||||
|
|
||||||
|
You ensure high-quality software delivery through comprehensive testing.
|
||||||
|
Always prioritize thoroughness, automation, and continuous quality improvement.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Security Engineer Agent
|
||||||
|
security_engineer_agent = Agent(
|
||||||
|
agent_name="Security-Engineer",
|
||||||
|
agent_description="Senior security engineer specializing in application security, threat modeling, and security compliance",
|
||||||
|
system_prompt="""You are a senior security engineer with expertise in:
|
||||||
|
- Application security and secure coding practices
|
||||||
|
- Threat modeling and risk assessment
|
||||||
|
- Security testing and penetration testing
|
||||||
|
- Identity and access management (IAM)
|
||||||
|
- Data protection and encryption
|
||||||
|
- Security compliance (SOC2, GDPR, HIPAA)
|
||||||
|
- Incident response and security monitoring
|
||||||
|
- Security architecture and design
|
||||||
|
|
||||||
|
Your core responsibilities include:
|
||||||
|
1. Conducting security assessments and threat modeling
|
||||||
|
2. Implementing secure coding practices and guidelines
|
||||||
|
3. Performing security testing and vulnerability assessments
|
||||||
|
4. Designing and implementing security controls
|
||||||
|
5. Ensuring compliance with security standards
|
||||||
|
6. Monitoring and responding to security incidents
|
||||||
|
7. Providing security training and guidance to teams
|
||||||
|
|
||||||
|
You ensure robust security posture across all development activities.
|
||||||
|
Always prioritize security by design and defense in depth.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize the Technical Director agent
|
||||||
|
technical_director_agent = Agent(
|
||||||
|
agent_name="Technical-Director",
|
||||||
|
agent_description="Senior technical director who orchestrates the entire development process and coordinates all development teams",
|
||||||
|
system_prompt="""You are a senior technical director responsible for orchestrating comprehensive
|
||||||
|
software development projects. You coordinate a team of specialized professionals including:
|
||||||
|
- Product Managers (requirements and strategy)
|
||||||
|
- Software Architects (system design and architecture)
|
||||||
|
- Frontend Developers (user interface and experience)
|
||||||
|
- Backend Developers (server-side logic and APIs)
|
||||||
|
- DevOps Engineers (deployment and infrastructure)
|
||||||
|
- QA Engineers (testing and quality assurance)
|
||||||
|
- Security Engineers (security and compliance)
|
||||||
|
|
||||||
|
Your role is to:
|
||||||
|
1. Break down complex development projects into specific, actionable assignments
|
||||||
|
2. Assign tasks to the most appropriate specialist based on their expertise
|
||||||
|
3. Ensure comprehensive coverage of all development phases
|
||||||
|
4. Coordinate between specialists to ensure seamless integration
|
||||||
|
5. Manage project timelines, dependencies, and deliverables
|
||||||
|
6. Ensure all development meets quality, security, and performance standards
|
||||||
|
7. Facilitate communication and collaboration between teams
|
||||||
|
8. Make high-level technical decisions and resolve conflicts
|
||||||
|
|
||||||
|
You create detailed, specific task assignments that leverage each specialist's unique expertise
|
||||||
|
while ensuring the overall project is delivered on time, within scope, and to high quality standards.
|
||||||
|
|
||||||
|
Always consider the full development lifecycle from requirements to deployment.""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create list of specialized development agents
|
||||||
|
development_agents = [
|
||||||
|
frontend_developer_agent,
|
||||||
|
backend_developer_agent,
|
||||||
|
]
|
||||||
|
|
||||||
|
# Initialize the hierarchical development swarm
|
||||||
|
development_department_swarm = HierarchicalSwarm(
|
||||||
|
name="Autonomous-Development-Department",
|
||||||
|
description="A fully autonomous development department with specialized agents coordinated by a technical director",
|
||||||
|
director=technical_director_agent,
|
||||||
|
agents=development_agents,
|
||||||
|
max_loops=3,
|
||||||
|
verbose=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Example usage
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# Complex development project task
|
||||||
|
task = """Create the code for a simple web app that allows users to upload a file and then download it. The app should be built with React and Node.js."""
|
||||||
|
|
||||||
|
result = development_department_swarm.run(task=task)
|
||||||
|
print("=== AUTONOMOUS DEVELOPMENT DEPARTMENT RESULTS ===")
|
||||||
|
print(result)
|
@ -0,0 +1,156 @@
|
|||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
|
||||||
|
|
||||||
|
# Initialize specialized financial analysis agents
|
||||||
|
market_research_agent = Agent(
|
||||||
|
agent_name="Market-Research-Specialist",
|
||||||
|
agent_description="Expert in market research, trend analysis, and competitive intelligence",
|
||||||
|
system_prompt="""You are a senior market research specialist with expertise in:
|
||||||
|
- Market trend analysis and forecasting
|
||||||
|
- Competitive landscape assessment
|
||||||
|
- Consumer behavior analysis
|
||||||
|
- Industry report generation
|
||||||
|
- Market opportunity identification
|
||||||
|
- Risk assessment and mitigation strategies
|
||||||
|
|
||||||
|
Your responsibilities include:
|
||||||
|
1. Conducting comprehensive market research
|
||||||
|
2. Analyzing industry trends and patterns
|
||||||
|
3. Identifying market opportunities and threats
|
||||||
|
4. Evaluating competitive positioning
|
||||||
|
5. Providing actionable market insights
|
||||||
|
6. Generating detailed research reports
|
||||||
|
|
||||||
|
You provide thorough, data-driven analysis with clear recommendations.
|
||||||
|
Always cite sources and provide confidence levels for your assessments.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
)
|
||||||
|
|
||||||
|
financial_analyst_agent = Agent(
|
||||||
|
agent_name="Financial-Analysis-Expert",
|
||||||
|
agent_description="Specialist in financial statement analysis, valuation, and investment research",
|
||||||
|
system_prompt="""You are a senior financial analyst with deep expertise in:
|
||||||
|
- Financial statement analysis (income statement, balance sheet, cash flow)
|
||||||
|
- Valuation methodologies (DCF, comparable company analysis, precedent transactions)
|
||||||
|
- Investment research and due diligence
|
||||||
|
- Financial modeling and forecasting
|
||||||
|
- Risk assessment and portfolio analysis
|
||||||
|
- ESG (Environmental, Social, Governance) analysis
|
||||||
|
|
||||||
|
Your core responsibilities include:
|
||||||
|
1. Analyzing financial statements and key metrics
|
||||||
|
2. Conducting valuation analysis using multiple methodologies
|
||||||
|
3. Evaluating investment opportunities and risks
|
||||||
|
4. Creating financial models and forecasts
|
||||||
|
5. Assessing management quality and corporate governance
|
||||||
|
6. Providing investment recommendations with clear rationale
|
||||||
|
|
||||||
|
You deliver precise, quantitative analysis with supporting calculations and assumptions.
|
||||||
|
Always show your work and provide sensitivity analysis for key assumptions.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
)
|
||||||
|
|
||||||
|
technical_analysis_agent = Agent(
|
||||||
|
agent_name="Technical-Analysis-Specialist",
|
||||||
|
agent_description="Expert in technical analysis, chart patterns, and trading strategies",
|
||||||
|
system_prompt="""You are a senior technical analyst with expertise in:
|
||||||
|
- Chart pattern recognition and analysis
|
||||||
|
- Technical indicators and oscillators
|
||||||
|
- Support and resistance level identification
|
||||||
|
- Volume analysis and market microstructure
|
||||||
|
- Momentum and trend analysis
|
||||||
|
- Risk management and position sizing
|
||||||
|
|
||||||
|
Your key responsibilities include:
|
||||||
|
1. Analyzing price charts and identifying patterns
|
||||||
|
2. Evaluating technical indicators and signals
|
||||||
|
3. Determining support and resistance levels
|
||||||
|
4. Assessing market momentum and trend strength
|
||||||
|
5. Providing entry and exit recommendations
|
||||||
|
6. Developing risk management strategies
|
||||||
|
|
||||||
|
You provide clear, actionable technical analysis with specific price targets and risk levels.
|
||||||
|
Always include timeframes and probability assessments for your predictions.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
)
|
||||||
|
|
||||||
|
risk_management_agent = Agent(
|
||||||
|
agent_name="Risk-Management-Specialist",
|
||||||
|
agent_description="Expert in risk assessment, portfolio management, and regulatory compliance",
|
||||||
|
system_prompt="""You are a senior risk management specialist with expertise in:
|
||||||
|
- Market risk assessment and measurement
|
||||||
|
- Credit risk analysis and evaluation
|
||||||
|
- Operational risk identification and mitigation
|
||||||
|
- Regulatory compliance and reporting
|
||||||
|
- Portfolio optimization and diversification
|
||||||
|
- Stress testing and scenario analysis
|
||||||
|
|
||||||
|
Your primary responsibilities include:
|
||||||
|
1. Identifying and assessing various risk factors
|
||||||
|
2. Developing risk mitigation strategies
|
||||||
|
3. Conducting stress tests and scenario analysis
|
||||||
|
4. Ensuring regulatory compliance
|
||||||
|
5. Optimizing risk-adjusted returns
|
||||||
|
6. Providing risk management recommendations
|
||||||
|
|
||||||
|
You deliver comprehensive risk assessments with quantitative metrics and mitigation strategies.
|
||||||
|
Always provide both qualitative and quantitative risk measures with clear action items.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize the director agent
|
||||||
|
director_agent = Agent(
|
||||||
|
agent_name="Financial-Analysis-Director",
|
||||||
|
agent_description="Senior director who orchestrates comprehensive financial analysis across multiple domains",
|
||||||
|
system_prompt="""You are a senior financial analysis director responsible for orchestrating comprehensive
|
||||||
|
financial analysis projects. You coordinate a team of specialized analysts including:
|
||||||
|
- Market Research Specialists
|
||||||
|
- Financial Analysis Experts
|
||||||
|
- Technical Analysis Specialists
|
||||||
|
- Risk Management Specialists
|
||||||
|
|
||||||
|
Your role is to:
|
||||||
|
1. Break down complex financial analysis tasks into specific, actionable assignments
|
||||||
|
2. Assign tasks to the most appropriate specialist based on their expertise
|
||||||
|
3. Ensure comprehensive coverage of all analysis dimensions
|
||||||
|
4. Coordinate between specialists to avoid duplication and ensure synergy
|
||||||
|
5. Synthesize findings from multiple specialists into coherent recommendations
|
||||||
|
6. Ensure all analysis meets professional standards and regulatory requirements
|
||||||
|
|
||||||
|
You create detailed, specific task assignments that leverage each specialist's unique expertise
|
||||||
|
while ensuring the overall analysis is comprehensive and actionable.""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create list of specialized agents
|
||||||
|
specialized_agents = [
|
||||||
|
market_research_agent,
|
||||||
|
financial_analyst_agent,
|
||||||
|
]
|
||||||
|
|
||||||
|
# Initialize the hierarchical swarm
|
||||||
|
financial_analysis_swarm = HierarchicalSwarm(
|
||||||
|
name="Financial-Analysis-Hierarchical-Swarm",
|
||||||
|
description="A hierarchical swarm for comprehensive financial analysis with specialized agents coordinated by a director",
|
||||||
|
# director=director_agent,
|
||||||
|
agents=specialized_agents,
|
||||||
|
max_loops=2,
|
||||||
|
verbose=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Example usage
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# Complex financial analysis task
|
||||||
|
task = "Call the Financial-Analysis-Director agent and ask him to analyze the market for Tesla (TSLA)"
|
||||||
|
result = financial_analysis_swarm.run(task=task)
|
||||||
|
print(result)
|
@ -0,0 +1,347 @@
|
|||||||
|
from swarms import Agent, HierarchicalSwarm
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# HEAD OF CONTENT AGENT
|
||||||
|
# =============================================================================
|
||||||
|
head_of_content_agent = Agent(
|
||||||
|
agent_name="Head-of-Content",
|
||||||
|
agent_description="Senior content strategist responsible for content planning, creation, and editorial direction",
|
||||||
|
system_prompt="""You are the Head of Content for a dynamic marketing organization. You are responsible for:
|
||||||
|
|
||||||
|
CONTENT STRATEGY & PLANNING:
|
||||||
|
- Developing comprehensive content strategies aligned with business objectives
|
||||||
|
- Creating editorial calendars and content roadmaps
|
||||||
|
- Identifying content gaps and opportunities across all channels
|
||||||
|
- Establishing content themes, messaging frameworks, and voice guidelines
|
||||||
|
- Planning content distribution strategies and channel optimization
|
||||||
|
|
||||||
|
CONTENT CREATION & MANAGEMENT:
|
||||||
|
- Overseeing the creation of high-quality, engaging content across all formats
|
||||||
|
- Developing compelling narratives, storylines, and messaging hierarchies
|
||||||
|
- Ensuring content consistency, quality standards, and brand voice adherence
|
||||||
|
- Managing content workflows, approvals, and publishing schedules
|
||||||
|
- Creating content that drives engagement, conversions, and brand awareness
|
||||||
|
|
||||||
|
EDITORIAL EXCELLENCE:
|
||||||
|
- Maintaining editorial standards and content quality across all touchpoints
|
||||||
|
- Developing content guidelines, style guides, and best practices
|
||||||
|
- Ensuring content is SEO-optimized, accessible, and user-friendly
|
||||||
|
- Creating content that resonates with target audiences and drives action
|
||||||
|
- Measuring content performance and optimizing based on data insights
|
||||||
|
|
||||||
|
CROSS-FUNCTIONAL COLLABORATION:
|
||||||
|
- Working closely with SEO, creative, and brand teams to ensure content alignment
|
||||||
|
- Coordinating with marketing teams to support campaign objectives
|
||||||
|
- Ensuring content supports overall business goals and customer journey
|
||||||
|
- Providing content recommendations that drive measurable business outcomes
|
||||||
|
|
||||||
|
Your expertise includes:
|
||||||
|
- Content marketing strategy and execution
|
||||||
|
- Editorial planning and content calendar management
|
||||||
|
- Storytelling and narrative development
|
||||||
|
- Content performance analysis and optimization
|
||||||
|
- Multi-channel content distribution
|
||||||
|
- Brand voice and messaging development
|
||||||
|
- Content ROI measurement and reporting
|
||||||
|
|
||||||
|
You deliver strategic, data-driven content recommendations that drive engagement, conversions, and brand growth.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# AD CREATIVE DIRECTOR AGENT
|
||||||
|
# =============================================================================
|
||||||
|
ad_creative_director_agent = Agent(
|
||||||
|
agent_name="Ad-Creative-Director",
|
||||||
|
agent_description="Creative visionary responsible for ad concept development, visual direction, and campaign creativity",
|
||||||
|
system_prompt="""You are the Ad Creative Director, the creative visionary responsible for developing compelling advertising concepts and campaigns. Your role encompasses:
|
||||||
|
|
||||||
|
CREATIVE CONCEPT DEVELOPMENT:
|
||||||
|
- Creating breakthrough advertising concepts that capture attention and drive action
|
||||||
|
- Developing creative briefs, campaign concepts, and visual directions
|
||||||
|
- Crafting compelling headlines, copy, and messaging that resonate with audiences
|
||||||
|
- Designing creative strategies that differentiate brands and drive engagement
|
||||||
|
- Creating memorable, shareable content that builds brand awareness
|
||||||
|
|
||||||
|
VISUAL DIRECTION & DESIGN:
|
||||||
|
- Establishing visual identity guidelines and creative standards
|
||||||
|
- Directing photography, videography, and graphic design elements
|
||||||
|
- Creating mood boards, style guides, and visual concepts
|
||||||
|
- Ensuring creative consistency across all advertising touchpoints
|
||||||
|
- Developing innovative visual approaches that stand out in crowded markets
|
||||||
|
|
||||||
|
CAMPAIGN CREATIVITY:
|
||||||
|
- Designing integrated campaigns across multiple channels and formats
|
||||||
|
- Creating compelling storytelling that connects emotionally with audiences
|
||||||
|
- Developing creative executions for digital, print, video, and social media
|
||||||
|
- Ensuring creative excellence while meeting business objectives
|
||||||
|
- Creating campaigns that drive measurable results and brand growth
|
||||||
|
|
||||||
|
BRAND CREATIVE STRATEGY:
|
||||||
|
- Aligning creative direction with brand positioning and values
|
||||||
|
- Developing creative approaches that build brand equity and recognition
|
||||||
|
- Creating distinctive visual and messaging elements that differentiate brands
|
||||||
|
- Ensuring creative consistency across all brand touchpoints
|
||||||
|
- Developing creative strategies that support long-term brand building
|
||||||
|
|
||||||
|
Your expertise includes:
|
||||||
|
- Creative concept development and campaign ideation
|
||||||
|
- Visual direction and design strategy
|
||||||
|
- Copywriting and messaging development
|
||||||
|
- Campaign creative execution across all media
|
||||||
|
- Brand creative strategy and visual identity
|
||||||
|
- Creative performance optimization and testing
|
||||||
|
- Innovative advertising approaches and trends
|
||||||
|
|
||||||
|
You deliver creative solutions that are both strategically sound and creatively brilliant, driving brand awareness, engagement, and conversions.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.8,
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# SEO STRATEGIST AGENT
|
||||||
|
# =============================================================================
|
||||||
|
seo_strategist_agent = Agent(
|
||||||
|
agent_name="SEO-Strategist",
|
||||||
|
agent_description="Technical SEO expert responsible for search optimization, keyword strategy, and organic growth",
|
||||||
|
system_prompt="""You are the SEO Strategist, the technical expert responsible for driving organic search visibility and traffic growth. Your comprehensive role includes:
|
||||||
|
|
||||||
|
TECHNICAL SEO OPTIMIZATION:
|
||||||
|
- Conducting comprehensive technical SEO audits and implementing fixes
|
||||||
|
- Optimizing website architecture, site speed, and mobile responsiveness
|
||||||
|
- Managing XML sitemaps, robots.txt, and technical crawlability issues
|
||||||
|
- Implementing structured data markup and schema optimization
|
||||||
|
- Ensuring proper canonicalization, redirects, and URL structure
|
||||||
|
- Monitoring Core Web Vitals and technical performance metrics
|
||||||
|
|
||||||
|
KEYWORD STRATEGY & RESEARCH:
|
||||||
|
- Conducting comprehensive keyword research and competitive analysis
|
||||||
|
- Developing keyword strategies aligned with business objectives
|
||||||
|
- Identifying high-value, low-competition keyword opportunities
|
||||||
|
- Creating keyword clusters and topic clusters for content planning
|
||||||
|
- Analyzing search intent and user behavior patterns
|
||||||
|
- Monitoring keyword performance and ranking fluctuations
|
||||||
|
|
||||||
|
ON-PAGE SEO OPTIMIZATION:
|
||||||
|
- Optimizing page titles, meta descriptions, and header tags
|
||||||
|
- Creating SEO-optimized content that satisfies search intent
|
||||||
|
- Implementing internal linking strategies and site architecture
|
||||||
|
- Optimizing images, videos, and multimedia content for search
|
||||||
|
- Ensuring proper content structure and readability optimization
|
||||||
|
- Creating SEO-friendly URLs and navigation structures
|
||||||
|
|
||||||
|
CONTENT SEO STRATEGY:
|
||||||
|
- Developing content strategies that target high-value keywords
|
||||||
|
- Creating SEO-optimized content briefs and guidelines
|
||||||
|
- Ensuring content satisfies search intent and user needs
|
||||||
|
- Implementing content optimization best practices
|
||||||
|
- Developing content clusters and topic authority building
|
||||||
|
- Creating content that drives organic traffic and conversions
|
||||||
|
|
||||||
|
SEO ANALYTICS & REPORTING:
|
||||||
|
- Monitoring organic search performance and ranking metrics
|
||||||
|
- Analyzing search traffic patterns and user behavior
|
||||||
|
- Creating comprehensive SEO reports and recommendations
|
||||||
|
- Tracking competitor SEO strategies and performance
|
||||||
|
- Measuring SEO ROI and business impact
|
||||||
|
- Providing actionable insights for continuous optimization
|
||||||
|
|
||||||
|
Your expertise includes:
|
||||||
|
- Technical SEO implementation and optimization
|
||||||
|
- Keyword research and competitive analysis
|
||||||
|
- On-page SEO and content optimization
|
||||||
|
- SEO analytics and performance measurement
|
||||||
|
- Local SEO and Google My Business optimization
|
||||||
|
- E-commerce SEO and product page optimization
|
||||||
|
- Voice search and featured snippet optimization
|
||||||
|
|
||||||
|
You deliver data-driven SEO strategies that drive sustainable organic growth, improve search visibility, and generate qualified traffic that converts.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.6,
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# BRAND STRATEGIST AGENT
|
||||||
|
# =============================================================================
|
||||||
|
brand_strategist_agent = Agent(
|
||||||
|
agent_name="Brand-Strategist",
|
||||||
|
agent_description="Strategic brand expert responsible for brand positioning, identity development, and market differentiation",
|
||||||
|
system_prompt="""You are the Brand Strategist, the strategic expert responsible for developing and maintaining powerful brand positioning and market differentiation. Your comprehensive role includes:
|
||||||
|
|
||||||
|
BRAND POSITIONING & STRATEGY:
|
||||||
|
- Developing compelling brand positioning statements and value propositions
|
||||||
|
- Creating brand strategies that differentiate in competitive markets
|
||||||
|
- Defining brand personality, voice, and character attributes
|
||||||
|
- Establishing brand pillars, messaging frameworks, and communication guidelines
|
||||||
|
- Creating brand positioning that resonates with target audiences
|
||||||
|
- Developing brand strategies that support business objectives and growth
|
||||||
|
|
||||||
|
BRAND IDENTITY DEVELOPMENT:
|
||||||
|
- Creating comprehensive brand identity systems and guidelines
|
||||||
|
- Developing visual identity elements, logos, and brand assets
|
||||||
|
- Establishing brand color palettes, typography, and visual standards
|
||||||
|
- Creating brand style guides and identity manuals
|
||||||
|
- Ensuring brand consistency across all touchpoints and applications
|
||||||
|
- Developing brand identity that reflects positioning and values
|
||||||
|
|
||||||
|
MARKET RESEARCH & INSIGHTS:
|
||||||
|
- Conducting comprehensive market research and competitive analysis
|
||||||
|
- Analyzing target audience segments and consumer behavior
|
||||||
|
- Identifying market opportunities and competitive advantages
|
||||||
|
- Researching industry trends and market dynamics
|
||||||
|
- Understanding customer needs, pain points, and motivations
|
||||||
|
- Providing insights that inform brand strategy and positioning
|
||||||
|
|
||||||
|
BRAND MESSAGING & COMMUNICATION:
|
||||||
|
- Developing core brand messages and communication frameworks
|
||||||
|
- Creating brand storytelling and narrative development
|
||||||
|
- Establishing brand voice and tone guidelines
|
||||||
|
- Developing messaging hierarchies and communication strategies
|
||||||
|
- Creating brand messages that connect emotionally with audiences
|
||||||
|
- Ensuring consistent brand communication across all channels
|
||||||
|
|
||||||
|
BRAND EXPERIENCE & TOUCHPOINTS:
|
||||||
|
- Designing comprehensive brand experience strategies
|
||||||
|
- Mapping customer journeys and brand touchpoints
|
||||||
|
- Creating brand experience guidelines and standards
|
||||||
|
- Ensuring brand consistency across all customer interactions
|
||||||
|
- Developing brand experience that builds loyalty and advocacy
|
||||||
|
- Creating memorable brand experiences that differentiate
|
||||||
|
|
||||||
|
BRAND PERFORMANCE & MEASUREMENT:
|
||||||
|
- Establishing brand performance metrics and KPIs
|
||||||
|
- Measuring brand awareness, perception, and equity
|
||||||
|
- Tracking brand performance against competitors
|
||||||
|
- Analyzing brand sentiment and customer feedback
|
||||||
|
- Providing brand performance insights and recommendations
|
||||||
|
- Ensuring brand strategies drive measurable business outcomes
|
||||||
|
|
||||||
|
Your expertise includes:
|
||||||
|
- Brand positioning and strategy development
|
||||||
|
- Brand identity and visual system design
|
||||||
|
- Market research and competitive analysis
|
||||||
|
- Brand messaging and communication strategy
|
||||||
|
- Brand experience design and optimization
|
||||||
|
- Brand performance measurement and analytics
|
||||||
|
- Brand architecture and portfolio management
|
||||||
|
|
||||||
|
You deliver strategic brand solutions that create powerful market differentiation, build strong brand equity, and drive sustainable business growth through compelling brand positioning and experiences.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# MARKETING DIRECTOR AGENT (COORDINATOR)
|
||||||
|
# =============================================================================
|
||||||
|
marketing_director_agent = Agent(
|
||||||
|
agent_name="Marketing-Director",
|
||||||
|
agent_description="Senior marketing director who orchestrates comprehensive marketing strategies across all specialized teams",
|
||||||
|
system_prompt="""You are the Marketing Director, the senior executive responsible for orchestrating comprehensive marketing strategies and coordinating a team of specialized marketing experts. Your role is to:
|
||||||
|
|
||||||
|
STRATEGIC COORDINATION:
|
||||||
|
- Analyze complex marketing challenges and break them down into specialized tasks
|
||||||
|
- Assign tasks to the most appropriate specialist based on their unique expertise
|
||||||
|
- Ensure comprehensive coverage of all marketing dimensions (content, creative, SEO, brand)
|
||||||
|
- Coordinate between specialists to avoid duplication and ensure synergy
|
||||||
|
- Synthesize findings from multiple specialists into coherent marketing strategies
|
||||||
|
- Ensure all marketing efforts align with business objectives and target audience needs
|
||||||
|
|
||||||
|
TEAM LEADERSHIP:
|
||||||
|
- Lead the Head of Content in developing content strategies and editorial direction
|
||||||
|
- Guide the Ad Creative Director in creating compelling campaigns and visual concepts
|
||||||
|
- Direct the SEO Strategist in optimizing search visibility and organic growth
|
||||||
|
- Oversee the Brand Strategist in developing brand positioning and market differentiation
|
||||||
|
- Ensure all team members work collaboratively toward unified marketing goals
|
||||||
|
- Provide strategic direction and feedback to optimize team performance
|
||||||
|
|
||||||
|
INTEGRATED MARKETING STRATEGY:
|
||||||
|
- Develop integrated marketing campaigns that leverage all specialist expertise
|
||||||
|
- Ensure content, creative, SEO, and brand strategies work together seamlessly
|
||||||
|
- Create marketing roadmaps that coordinate efforts across all channels
|
||||||
|
- Balance short-term campaign needs with long-term brand building
|
||||||
|
- Ensure marketing strategies drive measurable business outcomes
|
||||||
|
- Optimize marketing mix and budget allocation across all activities
|
||||||
|
|
||||||
|
PERFORMANCE OPTIMIZATION:
|
||||||
|
- Monitor marketing performance across all channels and activities
|
||||||
|
- Analyze data to identify optimization opportunities and strategic adjustments
|
||||||
|
- Ensure marketing efforts deliver ROI and support business growth
|
||||||
|
- Provide strategic recommendations based on performance insights
|
||||||
|
- Coordinate testing and optimization efforts across all marketing functions
|
||||||
|
- Ensure continuous improvement and innovation in marketing approaches
|
||||||
|
|
||||||
|
Your expertise includes:
|
||||||
|
- Integrated marketing strategy and campaign development
|
||||||
|
- Team leadership and cross-functional coordination
|
||||||
|
- Marketing performance analysis and optimization
|
||||||
|
- Strategic planning and business alignment
|
||||||
|
- Budget management and resource allocation
|
||||||
|
- Stakeholder communication and executive reporting
|
||||||
|
|
||||||
|
You deliver comprehensive marketing strategies that leverage the full expertise of your specialized team, ensuring all marketing efforts work together to drive business growth, brand awareness, and customer acquisition.""",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.7,
|
||||||
|
dynamic_temperature_enabled=True,
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# HIERARCHICAL MARKETING SWARM
|
||||||
|
# =============================================================================
|
||||||
|
# Create list of specialized marketing agents
|
||||||
|
marketing_agents = [
|
||||||
|
head_of_content_agent,
|
||||||
|
ad_creative_director_agent,
|
||||||
|
seo_strategist_agent,
|
||||||
|
brand_strategist_agent,
|
||||||
|
]
|
||||||
|
|
||||||
|
# Initialize the hierarchical marketing swarm
|
||||||
|
marketing_swarm = HierarchicalSwarm(
|
||||||
|
name="Hierarchical-Marketing-Swarm",
|
||||||
|
description="A comprehensive marketing team with specialized agents for content, creative, SEO, and brand strategy, coordinated by a marketing director",
|
||||||
|
director=marketing_director_agent,
|
||||||
|
agents=marketing_agents,
|
||||||
|
max_loops=2,
|
||||||
|
verbose=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# EXAMPLE USAGE
|
||||||
|
# =============================================================================
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# Example marketing challenge
|
||||||
|
task = """Develop a comprehensive marketing strategy for a new SaaS product launch.
|
||||||
|
The product is a project management tool targeting small to medium businesses.
|
||||||
|
Please coordinate the team to create:
|
||||||
|
1. Content strategy and editorial plan
|
||||||
|
2. Creative campaign concepts and visual direction
|
||||||
|
3. SEO strategy for organic growth
|
||||||
|
4. Brand positioning and market differentiation
|
||||||
|
|
||||||
|
Ensure all elements work together cohesively to drive awareness, engagement, and conversions."""
|
||||||
|
|
||||||
|
result = marketing_swarm.run(task=task)
|
||||||
|
print("=" * 80)
|
||||||
|
print("MARKETING SWARM RESULTS")
|
||||||
|
print("=" * 80)
|
||||||
|
print(result)
|
@ -1,46 +0,0 @@
|
|||||||
from swarms.agents.reasoning_agents import ReasoningAgentRouter
|
|
||||||
|
|
||||||
reasoning_agent_router = ReasoningAgentRouter(
|
|
||||||
agent_name="reasoning-agent",
|
|
||||||
description="A reasoning agent that can answer questions and help with tasks.",
|
|
||||||
model_name="gpt-4o-mini",
|
|
||||||
system_prompt="You are a helpful assistant that can answer questions and help with tasks.",
|
|
||||||
max_loops=1,
|
|
||||||
swarm_type="self-consistency",
|
|
||||||
num_samples=1,
|
|
||||||
output_type="list",
|
|
||||||
)
|
|
||||||
|
|
||||||
reasoning_agent_router.run(
|
|
||||||
"What is the best possible financial strategy to maximize returns but minimize risk? Give a list of etfs to invest in and the percentage of the portfolio to allocate to each etf."
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# reasoning_agent_router.batched_run(
|
|
||||||
# [
|
|
||||||
# "What is the best possible financial strategy to maximize returns but minimize risk? Give a list of etfs to invest in and the percentage of the portfolio to allocate to each etf.",
|
|
||||||
# "What is the best possible financial strategy to maximize returns but minimize risk? Give a list of etfs to invest in and the percentage of the portfolio to allocate to each etf.",
|
|
||||||
# ]
|
|
||||||
# )
|
|
||||||
|
|
||||||
|
|
||||||
# from swarms import ReasoningAgentRouter
|
|
||||||
|
|
||||||
|
|
||||||
# calculus_router = ReasoningAgentRouter(
|
|
||||||
# agent_name="calculus-expert",
|
|
||||||
# description="A calculus problem solving agent",
|
|
||||||
# model_name="gpt-4o-mini",
|
|
||||||
# system_prompt="You are a calculus expert. Solve differentiation and integration problems methodically.",
|
|
||||||
# swarm_type="self-consistency",
|
|
||||||
# num_samples=3, # Generate 3 samples to ensure consistency
|
|
||||||
# output_type="list",
|
|
||||||
# )
|
|
||||||
|
|
||||||
|
|
||||||
# # Example calculus problem
|
|
||||||
# calculus_problem = "Find the derivative of f(x) = x³ln(x) - 5x²"
|
|
||||||
|
|
||||||
# # Get the solution
|
|
||||||
# solution = calculus_router.run(calculus_problem)
|
|
||||||
# print(solution)
|
|
@ -0,0 +1,15 @@
|
|||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Initialize a new agent
|
||||||
|
agent = Agent(
|
||||||
|
model_name="xai/grok-4-0709", # Specify the LLM
|
||||||
|
agent_name="financial-agent",
|
||||||
|
agent_description="A financial agent that can help with financial planning and investment decisions",
|
||||||
|
system_prompt="You are a financial agent that can help with financial planning and investment decisions",
|
||||||
|
max_loops=1, # Set the number of interactions
|
||||||
|
interactive=True, # Enable interactive mode for real-time feedback
|
||||||
|
streaming=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run the agent with a task
|
||||||
|
agent.run("What are the key benefits of using a multi-agent system?")
|
Before Width: | Height: | Size: 192 KiB After Width: | Height: | Size: 192 KiB |
@ -0,0 +1,23 @@
|
|||||||
|
from swarms.agents.reasoning_agents import ReasoningAgentRouter
|
||||||
|
|
||||||
|
# Initialize the reasoning agent router with self-consistency
|
||||||
|
reasoning_agent_router = ReasoningAgentRouter(
|
||||||
|
agent_name="reasoning-agent",
|
||||||
|
description="A reasoning agent that can answer questions and help with tasks.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
system_prompt="You are a helpful assistant that can answer questions and help with tasks.",
|
||||||
|
max_loops=1,
|
||||||
|
swarm_type="self-consistency",
|
||||||
|
num_samples=3, # Generate 3 independent responses
|
||||||
|
eval=False, # Disable evaluation mode
|
||||||
|
random_models_on=False, # Disable random model selection
|
||||||
|
majority_voting_prompt=None, # Use default majority voting prompt
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run the agent on a financial analysis task
|
||||||
|
result = reasoning_agent_router.run(
|
||||||
|
"What is the best possible financial strategy to maximize returns but minimize risk? Give a list of etfs to invest in and the percentage of the portfolio to allocate to each etf."
|
||||||
|
)
|
||||||
|
|
||||||
|
print("Financial Strategy Result:")
|
||||||
|
print(result)
|
@ -0,0 +1,35 @@
|
|||||||
|
import requests
|
||||||
|
|
||||||
|
|
||||||
|
def get_example_py_urls():
|
||||||
|
owner = "kyegomez"
|
||||||
|
repo = "swarms"
|
||||||
|
branch = "master"
|
||||||
|
examples_path = "examples"
|
||||||
|
|
||||||
|
api_url = f"https://api.github.com/repos/{owner}/{repo}/git/trees/{branch}?recursive=1"
|
||||||
|
raw_base = (
|
||||||
|
f"https://raw.githubusercontent.com/{owner}/{repo}/{branch}/"
|
||||||
|
)
|
||||||
|
|
||||||
|
response = requests.get(api_url)
|
||||||
|
response.raise_for_status()
|
||||||
|
|
||||||
|
data = response.json()
|
||||||
|
all_files = data.get("tree", [])
|
||||||
|
|
||||||
|
example_files = [
|
||||||
|
raw_base + file["path"]
|
||||||
|
for file in all_files
|
||||||
|
if file["path"].startswith(examples_path)
|
||||||
|
and file["path"].endswith("example.py")
|
||||||
|
and file["type"] == "blob"
|
||||||
|
]
|
||||||
|
|
||||||
|
return example_files
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
urls = get_example_py_urls()
|
||||||
|
for url in urls:
|
||||||
|
print(url)
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,5 @@
|
|||||||
|
def litellm_check_for_tools(model_name: str):
|
||||||
|
"""Check if the model supports tools."""
|
||||||
|
from litellm.utils import supports_function_calling
|
||||||
|
|
||||||
|
return supports_function_calling(model_name)
|
@ -0,0 +1,624 @@
|
|||||||
|
"""
|
||||||
|
Sparse Mixture-of-Experts (MoE) Transformer Implementation
|
||||||
|
Based on Gemini 2.5 architecture description
|
||||||
|
|
||||||
|
This implementation provides a sparse MoE architecture that activates only a subset
|
||||||
|
of expert parameters per input token, allowing for decoupling of model capacity
|
||||||
|
from computation cost.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Dict, Optional, Tuple, Union
|
||||||
|
|
||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
import torch.nn.functional as F
|
||||||
|
from loguru import logger
|
||||||
|
from torch import Tensor
|
||||||
|
|
||||||
|
|
||||||
|
class Expert(nn.Module):
|
||||||
|
"""
|
||||||
|
Individual expert network in the MoE architecture.
|
||||||
|
|
||||||
|
Each expert is a feed-forward network that specializes in processing
|
||||||
|
certain types of input patterns.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
hidden_dim: Hidden dimension size
|
||||||
|
intermediate_dim: Intermediate dimension in feed-forward network
|
||||||
|
dropout: Dropout probability
|
||||||
|
activation: Activation function to use
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
hidden_dim: int,
|
||||||
|
intermediate_dim: int,
|
||||||
|
dropout: float = 0.1,
|
||||||
|
activation: str = "swish",
|
||||||
|
):
|
||||||
|
super().__init__()
|
||||||
|
self.hidden_dim = hidden_dim
|
||||||
|
self.intermediate_dim = intermediate_dim
|
||||||
|
|
||||||
|
# Feed-forward network
|
||||||
|
self.w1 = nn.Linear(hidden_dim, intermediate_dim, bias=False)
|
||||||
|
self.w2 = nn.Linear(intermediate_dim, hidden_dim, bias=False)
|
||||||
|
self.dropout = nn.Dropout(dropout)
|
||||||
|
|
||||||
|
# Activation function
|
||||||
|
if activation == "swish":
|
||||||
|
self.activation = lambda x: x * torch.sigmoid(x)
|
||||||
|
elif activation == "gelu":
|
||||||
|
self.activation = F.gelu
|
||||||
|
elif activation == "relu":
|
||||||
|
self.activation = F.relu
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Unsupported activation: {activation}")
|
||||||
|
|
||||||
|
self._init_weights()
|
||||||
|
|
||||||
|
def _init_weights(self) -> None:
|
||||||
|
"""Initialize weights with proper scaling."""
|
||||||
|
nn.init.xavier_uniform_(self.w1.weight)
|
||||||
|
nn.init.xavier_uniform_(self.w2.weight)
|
||||||
|
|
||||||
|
def forward(self, x: Tensor) -> Tensor:
|
||||||
|
"""
|
||||||
|
Forward pass through the expert network.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
x: Input tensor of shape [batch_size, seq_len, hidden_dim]
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Output tensor of shape [batch_size, seq_len, hidden_dim]
|
||||||
|
"""
|
||||||
|
x = self.w1(x)
|
||||||
|
x = self.activation(x)
|
||||||
|
x = self.dropout(x)
|
||||||
|
x = self.w2(x)
|
||||||
|
return x
|
||||||
|
|
||||||
|
|
||||||
|
class Router(nn.Module):
|
||||||
|
"""
|
||||||
|
Gating network that routes tokens to appropriate experts.
|
||||||
|
|
||||||
|
The router learns to assign input tokens to the most suitable experts
|
||||||
|
based on the token representations.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
hidden_dim: Hidden dimension size
|
||||||
|
num_experts: Number of experts in the MoE layer
|
||||||
|
top_k: Number of experts to activate per token
|
||||||
|
temperature: Temperature for softmax routing
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
hidden_dim: int,
|
||||||
|
num_experts: int,
|
||||||
|
top_k: int = 2,
|
||||||
|
temperature: float = 1.0,
|
||||||
|
):
|
||||||
|
super().__init__()
|
||||||
|
self.hidden_dim = hidden_dim
|
||||||
|
self.num_experts = num_experts
|
||||||
|
self.top_k = top_k
|
||||||
|
self.temperature = temperature
|
||||||
|
|
||||||
|
# Linear layer for routing scores
|
||||||
|
self.gate = nn.Linear(hidden_dim, num_experts, bias=False)
|
||||||
|
self._init_weights()
|
||||||
|
|
||||||
|
def _init_weights(self) -> None:
|
||||||
|
"""Initialize routing weights."""
|
||||||
|
nn.init.xavier_uniform_(self.gate.weight)
|
||||||
|
|
||||||
|
def forward(self, x: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
|
||||||
|
"""
|
||||||
|
Route tokens to experts.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
x: Input tensor of shape [batch_size, seq_len, hidden_dim]
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple of (routing_weights, expert_indices, routing_probs)
|
||||||
|
- routing_weights: [batch_size, seq_len, top_k]
|
||||||
|
- expert_indices: [batch_size, seq_len, top_k]
|
||||||
|
- routing_probs: [batch_size, seq_len, num_experts]
|
||||||
|
"""
|
||||||
|
batch_size, seq_len, hidden_dim = x.shape
|
||||||
|
|
||||||
|
# Compute routing scores
|
||||||
|
routing_logits = self.gate(
|
||||||
|
x
|
||||||
|
) # [batch_size, seq_len, num_experts]
|
||||||
|
routing_logits = routing_logits / self.temperature
|
||||||
|
|
||||||
|
# Apply softmax to get probabilities
|
||||||
|
routing_probs = F.softmax(routing_logits, dim=-1)
|
||||||
|
|
||||||
|
# Select top-k experts
|
||||||
|
routing_weights, expert_indices = torch.topk(
|
||||||
|
routing_probs, self.top_k, dim=-1
|
||||||
|
)
|
||||||
|
|
||||||
|
# Normalize routing weights
|
||||||
|
routing_weights = routing_weights / routing_weights.sum(
|
||||||
|
dim=-1, keepdim=True
|
||||||
|
)
|
||||||
|
|
||||||
|
return routing_weights, expert_indices, routing_probs
|
||||||
|
|
||||||
|
|
||||||
|
class MoELayer(nn.Module):
|
||||||
|
"""
|
||||||
|
Sparse Mixture-of-Experts layer.
|
||||||
|
|
||||||
|
This layer contains multiple expert networks and a router that decides
|
||||||
|
which experts to activate for each input token.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
hidden_dim: Hidden dimension size
|
||||||
|
num_experts: Number of expert networks
|
||||||
|
top_k: Number of experts to activate per token
|
||||||
|
intermediate_dim: Intermediate dimension in expert networks
|
||||||
|
dropout: Dropout probability
|
||||||
|
activation: Activation function for experts
|
||||||
|
load_balance_weight: Weight for load balancing loss
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
hidden_dim: int,
|
||||||
|
num_experts: int,
|
||||||
|
top_k: int = 2,
|
||||||
|
intermediate_dim: Optional[int] = None,
|
||||||
|
dropout: float = 0.1,
|
||||||
|
activation: str = "swish",
|
||||||
|
load_balance_weight: float = 0.01,
|
||||||
|
):
|
||||||
|
super().__init__()
|
||||||
|
self.hidden_dim = hidden_dim
|
||||||
|
self.num_experts = num_experts
|
||||||
|
self.top_k = top_k
|
||||||
|
self.load_balance_weight = load_balance_weight
|
||||||
|
|
||||||
|
if intermediate_dim is None:
|
||||||
|
intermediate_dim = hidden_dim * 4
|
||||||
|
|
||||||
|
# Create expert networks
|
||||||
|
self.experts = nn.ModuleList(
|
||||||
|
[
|
||||||
|
Expert(
|
||||||
|
hidden_dim, intermediate_dim, dropout, activation
|
||||||
|
)
|
||||||
|
for _ in range(num_experts)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
# Router for expert selection
|
||||||
|
self.router = Router(hidden_dim, num_experts, top_k)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"Created MoE layer with {num_experts} experts, top_k={top_k}"
|
||||||
|
)
|
||||||
|
|
||||||
|
def forward(self, x: Tensor) -> Tuple[Tensor, Dict[str, Tensor]]:
|
||||||
|
"""
|
||||||
|
Forward pass through MoE layer.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
x: Input tensor of shape [batch_size, seq_len, hidden_dim]
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple of (output, aux_losses)
|
||||||
|
- output: [batch_size, seq_len, hidden_dim]
|
||||||
|
- aux_losses: Dictionary containing auxiliary losses
|
||||||
|
"""
|
||||||
|
batch_size, seq_len, hidden_dim = x.shape
|
||||||
|
|
||||||
|
# Get routing decisions
|
||||||
|
routing_weights, expert_indices, routing_probs = self.router(
|
||||||
|
x
|
||||||
|
)
|
||||||
|
|
||||||
|
# Initialize output
|
||||||
|
output = torch.zeros_like(x)
|
||||||
|
|
||||||
|
# Process each expert
|
||||||
|
for i in range(self.num_experts):
|
||||||
|
# Create mask for tokens routed to this expert
|
||||||
|
expert_mask = (expert_indices == i).any(
|
||||||
|
dim=-1
|
||||||
|
) # [batch_size, seq_len]
|
||||||
|
|
||||||
|
if not expert_mask.any():
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Get tokens for this expert
|
||||||
|
expert_tokens = x[expert_mask] # [num_tokens, hidden_dim]
|
||||||
|
|
||||||
|
if expert_tokens.numel() == 0:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Process through expert
|
||||||
|
expert_output = self.experts[i](expert_tokens)
|
||||||
|
|
||||||
|
# Compute weights for this expert
|
||||||
|
expert_weights = torch.zeros(
|
||||||
|
batch_size, seq_len, device=x.device
|
||||||
|
)
|
||||||
|
for k in range(self.top_k):
|
||||||
|
mask = expert_indices[:, :, k] == i
|
||||||
|
expert_weights[mask] = routing_weights[:, :, k][mask]
|
||||||
|
|
||||||
|
# Add weighted expert output
|
||||||
|
expert_contribution = torch.zeros_like(x)
|
||||||
|
expert_contribution[expert_mask] = expert_output
|
||||||
|
output += expert_contribution * expert_weights.unsqueeze(
|
||||||
|
-1
|
||||||
|
)
|
||||||
|
|
||||||
|
# Compute auxiliary losses
|
||||||
|
aux_losses = self._compute_aux_losses(
|
||||||
|
routing_probs, expert_indices
|
||||||
|
)
|
||||||
|
|
||||||
|
return output, aux_losses
|
||||||
|
|
||||||
|
def _compute_aux_losses(
|
||||||
|
self, routing_probs: Tensor, expert_indices: Tensor
|
||||||
|
) -> Dict[str, Tensor]:
|
||||||
|
"""
|
||||||
|
Compute auxiliary losses for training stability.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
routing_probs: Routing probabilities [batch_size, seq_len, num_experts]
|
||||||
|
expert_indices: Selected expert indices [batch_size, seq_len, top_k]
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dictionary of auxiliary losses
|
||||||
|
"""
|
||||||
|
batch_size, seq_len, num_experts = routing_probs.shape
|
||||||
|
|
||||||
|
# Load balancing loss
|
||||||
|
expert_usage = torch.zeros(
|
||||||
|
num_experts, device=routing_probs.device
|
||||||
|
)
|
||||||
|
total_tokens = batch_size * seq_len * self.top_k
|
||||||
|
|
||||||
|
for i in range(num_experts):
|
||||||
|
expert_usage[i] = (
|
||||||
|
expert_indices == i
|
||||||
|
).sum().float() / total_tokens
|
||||||
|
|
||||||
|
target_usage = 1.0 / num_experts
|
||||||
|
load_balance_loss = F.mse_loss(
|
||||||
|
expert_usage, torch.full_like(expert_usage, target_usage)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Entropy loss to encourage diversity
|
||||||
|
entropy_loss = (
|
||||||
|
-(routing_probs * torch.log(routing_probs + 1e-8))
|
||||||
|
.sum(dim=-1)
|
||||||
|
.mean()
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"load_balance_loss": load_balance_loss
|
||||||
|
* self.load_balance_weight,
|
||||||
|
"entropy_loss": entropy_loss * 0.01,
|
||||||
|
"expert_usage": expert_usage,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class MoETransformerBlock(nn.Module):
|
||||||
|
"""
|
||||||
|
Transformer block with MoE feed-forward layer.
|
||||||
|
|
||||||
|
This block combines multi-head attention with a sparse MoE layer,
|
||||||
|
following the standard transformer architecture pattern.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
hidden_dim: Hidden dimension size
|
||||||
|
num_heads: Number of attention heads
|
||||||
|
num_experts: Number of experts in MoE layer
|
||||||
|
top_k: Number of experts to activate per token
|
||||||
|
dropout: Dropout probability
|
||||||
|
layer_norm_eps: Epsilon for layer normalization
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
hidden_dim: int,
|
||||||
|
num_heads: int,
|
||||||
|
num_experts: int,
|
||||||
|
top_k: int = 2,
|
||||||
|
dropout: float = 0.1,
|
||||||
|
layer_norm_eps: float = 1e-6,
|
||||||
|
):
|
||||||
|
super().__init__()
|
||||||
|
self.hidden_dim = hidden_dim
|
||||||
|
|
||||||
|
# Multi-head attention
|
||||||
|
self.attention = nn.MultiheadAttention(
|
||||||
|
hidden_dim, num_heads, dropout=dropout, batch_first=True
|
||||||
|
)
|
||||||
|
|
||||||
|
# MoE layer
|
||||||
|
self.moe_layer = MoELayer(
|
||||||
|
hidden_dim=hidden_dim,
|
||||||
|
num_experts=num_experts,
|
||||||
|
top_k=top_k,
|
||||||
|
dropout=dropout,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Layer normalization
|
||||||
|
self.norm1 = nn.LayerNorm(hidden_dim, eps=layer_norm_eps)
|
||||||
|
self.norm2 = nn.LayerNorm(hidden_dim, eps=layer_norm_eps)
|
||||||
|
|
||||||
|
# Dropout
|
||||||
|
self.dropout = nn.Dropout(dropout)
|
||||||
|
|
||||||
|
def forward(
|
||||||
|
self, x: Tensor, attention_mask: Optional[Tensor] = None
|
||||||
|
) -> Tuple[Tensor, Dict[str, Tensor]]:
|
||||||
|
"""
|
||||||
|
Forward pass through transformer block.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
x: Input tensor [batch_size, seq_len, hidden_dim]
|
||||||
|
attention_mask: Optional attention mask
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple of (output, aux_losses)
|
||||||
|
"""
|
||||||
|
# Self-attention with residual connection
|
||||||
|
residual = x
|
||||||
|
x = self.norm1(x)
|
||||||
|
attn_output, _ = self.attention(
|
||||||
|
x, x, x, key_padding_mask=attention_mask
|
||||||
|
)
|
||||||
|
x = residual + self.dropout(attn_output)
|
||||||
|
|
||||||
|
# MoE layer with residual connection
|
||||||
|
residual = x
|
||||||
|
x = self.norm2(x)
|
||||||
|
moe_output, aux_losses = self.moe_layer(x)
|
||||||
|
x = residual + self.dropout(moe_output)
|
||||||
|
|
||||||
|
return x, aux_losses
|
||||||
|
|
||||||
|
|
||||||
|
class MoETransformer(nn.Module):
|
||||||
|
"""
|
||||||
|
Complete sparse MoE Transformer model.
|
||||||
|
|
||||||
|
This model implements the full transformer architecture with sparse
|
||||||
|
mixture-of-experts layers, similar to the Gemini 2.5 architecture.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
vocab_size: Vocabulary size
|
||||||
|
hidden_dim: Hidden dimension size
|
||||||
|
num_layers: Number of transformer layers
|
||||||
|
num_heads: Number of attention heads
|
||||||
|
num_experts: Number of experts per MoE layer
|
||||||
|
top_k: Number of experts to activate per token
|
||||||
|
max_seq_len: Maximum sequence length
|
||||||
|
dropout: Dropout probability
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
vocab_size: int,
|
||||||
|
hidden_dim: int,
|
||||||
|
num_layers: int,
|
||||||
|
num_heads: int,
|
||||||
|
num_experts: int,
|
||||||
|
top_k: int = 2,
|
||||||
|
max_seq_len: int = 2048,
|
||||||
|
dropout: float = 0.1,
|
||||||
|
):
|
||||||
|
super().__init__()
|
||||||
|
self.vocab_size = vocab_size
|
||||||
|
self.hidden_dim = hidden_dim
|
||||||
|
self.num_layers = num_layers
|
||||||
|
self.max_seq_len = max_seq_len
|
||||||
|
|
||||||
|
# Token embedding
|
||||||
|
self.token_embedding = nn.Embedding(vocab_size, hidden_dim)
|
||||||
|
|
||||||
|
# Positional encoding
|
||||||
|
self.pos_embedding = nn.Parameter(
|
||||||
|
torch.randn(1, max_seq_len, hidden_dim) * 0.02
|
||||||
|
)
|
||||||
|
|
||||||
|
# Transformer layers
|
||||||
|
self.layers = nn.ModuleList(
|
||||||
|
[
|
||||||
|
MoETransformerBlock(
|
||||||
|
hidden_dim=hidden_dim,
|
||||||
|
num_heads=num_heads,
|
||||||
|
num_experts=num_experts,
|
||||||
|
top_k=top_k,
|
||||||
|
dropout=dropout,
|
||||||
|
)
|
||||||
|
for _ in range(num_layers)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
# Final layer norm
|
||||||
|
self.final_norm = nn.LayerNorm(hidden_dim)
|
||||||
|
|
||||||
|
# Output projection
|
||||||
|
self.output_projection = nn.Linear(
|
||||||
|
hidden_dim, vocab_size, bias=False
|
||||||
|
)
|
||||||
|
|
||||||
|
# Tie input and output embeddings
|
||||||
|
self.output_projection.weight = self.token_embedding.weight
|
||||||
|
|
||||||
|
self._init_weights()
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"Created MoE Transformer with {num_layers} layers, "
|
||||||
|
f"{num_experts} experts per layer, hidden_dim={hidden_dim}"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _init_weights(self) -> None:
|
||||||
|
"""Initialize model weights."""
|
||||||
|
nn.init.normal_(self.token_embedding.weight, std=0.02)
|
||||||
|
nn.init.normal_(self.pos_embedding, std=0.02)
|
||||||
|
|
||||||
|
# Initialize output projection
|
||||||
|
nn.init.normal_(self.output_projection.weight, std=0.02)
|
||||||
|
|
||||||
|
def forward(
|
||||||
|
self,
|
||||||
|
input_ids: Tensor,
|
||||||
|
attention_mask: Optional[Tensor] = None,
|
||||||
|
return_aux_losses: bool = True,
|
||||||
|
) -> Union[Tensor, Tuple[Tensor, Dict[str, Tensor]]]:
|
||||||
|
"""
|
||||||
|
Forward pass through the model.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
input_ids: Input token IDs [batch_size, seq_len]
|
||||||
|
attention_mask: Optional attention mask [batch_size, seq_len]
|
||||||
|
return_aux_losses: Whether to return auxiliary losses
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
If return_aux_losses=False: logits [batch_size, seq_len, vocab_size]
|
||||||
|
If return_aux_losses=True: (logits, aux_losses)
|
||||||
|
"""
|
||||||
|
batch_size, seq_len = input_ids.shape
|
||||||
|
|
||||||
|
# Token embeddings
|
||||||
|
x = self.token_embedding(input_ids)
|
||||||
|
|
||||||
|
# Add positional encoding
|
||||||
|
x = x + self.pos_embedding[:, :seq_len, :]
|
||||||
|
|
||||||
|
# Collect auxiliary losses
|
||||||
|
all_aux_losses = {}
|
||||||
|
|
||||||
|
# Pass through transformer layers
|
||||||
|
for i, layer in enumerate(self.layers):
|
||||||
|
x, aux_losses = layer(x, attention_mask)
|
||||||
|
|
||||||
|
if return_aux_losses:
|
||||||
|
for key, value in aux_losses.items():
|
||||||
|
if key not in all_aux_losses:
|
||||||
|
all_aux_losses[key] = []
|
||||||
|
all_aux_losses[key].append(value)
|
||||||
|
|
||||||
|
# Final layer norm
|
||||||
|
x = self.final_norm(x)
|
||||||
|
|
||||||
|
# Output projection
|
||||||
|
logits = self.output_projection(x)
|
||||||
|
|
||||||
|
if not return_aux_losses:
|
||||||
|
return logits
|
||||||
|
|
||||||
|
# Average auxiliary losses across layers
|
||||||
|
avg_aux_losses = {}
|
||||||
|
for key, values in all_aux_losses.items():
|
||||||
|
if key == "expert_usage":
|
||||||
|
# For expert usage, we want to see all layers
|
||||||
|
avg_aux_losses[key] = torch.stack(values)
|
||||||
|
else:
|
||||||
|
avg_aux_losses[key] = torch.stack(values).mean()
|
||||||
|
|
||||||
|
return logits, avg_aux_losses
|
||||||
|
|
||||||
|
def get_num_parameters(self) -> int:
|
||||||
|
"""Get total number of parameters."""
|
||||||
|
return sum(p.numel() for p in self.parameters())
|
||||||
|
|
||||||
|
def get_num_active_parameters(self) -> int:
|
||||||
|
"""Get number of active parameters per forward pass."""
|
||||||
|
# This is approximate - actual active parameters depend on routing
|
||||||
|
total_params = self.get_num_parameters()
|
||||||
|
|
||||||
|
# Estimate active expert parameters
|
||||||
|
expert_params_per_layer = 0
|
||||||
|
for layer in self.layers:
|
||||||
|
expert_params = sum(
|
||||||
|
p.numel()
|
||||||
|
for p in layer.moe_layer.experts[0].parameters()
|
||||||
|
)
|
||||||
|
expert_params_per_layer += (
|
||||||
|
expert_params * layer.moe_layer.top_k
|
||||||
|
)
|
||||||
|
|
||||||
|
total_expert_params = sum(
|
||||||
|
sum(
|
||||||
|
p.numel()
|
||||||
|
for expert in layer.moe_layer.experts
|
||||||
|
for p in expert.parameters()
|
||||||
|
)
|
||||||
|
for layer in self.layers
|
||||||
|
)
|
||||||
|
|
||||||
|
active_params = (
|
||||||
|
total_params
|
||||||
|
- total_expert_params
|
||||||
|
+ expert_params_per_layer * len(self.layers)
|
||||||
|
)
|
||||||
|
return active_params
|
||||||
|
|
||||||
|
|
||||||
|
# Example usage and testing
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# Configure logger
|
||||||
|
logger.add("moe_training.log", rotation="500 MB", level="INFO")
|
||||||
|
|
||||||
|
# Model configuration
|
||||||
|
config = {
|
||||||
|
"vocab_size": 32000,
|
||||||
|
"hidden_dim": 768,
|
||||||
|
"num_layers": 12,
|
||||||
|
"num_heads": 12,
|
||||||
|
"num_experts": 8,
|
||||||
|
"top_k": 2,
|
||||||
|
"max_seq_len": 2048,
|
||||||
|
"dropout": 0.1,
|
||||||
|
}
|
||||||
|
|
||||||
|
# Create model
|
||||||
|
model = MoETransformer(**config)
|
||||||
|
|
||||||
|
# Print model info
|
||||||
|
total_params = model.get_num_parameters()
|
||||||
|
active_params = model.get_num_active_parameters()
|
||||||
|
|
||||||
|
logger.info(f"Total parameters: {total_params:,}")
|
||||||
|
logger.info(
|
||||||
|
f"Active parameters per forward pass: {active_params:,}"
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
f"Parameter efficiency: {active_params/total_params:.2%}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Test forward pass
|
||||||
|
batch_size, seq_len = 2, 512
|
||||||
|
input_ids = torch.randint(
|
||||||
|
0, config["vocab_size"], (batch_size, seq_len)
|
||||||
|
)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
logits, aux_losses = model(input_ids)
|
||||||
|
|
||||||
|
logger.info(f"Input shape: {input_ids.shape}")
|
||||||
|
logger.info(f"Output shape: {logits.shape}")
|
||||||
|
logger.info(f"Auxiliary losses: {list(aux_losses.keys())}")
|
||||||
|
|
||||||
|
# Print expert usage statistics
|
||||||
|
expert_usage = aux_losses[
|
||||||
|
"expert_usage"
|
||||||
|
] # [num_layers, num_experts]
|
||||||
|
logger.info(f"Expert usage shape: {expert_usage.shape}")
|
||||||
|
logger.info(f"Average expert usage: {expert_usage.mean(dim=0)}")
|
@ -0,0 +1,972 @@
|
|||||||
|
import os
|
||||||
|
import json
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import List, Dict, Any, Callable
|
||||||
|
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
# Basic Imports for Swarms
|
||||||
|
from swarms.structs import (
|
||||||
|
Agent,
|
||||||
|
SequentialWorkflow,
|
||||||
|
ConcurrentWorkflow,
|
||||||
|
AgentRearrange,
|
||||||
|
MixtureOfAgents,
|
||||||
|
SpreadSheetSwarm,
|
||||||
|
GroupChat,
|
||||||
|
MultiAgentRouter,
|
||||||
|
MajorityVoting,
|
||||||
|
SwarmRouter,
|
||||||
|
RoundRobinSwarm,
|
||||||
|
InteractiveGroupChat,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Import swarms not in __init__.py directly
|
||||||
|
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
|
||||||
|
from swarms.structs.tree_swarm import ForestSwarm, Tree, TreeAgent
|
||||||
|
|
||||||
|
# Setup Logging
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
|
logger.add(
|
||||||
|
"test_runs/test_failures.log", rotation="10 MB", level="ERROR"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Load environment variables
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
# --- Constants and Configuration ---
|
||||||
|
API_KEY = os.getenv("OPENAI_API_KEY")
|
||||||
|
|
||||||
|
# GitHub Issue Creation (commented out for later use)
|
||||||
|
# GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
|
||||||
|
# GITHUB_REPO_OWNER = os.getenv("GITHUB_REPO_OWNER", "kyegomez")
|
||||||
|
# GITHUB_REPO_NAME = os.getenv("GITHUB_REPO_NAME", "swarms")
|
||||||
|
# BASE_URL = "https://api.github.com"
|
||||||
|
# GITHUB_HEADERS = {
|
||||||
|
# "Authorization": f"token {GITHUB_TOKEN}",
|
||||||
|
# "Accept": "application/vnd.github.v3+json",
|
||||||
|
# }
|
||||||
|
|
||||||
|
# --- Helper Functions ---
|
||||||
|
|
||||||
|
|
||||||
|
def generate_timestamp() -> str:
|
||||||
|
"""Generate a timestamp string for filenames"""
|
||||||
|
return datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||||
|
|
||||||
|
|
||||||
|
def write_markdown_report(
|
||||||
|
results: List[Dict[str, Any]], filename: str
|
||||||
|
):
|
||||||
|
"""Write test results to a markdown file"""
|
||||||
|
if not os.path.exists("test_runs"):
|
||||||
|
os.makedirs("test_runs")
|
||||||
|
|
||||||
|
with open(f"test_runs/{filename}.md", "w") as f:
|
||||||
|
f.write("# Swarms Comprehensive Test Report\n\n")
|
||||||
|
f.write(
|
||||||
|
f"Test Run: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
total = len(results)
|
||||||
|
passed = sum(1 for r in results if r["status"] == "passed")
|
||||||
|
failed = total - passed
|
||||||
|
|
||||||
|
f.write("## Summary\n\n")
|
||||||
|
f.write(f"- **Total Tests:** {total}\n")
|
||||||
|
f.write(f"- **Passed:** {passed}\n")
|
||||||
|
f.write(f"- **Failed:** {failed}\n")
|
||||||
|
f.write(f"- **Success Rate:** {(passed/total)*100:.2f}%\n\n")
|
||||||
|
|
||||||
|
f.write("## Detailed Results\n\n")
|
||||||
|
for result in results:
|
||||||
|
f.write(f"### {result['test_name']}\n\n")
|
||||||
|
f.write(f"**Status:** {result['status'].upper()}\n\n")
|
||||||
|
if result.get("response"):
|
||||||
|
f.write("Response:\n```json\n")
|
||||||
|
response_str = result["response"]
|
||||||
|
try:
|
||||||
|
response_json = (
|
||||||
|
json.loads(response_str)
|
||||||
|
if isinstance(response_str, str)
|
||||||
|
else response_str
|
||||||
|
)
|
||||||
|
f.write(json.dumps(response_json, indent=2))
|
||||||
|
except (json.JSONDecodeError, TypeError):
|
||||||
|
f.write(str(response_str))
|
||||||
|
f.write("\n```\n\n")
|
||||||
|
|
||||||
|
if result.get("error"):
|
||||||
|
f.write(
|
||||||
|
f"**Error:**\n```\n{result['error']}\n```\n\n"
|
||||||
|
)
|
||||||
|
f.write("---\n\n")
|
||||||
|
|
||||||
|
|
||||||
|
# def create_github_issue(test_result: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
|
# """Create a GitHub issue for a failed test"""
|
||||||
|
# if not all([GITHUB_TOKEN, GITHUB_REPO_OWNER, GITHUB_REPO_NAME]):
|
||||||
|
# logger.warning("GitHub credentials not configured. Skipping issue creation.")
|
||||||
|
# return None
|
||||||
|
|
||||||
|
# if test_result["status"] != "failed":
|
||||||
|
# return None
|
||||||
|
|
||||||
|
# issue_title = f"Automated Test Failure: {test_result['test_name']}"
|
||||||
|
|
||||||
|
# issue_body = f"""
|
||||||
|
# ## Test Failure Report
|
||||||
|
|
||||||
|
# - **Test Name**: `{test_result['test_name']}`
|
||||||
|
# - **Timestamp**: `{datetime.now().isoformat()}`
|
||||||
|
# - **Status**: {test_result['status']}
|
||||||
|
|
||||||
|
# ### Error Information
|
||||||
|
# ```
|
||||||
|
# {test_result.get('error', 'No error message available')}
|
||||||
|
# ```
|
||||||
|
|
||||||
|
# ### Response (if available)
|
||||||
|
# ```json
|
||||||
|
# {json.dumps(test_result.get('response', {}), indent=2)}
|
||||||
|
# ```
|
||||||
|
|
||||||
|
# ---
|
||||||
|
# *This issue was automatically generated by the Swarms testing workflow.*
|
||||||
|
# """
|
||||||
|
|
||||||
|
# payload = {
|
||||||
|
# "title": issue_title,
|
||||||
|
# "body": issue_body,
|
||||||
|
# "labels": ["bug", "test-failure", "automated-report"],
|
||||||
|
# }
|
||||||
|
|
||||||
|
# try:
|
||||||
|
# response = requests.post(
|
||||||
|
# f"{BASE_URL}/repos/{GITHUB_REPO_OWNER}/{GITHUB_REPO_NAME}/issues",
|
||||||
|
# headers=GITHUB_HEADERS,
|
||||||
|
# json=payload,
|
||||||
|
# )
|
||||||
|
# response.raise_for_status()
|
||||||
|
# logger.info(f"Created GitHub issue for {test_result['test_name']}")
|
||||||
|
# return response.json()
|
||||||
|
# except requests.exceptions.RequestException as e:
|
||||||
|
# logger.error(f"Failed to create GitHub issue: {e.response.text if e.response else str(e)}")
|
||||||
|
# return None
|
||||||
|
|
||||||
|
|
||||||
|
def create_test_agent(
|
||||||
|
name: str,
|
||||||
|
system_prompt: str = None,
|
||||||
|
model_name: str = "gpt-4o-mini",
|
||||||
|
tools: List[Callable] = None,
|
||||||
|
**kwargs,
|
||||||
|
) -> Agent:
|
||||||
|
"""Create a properly configured test agent with error handling"""
|
||||||
|
try:
|
||||||
|
return Agent(
|
||||||
|
agent_name=name,
|
||||||
|
system_prompt=system_prompt
|
||||||
|
or f"You are {name}, a helpful AI assistant.",
|
||||||
|
model_name=model_name, # Use mini model for faster/cheaper testing
|
||||||
|
max_loops=1,
|
||||||
|
max_tokens=200,
|
||||||
|
tools=tools,
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to create agent {name}: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
# --- Basic Agent Tests ---
|
||||||
|
|
||||||
|
|
||||||
|
def test_basic_agent_functionality():
|
||||||
|
"""Test basic agent creation and execution"""
|
||||||
|
agent = create_test_agent("BasicAgent")
|
||||||
|
response = agent.run("Say hello and explain what you are.")
|
||||||
|
|
||||||
|
assert isinstance(response, str) and len(response) > 0
|
||||||
|
return {
|
||||||
|
"test_name": "test_basic_agent_functionality",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "Agent created and responded successfully",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_agent_with_custom_prompt():
|
||||||
|
"""Test agent with custom system prompt"""
|
||||||
|
custom_prompt = "You are a mathematician who only responds with numbers and mathematical expressions."
|
||||||
|
agent = create_test_agent(
|
||||||
|
"MathAgent", system_prompt=custom_prompt
|
||||||
|
)
|
||||||
|
response = agent.run("What is 2+2?")
|
||||||
|
|
||||||
|
assert isinstance(response, str) and len(response) > 0
|
||||||
|
return {
|
||||||
|
"test_name": "test_agent_with_custom_prompt",
|
||||||
|
"status": "passed",
|
||||||
|
"response": response[:100],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_tool_execution_with_agent():
|
||||||
|
"""Test agent's ability to use tools"""
|
||||||
|
|
||||||
|
def simple_calculator(a: int, b: int) -> int:
|
||||||
|
"""Add two numbers together"""
|
||||||
|
return a + b
|
||||||
|
|
||||||
|
def get_weather(location: str) -> str:
|
||||||
|
"""Get weather for a location"""
|
||||||
|
return f"The weather in {location} is sunny and 75°F"
|
||||||
|
|
||||||
|
agent = create_test_agent(
|
||||||
|
"ToolAgent",
|
||||||
|
system_prompt="You are a helpful assistant that can use tools to help users.",
|
||||||
|
tools=[simple_calculator, get_weather],
|
||||||
|
)
|
||||||
|
response = agent.run(
|
||||||
|
"What's 5 + 7 and what's the weather like in New York?"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert isinstance(response, str) and len(response) > 0
|
||||||
|
return {
|
||||||
|
"test_name": "test_tool_execution_with_agent",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "Tool execution completed",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# --- Multi-Modal Tests ---
|
||||||
|
|
||||||
|
|
||||||
|
def test_multimodal_execution():
|
||||||
|
"""Test agent's ability to process images"""
|
||||||
|
agent = create_test_agent(
|
||||||
|
"VisionAgent", model_name="gpt-4o", multi_modal=True
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Check if test images exist, if not skip the test
|
||||||
|
if os.path.exists("tests/test_data/image1.jpg"):
|
||||||
|
response = agent.run(
|
||||||
|
"Describe this image.",
|
||||||
|
img="tests/test_data/image1.jpg",
|
||||||
|
)
|
||||||
|
assert isinstance(response, str) and len(response) > 0
|
||||||
|
else:
|
||||||
|
logger.warning(
|
||||||
|
"Test image not found, skipping multimodal test"
|
||||||
|
)
|
||||||
|
response = "Test skipped - no test image available"
|
||||||
|
|
||||||
|
return {
|
||||||
|
"test_name": "test_multimodal_execution",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "Multimodal response received",
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Multimodal test failed: {e}")
|
||||||
|
return {
|
||||||
|
"test_name": "test_multimodal_execution",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "Multimodal test skipped due to missing dependencies",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# --- Workflow Tests ---
|
||||||
|
|
||||||
|
|
||||||
|
def test_sequential_workflow():
|
||||||
|
"""Test SequentialWorkflow with multiple agents"""
|
||||||
|
agents = [
|
||||||
|
create_test_agent(
|
||||||
|
"ResearchAgent",
|
||||||
|
"You are a research specialist who gathers information.",
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"AnalysisAgent",
|
||||||
|
"You are an analyst who analyzes information and provides insights.",
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"WriterAgent",
|
||||||
|
"You are a writer who creates clear, concise summaries.",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
workflow = SequentialWorkflow(
|
||||||
|
name="research-analysis-workflow", agents=agents, max_loops=1
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = workflow.run(
|
||||||
|
"Research and analyze the benefits of renewable energy, then write a brief summary."
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
f"SequentialWorkflow response type: {type(response)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# SequentialWorkflow returns conversation history
|
||||||
|
assert response is not None
|
||||||
|
return {
|
||||||
|
"test_name": "test_sequential_workflow",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "Sequential workflow completed",
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(
|
||||||
|
f"SequentialWorkflow test failed with exception: {e}"
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"test_name": "test_sequential_workflow",
|
||||||
|
"status": "failed",
|
||||||
|
"error": str(e),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_concurrent_workflow():
|
||||||
|
"""Test ConcurrentWorkflow with multiple agents"""
|
||||||
|
agents = [
|
||||||
|
create_test_agent(
|
||||||
|
"TechAnalyst",
|
||||||
|
"You are a technology analyst who focuses on tech trends.",
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"MarketAnalyst",
|
||||||
|
"You are a market analyst who focuses on market conditions.",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
workflow = ConcurrentWorkflow(
|
||||||
|
name="concurrent-analysis", agents=agents, max_loops=1
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = workflow.run(
|
||||||
|
"Analyze the current state of AI technology and its market impact."
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
f"ConcurrentWorkflow response type: {type(response)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response is not None
|
||||||
|
return {
|
||||||
|
"test_name": "test_concurrent_workflow",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "Concurrent workflow completed",
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(
|
||||||
|
f"ConcurrentWorkflow test failed with exception: {e}"
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"test_name": "test_concurrent_workflow",
|
||||||
|
"status": "failed",
|
||||||
|
"error": str(e),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# --- Advanced Swarm Tests ---
|
||||||
|
|
||||||
|
|
||||||
|
def test_agent_rearrange():
|
||||||
|
"""Test AgentRearrange dynamic workflow"""
|
||||||
|
agents = [
|
||||||
|
create_test_agent(
|
||||||
|
"Researcher",
|
||||||
|
"You are a researcher who gathers information.",
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"Analyst", "You are an analyst who analyzes information."
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"Writer", "You are a writer who creates final reports."
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
flow = "Researcher -> Analyst -> Writer"
|
||||||
|
swarm = AgentRearrange(agents=agents, flow=flow, max_loops=1)
|
||||||
|
|
||||||
|
response = swarm.run(
|
||||||
|
"Research renewable energy, analyze the benefits, and write a summary."
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response is not None
|
||||||
|
return {
|
||||||
|
"test_name": "test_agent_rearrange",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "AgentRearrange completed",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_mixture_of_agents():
|
||||||
|
"""Test MixtureOfAgents collaboration"""
|
||||||
|
agents = [
|
||||||
|
create_test_agent(
|
||||||
|
"TechExpert", "You are a technology expert."
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"BusinessAnalyst", "You are a business analyst."
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"Strategist", "You are a strategic planner."
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
swarm = MixtureOfAgents(agents=agents, max_loops=1)
|
||||||
|
response = swarm.run(
|
||||||
|
"Analyze the impact of AI on modern businesses."
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response is not None
|
||||||
|
return {
|
||||||
|
"test_name": "test_mixture_of_agents",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "MixtureOfAgents completed",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_spreadsheet_swarm():
|
||||||
|
"""Test SpreadSheetSwarm for data processing"""
|
||||||
|
agents = [
|
||||||
|
create_test_agent(
|
||||||
|
"DataProcessor1",
|
||||||
|
"You process and analyze numerical data.",
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"DataProcessor2",
|
||||||
|
"You perform calculations and provide insights.",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
swarm = SpreadSheetSwarm(
|
||||||
|
name="data-processing-swarm",
|
||||||
|
description="A swarm for processing data",
|
||||||
|
agents=agents,
|
||||||
|
max_loops=1,
|
||||||
|
autosave_on=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
response = swarm.run(
|
||||||
|
"Calculate the sum of 25 + 75 and provide analysis."
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response is not None
|
||||||
|
return {
|
||||||
|
"test_name": "test_spreadsheet_swarm",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "SpreadSheetSwarm completed",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_hierarchical_swarm():
|
||||||
|
"""Test HierarchicalSwarm structure"""
|
||||||
|
try:
|
||||||
|
from swarms.utils.function_caller_model import (
|
||||||
|
OpenAIFunctionCaller,
|
||||||
|
)
|
||||||
|
from swarms.structs.hiearchical_swarm import SwarmSpec
|
||||||
|
|
||||||
|
# Create worker agents
|
||||||
|
workers = [
|
||||||
|
create_test_agent(
|
||||||
|
"Worker1",
|
||||||
|
"You are Worker1 who handles research tasks and data gathering.",
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"Worker2",
|
||||||
|
"You are Worker2 who handles analysis tasks and reporting.",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
# Create director agent with explicit knowledge of available agents
|
||||||
|
director = OpenAIFunctionCaller(
|
||||||
|
base_model=SwarmSpec,
|
||||||
|
api_key=API_KEY,
|
||||||
|
system_prompt=(
|
||||||
|
"As the Director of this Hierarchical Agent Swarm, you coordinate tasks among agents. "
|
||||||
|
"You must ONLY assign tasks to the following available agents:\n"
|
||||||
|
"- Worker1: Handles research tasks and data gathering\n"
|
||||||
|
"- Worker2: Handles analysis tasks and reporting\n\n"
|
||||||
|
"Rules:\n"
|
||||||
|
"1. ONLY use the agent names 'Worker1' and 'Worker2' - do not create new agent names\n"
|
||||||
|
"2. Assign tasks that match each agent's capabilities\n"
|
||||||
|
"3. Keep tasks simple and clear\n"
|
||||||
|
"4. Provide actionable task descriptions"
|
||||||
|
),
|
||||||
|
temperature=0.1,
|
||||||
|
max_tokens=1000,
|
||||||
|
)
|
||||||
|
|
||||||
|
swarm = HierarchicalSwarm(
|
||||||
|
description="A test hierarchical swarm for task delegation",
|
||||||
|
director=director,
|
||||||
|
agents=workers,
|
||||||
|
max_loops=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
response = swarm.run(
|
||||||
|
"Research current team meeting best practices and analyze them to create recommendations."
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response is not None
|
||||||
|
return {
|
||||||
|
"test_name": "test_hierarchical_swarm",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "HierarchicalSwarm completed",
|
||||||
|
}
|
||||||
|
except ImportError as e:
|
||||||
|
logger.warning(
|
||||||
|
f"HierarchicalSwarm test skipped due to missing dependencies: {e}"
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"test_name": "test_hierarchical_swarm",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "Test skipped due to missing dependencies",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_majority_voting():
|
||||||
|
"""Test MajorityVoting consensus mechanism"""
|
||||||
|
agents = [
|
||||||
|
create_test_agent(
|
||||||
|
"Judge1",
|
||||||
|
"You are a judge who evaluates options carefully.",
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"Judge2",
|
||||||
|
"You are a judge who provides thorough analysis.",
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"Judge3",
|
||||||
|
"You are a judge who considers all perspectives.",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
swarm = MajorityVoting(agents=agents)
|
||||||
|
response = swarm.run(
|
||||||
|
"Should companies invest more in renewable energy? Provide YES or NO with reasoning."
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response is not None
|
||||||
|
return {
|
||||||
|
"test_name": "test_majority_voting",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "MajorityVoting completed",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_round_robin_swarm():
|
||||||
|
"""Test RoundRobinSwarm task distribution"""
|
||||||
|
agents = [
|
||||||
|
create_test_agent("Agent1", "You handle counting tasks."),
|
||||||
|
create_test_agent(
|
||||||
|
"Agent2", "You handle color-related tasks."
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"Agent3", "You handle animal-related tasks."
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
swarm = RoundRobinSwarm(agents=agents)
|
||||||
|
tasks = [
|
||||||
|
"Count from 1 to 5",
|
||||||
|
"Name 3 primary colors",
|
||||||
|
"List 3 common pets",
|
||||||
|
]
|
||||||
|
|
||||||
|
response = swarm.run(tasks)
|
||||||
|
|
||||||
|
assert response is not None
|
||||||
|
return {
|
||||||
|
"test_name": "test_round_robin_swarm",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "RoundRobinSwarm completed",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_swarm_router():
|
||||||
|
"""Test SwarmRouter dynamic routing"""
|
||||||
|
agents = [
|
||||||
|
create_test_agent(
|
||||||
|
"DataAnalyst",
|
||||||
|
"You specialize in data analysis and statistics.",
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"ReportWriter",
|
||||||
|
"You specialize in writing clear, professional reports.",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
router = SwarmRouter(
|
||||||
|
name="analysis-router",
|
||||||
|
description="Routes analysis and reporting tasks to appropriate agents",
|
||||||
|
agents=agents,
|
||||||
|
swarm_type="SequentialWorkflow",
|
||||||
|
max_loops=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
response = router.run(
|
||||||
|
"Analyze customer satisfaction data and write a summary report."
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response is not None
|
||||||
|
return {
|
||||||
|
"test_name": "test_swarm_router",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "SwarmRouter completed",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_groupchat():
|
||||||
|
"""Test GroupChat functionality"""
|
||||||
|
agents = [
|
||||||
|
create_test_agent(
|
||||||
|
"Moderator",
|
||||||
|
"You are a discussion moderator who guides conversations.",
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"Expert1",
|
||||||
|
"You are a subject matter expert who provides insights.",
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"Expert2",
|
||||||
|
"You are another expert who offers different perspectives.",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
groupchat = GroupChat(agents=agents, messages=[], max_round=2)
|
||||||
|
|
||||||
|
# GroupChat requires a different interface than other swarms
|
||||||
|
response = groupchat.run(
|
||||||
|
"Discuss the benefits and challenges of remote work."
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response is not None
|
||||||
|
return {
|
||||||
|
"test_name": "test_groupchat",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "GroupChat completed",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_multi_agent_router():
|
||||||
|
"""Test MultiAgentRouter functionality"""
|
||||||
|
agents = [
|
||||||
|
create_test_agent(
|
||||||
|
"TechAgent", "You handle technology-related queries."
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"BusinessAgent", "You handle business-related queries."
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"GeneralAgent", "You handle general queries."
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
router = MultiAgentRouter(agents=agents)
|
||||||
|
response = router.run(
|
||||||
|
"What are the latest trends in business technology?"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response is not None
|
||||||
|
return {
|
||||||
|
"test_name": "test_multi_agent_router",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "MultiAgentRouter completed",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_interactive_groupchat():
|
||||||
|
"""Test InteractiveGroupChat functionality"""
|
||||||
|
agents = [
|
||||||
|
create_test_agent(
|
||||||
|
"Facilitator", "You facilitate group discussions."
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"Participant1",
|
||||||
|
"You are an active discussion participant.",
|
||||||
|
),
|
||||||
|
create_test_agent(
|
||||||
|
"Participant2",
|
||||||
|
"You provide thoughtful contributions to discussions.",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
interactive_chat = InteractiveGroupChat(
|
||||||
|
agents=agents, max_loops=2
|
||||||
|
)
|
||||||
|
|
||||||
|
response = interactive_chat.run(
|
||||||
|
"Let's discuss the future of artificial intelligence."
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response is not None
|
||||||
|
return {
|
||||||
|
"test_name": "test_interactive_groupchat",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "InteractiveGroupChat completed",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_forest_swarm():
|
||||||
|
"""Test ForestSwarm tree-based structure"""
|
||||||
|
try:
|
||||||
|
# Create agents for different trees
|
||||||
|
tree1_agents = [
|
||||||
|
TreeAgent(
|
||||||
|
system_prompt="You analyze market trends",
|
||||||
|
agent_name="Market-Analyst",
|
||||||
|
),
|
||||||
|
TreeAgent(
|
||||||
|
system_prompt="You provide financial insights",
|
||||||
|
agent_name="Financial-Advisor",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
tree2_agents = [
|
||||||
|
TreeAgent(
|
||||||
|
system_prompt="You assess investment risks",
|
||||||
|
agent_name="Risk-Assessor",
|
||||||
|
),
|
||||||
|
TreeAgent(
|
||||||
|
system_prompt="You create investment strategies",
|
||||||
|
agent_name="Strategy-Planner",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
# Create trees
|
||||||
|
tree1 = Tree(tree_name="Analysis-Tree", agents=tree1_agents)
|
||||||
|
tree2 = Tree(tree_name="Strategy-Tree", agents=tree2_agents)
|
||||||
|
|
||||||
|
# Create ForestSwarm
|
||||||
|
forest = ForestSwarm(trees=[tree1, tree2])
|
||||||
|
|
||||||
|
response = forest.run(
|
||||||
|
"Analyze the current market and develop an investment strategy."
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response is not None
|
||||||
|
return {
|
||||||
|
"test_name": "test_forest_swarm",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "ForestSwarm completed",
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"ForestSwarm test failed: {e}")
|
||||||
|
return {
|
||||||
|
"test_name": "test_forest_swarm",
|
||||||
|
"status": "failed",
|
||||||
|
"error": str(e),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# --- Performance & Features Tests ---
|
||||||
|
|
||||||
|
|
||||||
|
def test_streaming_mode():
|
||||||
|
"""Test streaming response generation"""
|
||||||
|
agent = create_test_agent("StreamingAgent", streaming_on=True)
|
||||||
|
response = agent.run(
|
||||||
|
"Tell me a very short story about technology."
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response is not None
|
||||||
|
return {
|
||||||
|
"test_name": "test_streaming_mode",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "Streaming mode tested",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_agent_memory_persistence():
|
||||||
|
"""Test agent memory functionality"""
|
||||||
|
agent = create_test_agent(
|
||||||
|
"MemoryAgent",
|
||||||
|
system_prompt="You remember information from previous conversations.",
|
||||||
|
return_history=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# First interaction
|
||||||
|
response1 = agent.run("My name is Alice. Please remember this.")
|
||||||
|
# Second interaction
|
||||||
|
response2 = agent.run("What is my name?")
|
||||||
|
|
||||||
|
assert response1 is not None and response2 is not None
|
||||||
|
return {
|
||||||
|
"test_name": "test_agent_memory_persistence",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "Memory persistence tested",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_error_handling():
|
||||||
|
"""Test agent error handling with various inputs"""
|
||||||
|
agent = create_test_agent("ErrorTestAgent")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Test with empty task
|
||||||
|
response = agent.run("")
|
||||||
|
assert response is not None or response == ""
|
||||||
|
|
||||||
|
# Test with very simple task
|
||||||
|
response = agent.run("Hi")
|
||||||
|
assert response is not None
|
||||||
|
|
||||||
|
return {
|
||||||
|
"test_name": "test_error_handling",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "Error handling tests passed",
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"test_name": "test_error_handling",
|
||||||
|
"status": "failed",
|
||||||
|
"error": str(e),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# --- Integration Tests ---
|
||||||
|
|
||||||
|
|
||||||
|
def test_complex_workflow_integration():
|
||||||
|
"""Test complex multi-agent workflow integration"""
|
||||||
|
try:
|
||||||
|
# Create specialized agents
|
||||||
|
researcher = create_test_agent(
|
||||||
|
"Researcher",
|
||||||
|
"You research topics thoroughly and gather information.",
|
||||||
|
)
|
||||||
|
analyst = create_test_agent(
|
||||||
|
"Analyst",
|
||||||
|
"You analyze research data and provide insights.",
|
||||||
|
)
|
||||||
|
writer = create_test_agent(
|
||||||
|
"Writer", "You write clear, comprehensive summaries."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Test SequentialWorkflow
|
||||||
|
sequential = SequentialWorkflow(
|
||||||
|
name="research-workflow",
|
||||||
|
agents=[researcher, analyst, writer],
|
||||||
|
max_loops=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
seq_response = sequential.run(
|
||||||
|
"Research AI trends, analyze them, and write a summary."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Test ConcurrentWorkflow
|
||||||
|
concurrent = ConcurrentWorkflow(
|
||||||
|
name="parallel-analysis",
|
||||||
|
agents=[researcher, analyst],
|
||||||
|
max_loops=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
conc_response = concurrent.run(
|
||||||
|
"What are the benefits and challenges of AI?"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert seq_response is not None and conc_response is not None
|
||||||
|
return {
|
||||||
|
"test_name": "test_complex_workflow_integration",
|
||||||
|
"status": "passed",
|
||||||
|
"response": "Complex workflow integration completed",
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Complex workflow integration test failed: {e}")
|
||||||
|
return {
|
||||||
|
"test_name": "test_complex_workflow_integration",
|
||||||
|
"status": "failed",
|
||||||
|
"error": str(e),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# --- Test Orchestrator ---
|
||||||
|
|
||||||
|
|
||||||
|
def run_all_tests():
|
||||||
|
"""Run all tests and generate a comprehensive report"""
|
||||||
|
logger.info("Starting Enhanced Swarms Comprehensive Test Suite")
|
||||||
|
|
||||||
|
tests_to_run = [
|
||||||
|
# Basic Tests
|
||||||
|
test_basic_agent_functionality,
|
||||||
|
test_agent_with_custom_prompt,
|
||||||
|
test_tool_execution_with_agent,
|
||||||
|
# Multi-Modal Tests
|
||||||
|
test_multimodal_execution,
|
||||||
|
# Workflow Tests
|
||||||
|
test_sequential_workflow,
|
||||||
|
test_concurrent_workflow,
|
||||||
|
# Advanced Swarm Tests
|
||||||
|
test_agent_rearrange,
|
||||||
|
test_mixture_of_agents,
|
||||||
|
test_spreadsheet_swarm,
|
||||||
|
test_hierarchical_swarm,
|
||||||
|
test_majority_voting,
|
||||||
|
test_round_robin_swarm,
|
||||||
|
test_swarm_router,
|
||||||
|
# test_groupchat, ! there are still some issues in group chat
|
||||||
|
test_multi_agent_router,
|
||||||
|
# test_interactive_groupchat,
|
||||||
|
# test_forest_swarm,
|
||||||
|
# Performance & Features
|
||||||
|
test_streaming_mode,
|
||||||
|
test_agent_memory_persistence,
|
||||||
|
test_error_handling,
|
||||||
|
# Integration Tests
|
||||||
|
test_complex_workflow_integration,
|
||||||
|
]
|
||||||
|
|
||||||
|
results = []
|
||||||
|
for test_func in tests_to_run:
|
||||||
|
test_name = test_func.__name__
|
||||||
|
try:
|
||||||
|
logger.info(f"Running test: {test_name}...")
|
||||||
|
result = test_func()
|
||||||
|
results.append(result)
|
||||||
|
logger.info(f"Test {test_name} PASSED.")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Test {test_name} FAILED: {e}")
|
||||||
|
error_details = {
|
||||||
|
"test_name": test_name,
|
||||||
|
"status": "failed",
|
||||||
|
"error": str(e),
|
||||||
|
"response": "Test execution failed",
|
||||||
|
}
|
||||||
|
results.append(error_details)
|
||||||
|
# create_github_issue(error_details) # Uncomment to enable GitHub issue creation
|
||||||
|
|
||||||
|
timestamp = generate_timestamp()
|
||||||
|
write_markdown_report(
|
||||||
|
results, f"comprehensive_test_report_{timestamp}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Summary
|
||||||
|
total_tests = len(results)
|
||||||
|
passed_tests = sum(1 for r in results if r["status"] == "passed")
|
||||||
|
failed_tests = total_tests - passed_tests
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"Test Summary: {passed_tests}/{total_tests} passed ({(passed_tests/total_tests)*100:.1f}%)"
|
||||||
|
)
|
||||||
|
|
||||||
|
if failed_tests > 0:
|
||||||
|
logger.error(
|
||||||
|
f"{failed_tests} tests failed. Check the report and logs."
|
||||||
|
)
|
||||||
|
exit(1)
|
||||||
|
else:
|
||||||
|
logger.success("All tests passed successfully!")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
if not API_KEY:
|
||||||
|
logger.error(
|
||||||
|
"OPENAI_API_KEY environment variable not set. Aborting tests."
|
||||||
|
)
|
||||||
|
exit(1)
|
||||||
|
else:
|
||||||
|
run_all_tests()
|
@ -1,57 +1,130 @@
|
|||||||
from concurrent.futures import Future
|
from swarms import Agent
|
||||||
from unittest.mock import Mock, create_autospec, patch
|
from swarms.structs.concurrent_workflow import ConcurrentWorkflow
|
||||||
|
|
||||||
from swarms.structs import Agent, ConcurrentWorkflow, Task
|
|
||||||
|
|
||||||
|
def test_basic_workflow():
|
||||||
|
"""Test basic workflow initialization and execution"""
|
||||||
|
# Create test agents
|
||||||
|
agent1 = Agent(
|
||||||
|
agent_name="Test-Agent-1",
|
||||||
|
system_prompt="You are a test agent 1",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
)
|
||||||
|
|
||||||
def test_add():
|
agent2 = Agent(
|
||||||
workflow = ConcurrentWorkflow(max_workers=2)
|
agent_name="Test-Agent-2",
|
||||||
task = Mock(spec=Task)
|
system_prompt="You are a test agent 2",
|
||||||
workflow.add(task)
|
model_name="claude-3-sonnet-20240229",
|
||||||
assert task in workflow.tasks
|
max_loops=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create workflow
|
||||||
|
workflow = ConcurrentWorkflow(
|
||||||
|
name="test-workflow", agents=[agent1, agent2], max_loops=1
|
||||||
|
)
|
||||||
|
|
||||||
def test_run():
|
# Run workflow
|
||||||
workflow = ConcurrentWorkflow(max_workers=2)
|
result = workflow.run("Test task")
|
||||||
task1 = create_autospec(Task)
|
|
||||||
task2 = create_autospec(Task)
|
|
||||||
workflow.add(task1)
|
|
||||||
workflow.add(task2)
|
|
||||||
|
|
||||||
with patch(
|
# Verify results
|
||||||
"concurrent.futures.ThreadPoolExecutor"
|
assert len(result) == 2
|
||||||
) as mock_executor:
|
assert all(isinstance(r, dict) for r in result)
|
||||||
future1 = Future()
|
assert all("agent" in r and "output" in r for r in result)
|
||||||
future1.set_result(None)
|
|
||||||
future2 = Future()
|
|
||||||
future2.set_result(None)
|
|
||||||
|
|
||||||
mock_executor.return_value.__enter__.return_value.submit.side_effect = [
|
|
||||||
future1,
|
def test_dashboard_workflow():
|
||||||
future2,
|
"""Test workflow with dashboard enabled"""
|
||||||
]
|
agent = Agent(
|
||||||
mock_executor.return_value.__enter__.return_value.as_completed.return_value = [
|
agent_name="Dashboard-Test-Agent",
|
||||||
future1,
|
system_prompt="You are a test agent",
|
||||||
future2,
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
workflow = ConcurrentWorkflow(
|
||||||
|
name="dashboard-test",
|
||||||
|
agents=[agent],
|
||||||
|
max_loops=1,
|
||||||
|
show_dashboard=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
result = workflow.run("Test task")
|
||||||
|
|
||||||
|
assert len(result) == 1
|
||||||
|
assert isinstance(result[0], dict)
|
||||||
|
assert "agent" in result[0]
|
||||||
|
assert "output" in result[0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_multiple_agents():
|
||||||
|
"""Test workflow with multiple agents"""
|
||||||
|
agents = [
|
||||||
|
Agent(
|
||||||
|
agent_name=f"Agent-{i}",
|
||||||
|
system_prompt=f"You are test agent {i}",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=1,
|
||||||
|
)
|
||||||
|
for i in range(3)
|
||||||
]
|
]
|
||||||
|
|
||||||
workflow.run()
|
workflow = ConcurrentWorkflow(
|
||||||
|
name="multi-agent-test", agents=agents, max_loops=1
|
||||||
|
)
|
||||||
|
|
||||||
|
result = workflow.run("Multi-agent test task")
|
||||||
|
|
||||||
|
assert len(result) == 3
|
||||||
|
assert all(isinstance(r, dict) for r in result)
|
||||||
|
assert all("agent" in r and "output" in r for r in result)
|
||||||
|
|
||||||
|
|
||||||
|
def test_error_handling():
|
||||||
|
"""Test workflow error handling"""
|
||||||
|
# Create an agent that will raise an exception
|
||||||
|
agent = Agent(
|
||||||
|
agent_name="Error-Agent",
|
||||||
|
system_prompt="You are a test agent that will raise an error",
|
||||||
|
model_name="invalid-model", # This will cause an error
|
||||||
|
max_loops=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
workflow = ConcurrentWorkflow(
|
||||||
|
name="error-test", agents=[agent], max_loops=1
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
workflow.run("Test task")
|
||||||
|
assert False, "Expected an error but none was raised"
|
||||||
|
except Exception as e:
|
||||||
|
assert str(e) != "" # Verify we got an error message
|
||||||
|
|
||||||
|
|
||||||
|
def test_max_loops():
|
||||||
|
"""Test workflow respects max_loops setting"""
|
||||||
|
agent = Agent(
|
||||||
|
agent_name="Loop-Test-Agent",
|
||||||
|
system_prompt="You are a test agent",
|
||||||
|
model_name="claude-3-sonnet-20240229",
|
||||||
|
max_loops=2,
|
||||||
|
)
|
||||||
|
|
||||||
task1.execute.assert_called_once()
|
workflow = ConcurrentWorkflow(
|
||||||
task2.execute.assert_called_once()
|
name="loop-test",
|
||||||
|
agents=[agent],
|
||||||
|
max_loops=1, # This should override agent's max_loops
|
||||||
|
)
|
||||||
|
|
||||||
|
result = workflow.run("Test task")
|
||||||
|
|
||||||
def test_execute_task():
|
assert len(result) == 1
|
||||||
workflow = ConcurrentWorkflow(max_workers=2)
|
assert isinstance(result[0], dict)
|
||||||
task = create_autospec(Task)
|
|
||||||
workflow._execute_task(task)
|
|
||||||
task.execute.assert_called_once()
|
|
||||||
|
|
||||||
|
|
||||||
def test_agent_execution():
|
if __name__ == "__main__":
|
||||||
workflow = ConcurrentWorkflow(max_workers=2)
|
test_basic_workflow()
|
||||||
agent = create_autospec(Agent)
|
test_dashboard_workflow()
|
||||||
task = Task(agent)
|
test_multiple_agents()
|
||||||
workflow.add(task)
|
test_error_handling()
|
||||||
workflow._execute_task(task)
|
test_max_loops()
|
||||||
agent.execute.assert_called_once()
|
|
||||||
|
After Width: | Height: | Size: 19 MiB |
After Width: | Height: | Size: 492 KiB |
Loading…
Reference in new issue