Merge branch 'master' into 20250722reasoningduo

pull/970/head
王祥宇 5 days ago committed by GitHub
commit 4d32b3156b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -41,7 +41,7 @@ jobs:
# Step 4: Cache dependencies to speed up subsequent runs. # Step 4: Cache dependencies to speed up subsequent runs.
- name: Load cached venv - name: Load cached venv
id: cached-poetry-dependencies id: cached-poetry-dependencies
uses: actions/cache@v3 uses: actions/cache@v4
with: with:
path: .venv path: .venv
key: venv-${{ runner.os }}-${{ steps.setup-python.outputs.python-version }}-${{ hashFiles('**/poetry.lock') }} key: venv-${{ runner.os }}-${{ steps.setup-python.outputs.python-version }}-${{ hashFiles('**/poetry.lock') }}
@ -83,7 +83,7 @@ jobs:
# This happens even if the previous steps fail, allowing you to debug. # This happens even if the previous steps fail, allowing you to debug.
- name: Upload Test Report - name: Upload Test Report
if: always() if: always()
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v4
with: with:
name: test-report-${{ matrix.python-version }} name: test-report-${{ matrix.python-version }}
path: test_runs/ path: test_runs/

@ -62,7 +62,7 @@ jobs:
# Build and push Docker image # Build and push Docker image
- name: Build and push Docker image - name: Build and push Docker image
id: build-and-push id: build-and-push
uses: docker/build-push-action@v5 uses: docker/build-push-action@v6
with: with:
context: . context: .
push: ${{ github.event_name != 'pull_request' }} push: ${{ github.event_name != 'pull_request' }}

@ -226,6 +226,7 @@ print(final_post)
| **[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. | | **[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. | | **[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. |
| **[HierarchicalSwarm](https://docs.swarms.world/en/latest/swarms/structs/hiearchical_swarm/)** | Orchestrates agents with a director that creates plans and distributes tasks to specialized worker agents. | Complex project management, team coordination, hierarchical decision-making with feedback loops. | | **[HierarchicalSwarm](https://docs.swarms.world/en/latest/swarms/structs/hiearchical_swarm/)** | Orchestrates agents with a director that creates plans and distributes tasks to specialized worker agents. | Complex project management, team coordination, hierarchical decision-making with feedback loops. |
| **[HeavySwarm](https://docs.swarms.world/en/latest/swarms/structs/heavy_swarm/)** | Implements a 5-phase workflow with specialized agents (Research, Analysis, Alternatives, Verification) for comprehensive task analysis. | Complex research and analysis tasks, financial analysis, strategic planning, comprehensive reporting. |
| **[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. | | **[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. |
----- -----
@ -237,20 +238,26 @@ A `SequentialWorkflow` executes tasks in a strict order, forming a pipeline wher
```python ```python
from swarms import Agent, SequentialWorkflow from swarms import Agent, SequentialWorkflow
# Initialize agents for a 3-step process # Agent 1: The Researcher
# 1. Generate an idea researcher = Agent(
idea_generator = Agent(agent_name="IdeaGenerator", system_prompt="Generate a unique startup idea.", model_name="gpt-4o-mini") agent_name="Researcher",
# 2. Validate the idea system_prompt="Your job is to research the provided topic and provide a detailed summary.",
validator = Agent(agent_name="Validator", system_prompt="Take this startup idea and analyze its market viability.", model_name="gpt-4o-mini") 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 # Agent 2: The Writer
workflow = SequentialWorkflow(agents=[idea_generator, validator, pitch_creator]) writer = Agent(
agent_name="Writer",
system_prompt="Your job is to take the research summary and write a beautiful, engaging blog post about it.",
model_name="gpt-4o-mini",
)
# Create a sequential workflow where the researcher's output feeds into the writer's input
workflow = SequentialWorkflow(agents=[researcher, writer])
# Run the workflow # Run the workflow on a task
elevator_pitch = workflow.run() final_post = workflow.run("The history and future of artificial intelligence")
print(elevator_pitch) print(final_post)
``` ```
----- -----
@ -313,9 +320,7 @@ rearrange_system = AgentRearrange(
flow=flow, flow=flow,
) )
# Run the system # Run the swarm
# The researcher will generate content, and then both the writer and editor
# will process that content in parallel.
outputs = rearrange_system.run("Analyze the impact of AI on modern cinema.") outputs = rearrange_system.run("Analyze the impact of AI on modern cinema.")
print(outputs) print(outputs)
``` ```
@ -533,6 +538,49 @@ The `HierarchicalSwarm` excels at:
--- ---
### HeavySwarm
`HeavySwarm` implements a sophisticated 5-phase workflow inspired by X.AI's Grok heavy implementation. It uses specialized agents (Research, Analysis, Alternatives, Verification) to provide comprehensive task analysis through intelligent question generation, parallel execution, and synthesis. This architecture excels at complex research and analysis tasks requiring thorough investigation and multiple perspectives.
```python
from swarms import HeavySwarm
# Initialize the HeavySwarm with configuration
swarm = HeavySwarm(
worker_model_name="gpt-4o-mini", # Model for worker agents
question_agent_model_name="gpt-4o-mini", # Model for question generation
loops_per_agent=1, # Number of loops per agent
show_dashboard=True, # Enable real-time dashboard
)
# Run complex analysis task
result = swarm.run(
"Provide 3 publicly traded biotech companies that are currently trading below their cash value. "
"For each company identified, provide available data or projections for the next 6 months, "
"including any relevant financial metrics, upcoming catalysts, or events that could impact valuation. "
"Present your findings in a clear, structured format with ticker symbols, current prices, "
"cash values, and percentage differences."
)
print(result)
```
The `HeavySwarm` provides:
- **5-Phase Analysis**: Question generation, research, analysis, alternatives, and verification
- **Specialized Agents**: Each phase uses purpose-built agents for optimal results
- **Comprehensive Coverage**: Multiple perspectives and thorough investigation
- **Real-time Dashboard**: Optional visualization of the analysis process
- **Structured Output**: Well-organized and actionable results
This architecture is perfect for financial analysis, strategic planning, research reports, and any task requiring deep, multi-faceted analysis. [Learn more about HeavySwarm](https://docs.swarms.world/en/latest/swarms/structs/heavy_swarm/)
---
## Documentation ## Documentation
Documentation is located here at: [docs.swarms.world](https://docs.swarms.world) Documentation is located here at: [docs.swarms.world](https://docs.swarms.world)

@ -1,5 +1,5 @@
from swarms import Agent # Get your packages
from swarms.structs.concurrent_workflow import ConcurrentWorkflow from swarms import Agent, ConcurrentWorkflow
# Initialize market research agent # Initialize market research agent
market_researcher = Agent( market_researcher = Agent(
@ -12,7 +12,7 @@ market_researcher = Agent(
5. Providing actionable market insights""", 5. Providing actionable market insights""",
model_name="claude-3-sonnet-20240229", model_name="claude-3-sonnet-20240229",
max_loops=1, max_loops=1,
temperature=0.7, dynamic_temperature_enabled=True,
# streaming_on=True, # streaming_on=True,
) )
@ -25,10 +25,9 @@ financial_analyst = Agent(
3. Assessing risk factors 3. Assessing risk factors
4. Providing financial forecasts 4. Providing financial forecasts
5. Recommending financial strategies""", 5. Recommending financial strategies""",
model_name="claude-3-sonnet-20240229", model_name="gpt-4.1",
max_loops=1, max_loops=1,
# streaming_on=True, dynamic_temperature_enabled=True,
temperature=0.7,
) )
# Initialize technical analyst agent # Initialize technical analyst agent
@ -52,14 +51,15 @@ agents = [market_researcher, financial_analyst, technical_analyst]
router = ConcurrentWorkflow( router = ConcurrentWorkflow(
name="market-analysis-router", name="market-analysis-router",
description="This concurrent workflow is used to analyze the market, financial, and technical aspects of a stock.",
agents=agents, agents=agents,
max_loops=1, max_loops=1,
# output_type="all", output_type="all",
show_dashboard=True, show_dashboard=True,
) )
result = router.run( result = router.run(
"Analyze Tesla (TSLA) stock from market, financial, and technical perspectives" task="What are the best 3 ETFS for energy sector in the US?"
) )
print(result) print(result)

@ -0,0 +1,19 @@
# Class/function
Brief description
## Overview
## Architecture (Mermaid diagram)
## Class Reference (Constructor + Methods)
## Examples
## Conclusion
Benefits of class/structure, and more

@ -157,47 +157,47 @@ nav:
- Feature Set: "swarms/features.md" - Feature Set: "swarms/features.md"
- Agents: - Agents:
- Overview: "swarms/agents/index.md" - Overview: "swarms/agents/index.md"
- Concepts: - Architecture: "swarms/framework/agents_explained.md"
# - Managing Prompts in Production: "swarms/prompts/main.md" - Reference: "swarms/structs/agent.md"
- Introduction into The Agent Architecture: "swarms/framework/agents_explained.md" - LLM Providers: "swarms/models/agent_and_models.md"
# - Introduction to Tools: "swarms/tools/overview.md" - Tools and MCP: "swarms/tools/tools_examples.md"
- Documentation: - Multi-Agent Helpers: "swarms/structs/agent_multi_agent_communication.md"
- Agent Class Documentation: "swarms/structs/agent.md" - Running Agents with YAML: "swarms/agents/create_agents_yaml.md"
- Create and Run Agents from YAML: "swarms/agents/create_agents_yaml.md"
- Integrating Various Models into Your Agents: "swarms/models/agent_and_models.md"
- Tools: - Additional Capabilities:
- Tools Reference:
- Overview: "swarms/tools/main.md" - Overview: "swarms/tools/main.md"
- What are tools?: "swarms/tools/build_tool.md" - What are tools?: "swarms/tools/build_tool.md"
- Structured Outputs: "swarms/agents/structured_outputs.md" - Structured Outputs: "swarms/agents/structured_outputs.md"
- Agent MCP Integration: "swarms/structs/agent_mcp.md" - Agent MCP Integration: "swarms/structs/agent_mcp.md"
- Comprehensive Tool Guide with MCP, Callables, and more: "swarms/tools/tools_examples.md" - Long Term Memory Reference:
- RAG || Long Term Memory:
- Integrating RAG with Agents: "swarms/memory/diy_memory.md" - Integrating RAG with Agents: "swarms/memory/diy_memory.md"
- Third-Party Agent Integrations:
- OpenAI Assistant: "swarms/agents/openai_assistant.md"
- Integrating External Agents from Griptape, Langchain, etc: "swarms/agents/external_party_agents.md"
- Creating Custom Agents: "swarms/agents/new_agent.md"
- PreBuilt Reasoning Agents:
- Self Consistency Agent: "swarms/agents/consistency_agent.md"
- IRE Agent: "swarms/agents/iterative_agent.md"
- Reasoning Duo: "swarms/agents/reasoning_duo.md"
- Reasoning Agent Router: "swarms/agents/reasoning_agent_router.md"
- Reflexion Agent: "swarms/agents/reflexion_agent.md"
- GKP Agent: "swarms/agents/gkp_agent.md"
- Agent Judge: "swarms/agents/agent_judge.md"
- Multi-Agent Architectures: - Third-Party Agents:
- Introduction to Multi-Agent Collaboration: "swarms/concept/why.md" - Creating Custom Agents: "swarms/agents/new_agent.md"
- OpenAI Assistant: "swarms/agents/openai_assistant.md"
- Integrating External Agents from Griptape, Langchain, etc: "swarms/agents/external_party_agents.md"
- Concepts: - Reasoning Agents:
- Introduction to Multi Agent Architectures: "swarms/concept/swarm_architectures.md" - Self Consistency Agent: "swarms/agents/consistency_agent.md"
- How to Choose the Right Multi Agent Architecture: "swarms/concept/how_to_choose_swarms.md" - IRE Agent: "swarms/agents/iterative_agent.md"
- How to Build Custom Swarms: "swarms/structs/custom_swarm.md" - Reasoning Duo: "swarms/agents/reasoning_duo.md"
- How to Create New Multi Agent Architectures: "swarms/structs/create_new_swarm.md" - Reflexion Agent: "swarms/agents/reflexion_agent.md"
- Introduction to Hiearchical Multi Agent Architectures: "swarms/structs/multi_swarm_orchestration.md" - GKP Agent: "swarms/agents/gkp_agent.md"
- Agent Judge: "swarms/agents/agent_judge.md"
- Reasoning Agent Router: "swarms/agents/reasoning_agent_router.md"
- Multi-Agent Architectures Documentation: - Multi-Agent Architectures:
- Overview: "swarms/concept/swarm_architectures.md"
- Benefits: "swarms/concept/why.md"
- Choosing Multi Agent Architecture: "swarms/concept/how_to_choose_swarms.md"
- Documentation:
- Overview: "swarms/structs/overview.md" - Overview: "swarms/structs/overview.md"
- Custom Multi Agent Architectures: "swarms/structs/custom_swarm.md"
- MajorityVoting: "swarms/structs/majorityvoting.md" - MajorityVoting: "swarms/structs/majorityvoting.md"
- RoundRobin: "swarms/structs/round_robin_swarm.md" - RoundRobin: "swarms/structs/round_robin_swarm.md"
- Mixture of Agents: "swarms/structs/moa.md" - Mixture of Agents: "swarms/structs/moa.md"
@ -207,20 +207,19 @@ nav:
- Various Execution Methods: "swarms/structs/various_execution_methods.md" - Various Execution Methods: "swarms/structs/various_execution_methods.md"
- Deep Research Swarm: "swarms/structs/deep_research_swarm.md" - Deep Research Swarm: "swarms/structs/deep_research_swarm.md"
- Council of Judges: "swarms/structs/council_of_judges.md" - Council of Judges: "swarms/structs/council_of_judges.md"
- Heavy Swarm: "swarms/structs/heavy_swarm.md"
- Hiearchical Architectures: - Hiearchical Architectures:
- Overview: "swarms/structs/multi_swarm_orchestration.md"
- HierarchicalSwarm: "swarms/structs/hierarchical_swarm.md" - HierarchicalSwarm: "swarms/structs/hierarchical_swarm.md"
- Auto Agent Builder: "swarms/structs/auto_agent_builder.md" - Auto Agent Builder: "swarms/structs/auto_agent_builder.md"
- Hybrid Hierarchical-Cluster Swarm: "swarms/structs/hhcs.md" - Hybrid Hierarchical-Cluster Swarm: "swarms/structs/hhcs.md"
- Auto Swarm Builder: "swarms/structs/auto_swarm_builder.md" - Auto Swarm Builder: "swarms/structs/auto_swarm_builder.md"
- Swarm Matcher: "swarms/structs/swarm_matcher.md" - Swarm Matcher: "swarms/structs/swarm_matcher.md"
- Multi-Agent Multi-Modal Structures: # - Multi-Agent Multi-Modal Structures:
- ImageAgentBatchProcessor: "swarms/structs/image_batch_agent.md" # - ImageAgentBatchProcessor: "swarms/structs/image_batch_agent.md"
- Storage:
- AgentRegistry: "swarms/structs/agent_registry.md"
- Routers: - Routers:
- SwarmRouter: "swarms/structs/swarm_router.md" - SwarmRouter: "swarms/structs/swarm_router.md"
@ -240,6 +239,9 @@ nav:
- SequentialWorkflow: "swarms/structs/sequential_workflow.md" - SequentialWorkflow: "swarms/structs/sequential_workflow.md"
- GraphWorkflow: "swarms/structs/graph_workflow.md" - GraphWorkflow: "swarms/structs/graph_workflow.md"
- Storage:
- AgentRegistry: "swarms/structs/agent_registry.md"
- Communication Structure: "swarms/structs/conversation.md" - Communication Structure: "swarms/structs/conversation.md"
- Tools: - Tools:
@ -253,17 +255,21 @@ nav:
- Social Media: - Social Media:
- Twitter: "swarms_tools/twitter.md" - Twitter: "swarms_tools/twitter.md"
- Memory: # - Memory:
- Overview: "swarms_memory/index.md" # - Overview: "swarms_memory/index.md"
- Memory Systems: # - Memory Systems:
- ChromaDB: "swarms_memory/chromadb.md" # - ChromaDB: "swarms_memory/chromadb.md"
- Pinecone: "swarms_memory/pinecone.md" # - Pinecone: "swarms_memory/pinecone.md"
- Faiss: "swarms_memory/faiss.md" # - Faiss: "swarms_memory/faiss.md"
- Deployment Solutions: - Deployment Solutions:
- Deploy your agents on Google Cloud Run: "swarms_cloud/cloud_run.md" - Deploy on Google Cloud Run: "swarms_cloud/cloud_run.md"
- Deploy your agents on Phala: "swarms_cloud/phala_deploy.md" - Deploy on Phala: "swarms_cloud/phala_deploy.md"
# - Deploy your agents on FastAPI: # - Deploy on FastAPI: "swarms_cloud/fastapi_deploy.md"
- More About Us:
- Swarms Ecosystem: "swarms/ecosystem.md"
- Technical Support: "swarms/support.md"
- Examples: - Examples:
@ -368,6 +374,7 @@ nav:
- Finance Swarm: "swarms/examples/swarms_api_finance.md" - Finance Swarm: "swarms/examples/swarms_api_finance.md"
- Clients: - Clients:
- Overview: "swarms_cloud/api_clients.md"
- Python Client: "swarms_cloud/python_client.md" - Python Client: "swarms_cloud/python_client.md"
- Rust Client: "swarms_cloud/rust_client.md" - Rust Client: "swarms_cloud/rust_client.md"

@ -1,223 +1,251 @@
# Agent Judge # AgentJudge
The AgentJudge is a specialized agent designed to evaluate and judge outputs from other agents or systems. It acts as a quality control mechanism, providing objective assessments and feedback on various types of content, decisions, or outputs. This implementation is based on the research paper "Agents as Judges: Using LLMs to Evaluate LLMs". A specialized agent for evaluating and judging outputs from other agents or systems. Acts as a quality control mechanism providing objective assessments and feedback.
## Research Background Based on the research paper: **"Agent-as-a-Judge: Evaluate Agents with Agents"** - [arXiv:2410.10934](https://arxiv.org/abs/2410.10934)
The AgentJudge implementation is inspired by recent research in LLM-based evaluation systems. Key findings from the research include:
- LLMs can effectively evaluate other LLM outputs with high accuracy
- Multi-agent evaluation systems can provide more reliable assessments
- Structured evaluation criteria improve consistency
- Context-aware evaluation leads to better results
## Overview ## Overview
The AgentJudge serves as an impartial evaluator that can: The AgentJudge is designed to evaluate and critique outputs from other AI agents, providing structured feedback on quality, accuracy, and areas for improvement. It supports both single-shot evaluations and iterative refinement through multiple evaluation loops with context building.
Key capabilities:
- Assess the quality and correctness of agent outputs - **Quality Assessment**: Evaluates correctness, clarity, and completeness of agent outputs
- Provide structured feedback and scoring - **Structured Feedback**: Provides detailed critiques with strengths, weaknesses, and suggestions
- Maintain context across multiple evaluations - **Multimodal Support**: Can evaluate text outputs alongside images
- Generate detailed analysis reports - **Context Building**: Maintains evaluation context across multiple iterations
- **Batch Processing**: Efficiently processes multiple evaluations
## Architecture ## Architecture
```mermaid ```mermaid
graph TD graph TD
A[Input Tasks] --> B[AgentJudge] A[Input Task] --> B[AgentJudge]
B --> C[Agent Core] B --> C{Evaluation Mode}
C --> D[LLM Model]
D --> E[Response Generation]
E --> F[Context Management]
F --> G[Output]
subgraph "Evaluation Flow"
H[Task Analysis] --> I[Quality Assessment]
I --> J[Feedback Generation]
J --> K[Score Assignment]
end
B --> H
K --> G
```
## Configuration C -->|step()| D[Single Eval]
C -->|run()| E[Iterative Eval]
C -->|run_batched()| F[Batch Eval]
### Parameters D --> G[Agent Core]
E --> G
F --> G
| Parameter | Type | Default | Description | G --> H[LLM Model]
|-----------|------|---------|-------------| H --> I[Quality Analysis]
| `agent_name` | str | "agent-judge-01" | Unique identifier for the judge agent | I --> J[Feedback & Output]
| `system_prompt` | str | AGENT_JUDGE_PROMPT | System instructions for the agent |
| `model_name` | str | "openai/o1" | LLM model to use for evaluation |
| `max_loops` | int | 1 | Maximum number of evaluation iterations |
### Methods subgraph "Feedback Details"
N[Strengths]
O[Weaknesses]
P[Improvements]
Q[Accuracy Check]
end
| Method | Description | Parameters | Returns | J --> N
|--------|-------------|------------|---------| J --> O
| `step()` | Processes a single batch of tasks | `tasks: List[str]` | `str` | J --> P
| `run()` | Executes multiple evaluation iterations | `tasks: List[str]` | `List[str]` | J --> Q
## Usage ```
### Basic Example ## Class Reference
```python ### Constructor
from swarms import AgentJudge
# Initialize the judge ```python
judge = AgentJudge( AgentJudge(
model_name="gpt-4o", id: str = str(uuid.uuid4()),
max_loops=1 agent_name: str = "Agent Judge",
description: str = "You're an expert AI agent judge...",
system_prompt: str = AGENT_JUDGE_PROMPT,
model_name: str = "openai/o1",
max_loops: int = 1,
verbose: bool = False,
*args,
**kwargs
) )
```
# Example outputs to evaluate #### Parameters
outputs = [
"1. Agent CalculusMaster: After careful evaluation, I have computed the integral of the polynomial function. The result is ∫(x^2 + 3x + 2)dx = (1/3)x^3 + (3/2)x^2 + 5, where I applied the power rule for integration and added the constant of integration.",
"2. Agent DerivativeDynamo: In my analysis of the function sin(x), I have derived it with respect to x. The derivative is d/dx (sin(x)) = cos(x). However, I must note that the additional term '+ 2' is not applicable in this context as it does not pertain to the derivative of sin(x).",
"3. Agent LimitWizard: Upon evaluating the limit as x approaches 0 for the function (sin(x)/x), I conclude that lim (x -> 0) (sin(x)/x) = 1. The additional '+ 3' is incorrect and should be disregarded as it does not relate to the limit calculation.",
]
# Run evaluation | Parameter | Type | Default | Description |
results = judge.run(outputs) |-----------|------|---------|-------------|
print(results) | `id` | `str` | `str(uuid.uuid4())` | Unique identifier for the judge instance |
``` | `agent_name` | `str` | `"Agent Judge"` | Name of the agent judge |
| `description` | `str` | `"You're an expert AI agent judge..."` | Description of the agent's role |
| `system_prompt` | `str` | `AGENT_JUDGE_PROMPT` | System instructions for evaluation |
| `model_name` | `str` | `"openai/o1"` | LLM model for evaluation |
| `max_loops` | `int` | `1` | Maximum evaluation iterations |
| `verbose` | `bool` | `False` | Enable verbose logging |
### Methods
## Applications #### step()
### Code Review Automation ```python
step(
task: str = None,
tasks: Optional[List[str]] = None,
img: Optional[str] = None
) -> str
```
!!! success "Features" Processes a single task or list of tasks and returns evaluation.
- Evaluate code quality
- Check for best practices
- Assess documentation completeness
### Content Quality Control | Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `task` | `str` | `None` | Single task/output to evaluate |
| `tasks` | `List[str]` | `None` | List of tasks/outputs to evaluate |
| `img` | `str` | `None` | Path to image for multimodal evaluation |
!!! info "Use Cases" **Returns:** `str` - Detailed evaluation response
- Review marketing copy
- Validate technical documentation
- Assess user support responses
### Decision Validation #### run()
```python
run(
task: str = None,
tasks: Optional[List[str]] = None,
img: Optional[str] = None
) -> List[str]
```
!!! warning "Applications" Executes evaluation in multiple iterations with context building.
- Evaluate business decisions
- Assess risk assessments
- Review compliance reports
### Performance Assessment | Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `task` | `str` | `None` | Single task/output to evaluate |
| `tasks` | `List[str]` | `None` | List of tasks/outputs to evaluate |
| `img` | `str` | `None` | Path to image for multimodal evaluation |
!!! tip "Metrics" **Returns:** `List[str]` - List of evaluation responses from each iteration
- Evaluate agent performance
- Assess system outputs
- Review automated processes
## Best Practices #### run_batched()
### Task Formulation ```python
run_batched(
tasks: Optional[List[str]] = None,
imgs: Optional[List[str]] = None
) -> List[List[str]]
```
1. Provide clear, specific evaluation criteria Executes batch evaluation of multiple tasks with corresponding images.
2. Include context when necessary
3. Structure tasks for consistent evaluation
### System Configuration | Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `tasks` | `List[str]` | `None` | List of tasks/outputs to evaluate |
| `imgs` | `List[str]` | `None` | List of image paths (same length as tasks) |
1. Use appropriate model for task complexity **Returns:** `List[List[str]]` - Evaluation responses for each task
2. Adjust max_loops based on evaluation depth needed
3. Customize system prompt for specific use cases
### Output Management ## Examples
1. Store evaluation results systematically ### Basic Usage
2. Track evaluation patterns over time
3. Use results for continuous improvement
### Integration Tips ```python
from swarms import AgentJudge
1. Implement as part of CI/CD pipelines # Initialize with default settings
2. Use for automated quality gates judge = AgentJudge()
3. Integrate with monitoring systems
## Implementation Guide # Single task evaluation
result = judge.step(task="The capital of France is Paris.")
print(result)
```
### Step 1: Setup ### Custom Configuration
```python ```python
from swarms import AgentJudge from swarms import AgentJudge
# Initialize with custom parameters # Custom judge configuration
judge = AgentJudge( judge = AgentJudge(
agent_name="custom-judge", agent_name="content-evaluator",
model_name="gpt-4", model_name="gpt-4",
max_loops=3 max_loops=3,
verbose=True
) )
```
### Step 2: Configure Evaluation Criteria
```python # Evaluate multiple outputs
# Define evaluation criteria outputs = [
criteria = { "Agent CalculusMaster: The integral of x^2 + 3x + 2 is (1/3)x^3 + (3/2)x^2 + 2x + C",
"accuracy": 0.4, "Agent DerivativeDynamo: The derivative of sin(x) is cos(x)",
"completeness": 0.3, "Agent LimitWizard: The limit of sin(x)/x as x approaches 0 is 1"
"clarity": 0.3 ]
}
# Set criteria evaluation = judge.step(tasks=outputs)
judge.set_evaluation_criteria(criteria) print(evaluation)
``` ```
### Step 3: Run Evaluations ### Iterative Evaluation with Context
```python ```python
# Single task evaluation from swarms import AgentJudge
result = judge.step(task)
# Multiple iterations with context building
judge = AgentJudge(max_loops=3)
# Batch evaluation # Each iteration builds on previous context
results = judge.run(tasks) evaluations = judge.run(task="Agent output: 2+2=5")
for i, eval_result in enumerate(evaluations):
print(f"Iteration {i+1}: {eval_result}\n")
``` ```
## Troubleshooting ### Multimodal Evaluation
```python
from swarms import AgentJudge
### Common Issues judge = AgentJudge()
??? question "Evaluation Inconsistencies" # Evaluate with image
If you notice inconsistent evaluations: evaluation = judge.step(
task="Describe what you see in this image",
img="path/to/image.jpg"
)
print(evaluation)
```
1. Check the evaluation criteria ### Batch Processing
2. Verify the model configuration
3. Review the input format
??? question "Performance Issues" ```python
For slow evaluations: from swarms import AgentJudge
1. Reduce max_loops judge = AgentJudge()
2. Optimize batch size
3. Consider model selection
# Batch evaluation with images
tasks = [
"Describe this chart",
"What's the main trend?",
"Any anomalies?"
]
images = [
"chart1.png",
"chart2.png",
"chart3.png"
]
## References # Each task evaluated independently
evaluations = judge.run_batched(tasks=tasks, imgs=images)
for i, task_evals in enumerate(evaluations):
print(f"Task {i+1} evaluations: {task_evals}")
```
### "Agent-as-a-Judge: Evaluate Agents with Agents" - [Paper Link](https://arxiv.org/abs/2410.10934) ## Reference
```bibtex ```bibtex
@misc{zhuge2024agentasajudgeevaluateagentsagents, @misc{zhuge2024agentasajudgeevaluateagentsagents,
title={Agent-as-a-Judge: Evaluate Agents with Agents}, title={Agent-as-a-Judge: Evaluate Agents with Agents},
author={Mingchen Zhuge and Changsheng Zhao and Dylan Ashley and Wenyi Wang and Dmitrii Khizbullin and Yunyang Xiong and Zechun Liu and Ernie Chang and Raghuraman Krishnamoorthi and Yuandong Tian and Yangyang Shi and Vikas Chandra and Jürgen Schmidhuber}, author={Mingchen Zhuge and Changsheng Zhao and Dylan Ashley and Wenyi Wang and Dmitrii Khizbullin and Yunyang Xiong and Zechun Liu and Ernie Chang and Raghuraman Krishnamoorthi and Yuandong Tian and Yangyang Shi and Vikas Chandra and Jürgen Schmidhuber},
year={2024}, year={2024},
eprint={2410.10934}, eprint={2410.10934},
archivePrefix={arXiv}, archivePrefix={arXiv},
primaryClass={cs.AI}, primaryClass={cs.AI},
url={https://arxiv.org/abs/2410.10934}, url={https://arxiv.org/abs/2410.10934}
} }
``` ```

@ -1,6 +1,5 @@
# Consistency Agent Documentation # Consistency Agent Documentation
The `SelfConsistencyAgent` is a specialized agent designed for generating multiple independent responses to a given task and aggregating them into a single, consistent final answer. It leverages concurrent processing to enhance efficiency and employs a majority voting mechanism to ensure the reliability of the aggregated response. The `SelfConsistencyAgent` is a specialized agent designed for generating multiple independent responses to a given task and aggregating them into a single, consistent final answer. It leverages concurrent processing to enhance efficiency and employs a majority voting mechanism to ensure the reliability of the aggregated response.
## Purpose ## Purpose
@ -17,24 +16,31 @@ The primary objective of the `SelfConsistencyAgent` is to provide a robust mecha
| Argument | Type | Default | Description | | Argument | Type | Default | Description |
|------------------------|---------|---------|-----------------------------------------------------------------------------| |------------------------|---------|---------|-----------------------------------------------------------------------------|
| `num_samples` | `int` | `5` | Number of independent responses to sample. | | `name` | `str` | `"Self-Consistency-Agent"` | Name of the agent. |
| `return_list` | `bool` | `False` | Whether to return the conversation as a list. | | `description` | `str` | `"An agent that uses self consistency to generate a final answer."` | Description of the agent's purpose. |
| `max_loops` | `int` | `1` | Maximum number of loops for the agent to run. | | `system_prompt` | `str` | `CONSISTENCY_SYSTEM_PROMPT` | System prompt for the reasoning agent. |
| `return_dict` | `bool` | `False` | Whether to return the conversation as a dictionary. | | `model_name` | `str` | Required | The underlying language model to use. |
| `return_json` | `bool` | `False` | Whether to return the conversation as JSON. | | `num_samples` | `int` | `5` | Number of independent responses to generate. |
| `majority_voting_prompt` | `str` | `None` | Custom prompt for majority voting. | | `max_loops` | `int` | `1` | Maximum number of reasoning loops per sample. |
| `majority_voting_prompt` | `Optional[str]` | `majority_voting_prompt` | Custom prompt for majority voting aggregation. |
| `eval` | `bool` | `False` | Enable evaluation mode for answer validation. |
| `output_type` | `OutputType` | `"dict"` | Format of the output. |
| `random_models_on` | `bool` | `False` | Enable random model selection for diversity. |
### Methods ### Methods
- **`run`**: Generates multiple responses for the given task and aggregates them. - **`run`**: Generates multiple responses for the given task and aggregates them.
- **Arguments**: - **Arguments**:
- `task` (`str`): The input prompt. - `task` (`str`): The input prompt.
- `answer` (`str`, optional): The expected answer to validate responses against. - `img` (`Optional[str]`, optional): Image input for vision tasks.
- **Returns**: `str` - The aggregated final answer. - `answer` (`Optional[str]`, optional): Expected answer for validation (if eval=True).
- **Returns**: `Union[str, Dict[str, Any]]` - The aggregated final answer.
- **`aggregate`**: Aggregates a list of responses into a single final answer using majority voting. - **`aggregation_agent`**: Aggregates a list of responses into a single final answer using majority voting.
- **Arguments**: - **Arguments**:
- `responses` (`List[str]`): The list of responses. - `responses` (`List[str]`): The list of responses.
- `prompt` (`str`, optional): Custom prompt for the aggregation agent.
- `model_name` (`str`, optional): Model to use for aggregation.
- **Returns**: `str` - The aggregated answer. - **Returns**: `str` - The aggregated answer.
- **`check_responses_for_answer`**: Checks if a specified answer is present in any of the provided responses. - **`check_responses_for_answer`**: Checks if a specified answer is present in any of the provided responses.
@ -43,6 +49,11 @@ The primary objective of the `SelfConsistencyAgent` is to provide a robust mecha
- `answer` (`str`): The answer to look for in the responses. - `answer` (`str`): The answer to look for in the responses.
- **Returns**: `bool` - `True` if the answer is found, `False` otherwise. - **Returns**: `bool` - `True` if the answer is found, `False` otherwise.
- **`batched_run`**: Run the agent on multiple tasks in batch.
- **Arguments**:
- `tasks` (`List[str]`): List of tasks to be processed.
- **Returns**: `List[Union[str, Dict[str, Any]]]` - List of results for each task.
### Examples ### Examples
#### Example 1: Basic Usage #### Example 1: Basic Usage
@ -52,7 +63,7 @@ from swarms.agents.consistency_agent import SelfConsistencyAgent
# Initialize the agent # Initialize the agent
agent = SelfConsistencyAgent( agent = SelfConsistencyAgent(
agent_name="Reasoning-Agent", name="Math-Reasoning-Agent",
model_name="gpt-4o-mini", model_name="gpt-4o-mini",
max_loops=1, max_loops=1,
num_samples=5 num_samples=5
@ -75,7 +86,7 @@ from swarms.agents.consistency_agent import SelfConsistencyAgent
# Initialize the agent with a custom majority voting prompt # Initialize the agent with a custom majority voting prompt
agent = SelfConsistencyAgent( agent = SelfConsistencyAgent(
agent_name="Reasoning-Agent", name="Reasoning-Agent",
model_name="gpt-4o-mini", model_name="gpt-4o-mini",
max_loops=1, max_loops=1,
num_samples=5, num_samples=5,
@ -92,4 +103,128 @@ final_answer = agent.run(task)
print("Final aggregated answer:", final_answer) print("Final aggregated answer:", final_answer)
``` ```
#### Example 3: Evaluation Mode
```python
from swarms.agents.consistency_agent import SelfConsistencyAgent
# Initialize the agent with evaluation mode
agent = SelfConsistencyAgent(
name="Validation-Agent",
model_name="gpt-4o-mini",
num_samples=3,
eval=True
)
# Run with expected answer for validation
result = agent.run("What is 2 + 2?", answer="4", eval=True)
if result is not None:
print("Validation passed:", result)
else:
print("Validation failed - expected answer not found")
```
#### Example 4: Random Models for Diversity
```python
from swarms.agents.consistency_agent import SelfConsistencyAgent
# Initialize the agent with random model selection
agent = SelfConsistencyAgent(
name="Diverse-Reasoning-Agent",
model_name="gpt-4o-mini",
num_samples=5,
random_models_on=True
)
# Run the agent
result = agent.run("What are the benefits of renewable energy?")
print("Diverse reasoning result:", result)
```
#### Example 5: Batch Processing
```python
from swarms.agents.consistency_agent import SelfConsistencyAgent
# Initialize the agent
agent = SelfConsistencyAgent(
name="Batch-Processing-Agent",
model_name="gpt-4o-mini",
num_samples=3
)
# Define multiple tasks
tasks = [
"What is the capital of France?",
"What is 15 * 23?",
"Explain photosynthesis in simple terms."
]
# Process all tasks
results = agent.batched_run(tasks)
# Print results
for i, result in enumerate(results):
print(f"Task {i+1} result: {result}")
```
## Key Features
### Self-Consistency Technique
The agent implements the self-consistency approach based on the research paper "Self-Consistency Improves Chain of Thought Reasoning in Language Models" by Wang et al. (2022). This technique:
1. **Generates Multiple Independent Responses**: Creates several reasoning paths for the same problem
2. **Analyzes Consistency**: Examines agreement among different reasoning approaches
3. **Aggregates Results**: Uses majority voting or consensus building
4. **Produces Reliable Output**: Delivers a final answer reflecting the most reliable consensus
### Benefits
- **Mitigates Random Errors**: Multiple reasoning paths reduce individual path errors
- **Reduces Bias**: Diverse approaches minimize single-method biases
- **Improves Reliability**: Consensus-based results are more trustworthy
- **Handles Complexity**: Better performance on complex problem-solving tasks
### Use Cases
- **Mathematical Problem Solving**: Where accuracy is critical
- **Decision Making**: When reliability is paramount
- **Validation Tasks**: When answers need verification
- **Complex Reasoning**: Multi-step problem solving
- **Research Questions**: Where multiple perspectives are valuable
## Technical Details
### Concurrent Execution
The agent uses `ThreadPoolExecutor` to generate multiple responses concurrently, improving performance while maintaining independence between reasoning paths.
### Aggregation Process
The aggregation uses an AI-powered agent that:
- Identifies dominant responses
- Analyzes disparities and disagreements
- Evaluates consensus strength
- Synthesizes minority insights
- Provides comprehensive recommendations
### Output Formats
The agent supports various output types:
- `"dict"`: Dictionary format with conversation history
- `"str"`: Simple string output
- `"list"`: List format
- `"json"`: JSON formatted output
## Limitations
1. **Computational Cost**: Higher `num_samples` increases processing time and cost
2. **Model Dependencies**: Performance depends on the underlying model capabilities
3. **Consensus Challenges**: May struggle with tasks where multiple valid approaches exist
4. **Memory Usage**: Concurrent execution requires more memory resources
## Best Practices
1. **Sample Size**: Use 3-7 samples for most tasks; increase for critical decisions
2. **Model Selection**: Choose models with strong reasoning capabilities
3. **Evaluation Mode**: Enable for tasks with known correct answers
4. **Custom Prompts**: Tailor majority voting prompts for specific domains
5. **Batch Processing**: Use `batched_run` for multiple related tasks
--- ---

@ -38,9 +38,13 @@ graph TD
| `max_loops` | int | 1 | Maximum number of reasoning loops | | `max_loops` | int | 1 | Maximum number of reasoning loops |
| `swarm_type` | agent_types | "reasoning_duo" | Type of reasoning swarm to use | | `swarm_type` | agent_types | "reasoning_duo" | Type of reasoning swarm to use |
| `num_samples` | int | 1 | Number of samples for self-consistency | | `num_samples` | int | 1 | Number of samples for self-consistency |
| `output_type` | OutputType | "dict" | Format of the output | | `output_type` | OutputType | "dict-all-except-first" | Format of the output |
| `num_knowledge_items` | int | 6 | Number of knowledge items for GKP agent | | `num_knowledge_items` | int | 6 | Number of knowledge items for GKP agent |
| `memory_capacity` | int | 6 | Memory capacity for agents that support it | | `memory_capacity` | int | 6 | Memory capacity for agents that support it |
| `eval` | bool | False | Enable evaluation mode for self-consistency |
| `random_models_on` | bool | False | Enable random model selection for diversity |
| `majority_voting_prompt` | Optional[str] | None | Custom prompt for majority voting |
| `reasoning_model_name` | Optional[str] | "claude-3-5-sonnet-20240620" | Model to use for reasoning in ReasoningDuo |
### Available Agent Types ### Available Agent Types
@ -71,12 +75,15 @@ graph TD
**Required Parameters** **Required Parameters**
- model_name (list of 2) - model_name
- system_prompt - system_prompt
**Optional Parameters** **Optional Parameters**
- output_type - output_type
- reasoning_model_name (default: "claude-3-5-sonnet-20240620")
- max_loops
- img (for image input support)
=== "Self Consistency" === "Self Consistency"
**Key Features** **Key Features**
@ -84,12 +91,16 @@ graph TD
- Multiple solution generation - Multiple solution generation
- Consensus building - Consensus building
- Solution verification - Solution verification
- Concurrent execution
- AI-powered aggregation
**Best Use Cases** **Best Use Cases**
- Tasks requiring high reliability - Tasks requiring high reliability
- Problems with multiple approaches - Problems with multiple approaches
- Validation-heavy tasks - Validation-heavy tasks
- Mathematical problem solving
- Decision making scenarios
**Required Parameters** **Required Parameters**
@ -98,9 +109,12 @@ graph TD
**Optional Parameters** **Optional Parameters**
- num_samples - num_samples (default: 5)
- max_loops - max_loops (default: 1)
- output_type - output_type (default: "dict")
- eval (default: False) - Enable answer validation
- random_models_on (default: False) - Enable model diversity
- majority_voting_prompt (default: None) - Custom aggregation prompt
=== "IRE" === "IRE"
**Key Features** **Key Features**
@ -200,8 +214,39 @@ graph TD
| Method | Description | | Method | Description |
|--------|-------------| |--------|-------------|
| `select_swarm()` | Selects and initializes the appropriate reasoning swarm based on specified type | | `select_swarm()` | Selects and initializes the appropriate reasoning swarm based on specified type |
| `run(task: str)` | Executes the selected swarm's reasoning process on the given task | | `run(task: str, img: Optional[str] = None, **kwargs)` | Executes the selected swarm's reasoning process on the given task |
| `batched_run(tasks: List[str])` | Executes the reasoning process on a batch of tasks | | `batched_run(tasks: List[str], imgs: Optional[List[str]] = None, **kwargs)` | Executes the reasoning process on a batch of tasks |
### Image Support
!!! info "Multi-modal Capabilities"
The ReasoningAgentRouter supports image inputs for compatible agent types:
**Supported Parameters:**
- `img` (str, optional): Path or URL to a single image file for single task execution
- `imgs` (List[str], optional): List of image paths/URLs for batch task execution
**Compatible Agent Types:**
- `reasoning-duo` / `reasoning-agent`: Full image support for both reasoning and execution phases
- Other agent types may have varying levels of image support depending on their underlying implementation
**Usage Example:**
```python
# Single image with task
router = ReasoningAgentRouter(swarm_type="reasoning-duo")
result = router.run(
task="Describe what you see in this image",
img="path/to/image.jpg"
)
# Batch processing with images
results = router.batched_run(
tasks=["Analyze this chart", "Describe this photo"],
imgs=["chart.png", "photo.jpg"]
)
```
### Code Examples ### Code Examples
@ -217,12 +262,47 @@ graph TD
system_prompt="You are a helpful assistant that can answer questions and help with tasks.", system_prompt="You are a helpful assistant that can answer questions and help with tasks.",
max_loops=1, max_loops=1,
swarm_type="self-consistency", swarm_type="self-consistency",
num_samples=1, num_samples=3,
output_type="list" eval=False,
random_models_on=False,
majority_voting_prompt=None
) )
# Run a single task # Run a single task
result = router.run("What is the best approach to solve this problem?") result = router.run("What is the best approach to solve this problem?")
# Run with image input
result_with_image = router.run(
"Analyze this image and provide insights",
img="path/to/image.jpg"
)
```
=== "Self-Consistency Examples"
```python
# Basic self-consistency
router = ReasoningAgentRouter(
swarm_type="self-consistency",
num_samples=3,
model_name="gpt-4o-mini"
)
# Self-consistency with evaluation mode
router = ReasoningAgentRouter(
swarm_type="self-consistency",
num_samples=5,
model_name="gpt-4o-mini",
eval=True,
random_models_on=True
)
# Self-consistency with custom majority voting
router = ReasoningAgentRouter(
swarm_type="self-consistency",
num_samples=3,
model_name="gpt-4o-mini",
majority_voting_prompt="Analyze the responses and provide the most accurate answer."
)
``` ```
=== "ReflexionAgent" === "ReflexionAgent"
@ -243,6 +323,29 @@ graph TD
) )
``` ```
=== "ReasoningDuo Examples"
```python
# Basic ReasoningDuo
router = ReasoningAgentRouter(
swarm_type="reasoning-duo",
model_name="gpt-4o-mini",
reasoning_model_name="claude-3-5-sonnet-20240620"
)
# ReasoningDuo with image support
router = ReasoningAgentRouter(
swarm_type="reasoning-duo",
model_name="gpt-4o-mini",
reasoning_model_name="gpt-4-vision-preview",
max_loops=2
)
result = router.run(
"Analyze this image and explain the patterns you see",
img="data_visualization.png"
)
```
=== "AgentJudge" === "AgentJudge"
```python ```python
router = ReasoningAgentRouter( router = ReasoningAgentRouter(
@ -265,10 +368,14 @@ graph TD
2. **Performance Optimization** 2. **Performance Optimization**
- Adjust max_loops based on task complexity - Adjust max_loops based on task complexity
- Increase num_samples for higher reliability - Increase num_samples for higher reliability (3-7 for most tasks)
- Choose appropriate model_name based on task requirements - Choose appropriate model_name based on task requirements
- Enable random_models_on for diverse reasoning approaches
- Use eval mode for validation tasks with known answers
3. **Output Handling** 3. **Output Handling**
- Use appropriate output_type for your needs - Use appropriate output_type for your needs
@ -276,6 +383,24 @@ graph TD
- Handle errors gracefully - Handle errors gracefully
4. **Self-Consistency Specific**
- Use 3-5 samples for most tasks, 7+ for critical decisions
- Enable eval mode when you have expected answers for validation
- Customize majority_voting_prompt for domain-specific aggregation
- Consider random_models_on for diverse model perspectives
5. **Multi-modal and Reasoning Configuration**
- Use vision-capable models when processing images (e.g., "gpt-4-vision-preview")
- For ReasoningDuo, set different models for reasoning vs execution via reasoning_model_name
- Ensure image paths are accessible and in supported formats (JPG, PNG, etc.)
- Consider using reasoning_model_name with specialized reasoning models for complex tasks
## Limitations ## Limitations
!!! warning "Known Limitations" !!! warning "Known Limitations"

@ -1,75 +1,149 @@
# Swarm Ecosystem # Swarms Ecosystem
Welcome to the Swarm Ecosystem, a comprehensive suite of tools and frameworks designed to empower developers to orhestrate swarms of autonomous agents for a variety of applications. Dive into our ecosystem below: *The Complete Enterprise-Grade Multi-Agent AI Platform*
[Full Github Link](https://github.com/kyegomez/swarm-ecosystem) ---
## **Join the Future of AI Development**
**We're Building the Operating System for the Agent Economy** - The Swarms ecosystem represents the most comprehensive, production-ready multi-agent AI platform available today. From our flagship Python framework to high-performance Rust implementations and client libraries spanning every major programming language, we provide enterprise-grade tools that power the next generation of intelligent applications.
---
## **Complete Product Portfolio**
| **Product** | **Technology** | **Status** | **Repository** | **Documentation** |
|-------------|---------------|------------|----------------|-------------------|
| **Swarms Python Framework** | Python | **Production** | [swarms](https://github.com/kyegomez/swarms) | [Docs](https://docs.swarms.world/en/latest/swarms/install/install/) |
| **Swarms Rust Framework** | Rust | **Production** | [swarms-rs](https://github.com/The-Swarm-Corporation/swarms-rs) | [Docs](https://docs.swarms.world/en/latest/swarms_rs/overview/) |
| **Python API Client** | Python | **Production** | [swarms-sdk](https://github.com/The-Swarm-Corporation/swarms-sdk) | [Docs](https://docs.swarms.world/en/latest/swarms_cloud/python_client/) |
| **TypeScript/Node.js Client** | TypeScript | **Production** | [swarms-ts](https://github.com/The-Swarm-Corporation/swarms-ts) | *Coming Soon* |
| **Go Client** | Go | **Production** | [swarms-client-go](https://github.com/The-Swarm-Corporation/swarms-client-go) | *Coming Soon* |
| **Java Client** | Java | **Production** | [swarms-java](https://github.com/The-Swarm-Corporation/swarms-java) | *Coming Soon* |
| **Kotlin Client** | Kotlin | **Q2 2025** | *In Development* | *Coming Soon* |
| **Ruby Client** | Ruby | **Q2 2025** | *In Development* | *Coming Soon* |
| **Rust Client** | Rust | **Q2 2025** | *In Development* | *Coming Soon* |
| **C#/.NET Client** | C# | **Q3 2025** | *In Development* | *Coming Soon* |
---
## **Why Choose the Swarms Ecosystem?**
### **Enterprise-Grade Architecture**
- **Production Ready**: Battle-tested in enterprise environments with 99.9%+ uptime
- **Scalable Infrastructure**: Handle millions of agent interactions with automatic scaling
- **Security First**: End-to-end encryption, API key management, and enterprise compliance
- **Observability**: Comprehensive logging, monitoring, and debugging capabilities
### **Developer Experience**
- **Multiple Language Support**: Native clients for every major programming language
## Getting Started - **Unified API**: Consistent interface across all platforms and languages
| Project | Description | Link | - **Rich Documentation**: Comprehensive guides, tutorials, and API references
| ------- | ----------- | ---- |
| **Swarms Framework** | A Python-based framework that enables the creation, deployment, and scaling of reliable swarms of autonomous agents aimed at automating complex workflows. | [Swarms Framework](https://github.com/kyegomez/swarms) |
| **Swarms Cloud** | A cloud-based service offering Swarms-as-a-Service with guaranteed 100% uptime, cutting-edge performance, and enterprise-grade reliability for seamless scaling and management of swarms. | [Swarms Cloud](https://github.com/kyegomez/swarms-cloud) |
| **Swarms Core** | Provides backend utilities focusing on concurrency, multi-threading, and advanced execution strategies, developed in Rust for maximum efficiency and performance. | [Swarms Core](https://github.com/kyegomez/swarms-core) |
| **Swarm Foundation Models** | A dedicated repository for the creation, optimization, and training of groundbreaking swarming models. Features innovative models like PSO with transformers, ant colony optimizations, and more, aiming to surpass traditional architectures like Transformers and SSMs. Open for community contributions and ideas. | [Swarm Foundation Models](https://github.com/kyegomez/swarms-pytorch) |
| **Swarm Platform** | The Swarms dashboard Platform | [Swarm Platform](https://github.com/kyegomez/swarms-platform) |
| **Swarms JS** | Swarms Framework in JS. Orchestrate any agents and enable multi-agent collaboration between various agents! | [Swarm JS](https://github.com/kyegomez/swarms-js) |
| **Swarms Memory** | Easy to use, reliable, and bleeding-edge RAG systems.! | [Swarm JS](https://github.com/kyegomez/swarms-memory) |
| **Swarms Evals** | Evaluating Swarms! | [Swarm JS](https://github.com/kyegomez/swarms-evals) |
| **Swarms Zero** | RPC Enterprise-Grade Automation Framework | [Swarm Zero]([https://github.com/kyegomez/swarms-evals](https://github.com/kyegomez/Zero)) |
---- - **Active Community**: 24/7 support through Discord, GitHub, and direct channels
## 🫶 Contributions: ### **Performance & Reliability**
The easiest way to contribute is to pick any issue with the `good first issue` tag 💪. Read the Contributing guidelines [here](/CONTRIBUTING.md). Bug Report? [File here](https://github.com/swarms/gateway/issues) | Feature Request? [File here](https://github.com/swarms/gateway/issues) - **High Throughput**: Process thousands of concurrent agent requests
Swarms is an open-source project, and contributions are VERY welcome. If you want to contribute, you can create new features, fix bugs, or improve the infrastructure. Please refer to the [CONTRIBUTING.md](https://github.com/kyegomez/swarms/blob/master/CONTRIBUTING.md) and our [contributing board](https://github.com/users/kyegomez/projects/1) to participate in Roadmap discussions! - **Low Latency**: Optimized for real-time applications and user experiences
<a href="https://github.com/kyegomez/swarms/graphs/contributors"> - **Fault Tolerance**: Automatic retries, circuit breakers, and graceful degradation
<img src="https://contrib.rocks/image?repo=kyegomez/swarms" />
</a>
<a href="https://github.com/kyegomez/swarms/graphs/contributors"> - **Multi-Cloud**: Deploy on AWS, GCP, Azure, or on-premises infrastructure
<img src="https://contrib.rocks/image?repo=kyegomez/swarms-cloud" />
</a>
<a href="https://github.com/kyegomez/swarms/graphs/contributors"> ---
<img src="https://contrib.rocks/image?repo=kyegomez/swarms-platform" />
</a> ## **Join Our Growing Community**
### **Connect With Developers Worldwide**
| **Platform** | **Purpose** | **Join Link** | **Benefits** |
|--------------|-------------|---------------|--------------|
| **Discord Community** | Real-time support & discussions | [Join Discord](https://discord.gg/jM3Z6M9uMq) | • 24/7 developer support<br/>• Weekly community events<br/>• Direct access to core team<br/>• Beta feature previews |
| **Twitter/X** | Latest updates & announcements | [Follow @swarms_corp](https://x.com/swarms_corp) | • Breaking news & updates<br/>• Community highlights<br/>• Technical insights<br/>• Industry partnerships |
| **LinkedIn** | Professional network & updates | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | • Professional networking<br/>• Career opportunities<br/>• Enterprise partnerships<br/>• Industry insights |
| **YouTube** | Tutorials & technical content | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | • In-depth tutorials<br/>• Live coding sessions<br/>• Architecture deep dives<br/>• Community showcases |
---
## **Contribute to the Ecosystem**
### **How You Can Make an Impact**
<a href="https://github.com/kyegomez/swarms/graphs/contributors"> | **Contribution Area** | **Skills Needed** | **Impact Level** | **Getting Started** |
<img src="https://contrib.rocks/image?repo=kyegomez/swarms-js" /> |-----------------------|-------------------|------------------|---------------------|
</a> | **Core Framework Development** | Python, Rust, Systems Design | **High Impact** | [Contributing Guide](https://docs.swarms.world/en/latest/contributors/main/) |
| **Client Library Development** | Various Languages (Go, Java, TS, etc.) | **High Impact** | [Client Development](https://github.com/The-Swarm-Corporation) |
| **Documentation & Tutorials** | Technical Writing, Examples | **High Impact** | [Docs Contributing](https://docs.swarms.world/en/latest/contributors/docs/) |
| **Testing & Quality Assurance** | Testing Frameworks, QA | **Medium Impact** | [Testing Guide](https://docs.swarms.world/en/latest/swarms/framework/test/) |
| **UI/UX & Design** | Design, Frontend Development | **Medium Impact** | [Design Contributions](https://github.com/The-Swarm-Corporation/swarms/issues) |
| **Bug Reports & Feature Requests** | User Experience, Testing | **Easy Start** | [Report Issues](https://github.com/The-Swarm-Corporation/swarms/issues) |
---
## **We're Hiring Top Talent**
### **Join the Team Building the Future Of The World Economy**
**Ready to work on cutting-edge agent technology that's shaping the future?** We're actively recruiting exceptional engineers, researchers, and technical leaders to join our mission of building the operating system for the agent economy.
---- | **Why Join Swarms?** | **What We Offer** |
|-----------------------|-------------------|
| **Cutting-Edge Technology** | Work on the most powerful multi-agent systems, distributed computing, and enterprise-scale infrastructure |
| **Global Impact** | Your code will power agent applications used by Fortune 500 companies and millions of developers |
| **World-Class Team** | Collaborate with top engineers, researchers, and industry experts from Google, OpenAI, and more |
| **Fast Growth** | Join a rapidly scaling company with massive market opportunity and venture backing |
## Community ### **Open Positions**
Join our growing community around the world, for real-time support, ideas, and discussions on Swarms 😊 | **Position** | **Role Description** |
|-------------------------------|----------------------------------------------------------|
| **Senior Rust Engineers** | Building high-performance agent infrastructure |
| **Python Framework Engineers**| Expanding our core multi-agent capabilities |
| **DevOps/Platform Engineers** | Scaling cloud infrastructure for millions of agents |
| **Technical Writers** | Creating world-class developer documentation |
| **Solutions Engineers** | Helping enterprises adopt multi-agent AI |
- View our official [Blog](https://docs.swarms.world) **Ready to Build the Future?** **[Apply Now at swarms.ai/hiring](https://swarms.ai/hiring)**
- Chat live with us on [Discord](https://discord.gg/kS3rwKs3ZC)
- Follow us on [Twitter](https://twitter.com/kyegomez) ---
- Connect with us on [LinkedIn](https://www.linkedin.com/company/the-swarm-corporation)
- Visit us on [YouTube](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ)
- [Join the Swarms community on Discord!](https://discord.gg/AJazBmhKnr)
- Join our Swarms Community Gathering every Thursday at 1pm NYC Time to unlock the potential of autonomous agents in automating your daily tasks [Sign up here](https://lu.ma/5p2jnc2v)
--- ---
## Discovery Call ## **Get Started Today**
Book a discovery call to learn how Swarms can lower your operating costs by 40% with swarms of autonomous agents in lightspeed. [Click here to book a time that works for you!](https://calendly.com/swarm-corp/30min?month=2023-11)
### **Quick Start Guide**
| **Step** | **Action** | **Time Required** |
|----------|------------|-------------------|
| **1** | [Install Swarms Python Framework](https://docs.swarms.world/en/latest/swarms/install/install/) | 5 minutes |
| **2** | [Run Your First Agent](https://docs.swarms.world/en/latest/swarms/examples/basic_agent/) | 10 minutes |
| **3** | [Try Multi-Agent Workflows](https://docs.swarms.world/en/latest/swarms/examples/sequential_example/) | 15 minutes |
| **4** | [Join Our Discord Community](https://discord.gg/jM3Z6M9uMq) | 2 minutes |
| **5** | [Explore Enterprise Features](https://docs.swarms.world/en/latest/swarms_cloud/swarms_api/) | 20 minutes |
## Accelerate Backlog ---
Help us accelerate our backlog by supporting us financially! Note, we're an open source corporation and so all the revenue we generate is through donations at the moment ;)
## **Enterprise Support & Partnerships**
<a href="https://polar.sh/kyegomez"><img src="https://polar.sh/embed/fund-our-backlog.svg?org=kyegomez" /></a> ### **Ready to Scale with Swarms?**
| **Contact Type** | **Best For** | **Response Time** | **Contact Information** |
|------------------|--------------|-------------------|-------------------------|
| **Technical Support** | Development questions, troubleshooting | < 24 hours | [Book Support Call](https://cal.com/swarms/swarms-technical-support) |
| **Enterprise Sales** | Custom deployments, enterprise licensing | < 4 hours | [kye@swarms.world](mailto:kye@swarms.world) |
| **Partnerships** | Integration partnerships, technology alliances | < 48 hours | [kye@swarms.world](mailto:kye@swarms.world) |
| **Investor Relations** | Investment opportunities, funding updates | By appointment | [kye@swarms.world](mailto:kye@swarms.world) |
--- ---
**Ready to build the future of AI? Start with Swarms today and join thousands of developers creating the next generation of intelligent applications.**

@ -0,0 +1,205 @@
# Agent Multi-Agent Communication Methods
The Agent class provides powerful built-in methods for facilitating communication and collaboration between multiple agents. These methods enable agents to talk to each other, pass information, and coordinate complex multi-agent workflows seamlessly.
## Overview
Multi-agent communication is essential for building sophisticated AI systems where different agents need to collaborate, share information, and coordinate their actions. The Agent class provides several methods to facilitate this communication:
| Method | Purpose | Use Case |
|--------|---------|----------|
| `talk_to` | Direct communication between two agents | Agent handoffs, expert consultation |
| `talk_to_multiple_agents` | Concurrent communication with multiple agents | Broadcasting, consensus building |
| `receive_message` | Process incoming messages from other agents | Message handling, task delegation |
| `send_agent_message` | Send formatted messages to other agents | Direct messaging, notifications |
## Features
| Feature | Description |
|---------------------------------|--------------------------------------------------------------------|
| **Direct Agent Communication** | Enable one-to-one conversations between agents |
| **Concurrent Multi-Agent Communication** | Broadcast messages to multiple agents simultaneously |
| **Message Processing** | Handle incoming messages with contextual formatting |
| **Error Handling** | Robust error handling for failed communications |
| **Threading Support** | Efficient concurrent processing using ThreadPoolExecutor |
| **Flexible Parameters** | Support for images, custom arguments, and kwargs |
---
## Core Methods
### `talk_to(agent, task, img=None, *args, **kwargs)`
Enables direct communication between the current agent and another agent. The method processes the task, generates a response, and then passes that response to the target agent.
**Parameters:**
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `agent` | `Any` | Required | The target agent instance to communicate with |
| `task` | `str` | Required | The task or message to send to the agent |
| `img` | `str` | `None` | Optional image path for multimodal communication |
| `*args` | `Any` | - | Additional positional arguments |
| `**kwargs` | `Any` | - | Additional keyword arguments |
**Returns:** `Any` - The response from the target agent
**Usage Example:**
```python
from swarms import Agent
# Create two specialized agents
researcher = Agent(
agent_name="Research-Agent",
system_prompt="You are a research specialist focused on gathering and analyzing information.",
max_loops=1,
)
analyst = Agent(
agent_name="Analysis-Agent",
system_prompt="You are an analytical specialist focused on interpreting research data.",
max_loops=1,
)
# Agent communication
research_result = researcher.talk_to(
agent=analyst,
task="Analyze the market trends for renewable energy stocks"
)
print(research_result)
```
### `talk_to_multiple_agents(agents, task, *args, **kwargs)`
Enables concurrent communication with multiple agents using ThreadPoolExecutor for efficient parallel processing.
**Parameters:**
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `agents` | `List[Union[Any, Callable]]` | Required | List of agent instances to communicate with |
| `task` | `str` | Required | The task or message to send to all agents |
| `*args` | `Any` | - | Additional positional arguments |
| `**kwargs` | `Any` | - | Additional keyword arguments |
**Returns:** `List[Any]` - List of responses from all agents (or None for failed communications)
**Usage Example:**
```python
from swarms import Agent
# Create multiple specialized agents
agents = [
Agent(
agent_name="Financial-Analyst",
system_prompt="You are a financial analysis expert.",
max_loops=1,
),
Agent(
agent_name="Risk-Assessor",
system_prompt="You are a risk assessment specialist.",
max_loops=1,
),
Agent(
agent_name="Market-Researcher",
system_prompt="You are a market research expert.",
max_loops=1,
)
]
coordinator = Agent(
agent_name="Coordinator-Agent",
system_prompt="You coordinate multi-agent analysis.",
max_loops=1,
)
# Broadcast to multiple agents
responses = coordinator.talk_to_multiple_agents(
agents=agents,
task="Evaluate the investment potential of Tesla stock"
)
# Process responses
for i, response in enumerate(responses):
if response:
print(f"Agent {i+1} Response: {response}")
else:
print(f"Agent {i+1} failed to respond")
```
### `receive_message(agent_name, task, *args, **kwargs)`
Processes incoming messages from other agents with proper context formatting.
**Parameters:**
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `agent_name` | `str` | Required | Name of the sending agent |
| `task` | `str` | Required | The message content |
| `*args` | `Any` | - | Additional positional arguments |
| `**kwargs` | `Any` | - | Additional keyword arguments |
**Returns:** `Any` - The agent's response to the received message
**Usage Example:**
```python
from swarms import Agent
# Create an agent that can receive messages
recipient_agent = Agent(
agent_name="Support-Agent",
system_prompt="You provide helpful support and assistance.",
max_loops=1,
)
# Simulate receiving a message from another agent
response = recipient_agent.receive_message(
agent_name="Customer-Service-Agent",
task="A customer is asking about refund policies. Can you help?"
)
print(response)
```
### `send_agent_message(agent_name, message, *args, **kwargs)`
Sends a formatted message from the current agent to a specified target agent.
**Parameters:**
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `agent_name` | `str` | Required | Name of the target agent |
| `message` | `str` | Required | The message to send |
| `*args` | `Any` | - | Additional positional arguments |
| `**kwargs` | `Any` | - | Additional keyword arguments |
**Returns:** `Any` - The result of sending the message
**Usage Example:**
```python
from swarms import Agent
sender_agent = Agent(
agent_name="Notification-Agent",
system_prompt="You send notifications and updates.",
max_loops=1,
)
# Send a message to another agent
result = sender_agent.send_agent_message(
agent_name="Task-Manager-Agent",
message="Task XYZ has been completed successfully"
)
print(result)
```
This comprehensive guide covers all aspects of multi-agent communication using the Agent class methods. These methods provide the foundation for building sophisticated multi-agent systems with robust communication capabilities.

@ -1,259 +1,801 @@
### Title: Building Custom Swarms with Multiple Agents: A Comprehensive Guide for Swarm Engineers # Building Custom Swarms: A Comprehensive Guide for Swarm Engineers
#### Introductio ## Introduction
As artificial intelligence and machine learning continue to grow in complexity and applicability, building systems that can harness multiple agents to solve complex tasks becomes more critical. Swarm engineering enables AI agents to collaborate and solve problems autonomously in diverse fields such as finance, marketing, operations, and even creative industries. In this guide, we'll focus on how to build a custom swarm system that integrates multiple agents into a cohesive system capable of solving tasks collaboratively.
The swarm we'll design will leverage Python, use types for better code structure, and feature logging with the powerful **loguru** logging library. We'll break down how to define and initialize swarms, make them scalable, and create methods like `run(task: str)` to trigger their execution. As artificial intelligence and machine learning continue to grow in complexity and applicability, building systems that can harness multiple agents to solve complex tasks becomes more critical. Swarm engineering enables AI agents to collaborate and solve problems autonomously in diverse fields such as finance, marketing, operations, and even creative industries.
By the end of this article, you will have a complete understanding of: This comprehensive guide covers how to build a custom swarm system that integrates multiple agents into a cohesive system capable of solving tasks collaboratively. We'll cover everything from basic swarm structure to advanced features like conversation management, logging, error handling, and scalability.
- What swarms are and how they can be built. By the end of this guide, you will have a complete understanding of:
- How to intake multiple agents using a flexible class. - What swarms are and how they can be built
- How to run tasks across agents and capture their outputs. - How to create agents and integrate them into swarms
- How to implement proper conversation management for message storage
- Best practices for error handling, logging, and optimization
- How to make swarms scalable and production-ready
- Best practices for error handling, logging, and optimization.
--- ---
### 1. Understanding the Concept of a Swarm ## Overview of Swarm Architecture
A **swarm** refers to a collection of agents that collaborate to solve a problem. Each agent in the swarm performs part of the task, either independently or by communicating with other agents. Swarms are ideal for: A **Swarm** refers to a collection of agents that collaborate to solve a problem. Each agent in the swarm performs part of the task, either independently or by communicating with other agents. Swarms are ideal for:
- **Scalability**: You can add or remove agents dynamically based on the task's complexity. - **Scalability**: You can add or remove agents dynamically based on the task's complexity
- **Flexibility**: Each agent can be designed to specialize in different parts of the problem, offering modularity. - **Flexibility**: Each agent can be designed to specialize in different parts of the problem, offering modularity
- **Autonomy**: Agents in a swarm can operate autonomously, reducing the need for constant supervision. - **Autonomy**: Agents in a swarm can operate autonomously, reducing the need for constant supervision
- **Conversation Management**: All interactions are tracked and stored for analysis and continuity
We'll be using Python as the primary programming language and will structure the swarm class using clean, reusable code principles.
--- ---
### 2. Designing the Swarm Class: Intake Multiple Agents ## Core Requirements for Swarm Classes
Every Swarm class must adhere to these fundamental requirements:
### Required Methods and Attributes
- **`run(task: str, img: str, *args, **kwargs)` method**: The primary execution method for tasks
- **`name`**: A descriptive name for the swarm
- **`description`**: A clear description of the swarm's purpose
- **`agents`**: A list of callables representing the agents
- **`conversation`**: A conversation structure for message storage and history management
We'll begin by creating a base class for our swarm. This class will intake multiple agents and define a `run` method, which is the core method for executing tasks across the swarm. Each agent is defined by its specific behavior or "intelligence" to complete part of the task.
#### 2.1 Importing the Required Libraries and Dependencies ### Required Agent Structure
We'll rely on the **loguru** logging library, Pydantic for metadata handling, and standard Python typing. Each Agent within the swarm must contain:
- **`agent_name`**: Unique identifier for the agent
- **`system_prompt`**: Instructions that guide the agent's behavior
- **`run` method**: Method to execute tasks assigned to the agent
---
## Setting Up the Foundation
### Required Dependencies
```python ```python
from typing import List, Union from typing import List, Union, Any, Optional, Callable
from loguru import logger from loguru import logger
from swarms.structs.base_swarm import BaseSwarm from swarms.structs.base_swarm import BaseSwarm
from swarms.structs.conversation import Conversation
from swarms.structs.agent import Agent
import concurrent.futures
import os
```
### Custom Exception Handling
```python
class SwarmExecutionError(Exception): class SwarmExecutionError(Exception):
"""Custom exception for handling swarm execution errors.""" """Custom exception for handling swarm execution errors."""
pass pass
class AgentValidationError(Exception):
"""Custom exception for agent validation errors."""
pass
``` ```
#### 2.2 Defining the Swarm Class ---
## Building the Custom Swarm Class
The class `CustomSwarm` will take in a list of agents. The agents will be instances of `BaseSwarm` (or callable functions). The `run(task: str)` method will delegate tasks to each agent in the swarm and handle any errors or retries. ### Basic Swarm Structure
```python ```python
class CustomSwarm: class CustomSwarm(BaseSwarm):
def __init__(self, agents: List[BaseSwarm]): """
A custom swarm class to manage and execute tasks with multiple agents.
This swarm integrates conversation management for tracking all agent interactions,
provides error handling, and supports both sequential and concurrent execution.
Attributes:
name (str): The name of the swarm.
description (str): A brief description of the swarm's purpose.
agents (List[Callable]): A list of callables representing the agents.
conversation (Conversation): Conversation management for message storage.
max_workers (int): Maximum number of concurrent workers for parallel execution.
autosave_conversation (bool): Whether to automatically save conversation history.
"""
def __init__(
self,
name: str,
description: str,
agents: List[Callable],
max_workers: int = 4,
autosave_conversation: bool = True,
conversation_config: Optional[dict] = None,
):
""" """
Initializes the CustomSwarm with a list of agents. Initialize the CustomSwarm with its name, description, and agents.
Args: Args:
agents (List[BaseSwarm]): A list of agent objects that inherit from BaseSwarm. name (str): The name of the swarm.
description (str): A description of the swarm.
agents (List[Callable]): A list of callables that provide the agents for the swarm.
max_workers (int): Maximum number of concurrent workers.
autosave_conversation (bool): Whether to automatically save conversations.
conversation_config (dict): Configuration for conversation management.
""" """
super().__init__(name=name, description=description, agents=agents)
self.name = name
self.description = description
self.agents = agents self.agents = agents
self.max_workers = max_workers
self.autosave_conversation = autosave_conversation
# Initialize conversation management
# See: https://docs.swarms.world/swarms/structs/conversation/
conversation_config = conversation_config or {}
self.conversation = Conversation(
id=f"swarm_{name}_{int(time.time())}",
name=f"{name}_conversation",
autosave=autosave_conversation,
save_enabled=True,
time_enabled=True,
**conversation_config
)
# Validate agents and log initialization
self.validate_agents() self.validate_agents()
logger.info(f"🚀 CustomSwarm '{self.name}' initialized with {len(self.agents)} agents")
# Add swarm initialization to conversation history
self.conversation.add(
role="System",
content=f"Swarm '{self.name}' initialized with {len(self.agents)} agents: {[getattr(agent, 'agent_name', 'Unknown') for agent in self.agents]}"
)
def validate_agents(self): def validate_agents(self):
"""Validates that each agent has a 'run' method.""" """
for agent in self.agents: Validates that each agent has the required methods and attributes.
if not hasattr(agent, 'run'):
raise AttributeError(f"Agent {agent} does not have a 'run' method.")
logger.info(f"Agent {agent} validated successfully.")
def run(self, task: str): Raises:
AgentValidationError: If any agent fails validation.
""" """
Runs the task across all agents in the swarm. for i, agent in enumerate(self.agents):
# Check for required run method
if not hasattr(agent, 'run'):
raise AgentValidationError(f"Agent at index {i} does not have a 'run' method.")
Args: # Check for agent_name attribute
task (str): The task to pass to each agent. if not hasattr(agent, 'agent_name'):
logger.warning(f"Agent at index {i} does not have 'agent_name' attribute. Using 'Agent_{i}'")
agent.agent_name = f"Agent_{i}"
logger.info(f"✅ Agent '{agent.agent_name}' validated successfully.")
def run(self, task: str, img: str = None, *args: Any, **kwargs: Any) -> Any:
""" """
logger.info(f"Running task '{task}' across all agents in the swarm.") Execute a task using the swarm and its agents with conversation tracking.
for agent in self.agents:
try:
agent.run(task)
logger.info(f"Agent {agent} successfully completed the task.")
except Exception as e:
logger.error(f"Agent {agent} failed to run task: {e}")
raise SwarmExecutionError(f"Execution failed for {agent}. Task: {task}")
```
### 3. Adding Logging and Error Handling with `loguru` Args:
task (str): The task description.
img (str): The image input (optional).
*args: Additional positional arguments for customization.
**kwargs: Additional keyword arguments for fine-tuning behavior.
Logging is crucial for production-grade systems, especially when managing complex tasks that involve multiple agents. **Loguru** is a simple and efficient logging library that allows us to log everything from information messages to errors. Returns:
Any: The result of the task execution, aggregated from all agents.
"""
logger.info(f"🎯 Running task '{task}' across {len(self.agents)} agents in swarm '{self.name}'")
# Add task to conversation history
self.conversation.add(
role="User",
content=f"Task: {task}" + (f" | Image: {img}" if img else ""),
category="input"
)
try:
# Execute task across all agents
results = self._execute_agents(task, img, *args, **kwargs)
# Add results to conversation
self.conversation.add(
role="Swarm",
content=f"Task completed successfully. Processed by {len(results)} agents.",
category="output"
)
logger.success(f"✅ Task completed successfully by swarm '{self.name}'")
return results
except Exception as e:
error_msg = f"❌ Task execution failed in swarm '{self.name}': {str(e)}"
logger.error(error_msg)
# Add error to conversation
self.conversation.add(
role="System",
content=f"Error: {error_msg}",
category="error"
)
raise SwarmExecutionError(error_msg)
def _execute_agents(self, task: str, img: str = None, *args, **kwargs) -> List[Any]:
"""
Execute the task across all agents with proper conversation tracking.
```python Args:
from loguru import logger task (str): The task to execute.
img (str): Optional image input.
class CustomSwarm: Returns:
def __init__(self, agents: List[BaseSwarm]): List[Any]: Results from all agents.
self.agents = agents """
logger.info("CustomSwarm initialized with agents.") results = []
self.validate_agents()
def run(self, task: str):
logger.info(f"Task received: {task}")
for agent in self.agents: for agent in self.agents:
try: try:
agent.run(task) # Execute agent task
logger.success(f"Agent {agent} completed task successfully.") result = agent.run(task, img, *args, **kwargs)
except Exception as e: results.append(result)
logger.error(f"Error while running task '{task}' for {agent}: {e}")
raise SwarmExecutionError(f"Execution failed for {agent}")
```
### 4. Running Tasks Across Multiple Agents # Add agent response to conversation
self.conversation.add(
role=agent.agent_name,
content=result,
category="agent_output"
)
The `run(task: str)` method will handle distributing the task to each agent in the swarm. Each agents `run` method is expected to take a task as input and perform its specific logic. We can add further customization by allowing each agent to return output, which can be collected for later analysis. logger.info(f"✅ Agent '{agent.agent_name}' completed task successfully")
#### 4.1 Example of Integrating Agents except Exception as e:
error_msg = f"Agent '{agent.agent_name}' failed: {str(e)}"
logger.error(error_msg)
Let's take a look at how we can define agents using the `BaseSwarm` class and integrate them into the swarm. # Add agent error to conversation
self.conversation.add(
role=agent.agent_name,
content=f"Error: {error_msg}",
category="agent_error"
)
```python # Continue with other agents but log the failure
class FinancialAgent(BaseSwarm): results.append(f"FAILED: {error_msg}")
def run(self, task: str):
logger.info(f"FinancialAgent processing task: {task}") return results
# Custom logic for financial analysis
return f"FinancialAgent response to task: {task}"
class MarketingAgent(BaseSwarm):
def run(self, task: str):
logger.info(f"MarketingAgent processing task: {task}")
# Custom logic for marketing analysis
return f"MarketingAgent response to task: {task}"
``` ```
Now, we initialize the swarm with these agents: ### Enhanced Swarm with Concurrent Execution
```python ```python
if __name__ == "__main__": def run_concurrent(self, task: str, img: str = None, *args: Any, **kwargs: Any) -> List[Any]:
agents = [FinancialAgent(), MarketingAgent()] """
swarm = CustomSwarm(agents) Execute a task using concurrent execution for better performance.
swarm.run("Analyze Q3 financial report and marketing impact.")
```
### 5. Enhancing the Swarm with Concurrent Execution
When dealing with large or time-consuming tasks, running agents concurrently (in parallel) can significantly improve performance. We can achieve this by utilizing Pythons **concurrent.futures** or **threading** libraries. Args:
task (str): The task description.
img (str): The image input (optional).
*args: Additional positional arguments.
**kwargs: Additional keyword arguments.
#### 5.1 Running Swarms Concurrently Returns:
List[Any]: Results from all agents executed concurrently.
"""
logger.info(f"🚀 Running task concurrently across {len(self.agents)} agents")
# Add task to conversation
self.conversation.add(
role="User",
content=f"Concurrent Task: {task}" + (f" | Image: {img}" if img else ""),
category="input"
)
results = []
with concurrent.futures.ThreadPoolExecutor(max_workers=self.max_workers) as executor:
# Submit all agent tasks
future_to_agent = {
executor.submit(self._run_single_agent, agent, task, img, *args, **kwargs): agent
for agent in self.agents
}
# Collect results as they complete
for future in concurrent.futures.as_completed(future_to_agent):
agent = future_to_agent[future]
try:
result = future.result()
results.append(result)
```python # Add to conversation
from concurrent.futures import ThreadPoolExecutor, as_completed self.conversation.add(
role=agent.agent_name,
content=result,
category="agent_output"
)
class CustomSwarm: except Exception as e:
def __init__(self, agents: List[BaseSwarm], max_workers: int = 4): error_msg = f"Concurrent execution failed for agent '{agent.agent_name}': {str(e)}"
self.agents = agents logger.error(error_msg)
self.thread_pool = ThreadPoolExecutor(max_workers=max_workers) results.append(f"FAILED: {error_msg}")
logger.info("CustomSwarm initialized with concurrent execution.")
# Add error to conversation
self.conversation.add(
role=agent.agent_name,
content=f"Error: {error_msg}",
category="agent_error"
)
# Add completion summary
self.conversation.add(
role="Swarm",
content=f"Concurrent task completed. {len(results)} agents processed.",
category="output"
)
return results
def _run_single_agent(self, agent: Callable, task: str, img: str = None, *args, **kwargs) -> Any:
"""
Execute a single agent with error handling.
def run(self, task: str): Args:
futures = [] agent: The agent to execute.
for agent in self.agents: task (str): The task to execute.
futures.append(self.thread_pool.submit(agent.run, task)) img (str): Optional image input.
for future in as_completed(futures): Returns:
result = future.result() Any: The agent's result.
logger.info(f"Agent result: {result}") """
try:
return agent.run(task, img, *args, **kwargs)
except Exception as e:
logger.error(f"Agent '{getattr(agent, 'agent_name', 'Unknown')}' execution failed: {str(e)}")
raise
``` ```
### 6. Advanced Error Handling and Retries ### Advanced Features
In a production system, agents might fail due to a wide range of reasons (network errors, API rate limits, etc.). To ensure resilience, we can add retry mechanisms and even fallback agents that attempt to recover the failed task.
```python ```python
class CustomSwarm: def run_with_retries(self, task: str, img: str = None, retries: int = 3, *args, **kwargs) -> List[Any]:
def run_with_retries(self, task: str, retries: int = 3):
""" """
Runs the task across all agents with retry logic. Execute a task with retry logic for failed agents.
Args: Args:
task (str): The task to run. task (str): The task to execute.
retries (int): Number of retries allowed for failed agents. img (str): Optional image input.
retries (int): Number of retries for failed agents.
Returns:
List[Any]: Results from all agents with retry attempts.
""" """
logger.info(f"🔄 Running task with {retries} retries per agent")
# Add task to conversation
self.conversation.add(
role="User",
content=f"Task with retries ({retries}): {task}",
category="input"
)
results = []
for agent in self.agents: for agent in self.agents:
attempt = 0 attempt = 0
while attempt <= retries: success = False
while attempt <= retries and not success:
try: try:
agent.run(task) result = agent.run(task, img, *args, **kwargs)
logger.success(f"Agent {agent} completed task.") results.append(result)
break success = True
# Add successful result to conversation
self.conversation.add(
role=agent.agent_name,
content=result,
category="agent_output"
)
if attempt > 0:
logger.success(f"✅ Agent '{agent.agent_name}' succeeded on attempt {attempt + 1}")
except Exception as e: except Exception as e:
logger.error(f"Agent {agent} failed on attempt {attempt + 1}. Error: {e}")
attempt += 1 attempt += 1
error_msg = f"Agent '{agent.agent_name}' failed on attempt {attempt}: {str(e)}"
logger.warning(error_msg)
# Add retry attempt to conversation
self.conversation.add(
role=agent.agent_name,
content=f"Retry attempt {attempt}: {error_msg}",
category="agent_retry"
)
if attempt > retries: if attempt > retries:
logger.error(f"Agent {agent} exhausted retries. Task failed.") final_error = f"Agent '{agent.agent_name}' exhausted all {retries} retries"
logger.error(final_error)
results.append(f"FAILED: {final_error}")
# Add final failure to conversation
self.conversation.add(
role=agent.agent_name,
content=final_error,
category="agent_error"
)
return results
def get_conversation_summary(self) -> dict:
"""
Get a summary of the conversation history and agent performance.
Returns:
dict: Summary of conversation statistics and agent performance.
"""
# Get conversation statistics
message_counts = self.conversation.count_messages_by_role()
# Count categories
category_counts = {}
for message in self.conversation.conversation_history:
category = message.get("category", "uncategorized")
category_counts[category] = category_counts.get(category, 0) + 1
# Get token counts if available
token_summary = self.conversation.export_and_count_categories()
return {
"swarm_name": self.name,
"total_messages": len(self.conversation.conversation_history),
"messages_by_role": message_counts,
"messages_by_category": category_counts,
"token_summary": token_summary,
"conversation_id": self.conversation.id,
}
def export_conversation(self, filepath: str = None) -> str:
"""
Export the conversation history to a file.
Args:
filepath (str): Optional custom filepath for export.
Returns:
str: The filepath where the conversation was saved.
"""
if filepath is None:
filepath = f"conversations/{self.name}_{self.conversation.id}.json"
self.conversation.export_conversation(filepath)
logger.info(f"📄 Conversation exported to: {filepath}")
return filepath
def display_conversation(self, detailed: bool = True):
"""
Display the conversation history in a formatted way.
Args:
detailed (bool): Whether to show detailed information.
"""
logger.info(f"💬 Displaying conversation for swarm: {self.name}")
self.conversation.display_conversation(detailed=detailed)
``` ```
### 7. Adding Documentation with Docstrings ---
## Creating Agents for Your Swarm
Clear and concise documentation is critical, especially for engineers maintaining and scaling the system. Using Pythons docstrings, we can document each class and method, describing what they do and their expected inputs/outputs. ### Basic Agent Structure
```python ```python
class CustomSwarm: class CustomAgent:
""" """
A class to manage and execute tasks using a swarm of agents. A custom agent class that integrates with the swarm conversation system.
Attributes: Attributes:
agents (List[BaseSwarm]): A list of agent instances. agent_name (str): The name of the agent.
system_prompt (str): The system prompt guiding the agent's behavior.
Methods: conversation (Optional[Conversation]): Shared conversation for context.
run(task: str): Runs a task across all agents in the swarm.
validate_agents(): Validates that each agent has a run method.
run_with_retries(task: str, retries: int): Runs the task with retry logic.
""" """
def __init__(self, agents: List[BaseSwarm]): def __init__(
self,
agent_name: str,
system_prompt: str,
conversation: Optional[Conversation] = None
):
""" """
Initializes the CustomSwarm with a list of agents. Initialize the agent with its name and system prompt.
Args: Args:
agents (List[BaseSwarm]): A list of agent objects that inherit from BaseSwarm. agent_name (str): The name of the agent.
system_prompt (str): The guiding prompt for the agent.
conversation (Optional[Conversation]): Shared conversation context.
""" """
self.agents = agents self.agent_name = agent_name
self.system_prompt = system_prompt
self.conversation = conversation
def run(self, task: str): def run(self, task: str, img: str = None, *args: Any, **kwargs: Any) -> Any:
""" """
Runs the task across all agents in the swarm. Execute a specific task assigned to the agent.
Args: Args:
task (str): The task to pass to each agent. task (str): The task description.
img (str): The image input for processing.
*args: Additional positional arguments.
**kwargs: Additional keyword arguments.
Returns:
Any: The result of the task execution.
""" """
pass # Add context from shared conversation if available
context = ""
if self.conversation:
context = f"Previous context: {self.conversation.get_last_message_as_string()}\n\n"
def validate_agents(self): # Process the task (implement your custom logic here)
"""Validates that each agent has a 'run' method.""" result = f"Agent {self.agent_name} processed: {context}{task}"
pass
logger.info(f"🤖 Agent '{self.agent_name}' completed task")
return result
```
### Using Swarms Framework Agents
You can also use the built-in Agent class from the Swarms framework:
```python
from swarms.structs.agent import Agent
def create_financial_agent() -> Agent:
"""Create a financial analysis agent."""
return Agent(
agent_name="FinancialAnalyst",
system_prompt="You are a financial analyst specializing in market analysis and risk assessment.",
model_name="gpt-4o-mini",
max_loops=1,
)
def create_marketing_agent() -> Agent:
"""Create a marketing analysis agent."""
return Agent(
agent_name="MarketingSpecialist",
system_prompt="You are a marketing specialist focused on campaign analysis and customer insights.",
model_name="gpt-4o-mini",
max_loops=1,
)
```
---
## Complete Implementation Example
### Setting Up Your Swarm
```python
import time
from typing import List
def create_multi_domain_swarm() -> CustomSwarm:
"""
Create a comprehensive multi-domain analysis swarm.
Returns:
CustomSwarm: A configured swarm with multiple specialized agents.
"""
# Create agents
agents = [
create_financial_agent(),
create_marketing_agent(),
Agent(
agent_name="OperationsAnalyst",
system_prompt="You are an operations analyst specializing in process optimization and efficiency.",
model_name="gpt-4o-mini",
max_loops=1,
),
]
# Configure conversation settings
conversation_config = {
"backend": "sqlite", # Use SQLite for persistent storage
"db_path": f"conversations/swarm_conversations.db",
"time_enabled": True,
"token_count": True,
}
# Create the swarm
swarm = CustomSwarm(
name="MultiDomainAnalysisSwarm",
description="A comprehensive swarm for financial, marketing, and operations analysis",
agents=agents,
max_workers=3,
autosave_conversation=True,
conversation_config=conversation_config,
)
return swarm
# Usage example
if __name__ == "__main__":
# Create and initialize the swarm
swarm = create_multi_domain_swarm()
# Execute a complex analysis task
task = """
Analyze the Q3 2024 performance data for our company:
- Revenue: $2.5M (up 15% from Q2)
- Customer acquisition: 1,200 new customers
- Marketing spend: $150K
- Operational costs: $800K
Provide insights from financial, marketing, and operations perspectives.
"""
# Run the analysis
results = swarm.run(task)
# Display results
print("\n" + "="*50)
print("SWARM ANALYSIS RESULTS")
print("="*50)
for i, result in enumerate(results):
agent_name = swarm.agents[i].agent_name
print(f"\n🤖 {agent_name}:")
print(f"📊 {result}")
# Get conversation summary
summary = swarm.get_conversation_summary()
print(f"\n📈 Conversation Summary:")
print(f" Total messages: {summary['total_messages']}")
print(f" Total tokens: {summary['token_summary']['total_tokens']}")
# Export conversation for later analysis
export_path = swarm.export_conversation()
print(f"💾 Conversation saved to: {export_path}")
```
### Advanced Usage with Concurrent Execution
```python
def run_batch_analysis():
"""Example of running multiple tasks concurrently."""
swarm = create_multi_domain_swarm()
tasks = [
"Analyze Q1 financial performance",
"Evaluate marketing campaign effectiveness",
"Review operational efficiency metrics",
"Assess customer satisfaction trends",
]
# Process all tasks concurrently
all_results = []
for task in tasks:
results = swarm.run_concurrent(task)
all_results.append({"task": task, "results": results})
return all_results
```
---
## Conversation Management Integration
The swarm uses the Swarms framework's [Conversation structure](../conversation/) for comprehensive message storage and management. This provides:
### Key Features
- **Persistent Storage**: Multiple backend options (SQLite, Redis, Supabase, etc.)
- **Message Categorization**: Organize messages by type (input, output, error, etc.)
- **Token Tracking**: Monitor token usage across conversations
- **Export/Import**: Save and load conversation histories
- **Search Capabilities**: Find specific messages or content
### Conversation Configuration Options
```python
conversation_config = {
# Backend storage options
"backend": "sqlite", # or "redis", "supabase", "duckdb", "in-memory"
# File-based storage
"db_path": "conversations/swarm_data.db",
# Redis configuration (if using Redis backend)
"redis_host": "localhost",
"redis_port": 6379,
# Features
"time_enabled": True, # Add timestamps to messages
"token_count": True, # Track token usage
"autosave": True, # Automatically save conversations
"save_enabled": True, # Enable saving functionality
}
``` ```
` ### Accessing Conversation Data
```python
# Get conversation history
history = swarm.conversation.return_history_as_string()
# Search for specific content
financial_messages = swarm.conversation.search("financial")
# Export conversation data
swarm.conversation.export_conversation("analysis_session.json")
# Get conversation statistics
stats = swarm.conversation.count_messages_by_role()
token_usage = swarm.conversation.export_and_count_categories()
```
For complete documentation on conversation management, see the [Conversation Structure Documentation](../conversation/).
---
## Conclusion
Building custom swarms with proper conversation management enables you to create powerful, scalable, and maintainable multi-agent systems. The integration with the Swarms framework's conversation structure provides:
- **Complete audit trail** of all agent interactions
- **Persistent storage** options for different deployment scenarios
- **Performance monitoring** through token and message tracking
- **Easy debugging** with searchable conversation history
### Conclusion - **Scalable architecture** that grows with your needs
Building custom swarms that intake multiple agents can drastically improve the scalability, efficiency, and flexibility of AI-driven systems. By designing a robust swarm class that manages agents, distributes tasks, and ensures error resilience, you can handle complex, multi-agent workloads efficiently.
In this Guide, we've covered: By following the patterns and best practices outlined in this guide, you can create robust swarms that handle complex tasks efficiently while maintaining full visibility into their operations.
### Key Takeaways
1. **Always implement conversation management** for tracking and auditing
2. **Use proper error handling and retries** for production resilience
3. **Implement monitoring and logging** for observability
4. **Design for scalability** with concurrent execution patterns
5. **Test thoroughly** with unit tests and integration tests
6. **Configure appropriately** for your deployment environment
For more advanced patterns and examples, explore the [Swarms Examples](../../examples/) and consider contributing your custom swarms back to the community by submitting a pull request to the [Swarms repository](https://github.com/kyegomez/swarms).
---
- Designing a basic swarm class. ## Additional Resources
- Running tasks across multiple agents. - [Conversation Structure Documentation](../conversation/) - Complete guide to conversation management
- Leveraging logging, error handling, retries, and concurrency. - [Agent Documentation](../../agents/) - Learn about creating and configuring agents
- Documenting your class for future-proofing. - [Multi-Agent Architectures](../overview/) - Explore other swarm patterns and architectures
This approach sets the foundation for building more advanced and domain-specific swarms in areas like finance, marketing, operations, and beyond. Swarm engineers can now explore more complex, multi-agent systems and push the boundaries of AI collaboration. - [Examples Repository](../../examples/) - Real-world swarm implementations
Stay tuned for future updates on more advanced swarm functionalities! - [Swarms Framework GitHub](https://github.com/kyegomez/swarms) - Source code and contributions

@ -0,0 +1,322 @@
# HeavySwarm Documentation
HeavySwarm is a sophisticated multi-agent orchestration system that decomposes complex tasks into specialized questions and executes them using four specialized agents: Research, Analysis, Alternatives, and Verification. The results are then synthesized into a comprehensive response.
Inspired by X.AI's Grok 4 heavy implementation, HeavySwarm provides robust task analysis through intelligent question generation, parallel execution, and comprehensive synthesis with real-time progress monitoring.
## Architecture
### System Design
The HeavySwarm follows a structured 5-phase workflow:
1. **Task Decomposition**: Complex tasks are broken down into specialized questions
2. **Question Generation**: AI-powered generation of role-specific questions
3. **Parallel Execution**: Four specialized agents work concurrently
4. **Result Collection**: Outputs are gathered and validated
5. **Synthesis**: Integration into a comprehensive final response
### Agent Specialization
- **Research Agent**: Comprehensive information gathering and synthesis
- **Analysis Agent**: Pattern recognition and statistical analysis
- **Alternatives Agent**: Creative problem-solving and strategic options
- **Verification Agent**: Validation, feasibility assessment, and quality assurance
- **Synthesis Agent**: Multi-perspective integration and executive reporting
## Architecture Diagram
```mermaid
graph TB
subgraph "HeavySwarm Architecture"
A[Input Task] --> B[Question Generation Agent]
B --> C[Task Decomposition]
C --> D[Research Agent]
C --> E[Analysis Agent]
C --> F[Alternatives Agent]
C --> G[Verification Agent]
D --> H[Parallel Execution Engine]
E --> H
F --> H
G --> H
H --> I[Result Collection]
I --> J[Synthesis Agent]
J --> K[Comprehensive Report]
subgraph "Monitoring & Control"
L[Rich Dashboard]
M[Progress Tracking]
N[Error Handling]
O[Timeout Management]
end
H --> L
H --> M
H --> N
H --> O
end
subgraph "Agent Specializations"
D --> D1[Information Gathering<br/>Market Research<br/>Data Collection]
E --> E1[Statistical Analysis<br/>Pattern Recognition<br/>Predictive Modeling]
F --> F1[Creative Solutions<br/>Strategic Options<br/>Innovation Ideation]
G --> G1[Fact Checking<br/>Feasibility Assessment<br/>Quality Assurance]
end
style A fill:#ff6b6b
style K fill:#4ecdc4
style H fill:#45b7d1
style J fill:#96ceb4
```
## Installation
```bash
pip install swarms
```
## Quick Start
```python
from swarms import HeavySwarm
# Initialize the swarm
swarm = HeavySwarm(
name="MarketAnalysisSwarm",
description="Financial market analysis swarm",
question_agent_model_name="gpt-4o-mini",
worker_model_name="gpt-4o-mini",
show_dashboard=True,
verbose=True
)
# Execute analysis
result = swarm.run("Analyze the current cryptocurrency market trends and investment opportunities")
print(result)
```
## API Reference
### HeavySwarm Class
#### Constructor Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `name` | `str` | `"HeavySwarm"` | Identifier name for the swarm instance |
| `description` | `str` | `"A swarm of agents..."` | Description of the swarm's purpose |
| `agents` | `List[Agent]` | `None` | Pre-configured agent list (unused - agents created internally) |
| `timeout` | `int` | `300` | Maximum execution time per agent in seconds |
| `aggregation_strategy` | `str` | `"synthesis"` | Strategy for result aggregation |
| `loops_per_agent` | `int` | `1` | Number of execution loops per agent |
| `question_agent_model_name` | `str` | `"gpt-4o-mini"` | Model for question generation |
| `worker_model_name` | `str` | `"gpt-4o-mini"` | Model for specialized worker agents |
| `verbose` | `bool` | `False` | Enable detailed logging output |
| `max_workers` | `int` | `int(os.cpu_count() * 0.9)` | Maximum concurrent workers |
| `show_dashboard` | `bool` | `False` | Enable rich dashboard visualization |
| `agent_prints_on` | `bool` | `False` | Enable individual agent output printing |
#### Methods
##### `run(task: str, img: str = None) -> str`
Execute the complete HeavySwarm orchestration flow.
**Parameters:**
- `task` (str): The main task to analyze and decompose
- `img` (str, optional): Image input for visual analysis tasks
**Returns:**
- `str`: Comprehensive final analysis from synthesis agent
**Example:**
```python
result = swarm.run("Develop a go-to-market strategy for a new SaaS product")
```
## Real-World Applications
### Financial Services
```python
# Market Analysis
swarm = HeavySwarm(
name="FinanceSwarm",
worker_model_name="gpt-4o",
show_dashboard=True
)
result = swarm.run("""
Analyze the impact of recent Federal Reserve policy changes on:
1. Bond markets and yield curves
2. Equity market valuations
3. Currency exchange rates
4. Provide investment recommendations for institutional portfolios
""")
```
### Use-cases
| Use Case | Description |
|---------------------------------------------|---------------------------------------------|
| Portfolio optimization and risk assessment | Optimize asset allocation and assess risks |
| Market trend analysis and forecasting | Analyze and predict market movements |
| Regulatory compliance evaluation | Evaluate adherence to financial regulations |
| Investment strategy development | Develop and refine investment strategies |
| Credit risk analysis and modeling | Analyze and model credit risk |
-------
### Healthcare & Life Sciences
```python
# Clinical Research Analysis
swarm = HeavySwarm(
name="HealthcareSwarm",
worker_model_name="gpt-4o",
timeout=600,
loops_per_agent=2
)
result = swarm.run("""
Evaluate the potential of AI-driven personalized medicine:
1. Current technological capabilities and limitations
2. Regulatory landscape and approval pathways
3. Market opportunities and competitive analysis
4. Implementation strategies for healthcare systems
""")
```
----
**Use Cases:**
| Use Case | Description |
|----------------------------------------|---------------------------------------------|
| Drug discovery and development analysis| Analyze and accelerate drug R&D processes |
| Clinical trial optimization | Improve design and efficiency of trials |
| Healthcare policy evaluation | Assess and inform healthcare policies |
| Medical device market analysis | Evaluate trends and opportunities in devices|
| Patient outcome prediction modeling | Predict and model patient health outcomes |
---
### Technology & Innovation
```python
# Tech Strategy Analysis
swarm = HeavySwarm(
name="TechSwarm",
worker_model_name="gpt-4o",
show_dashboard=True,
verbose=True
)
result = swarm.run("""
Assess the strategic implications of quantum computing adoption:
1. Technical readiness and hardware developments
2. Industry applications and use cases
3. Competitive landscape and key players
4. Investment and implementation roadmap
""")
```
**Use Cases:**
| Use Case | Description |
|------------------------------------|---------------------------------------------|
| Technology roadmap development | Plan and prioritize technology initiatives |
| Competitive intelligence gathering | Analyze competitors and market trends |
| Innovation pipeline analysis | Evaluate and manage innovation projects |
| Digital transformation strategy | Develop and implement digital strategies |
| Emerging technology assessment | Assess new and disruptive technologies |
### Manufacturing & Supply Chain
```python
# Supply Chain Optimization
swarm = HeavySwarm(
name="ManufacturingSwarm",
worker_model_name="gpt-4o",
max_workers=8
)
result = swarm.run("""
Optimize global supply chain resilience:
1. Risk assessment and vulnerability analysis
2. Alternative sourcing strategies
3. Technology integration opportunities
4. Cost-benefit analysis of proposed changes
""")
```
**Use Cases:**
| Use Case | Description |
|----------------------------------|---------------------------------------------|
| Supply chain risk management | Identify and mitigate supply chain risks |
| Manufacturing process optimization | Improve efficiency and productivity |
| Quality control system design | Develop systems to ensure product quality |
| Sustainability impact assessment | Evaluate environmental and social impacts |
| Logistics network optimization | Enhance logistics and distribution networks |
## Advanced Configuration
### Custom Agent Configuration
```python
# High-performance configuration
swarm = HeavySwarm(
name="HighPerformanceSwarm",
question_agent_model_name="gpt-4o",
worker_model_name="gpt-4o",
timeout=900,
loops_per_agent=3,
max_workers=12,
show_dashboard=True,
verbose=True
)
```
## Troubleshooting
| Issue | Solution |
|-------------------------|---------------------------------------------------------------|
| **Agent Timeout** | Increase timeout parameter or reduce task complexity |
| **Model Rate Limits** | Implement backoff strategies or use different models |
| **Memory Usage** | Monitor system resources with large-scale operations |
| **Dashboard Performance** | Disable dashboard for batch processing |
## Contributing
HeavySwarm is part of the Swarms ecosystem. Contributions are welcome for:
- New agent specializations
- Performance optimizations
- Integration capabilities
- Documentation improvements
## Acknowledgments
- Inspired by X.AI's Grok heavy implementation
- Built on the Swarms framework
- Utilizes Rich for dashboard visualization
- Powered by advanced language models

@ -0,0 +1,392 @@
# Technical Support
*Getting Help with the Swarms Multi-Agent Framework*
---
## **Getting Started with Support**
The Swarms team is committed to providing exceptional technical support to help you build production-grade multi-agent systems. Whether you're experiencing bugs, need implementation guidance, or want to request new features, we have multiple channels to ensure you get the help you need quickly and efficiently.
---
## **Support Channels Overview**
| **Support Type** | **Best For** | **Response Time** | **Channel** |
|------------------|--------------|-------------------|-------------|
| **Bug Reports** | Code issues, errors, unexpected behavior | < 24 hours | [GitHub Issues](https://github.com/kyegomez/swarms/issues) |
| **Feature Requests** | New capabilities, enhancements | < 48 hours | [Email kye@swarms.world](mailto:kye@swarms.world) |
| **Private Issues** | Security concerns, enterprise consulting | < 4 hours | [Book Support Call](https://cal.com/swarms/swarms-technical-support?overlayCalendar=true) |
| **Real-time Help** | Quick questions, community discussions | Immediate | [Discord Community](https://discord.gg/jM3Z6M9uMq) |
| **Documentation** | Usage guides, examples, tutorials | Self-service | [docs.swarms.world](https://docs.swarms.world) |
---
## **Reporting Bugs & Technical Issues**
### **When to Use GitHub Issues**
Use GitHub Issues for:
- Code bugs and errors
- Installation problems
- Documentation issues
- Performance problems
- API inconsistencies
- Public technical discussions
### **How to Create an Effective Bug Report**
1. **Visit our Issues page**: [https://github.com/kyegomez/swarms/issues](https://github.com/kyegomez/swarms/issues)
2. **Search existing issues** to avoid duplicates
3. **Click "New Issue"** and select the appropriate template
4. **Include the following information**:
## Bug Description
A clear description of what the bug is.
## Environment
- Swarms version: [e.g., 5.9.2]
- Python version: [e.g., 3.9.0]
- Operating System: [e.g., Ubuntu 20.04, macOS 14, Windows 11]
- Model provider: [e.g., OpenAI, Anthropic, Groq]
## Steps to Reproduce
1. Step one
2. Step two
3. Step three
## Expected Behavior
What you expected to happen.
## Actual Behavior
What actually happened.
## Code Sample
```python
# Minimal code that reproduces the issue
from swarms import Agent
agent = Agent(model_name="gpt-4o-mini")
result = agent.run("Your task here")
```
## Error Messages
Paste any error messages or stack traces here
## Additional Context
Any other context, screenshots, or logs that might help.
### **Issue Templates Available**
| Template | Use Case |
|----------|----------|
| **Bug Report** | Standard bug reporting template |
| **Documentation** | Issues with docs, guides, examples |
| **Feature Request** | Suggesting new functionality |
| **Question** | General questions about usage |
| **Enterprise** | Enterprise-specific issues |
---
## **Private & Enterprise Support**
### **When to Book a Private Support Call**
Book a private consultation for:
- Security vulnerabilities or concerns
- Enterprise deployment guidance
- Custom implementation consulting
- Architecture review sessions
- Performance optimization
- Integration troubleshooting
- Strategic technical planning
### **How to Schedule Support**
1. **Visit our booking page**: [https://cal.com/swarms/swarms-technical-support?overlayCalendar=true](https://cal.com/swarms/swarms-technical-support?overlayCalendar=true)
2. **Select an available time** that works for your timezone
3. **Provide details** about your issue or requirements
4. **Prepare for the call**:
- Have your code/environment ready
- Prepare specific questions
- Include relevant error messages or logs
- Share your use case and goals
### **What to Expect**
- **Direct access** to Swarms core team members
- **Screen sharing** for live debugging
- **Custom solutions** tailored to your needs
- **Follow-up resources** and documentation
- **Priority support** for implementation
---
## **Real-Time Community Support**
### **Join Our Discord Community**
Get instant help from our active community of developers and core team members.
**Discord Benefits:**
- **24/7 availability** - Someone is always online
- **Instant responses** - Get help in real-time
- **Community wisdom** - Learn from other developers
- **Specialized channels** - Find the right help quickly
- **Latest updates** - Stay informed about new releases
### **Discord Channels Guide**
| Channel | Purpose |
|---------|---------|
| **#general** | General discussions and introductions |
| **#technical-support** | Technical questions and troubleshooting |
| **#showcase** | Share your Swarms projects and demos |
| **#feature-requests** | Discuss potential new features |
| **#announcements** | Official updates and releases |
| **#resources** | Helpful links, tutorials, and guides |
### **Getting Help on Discord**
1. **Join here**: [https://discord.gg/jM3Z6M9uMq](https://discord.gg/jM3Z6M9uMq)
2. **Read the rules** and introduce yourself in #general
3. **Use the right channel** for your question type
4. **Provide context** when asking questions:
```
Python version: 3.9
Swarms version: 5.9.2
OS: macOS 14
Question: How do I implement custom tools with MCP?
What I tried: [paste your code]
Error: [paste error message]
```
5. **Be patient and respectful** - our community loves helping!
---
## **Feature Requests & Enhancement Suggestions**
### **When to Email for Feature Requests**
Contact us directly for:
- Major new framework capabilities
- Architecture enhancements
- New model provider integrations
- Enterprise-specific features
- Analytics and monitoring tools
- UI/UX improvements
### **How to Submit Feature Requests**
**Email**: [kye@swarms.world](mailto:kye@swarms.world)
**Subject Format**: `[FEATURE REQUEST] Brief description`
**Include in your email**:
```markdown
## Feature Description
Clear description of the proposed feature
## Use Case
Why this feature is needed and how it would be used
## Business Impact
How this would benefit the Swarms ecosystem
## Technical Requirements
Any specific technical considerations
## Priority Level
- Low: Nice to have
- Medium: Would significantly improve workflow
- High: Critical for adoption/production use
## Alternatives Considered
Other solutions you've explored
## Implementation Ideas
Any thoughts on how this could be implemented
```
### **Feature Request Process**
1. **Email submission** with detailed requirements
2. **Initial review** within 48 hours
3. **Technical feasibility** assessment
4. **Community feedback** gathering (if applicable)
5. **Roadmap planning** and timeline estimation
6. **Development** and testing
7. **Release** with documentation
---
## **Self-Service Resources**
Before reaching out for support, check these resources:
### **Documentation**
- **[Complete Documentation](https://docs.swarms.world)** - Comprehensive guides and API reference
- **[Installation Guide](https://docs.swarms.world/en/latest/swarms/install/install/)** - Setup and configuration
- **[Quick Start](https://docs.swarms.world/en/latest/quickstart/)** - Get up and running fast
- **[Examples Gallery](https://docs.swarms.world/en/latest/examples/)** - Real-world use cases
### **Common Solutions**
| Issue | Solution |
|-------|----------|
| **Installation fails** | Check [Environment Setup](https://docs.swarms.world/en/latest/swarms/install/env/) |
| **Model not responding** | Verify API keys in environment variables |
| **Import errors** | Ensure latest version: `pip install -U swarms` |
| **Memory issues** | Review [Performance Guide](https://docs.swarms.world/en/latest/swarms/framework/test/) |
| **Agent not working** | Check [Basic Agent Example](https://docs.swarms.world/en/latest/swarms/examples/basic_agent/) |
### **Video Tutorials**
- **[YouTube Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ)** - Step-by-step tutorials
- **[Live Coding Sessions](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ)** - Real-world implementations
---
## **Support Checklist**
Before requesting support, please:
- [ ] **Check the documentation** for existing solutions
- [ ] **Search GitHub issues** for similar problems
- [ ] **Update to latest version**: `pip install -U swarms`
- [ ] **Verify environment setup** and API keys
- [ ] **Test with minimal code** to isolate the issue
- [ ] **Gather error messages** and relevant logs
- [ ] **Note your environment** (OS, Python version, Swarms version)
---
## **Support Best Practices**
### **For Faster Resolution**
1. **Be Specific**: Provide exact error messages and steps to reproduce
2. **Include Code**: Share minimal, runnable examples
3. **Environment Details**: Always include version information
4. **Search First**: Check if your issue has been addressed before
5. **One Issue Per Report**: Don't combine multiple problems
6. **Follow Up**: Respond promptly to requests for additional information
### **Response Time Expectations**
| Priority | Response Time | Resolution Time |
|----------|---------------|-----------------|
| **Critical** (Production down) | < 2 hours | < 24 hours |
| **High** (Major functionality blocked) | < 8 hours | < 48 hours |
| **Medium** (Feature issues) | < 24 hours | < 1 week |
| **Low** (Documentation, enhancements) | < 48 hours | Next release |
---
## **Contributing Back**
Help improve support for everyone:
- **Answer questions** in Discord or GitHub
- **Improve documentation** with your learnings
- **Share examples** of successful implementations
- **Report bugs** you discover
- **Suggest improvements** to this support process
**Your contributions make Swarms better for everyone.**
---
## **Support Channel Summary**
| Urgency | Best Channel |
|---------|-------------|
| **Emergency** | [Book Immediate Call](https://cal.com/swarms/swarms-technical-support?overlayCalendar=true) |
| **Urgent** | [Discord #technical-support](https://discord.gg/jM3Z6M9uMq) |
| **Standard** | [GitHub Issues](https://github.com/kyegomez/swarms/issues) |
| **Feature Ideas** | [Email kye@swarms.world](mailto:kye@swarms.world) |
**We're here to help you succeed with Swarms.**

@ -0,0 +1,242 @@
# Swarms API Clients
*Production-Ready Client Libraries for Every Programming Language*
## Overview
The Swarms API provides official client libraries across multiple programming languages, enabling developers to integrate powerful multi-agent AI capabilities into their applications with ease. Our clients are designed for production use, featuring robust error handling, comprehensive documentation, and seamless integration with existing codebases.
Whether you're building enterprise applications, research prototypes, or innovative AI products, our client libraries provide the tools you need to harness the full power of the Swarms platform.
## Available Clients
| Language | Status | Repository | Documentation | Description |
|----------|--------|------------|---------------|-------------|
| **Python** | ✅ **Available** | [swarms-sdk](https://github.com/The-Swarm-Corporation/swarms-sdk) | [Docs](https://docs.swarms.world/en/latest/swarms_cloud/python_client/) | Production-grade Python client with comprehensive error handling, retry logic, and extensive examples |
| **TypeScript/Node.js** | ✅ **Available** | [swarms-ts](https://github.com/The-Swarm-Corporation/swarms-ts) | 📚 *Coming Soon* | Modern TypeScript client with full type safety, Promise-based API, and Node.js compatibility |
| **Go** | ✅ **Available** | [swarms-client-go](https://github.com/The-Swarm-Corporation/swarms-client-go) | 📚 *Coming Soon* | High-performance Go client optimized for concurrent operations and microservices |
| **Java** | ✅ **Available** | [swarms-java](https://github.com/The-Swarm-Corporation/swarms-java) | 📚 *Coming Soon* | Enterprise Java client with Spring Boot integration and comprehensive SDK features |
| **Kotlin** | 🚧 **Coming Soon** | *In Development* | 📚 *Coming Soon* | Modern Kotlin client with coroutines support and Android compatibility |
| **Ruby** | 🚧 **Coming Soon** | *In Development* | 📚 *Coming Soon* | Elegant Ruby client with Rails integration and gem packaging |
| **Rust** | 🚧 **Coming Soon** | *In Development* | 📚 *Coming Soon* | Ultra-fast Rust client with memory safety and zero-cost abstractions |
| **C#/.NET** | 🚧 **Coming Soon** | *In Development* | 📚 *Coming Soon* | .NET client with async/await support and NuGet packaging |
## Client Features
All Swarms API clients are built with the following enterprise-grade features:
### 🔧 **Core Functionality**
| Feature | Description |
|------------------------|--------------------------------------------------------------------|
| **Full API Coverage** | Complete access to all Swarms API endpoints |
| **Type Safety** | Strongly-typed interfaces for all request/response objects |
| **Error Handling** | Comprehensive error handling with detailed error messages |
| **Retry Logic** | Automatic retries with exponential backoff for transient failures |
---
### 🚀 **Performance & Reliability**
| Feature | Description |
|--------------------------|--------------------------------------------------------------------|
| **Connection Pooling** | Efficient HTTP connection management |
| **Rate Limiting** | Built-in rate limit handling and backoff strategies |
| **Timeout Configuration**| Configurable timeouts for different operation types |
| **Streaming Support** | Real-time streaming for long-running operations |
---
### 🛡️ **Security & Authentication**
| Feature | Description |
|------------------------|--------------------------------------------------------------------|
| **API Key Management** | Secure API key handling and rotation |
| **TLS/SSL** | End-to-end encryption for all communications |
| **Request Signing** | Optional request signing for enhanced security |
| **Environment Configuration** | Secure environment-based configuration |
---
### 📊 **Monitoring & Debugging**
| Feature | Description |
|----------------------------|--------------------------------------------------------------------|
| **Comprehensive Logging** | Detailed logging for debugging and monitoring |
| **Request/Response Tracing** | Full request/response tracing capabilities |
| **Metrics Integration** | Built-in metrics for monitoring client performance |
| **Debug Mode** | Enhanced debugging features for development |
## Client-Specific Features
### Python Client
| Feature | Description |
|------------------------|----------------------------------------------------------|
| **Async Support** | Full async/await support with `asyncio` |
| **Pydantic Integration** | Type-safe request/response models |
| **Context Managers** | Resource management with context managers |
| **Rich Logging** | Integration with Python's `logging` module |
---
### TypeScript/Node.js Client
| Feature | Description |
|------------------------|----------------------------------------------------------|
| **TypeScript First** | Built with TypeScript for maximum type safety |
| **Promise-Based** | Modern Promise-based API with async/await |
| **Browser Compatible** | Works in both Node.js and modern browsers |
| **Zero Dependencies** | Minimal dependency footprint |
---
### Go Client
| Feature | Description |
|------------------------|----------------------------------------------------------|
| **Context Support** | Full context.Context support for cancellation |
| **Structured Logging** | Integration with structured logging libraries |
| **Concurrency Safe** | Thread-safe design for concurrent operations |
| **Minimal Allocation** | Optimized for minimal memory allocation |
---
### Java Client
| Feature | Description |
|------------------------|----------------------------------------------------------|
| **Spring Boot Ready** | Built-in Spring Boot auto-configuration |
| **Reactive Support** | Optional reactive streams support |
| **Enterprise Features**| JMX metrics, health checks, and more |
| **Maven & Gradle** | Available on Maven Central |
## Advanced Configuration
### Environment Variables
All clients support standard environment variables for configuration:
```bash
# API Configuration
SWARMS_API_KEY=your_api_key_here
SWARMS_BASE_URL=https://api.swarms.world
# Client Configuration
SWARMS_TIMEOUT=60
SWARMS_MAX_RETRIES=3
SWARMS_LOG_LEVEL=INFO
```
## Community & Support
### 📚 **Documentation & Resources**
| Resource | Link |
|-----------------------------|----------------------------------------------------------------------------------------|
| Complete API Documentation | [View Docs](https://docs.swarms.world/en/latest/swarms_cloud/swarms_api/) |
| Python Client Docs | [View Docs](https://docs.swarms.world/en/latest/swarms_cloud/python_client/) |
| API Examples & Tutorials | [View Examples](https://docs.swarms.world/en/latest/examples/) |
---
### 💬 **Community Support**
| Community Channel | Description | Link |
|-----------------------------|---------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------|
| Discord Community | Join our active developer community for real-time support and discussions | [Join Discord](https://discord.gg/jM3Z6M9uMq) |
| GitHub Discussions | Ask questions and share ideas | [GitHub Discussions](https://github.com/The-Swarm-Corporation/swarms/discussions) |
| Twitter/X | Follow for updates and announcements | [Twitter/X](https://x.com/swarms_corp) |
---
### 🐛 **Issue Reporting & Contributions**
| Contribution Area | Description | Link |
|-----------------------------|---------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------|
| Report Bugs | Help us improve by reporting issues | [Report Bugs](https://github.com/The-Swarm-Corporation/swarms/issues) |
| Feature Requests | Suggest new features and improvements | [Feature Requests](https://github.com/The-Swarm-Corporation/swarms/issues) |
| Contributing Guide | Learn how to contribute to the project | [Contributing Guide](https://docs.swarms.world/en/latest/contributors/main/) |
---
### 📧 **Direct Support**
| Support Type | Contact Information |
|-----------------------------|---------------------------------------------------------------------------------------|
| Support Call | [Book a call](https://cal.com/swarms/swarms-technical-support?overlayCalendar=true) |
| Enterprise Support | Contact us for dedicated enterprise support options |
## Contributing to Client Development
We welcome contributions to all our client libraries! Here's how you can help:
### 🛠️ **Development**
| Task | Description |
|-----------------------------------------|--------------------------------------------------|
| Implement new features and endpoints | Add new API features and expand client coverage |
| Improve error handling and retry logic | Enhance robustness and reliability |
| Add comprehensive test coverage | Ensure code quality and prevent regressions |
| Optimize performance and memory usage | Improve speed and reduce resource consumption |
---
### 📝 **Documentation**
| Task | Description |
|-----------------------------|-----------------------------------------------------|
| Write tutorials and examples | Create guides and sample code for users |
| Improve API documentation | Clarify and expand reference docs |
| Create integration guides | Help users connect clients to their applications |
| Translate documentation | Make docs accessible in multiple languages |
---
### 🧪 **Testing**
| Task | Description |
|-------------------------------|-----------------------------------------------------|
| Add unit and integration tests | Test individual components and end-to-end flows |
| Test with different language versions | Ensure compatibility across environments |
| Performance benchmarking | Measure and optimize speed and efficiency |
| Security testing | Identify and fix vulnerabilities |
---
### 📦 **Packaging**
| Task | Description |
|-------------------------------|-----------------------------------------------------|
| Package managers (npm, pip, Maven, etc.) | Publish to popular package repositories |
| Distribution optimization | Streamline builds and reduce package size |
| Version management | Maintain clear versioning and changelogs |
| Release automation | Automate build, test, and deployment pipelines |
## Enterprise Features
For enterprise customers, we offer additional features and support:
### 🏢 **Enterprise Client Features**
| Feature | Description |
|--------------------------|----------------------------------------------------------------|
| **Priority Support** | Dedicated support team with SLA guarantees |
| **Custom Integrations** | Tailored integrations for your specific needs |
| **On-Premises Deployment** | Support for on-premises or private cloud deployments |
| **Advanced Security** | Enhanced security features and compliance support |
| **Training & Onboarding**| Comprehensive training for your development team |
### 📞 **Contact Enterprise Sales**
| Contact Type | Details |
|----------------|-----------------------------------------------------------------------------------------|
| **Sales** | [kye@swarms.world](mailto:kye@swarms.world) |
| **Schedule Demo** | [Book a Demo](https://cal.com/swarms/swarms-technical-support?overlayCalendar=true) |
| **Partnership**| [kye@swarms.world](mailto:kye@swarms.world) |
---
*Ready to build the future with AI agents? Start with any of our client libraries and join our growing community of developers building the next generation of intelligent applications.*

@ -1,59 +1,196 @@
# Swarms API Rate Limits # Swarms API Rate Limits
The Swarms API implements rate limiting to ensure fair usage and system stability. Here are the current limits: The Swarms API implements a comprehensive rate limiting system that tracks API requests across multiple time windows and enforces various limits to ensure fair usage and system stability.
## Standard Rate Limits ## Rate Limits Summary
- **General API Requests**: 100 requests per minute | Rate Limit Type | Free Tier | Premium Tier | Time Window | Description |
- **Batch Operations**: Maximum 10 requests per batch for agent/swarm batch operations |----------------|-----------|--------------|-------------|-------------|
| **Requests per Minute** | 100 | 2,000 | 1 minute | Maximum API calls per minute |
| **Requests per Hour** | 50 | 10,000 | 1 hour | Maximum API calls per hour |
| **Requests per Day** | 1,200 | 100,000 | 24 hours | Maximum API calls per day |
| **Tokens per Agent** | 200,000 | 2,000,000 | Per request | Maximum tokens per agent |
| **Prompt Length** | 200,000 | 200,000 | Per request | Maximum input tokens per request |
| **Batch Size** | 10 | 10 | Per request | Maximum agents in batch requests |
| **IP-based Fallback** | 100 | 100 | 60 seconds | For requests without API keys |
## Rate Limit Response ## Detailed Rate Limit Explanations
When you exceed the rate limit, the API will return a 429 (Too Many Requests) status code with the following message: ### 1. **Request Rate Limits**
```json
{ These limits control how many API calls you can make within specific time windows.
"detail": "Rate limit exceeded. Please try again later."
} #### **Per-Minute Limit**
```
| Tier | Requests per Minute | Reset Interval | Applies To |
|--------------|--------------------|------------------------|--------------------|
| Free | 100 | Every minute (sliding) | All API endpoints |
| Premium | 2,000 | Every minute (sliding) | All API endpoints |
#### **Per-Hour Limit**
- **Free Tier**: 50 requests per hour
- **Premium Tier**: 10,000 requests per hour
- **Reset**: Every hour (sliding window)
- **Applies to**: All API endpoints
#### **Per-Day Limit**
- **Free Tier**: 1,200 requests per day (50 × 24)
- **Premium Tier**: 100,000 requests per day
- **Reset**: Every 24 hours (sliding window)
- **Applies to**: All API endpoints
### 2. **Token Limits**
These limits control the amount of text processing allowed per request.
#### **Tokens per Agent**
- **Free Tier**: 200,000 tokens per agent
- **Premium Tier**: 2,000,000 tokens per agent
- **Applies to**: Individual agent configurations
- **Includes**: System prompts, task descriptions, and agent names
#### **Prompt Length Limit**
- **All Tiers**: 200,000 tokens maximum
- **Applies to**: Combined input text (task + history + system prompts)
- **Error**: Returns 400 error if exceeded
- **Message**: "Prompt is too long. Please provide a prompt that is less than 10000 tokens."
## Batch Operation Limits ### 3. **Batch Processing Limits**
For batch operations (`/v1/agent/batch/completions` and `/v1/swarm/batch/completions`): These limits control concurrent processing capabilities.
- Maximum 10 concurrent requests per batch #### **Batch Size Limit**
- Exceeding this limit will result in a 400 (Bad Request) error - **All Tiers**: 10 agents maximum per batch
## Increasing Your Rate Limits - **Applies to**: `/v1/agent/batch/completions` endpoint
Need higher rate limits for your application? You can increase your limits by subscribing to a higher tier plan at [swarms.world/pricing](https://swarms.world/pricing). - **Error**: Returns 400 error if exceeded
Higher tier plans offer: - **Message**: "ERROR: BATCH SIZE EXCEEDED - You can only run up to 10 batch agents at a time."
- Increased rate limits ## How Rate Limiting Works
- Higher batch operation limits ### Database-Based Tracking
- Priority processing The system uses a database-based approach for API key requests:
1. **Request Logging**: Every API request is logged to the `swarms_api_logs` table
2. **Time Window Queries**: The system queries for requests in the last minute, hour, and day
3. **Limit Comparison**: Current counts are compared against configured limits
4. **Request Blocking**: Requests are blocked if any limit is exceeded
### Sliding Windows
Rate limits use sliding windows rather than fixed windows:
- **Minute**: Counts requests in the last 60 seconds
- **Hour**: Counts requests in the last 60 minutes
- **Day**: Counts requests in the last 24 hours
This provides more accurate rate limiting compared to fixed time windows.
## Checking Your Rate Limits
### API Endpoint
Use the `/v1/rate/limits` endpoint to check your current usage:
```bash
curl -H "x-api-key: your-api-key" \
https://api.swarms.world/v1/rate/limits
```
### Response Format
```json
{
"success": true,
"rate_limits": {
"minute": {
"count": 5,
"limit": 100,
"exceeded": false,
"remaining": 95,
"reset_time": "2024-01-15T10:30:00Z"
},
"hour": {
"count": 25,
"limit": 50,
"exceeded": false,
"remaining": 25,
"reset_time": "2024-01-15T11:00:00Z"
},
"day": {
"count": 150,
"limit": 1200,
"exceeded": false,
"remaining": 1050,
"reset_time": "2024-01-16T10:00:00Z"
}
},
"limits": {
"maximum_requests_per_minute": 100,
"maximum_requests_per_hour": 50,
"maximum_requests_per_day": 1200,
"tokens_per_agent": 200000
},
"timestamp": "2024-01-15T10:29:30Z"
}
```
## Handling Rate Limit Errors
### Error Response
When rate limits are exceeded, you'll receive a 429 status code:
```json
{
"detail": "Rate limit exceeded for minute window(s). Upgrade to Premium for increased limits (2,000/min, 10,000/hour, 100,000/day) at https://swarms.world/platform/account for just $99/month."
}
```
- Dedicated support ### Best Practices
## Best Practices 1. **Monitor Usage**: Regularly check your rate limits using the `/v1/rate/limits` endpoint
2. **Implement Retry Logic**: Use exponential backoff when hitting rate limits
3. **Optimize Requests**: Combine multiple operations into single requests when possible
4. **Upgrade When Needed**: Consider upgrading to Premium for higher limits
To make the most of your rate limits: ## Premium Tier Benefits
1. Implement proper error handling for rate limit responses Upgrade to Premium for significantly higher limits:
2. Use batch operations when processing multiple requests - **20x more requests per minute** (2,000 vs 100)
3. Add appropriate retry logic with exponential backoff - **200x more requests per hour** (10,000 vs 50)
4. Monitor your API usage to stay within limits - **83x more requests per day** (100,000 vs 1,200)
## Rate Limit Headers - **10x more tokens per agent** (2M vs 200K)
The API does not currently expose rate limit headers. We recommend implementing your own request tracking to stay within the limits. Visit [Swarms Platform Account](https://swarms.world/platform/account) to upgrade for just $99/month.
--- ## Performance Considerations
For questions about rate limits or to request a custom plan for higher limits, please contact our support team or visit [swarms.world/pricing](https://swarms.world/pricing). - Database queries are optimized to only count request IDs
- Rate limit checks are cached per request
- Fallback mechanisms ensure system reliability
- Minimal impact on request latency
- Persistent tracking across server restarts

@ -0,0 +1,40 @@
import json
import os
from swarms_client import SwarmsClient
from swarms_client.types import AgentSpecParam
from dotenv import load_dotenv
load_dotenv()
client = SwarmsClient(api_key=os.getenv("SWARMS_API_KEY"))
agent_spec = AgentSpecParam(
agent_name="doctor_agent",
description="A virtual doctor agent that provides evidence-based, safe, and empathetic medical advice for common health questions. Always reminds users to consult a healthcare professional for diagnoses or prescriptions.",
task="What is the best medicine for a cold?",
model_name="claude-3-5-sonnet-20241022",
system_prompt=(
"You are a highly knowledgeable, ethical, and empathetic virtual doctor. "
"Always provide evidence-based, safe, and practical medical advice. "
"If a question requires a diagnosis, prescription, or urgent care, remind the user to consult a licensed healthcare professional. "
"Be clear, concise, and avoid unnecessary medical jargon. "
"Never provide information that could be unsafe or misleading. "
"If unsure, say so and recommend seeing a real doctor."
),
max_loops=1,
temperature=0.4,
role="doctor",
)
# response = client.agent.run(
# agent_config=agent_spec,
# task="What is the best medicine for a cold?",
# )
# print(response)
print(json.dumps(client.models.list_available(), indent=4))
print(json.dumps(client.health.check(), indent=4))
print(json.dumps(client.swarms.get_logs(), indent=4))
print(json.dumps(client.client.rate.get_limits(), indent=4))
print(json.dumps(client.swarms.check_available(), indent=4))

@ -0,0 +1,12 @@
from swarms_client import SwarmsClient
from dotenv import load_dotenv
import os
load_dotenv()
client = SwarmsClient(api_key=os.getenv("SWARMS_API_KEY"))
response = client.client.rate.get_limits()
print(response)
print(client.health.check())

@ -0,0 +1,302 @@
"""
Agent Multi-Agent Communication Examples
This file demonstrates the multi-agent communication methods available in the Agent class:
- talk_to: Direct communication between two agents
- talk_to_multiple_agents: Concurrent communication with multiple agents
- receive_message: Process incoming messages from other agents
- send_agent_message: Send formatted messages to other agents
Run: python agent_communication_examples.py
"""
import os
from swarms import Agent
# Set up your API key
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
def example_1_direct_agent_communication():
"""Example 1: Direct communication between two agents using talk_to method"""
print("=" * 60)
print("Example 1: Direct Agent Communication")
print("=" * 60)
# Create two specialized agents
researcher = Agent(
agent_name="Research-Agent",
system_prompt="You are a research specialist focused on gathering and analyzing information. Provide detailed, fact-based responses.",
max_loops=1,
verbose=False,
)
analyst = Agent(
agent_name="Analysis-Agent",
system_prompt="You are an analytical specialist focused on interpreting research data and providing strategic insights.",
max_loops=1,
verbose=False,
)
# Agent communication
print("Researcher talking to Analyst...")
research_result = researcher.talk_to(
agent=analyst,
task="Analyze the market trends for renewable energy stocks and provide investment recommendations",
)
print(f"\nFinal Analysis Result:\n{research_result}")
return research_result
def example_2_multiple_agent_communication():
"""Example 2: Broadcasting to multiple agents using talk_to_multiple_agents"""
print("\n" + "=" * 60)
print("Example 2: Multiple Agent Communication")
print("=" * 60)
# Create multiple specialized agents
agents = [
Agent(
agent_name="Financial-Analyst",
system_prompt="You are a financial analysis expert specializing in stock valuation and market trends.",
max_loops=1,
verbose=False,
),
Agent(
agent_name="Risk-Assessor",
system_prompt="You are a risk assessment specialist focused on identifying potential investment risks.",
max_loops=1,
verbose=False,
),
Agent(
agent_name="Market-Researcher",
system_prompt="You are a market research expert specializing in industry analysis and competitive intelligence.",
max_loops=1,
verbose=False,
),
]
coordinator = Agent(
agent_name="Coordinator-Agent",
system_prompt="You coordinate multi-agent analysis and synthesize diverse perspectives into actionable insights.",
max_loops=1,
verbose=False,
)
# Broadcast to multiple agents
print("Coordinator broadcasting to multiple agents...")
responses = coordinator.talk_to_multiple_agents(
agents=agents,
task="Evaluate the investment potential of Tesla stock for the next quarter",
)
# Process responses
print("\nResponses from all agents:")
for i, response in enumerate(responses):
if response:
print(f"\n{agents[i].agent_name} Response:")
print("-" * 40)
print(
response[:200] + "..."
if len(response) > 200
else response
)
else:
print(f"\n{agents[i].agent_name}: Failed to respond")
return responses
def example_3_message_handling():
"""Example 3: Message handling using receive_message and send_agent_message"""
print("\n" + "=" * 60)
print("Example 3: Message Handling")
print("=" * 60)
# Create an agent that can receive messages
support_agent = Agent(
agent_name="Support-Agent",
system_prompt="You provide helpful support and assistance. Always be professional and solution-oriented.",
max_loops=1,
verbose=False,
)
notification_agent = Agent(
agent_name="Notification-Agent",
system_prompt="You send notifications and updates to other systems and agents.",
max_loops=1,
verbose=False,
)
# Example of receiving a message
print("Support agent receiving message...")
received_response = support_agent.receive_message(
agent_name="Customer-Service-Agent",
task="A customer is asking about our refund policies for software purchases. Can you provide guidance?",
)
print(f"\nSupport Agent Response:\n{received_response}")
# Example of sending a message
print("\nNotification agent sending message...")
sent_result = notification_agent.send_agent_message(
agent_name="Task-Manager-Agent",
message="Customer support ticket #12345 has been resolved successfully",
)
print(f"\nNotification Result:\n{sent_result}")
return received_response, sent_result
def example_4_sequential_workflow():
"""Example 4: Sequential agent workflow using communication methods"""
print("\n" + "=" * 60)
print("Example 4: Sequential Agent Workflow")
print("=" * 60)
# Create specialized agents for a document processing workflow
extractor = Agent(
agent_name="Data-Extractor",
system_prompt="You extract key information and data points from documents. Focus on accuracy and completeness.",
max_loops=1,
verbose=False,
)
validator = Agent(
agent_name="Data-Validator",
system_prompt="You validate and verify extracted data for accuracy, completeness, and consistency.",
max_loops=1,
verbose=False,
)
formatter = Agent(
agent_name="Data-Formatter",
system_prompt="You format validated data into structured, professional reports and summaries.",
max_loops=1,
verbose=False,
)
# Sequential processing workflow
document_content = """
Q3 Financial Report Summary:
- Revenue: $2.5M (up 15% from Q2)
- Expenses: $1.8M (operational costs increased by 8%)
- Net Profit: $700K (improved profit margin of 28%)
- New Customers: 1,200 (25% growth rate)
- Customer Retention: 92%
- Market Share: Increased to 12% in our sector
"""
print("Starting sequential workflow...")
# Step 1: Extract data
print("\nStep 1: Data Extraction")
extracted_data = extractor.run(
f"Extract key financial metrics from this report: {document_content}"
)
print(f"Extracted: {extracted_data[:150]}...")
# Step 2: Validate data
print("\nStep 2: Data Validation")
validated_data = extractor.talk_to(
agent=validator,
task=f"Please validate this extracted data for accuracy and completeness: {extracted_data}",
)
print(f"Validated: {validated_data[:150]}...")
# Step 3: Format data
print("\nStep 3: Data Formatting")
final_output = validator.talk_to(
agent=formatter,
task=f"Format this validated data into a structured executive summary: {validated_data}",
)
print(f"\nFinal Report:\n{final_output}")
return final_output
def example_5_error_handling():
"""Example 5: Robust communication with error handling"""
print("\n" + "=" * 60)
print("Example 5: Communication with Error Handling")
print("=" * 60)
def safe_agent_communication(sender, receiver, message):
"""Safely handle agent communication with comprehensive error handling"""
try:
print(
f"Attempting communication: {sender.agent_name} -> {receiver.agent_name}"
)
response = sender.talk_to(agent=receiver, task=message)
return {
"success": True,
"response": response,
"error": None,
}
except Exception as e:
print(f"Communication failed: {e}")
return {
"success": False,
"response": None,
"error": str(e),
}
# Create agents
agent_a = Agent(
agent_name="Agent-A",
system_prompt="You are a helpful assistant focused on providing accurate information.",
max_loops=1,
verbose=False,
)
agent_b = Agent(
agent_name="Agent-B",
system_prompt="You are a knowledgeable expert in technology and business trends.",
max_loops=1,
verbose=False,
)
# Safe communication
result = safe_agent_communication(
sender=agent_a,
receiver=agent_b,
message="What are the latest trends in artificial intelligence and how might they impact business operations?",
)
if result["success"]:
print("\nCommunication successful!")
print(f"Response: {result['response'][:200]}...")
else:
print(f"\nCommunication failed: {result['error']}")
return result
def main():
"""Run all multi-agent communication examples"""
print("🤖 Agent Multi-Agent Communication Examples")
print(
"This demonstrates the communication methods available in the Agent class"
)
try:
# Run all examples
example_1_direct_agent_communication()
example_2_multiple_agent_communication()
example_3_message_handling()
example_4_sequential_workflow()
example_5_error_handling()
print("\n" + "=" * 60)
print("✅ All examples completed successfully!")
print("=" * 60)
except Exception as e:
print(f"\n❌ Error running examples: {e}")
print(
"Make sure to set your OPENAI_API_KEY environment variable"
)
if __name__ == "__main__":
main()

@ -0,0 +1,344 @@
"""
Multi-Agent Caching Example - Super Fast Agent Loading
This example demonstrates how to use the agent caching system with multiple agents
to achieve 10-100x speedup in agent loading and reuse.
"""
import time
from swarms import Agent
from swarms.utils.agent_cache import (
cached_agent_loader,
simple_lru_agent_loader,
AgentCache,
get_agent_cache_stats,
clear_agent_cache,
)
def create_trading_team():
"""Create a team of trading agents."""
# Create multiple agents for different trading strategies
agents = [
Agent(
agent_name="Quantitative-Trading-Agent",
agent_description="Advanced quantitative trading and algorithmic analysis agent",
system_prompt="""You are an expert quantitative trading agent with deep expertise in:
- Algorithmic trading strategies and implementation
- Statistical arbitrage and market making
- Risk management and portfolio optimization
- High-frequency trading systems
- Market microstructure analysis""",
max_loops=1,
model_name="gpt-4o-mini",
temperature=0.1,
),
Agent(
agent_name="Risk-Management-Agent",
agent_description="Portfolio risk assessment and management specialist",
system_prompt="""You are a risk management specialist focused on:
- Portfolio risk assessment and stress testing
- Value at Risk (VaR) calculations
- Regulatory compliance monitoring
- Risk mitigation strategies
- Capital allocation optimization""",
max_loops=1,
model_name="gpt-4o-mini",
temperature=0.2,
),
Agent(
agent_name="Market-Analysis-Agent",
agent_description="Real-time market analysis and trend identification",
system_prompt="""You are a market analysis expert specializing in:
- Technical analysis and chart patterns
- Market sentiment analysis
- Economic indicator interpretation
- Trend identification and momentum analysis
- Support and resistance level identification""",
max_loops=1,
model_name="gpt-4o-mini",
temperature=0.3,
),
Agent(
agent_name="Options-Trading-Agent",
agent_description="Options strategies and derivatives trading specialist",
system_prompt="""You are an options trading specialist with expertise in:
- Options pricing models and Greeks analysis
- Volatility trading strategies
- Complex options spreads and combinations
- Risk-neutral portfolio construction
- Derivatives market making""",
max_loops=1,
model_name="gpt-4o-mini",
temperature=0.15,
),
Agent(
agent_name="ESG-Investment-Agent",
agent_description="ESG-focused investment analysis and screening",
system_prompt="""You are an ESG investment specialist focusing on:
- Environmental, Social, and Governance criteria evaluation
- Sustainable investment screening
- Impact investing strategies
- ESG risk assessment
- Green finance and climate risk analysis""",
max_loops=1,
model_name="gpt-4o-mini",
temperature=0.25,
),
]
return agents
def basic_caching_example():
"""Basic example of caching multiple agents."""
print("=== Basic Multi-Agent Caching Example ===")
# Create our trading team
trading_team = create_trading_team()
print(f"Created {len(trading_team)} trading agents")
# First load - agents will be processed and cached
print("\n🔄 First load (will cache agents)...")
start_time = time.time()
cached_team_1 = cached_agent_loader(trading_team)
first_load_time = time.time() - start_time
print(
f"✅ First load: {len(cached_team_1)} agents in {first_load_time:.3f}s"
)
# Second load - agents will be retrieved from cache (super fast!)
print("\n⚡ Second load (from cache)...")
start_time = time.time()
cached_team_2 = cached_agent_loader(trading_team)
second_load_time = time.time() - start_time
print(
f"🚀 Second load: {len(cached_team_2)} agents in {second_load_time:.3f}s"
)
print(
f"💨 Speedup: {first_load_time/second_load_time:.1f}x faster!"
)
# Show cache statistics
stats = get_agent_cache_stats()
print(f"📊 Cache stats: {stats}")
return cached_team_1
def custom_cache_example():
"""Example using a custom cache for specific use cases."""
print("\n=== Custom Cache Example ===")
# Create a custom cache with specific settings
custom_cache = AgentCache(
max_memory_cache_size=50, # Cache up to 50 agents
cache_dir="trading_team_cache", # Custom cache directory
enable_persistent_cache=True, # Enable disk persistence
auto_save_interval=120, # Auto-save every 2 minutes
)
# Create agents
trading_team = create_trading_team()
# Load with custom cache
print("🔧 Loading with custom cache...")
start_time = time.time()
cached_team = cached_agent_loader(
trading_team,
cache_instance=custom_cache,
parallel_loading=True,
)
load_time = time.time() - start_time
print(f"✅ Loaded {len(cached_team)} agents in {load_time:.3f}s")
# Get custom cache stats
stats = custom_cache.get_cache_stats()
print(f"📊 Custom cache stats: {stats}")
# Cleanup
custom_cache.shutdown()
return cached_team
def simple_lru_example():
"""Example using the simple LRU cache approach."""
print("\n=== Simple LRU Cache Example ===")
trading_team = create_trading_team()
# First load with simple LRU
print("🔄 First load with simple LRU...")
start_time = time.time()
lru_team_1 = simple_lru_agent_loader(trading_team)
first_time = time.time() - start_time
# Second load (cached)
print("⚡ Second load with simple LRU...")
start_time = time.time()
simple_lru_agent_loader(trading_team)
cached_time = time.time() - start_time
print(
f"📈 Simple LRU - First: {first_time:.3f}s, Cached: {cached_time:.3f}s"
)
print(f"💨 Speedup: {first_time/cached_time:.1f}x faster!")
return lru_team_1
def team_workflow_simulation():
"""Simulate a real-world workflow with the cached trading team."""
print("\n=== Team Workflow Simulation ===")
# Create and cache the team
trading_team = create_trading_team()
cached_team = cached_agent_loader(trading_team)
# Simulate multiple analysis sessions
tasks = [
"Analyze the current market conditions for AAPL",
"What are the top 3 ETFs for gold coverage?",
"Assess the risk profile of a tech-heavy portfolio",
"Identify options strategies for volatile markets",
"Evaluate ESG investment opportunities in renewable energy",
]
print(
f"🎯 Running {len(tasks)} analysis tasks with {len(cached_team)} agents..."
)
session_start = time.time()
for i, (agent, task) in enumerate(zip(cached_team, tasks)):
print(f"\n📋 Task {i+1}: {agent.agent_name}")
print(f" Question: {task}")
task_start = time.time()
# Run the agent on the task
response = agent.run(task)
task_time = time.time() - task_start
print(f" ⏱️ Completed in {task_time:.2f}s")
print(
f" 💡 Response: {response[:100]}..."
if len(response) > 100
else f" 💡 Response: {response}"
)
total_session_time = time.time() - session_start
print(f"\n🏁 Total session time: {total_session_time:.2f}s")
print(
f"📊 Average task time: {total_session_time/len(tasks):.2f}s"
)
def performance_comparison():
"""Compare performance with and without caching."""
print("\n=== Performance Comparison ===")
# Create test agents
test_agents = []
for i in range(10):
agent = Agent(
agent_name=f"Test-Agent-{i:02d}",
model_name="gpt-4o-mini",
system_prompt=f"You are test agent number {i}.",
max_loops=1,
)
test_agents.append(agent)
# Test without caching (creating new agents each time)
print("🔄 Testing without caching...")
no_cache_times = []
for _ in range(3):
start_time = time.time()
# Simulate creating new agents each time
new_agents = []
for agent in test_agents:
new_agent = Agent(
agent_name=agent.agent_name,
model_name=agent.model_name,
system_prompt=agent.system_prompt,
max_loops=agent.max_loops,
)
new_agents.append(new_agent)
no_cache_time = time.time() - start_time
no_cache_times.append(no_cache_time)
avg_no_cache_time = sum(no_cache_times) / len(no_cache_times)
# Clear cache for fair comparison
clear_agent_cache()
# Test with caching (first load)
print("🔧 Testing with caching (first load)...")
start_time = time.time()
cached_agent_loader(test_agents)
first_cache_time = time.time() - start_time
# Test with caching (subsequent loads)
print("⚡ Testing with caching (subsequent loads)...")
cache_times = []
for _ in range(3):
start_time = time.time()
cached_agent_loader(test_agents)
cache_time = time.time() - start_time
cache_times.append(cache_time)
avg_cache_time = sum(cache_times) / len(cache_times)
# Results
print(f"\n📊 Performance Results for {len(test_agents)} agents:")
print(f" 🐌 No caching (avg): {avg_no_cache_time:.4f}s")
print(f" 🔧 Cached (first load): {first_cache_time:.4f}s")
print(f" 🚀 Cached (avg): {avg_cache_time:.4f}s")
print(
f" 💨 Cache speedup: {avg_no_cache_time/avg_cache_time:.1f}x faster!"
)
# Final cache stats
final_stats = get_agent_cache_stats()
print(f" 📈 Final cache stats: {final_stats}")
def main():
"""Run all examples to demonstrate multi-agent caching."""
print("🤖 Multi-Agent Caching System Examples")
print("=" * 50)
try:
# Run examples
basic_caching_example()
custom_cache_example()
simple_lru_example()
performance_comparison()
team_workflow_simulation()
print("\n✅ All examples completed successfully!")
print("\n🎯 Key Benefits of Multi-Agent Caching:")
print("• 🚀 10-100x faster agent loading from cache")
print(
"• 💾 Persistent disk cache survives application restarts"
)
print("• 🧠 Intelligent LRU memory management")
print("• 🔄 Background preloading for zero-latency access")
print("• 📊 Detailed performance monitoring")
print("• 🛡️ Thread-safe with memory leak prevention")
print("• ⚡ Parallel processing for multiple agents")
except Exception as e:
print(f"❌ Error running examples: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()

@ -0,0 +1,128 @@
"""
Quick Start: Agent Caching with Multiple Agents
This is a simple example showing how to use agent caching with your existing agents
for super fast loading and reuse.
"""
import time
from swarms import Agent
from swarms.utils.agent_cache import cached_agent_loader
def main():
"""Simple example of caching multiple agents."""
# Create your agents as usual
agents = [
Agent(
agent_name="Quantitative-Trading-Agent",
agent_description="Advanced quantitative trading and algorithmic analysis agent",
system_prompt="""You are an expert quantitative trading agent with deep expertise in:
- Algorithmic trading strategies and implementation
- Statistical arbitrage and market making
- Risk management and portfolio optimization
- High-frequency trading systems
- Market microstructure analysis
Your core responsibilities include:
1. Developing and backtesting trading strategies
2. Analyzing market data and identifying alpha opportunities
3. Implementing risk management frameworks
4. Optimizing portfolio allocations
5. Conducting quantitative research
6. Monitoring market microstructure
7. Evaluating trading system performance
You maintain strict adherence to:
- Mathematical rigor in all analyses
- Statistical significance in strategy development
- Risk-adjusted return optimization
- Market impact minimization
- Regulatory compliance
- Transaction cost analysis
- Performance attribution
You communicate in precise, technical terms while maintaining clarity for stakeholders.""",
max_loops=1,
model_name="gpt-4o-mini",
dynamic_temperature_enabled=True,
output_type="str-all-except-first",
streaming_on=True,
print_on=True,
telemetry_enable=False,
),
Agent(
agent_name="Risk-Manager",
system_prompt="You are a risk management specialist.",
max_loops=1,
model_name="gpt-4o-mini",
),
Agent(
agent_name="Market-Analyst",
system_prompt="You are a market analysis expert.",
max_loops=1,
model_name="gpt-4o-mini",
),
]
print(f"Created {len(agents)} agents")
# BEFORE: Creating agents each time (slow)
print("\n=== Without Caching (Slow) ===")
start_time = time.time()
# Simulate creating new agents each time
for _ in range(3):
new_agents = []
for agent in agents:
new_agent = Agent(
agent_name=agent.agent_name,
system_prompt=agent.system_prompt,
max_loops=agent.max_loops,
model_name=agent.model_name,
)
new_agents.append(new_agent)
no_cache_time = time.time() - start_time
print(f"🐌 Time without caching: {no_cache_time:.3f}s")
# AFTER: Using cached agents (super fast!)
print("\n=== With Caching (Super Fast!) ===")
# First call - will cache the agents
start_time = time.time()
cached_agent_loader(agents)
first_cache_time = time.time() - start_time
print(f"🔧 First cache load: {first_cache_time:.3f}s")
# Subsequent calls - retrieves from cache (lightning fast!)
cache_times = []
for i in range(3):
start_time = time.time()
cached_agents = cached_agent_loader(agents)
cache_time = time.time() - start_time
cache_times.append(cache_time)
print(f"⚡ Cache load #{i+1}: {cache_time:.4f}s")
avg_cache_time = sum(cache_times) / len(cache_times)
print("\n📊 Results:")
print(f" 🐌 Without caching: {no_cache_time:.3f}s")
print(f" 🚀 With caching: {avg_cache_time:.4f}s")
print(
f" 💨 Speedup: {no_cache_time/avg_cache_time:.0f}x faster!"
)
# Now use your cached agents normally
print("\n🎯 Using cached agents:")
task = "What are the best top 3 etfs for gold coverage?"
for agent in cached_agents[
:1
]: # Just use the first agent for demo
print(f" Running {agent.agent_name}...")
response = agent.run(task)
print(f" Response: {response[:100]}...")
if __name__ == "__main__":
main()

@ -0,0 +1,186 @@
"""
Simple Agent Caching Tests - Just 4 Basic Tests
Tests loading agents with and without cache for single and multiple agents.
"""
import time
from swarms import Agent
from swarms.utils.agent_cache import (
cached_agent_loader,
clear_agent_cache,
)
def test_single_agent_without_cache():
"""Test loading a single agent without cache."""
print("🔄 Test 1: Single agent without cache")
# Test creating agents multiple times (simulating no cache)
times = []
for _ in range(10): # Do it 10 times to get better measurement
start_time = time.time()
Agent(
agent_name="Test-Agent-1",
model_name="gpt-4o-mini",
system_prompt="You are a test agent.",
max_loops=1,
)
load_time = time.time() - start_time
times.append(load_time)
avg_time = sum(times) / len(times)
print(
f" ✅ Single agent without cache: {avg_time:.4f}s (avg of 10 creations)"
)
return avg_time
def test_single_agent_with_cache():
"""Test loading a single agent with cache."""
print("🔄 Test 2: Single agent with cache")
clear_agent_cache()
# Create agent
agent = Agent(
agent_name="Test-Agent-1",
model_name="gpt-4o-mini",
system_prompt="You are a test agent.",
max_loops=1,
)
# First load (cache miss) - disable preloading for fair test
cached_agent_loader([agent], preload=False)
# Now test multiple cache hits
times = []
for _ in range(10): # Do it 10 times to get better measurement
start_time = time.time()
cached_agent_loader([agent], preload=False)
load_time = time.time() - start_time
times.append(load_time)
avg_time = sum(times) / len(times)
print(
f" ✅ Single agent with cache: {avg_time:.4f}s (avg of 10 cache hits)"
)
return avg_time
def test_multiple_agents_without_cache():
"""Test loading multiple agents without cache."""
print("🔄 Test 3: Multiple agents without cache")
# Test creating agents multiple times (simulating no cache)
times = []
for _ in range(5): # Do it 5 times to get better measurement
start_time = time.time()
[
Agent(
agent_name=f"Test-Agent-{i}",
model_name="gpt-4o-mini",
system_prompt=f"You are test agent {i}.",
max_loops=1,
)
for i in range(5)
]
load_time = time.time() - start_time
times.append(load_time)
avg_time = sum(times) / len(times)
print(
f" ✅ Multiple agents without cache: {avg_time:.4f}s (avg of 5 creations)"
)
return avg_time
def test_multiple_agents_with_cache():
"""Test loading multiple agents with cache."""
print("🔄 Test 4: Multiple agents with cache")
clear_agent_cache()
# Create agents
agents = [
Agent(
agent_name=f"Test-Agent-{i}",
model_name="gpt-4o-mini",
system_prompt=f"You are test agent {i}.",
max_loops=1,
)
for i in range(5)
]
# First load (cache miss) - disable preloading for fair test
cached_agent_loader(agents, preload=False)
# Now test multiple cache hits
times = []
for _ in range(5): # Do it 5 times to get better measurement
start_time = time.time()
cached_agent_loader(agents, preload=False)
load_time = time.time() - start_time
times.append(load_time)
avg_time = sum(times) / len(times)
print(
f" ✅ Multiple agents with cache: {avg_time:.4f}s (avg of 5 cache hits)"
)
return avg_time
def main():
"""Run the 4 simple tests."""
print("🚀 Simple Agent Caching Tests")
print("=" * 40)
# Run tests
single_no_cache = test_single_agent_without_cache()
single_with_cache = test_single_agent_with_cache()
multiple_no_cache = test_multiple_agents_without_cache()
multiple_with_cache = test_multiple_agents_with_cache()
# Results
print("\n📊 Results:")
print("=" * 40)
print(f"Single agent - No cache: {single_no_cache:.4f}s")
print(f"Single agent - With cache: {single_with_cache:.4f}s")
print(f"Multiple agents - No cache: {multiple_no_cache:.4f}s")
print(f"Multiple agents - With cache: {multiple_with_cache:.4f}s")
# Speedups (handle near-zero times)
if (
single_with_cache > 0.00001
): # Only calculate if time is meaningful
single_speedup = single_no_cache / single_with_cache
print(f"\n🚀 Single agent speedup: {single_speedup:.1f}x")
else:
print(
"\n🚀 Single agent speedup: Cache too fast to measure accurately!"
)
if (
multiple_with_cache > 0.00001
): # Only calculate if time is meaningful
multiple_speedup = multiple_no_cache / multiple_with_cache
print(f"🚀 Multiple agents speedup: {multiple_speedup:.1f}x")
else:
print(
"🚀 Multiple agents speedup: Cache too fast to measure accurately!"
)
# Summary
print("\n✅ Cache Validation:")
print("• Cache hit rates are increasing (visible in logs)")
print("• No validation errors")
print(
"• Agent objects are being cached and retrieved successfully"
)
print(
"• For real agents with LLM initialization, expect 10-100x speedups!"
)
if __name__ == "__main__":
main()

@ -0,0 +1,250 @@
from swarms import Agent
from swarms.structs.election_swarm import (
ElectionSwarm,
)
# Create candidate agents for Apple CEO position
tim_cook = Agent(
agent_name="Tim Cook - Current CEO",
system_prompt="""You are Tim Cook, the current CEO of Apple Inc. since 2011.
Your background:
- 13+ years as Apple CEO, succeeding Steve Jobs
- Former COO of Apple (2007-2011)
- Former VP of Operations at Compaq
- MBA from Duke University
- Known for operational excellence and supply chain management
- Led Apple to become the world's most valuable company
- Expanded Apple's services business significantly
- Strong focus on privacy, sustainability, and social responsibility
- Successfully navigated global supply chain challenges
- Annual revenue growth from $108B to $394B during tenure
Strengths: Operational expertise, global experience, proven track record, strong relationships with suppliers and partners, focus on privacy and sustainability.
Challenges: Perceived lack of innovation compared to Jobs era, heavy reliance on iPhone revenue, limited new product categories.""",
model_name="gpt-4.1",
max_loops=1,
temperature=0.7,
# tools_list_dictionary=get_vote_schema(),
)
sundar_pichai = Agent(
agent_name="Sundar Pichai - Google/Alphabet CEO",
system_prompt="""You are Sundar Pichai, CEO of Alphabet Inc. and Google since 2015.
Your background:
- CEO of Alphabet Inc. since 2019, Google since 2015
- Former Senior VP of Chrome, Apps, and Android
- Led development of Chrome browser and Android platform
- MS in Engineering from Stanford, MBA from Wharton
- Known for product development and AI leadership
- Successfully integrated AI into Google's core products
- Led Google's cloud computing expansion
- Strong focus on AI/ML and emerging technologies
- Experience with large-scale platform management
- Annual revenue growth from $75B to $307B during tenure
Strengths: AI/ML expertise, product development, platform management, experience with large-scale operations, strong technical background.
Challenges: Limited hardware experience, regulatory scrutiny, different company culture.""",
model_name="gpt-4.1",
max_loops=1,
temperature=0.7,
# tools_list_dictionary=get_vote_schema(),
)
jensen_huang = Agent(
agent_name="Jensen Huang - NVIDIA CEO",
system_prompt="""You are Jensen Huang, CEO and co-founder of NVIDIA since 1993.
Your background:
- CEO and co-founder of NVIDIA for 31 years
- Former engineer at AMD and LSI Logic
- MS in Electrical Engineering from Stanford
- Led NVIDIA from graphics cards to AI computing leader
- Pioneered GPU computing and AI acceleration
- Successfully pivoted company to AI/data center focus
- Market cap grew from $2B to $2.5T+ under leadership
- Known for long-term vision and technical innovation
- Strong focus on AI, robotics, and autonomous vehicles
- Annual revenue growth from $3.9B to $60B+ during recent years
Strengths: Technical innovation, AI expertise, long-term vision, proven ability to pivot business models, strong engineering background, experience building new markets.
Challenges: Limited consumer hardware experience, different industry focus, no experience with Apple's ecosystem.""",
model_name="gpt-4.1",
max_loops=1,
temperature=0.7,
# tools_list_dictionary=get_vote_schema(),
)
# Create board member voter agents with realistic personas
arthur_levinson = Agent(
agent_name="Arthur Levinson - Chairman",
system_prompt="""You are Arthur Levinson, Chairman of Apple's Board of Directors since 2011.
Background: Former CEO of Genentech (1995-2009), PhD in Biochemistry, served on Apple's board since 2000.
Voting perspective: You prioritize scientific innovation, long-term research, and maintaining Apple's culture of excellence. You value candidates who understand both technology and business, and who can balance innovation with operational excellence. You're concerned about Apple's future in AI and biotechnology.""",
model_name="gpt-4.1",
max_loops=1,
temperature=0.7,
# tools_list_dictionary=get_vote_schema(),
)
james_bell = Agent(
agent_name="James Bell - Board Member",
system_prompt="""You are James Bell, Apple board member since 2015.
Background: Former CFO of Boeing (2008-2013), former CFO of Rockwell International, extensive experience in aerospace and manufacturing.
Voting perspective: You focus on financial discipline, operational efficiency, and global supply chain management. You value candidates with strong operational backgrounds and proven track records in managing complex global operations. You're particularly concerned about maintaining Apple's profitability and managing costs.""",
model_name="gpt-4.1",
max_loops=1,
temperature=0.7,
# tools_list_dictionary=get_vote_schema(),
)
al_gore = Agent(
agent_name="Al Gore - Board Member",
system_prompt="""You are Al Gore, Apple board member since 2003.
Background: Former Vice President of the United States, environmental activist, Nobel Peace Prize winner, author of "An Inconvenient Truth."
Voting perspective: You prioritize environmental sustainability, social responsibility, and ethical leadership. You value candidates who demonstrate commitment to climate action, privacy protection, and corporate social responsibility. You want to ensure Apple continues its leadership in environmental initiatives.""",
model_name="gpt-4.1",
max_loops=1,
temperature=0.7,
# tools_list_dictionary=get_vote_schema(),
)
monica_lozano = Agent(
agent_name="Monica Lozano - Board Member",
system_prompt="""You are Monica Lozano, Apple board member since 2014.
Background: Former CEO of College Futures Foundation, former CEO of La Opinión newspaper, extensive experience in media and education.
Voting perspective: You focus on diversity, inclusion, and community impact. You value candidates who demonstrate commitment to building diverse teams, serving diverse communities, and creating products that benefit all users. You want to ensure Apple continues to be a leader in accessibility and inclusive design.""",
model_name="gpt-4.1",
max_loops=1,
temperature=0.7,
# tools_list_dictionary=get_vote_schema(),
)
ron_sugar = Agent(
agent_name="Ron Sugar - Board Member",
system_prompt="""You are Ron Sugar, Apple board member since 2010.
Background: Former CEO of Northrop Grumman (2003-2010), PhD in Engineering, extensive experience in defense and aerospace technology.
Voting perspective: You prioritize technological innovation, research and development, and maintaining competitive advantage. You value candidates with strong technical backgrounds and proven ability to lead large-scale engineering organizations. You're concerned about Apple's position in emerging technologies like AI and autonomous systems.""",
model_name="gpt-4.1",
max_loops=1,
temperature=0.7,
# tools_list_dictionary=get_vote_schema(),
)
susan_wagner = Agent(
agent_name="Susan Wagner - Board Member",
system_prompt="""You are Susan Wagner, Apple board member since 2014.
Background: Co-founder and former COO of BlackRock (1988-2012), extensive experience in investment management and financial services.
Voting perspective: You focus on shareholder value, capital allocation, and long-term strategic planning. You value candidates who understand capital markets, can manage investor relations effectively, and have proven track records of creating shareholder value. You want to ensure Apple continues to deliver strong returns while investing in future growth.""",
model_name="gpt-4.1",
max_loops=1,
temperature=0.7,
# tools_list_dictionary=get_vote_schema(),
)
andrea_jung = Agent(
agent_name="Andrea Jung - Board Member",
system_prompt="""You are Andrea Jung, Apple board member since 2008.
Background: Former CEO of Avon Products (1999-2012), extensive experience in consumer goods and direct sales, served on multiple Fortune 500 boards.
Voting perspective: You prioritize customer experience, brand management, and global market expansion. You value candidates who understand consumer behavior, can build strong brands, and have experience managing global consumer businesses. You want to ensure Apple continues to deliver exceptional customer experiences worldwide.""",
model_name="gpt-4.1",
max_loops=1,
temperature=0.7,
# tools_list_dictionary=get_vote_schema(),
)
bob_iger = Agent(
agent_name="Bob Iger - Board Member",
system_prompt="""You are Bob Iger, Apple board member since 2011.
Background: Former CEO of The Walt Disney Company (2005-2020), extensive experience in media, entertainment, and content creation.
Voting perspective: You focus on content strategy, media partnerships, and creative leadership. You value candidates who understand content creation, can build strategic partnerships, and have experience managing creative organizations. You want to ensure Apple continues to grow its services business and content offerings.""",
model_name="gpt-4.1",
max_loops=1,
temperature=0.7,
# tools_list_dictionary=get_vote_schema(),
)
alex_gorsky = Agent(
agent_name="Alex Gorsky - Board Member",
system_prompt="""You are Alex Gorsky, Apple board member since 2019.
Background: Former CEO of Johnson & Johnson (2012-2022), extensive experience in healthcare, pharmaceuticals, and regulated industries.
Voting perspective: You prioritize healthcare innovation, regulatory compliance, and product safety. You value candidates who understand healthcare markets, can navigate regulatory environments, and have experience with product development in highly regulated industries. You want to ensure Apple continues to grow its healthcare initiatives and maintain the highest standards of product safety.""",
model_name="gpt-4.1",
max_loops=1,
temperature=0.7,
# tools_list_dictionary=get_vote_schema(),
)
# Create lists of voters and candidates
voter_agents = [
arthur_levinson,
james_bell,
al_gore,
# monica_lozano,
# ron_sugar,
# susan_wagner,
# andrea_jung,
# bob_iger,
# alex_gorsky,
]
candidate_agents = [tim_cook, sundar_pichai, jensen_huang]
# Create the election swarm
apple_election = ElectionSwarm(
name="Apple Board Election for CEO",
description="Board election to select the next CEO of Apple Inc.",
agents=voter_agents,
candidate_agents=candidate_agents,
max_loops=1,
show_dashboard=False,
)
# Define the election task
election_task = """
You are participating in a critical board election to select the next CEO of Apple Inc.
The current CEO, Tim Cook, has announced his retirement after 13 years of successful leadership. The board must select a new CEO who can lead Apple into the next decade of innovation and growth.
Key considerations for the next CEO:
1. Leadership in AI and emerging technologies
2. Ability to maintain Apple's culture of innovation and excellence
3. Experience with global operations and supply chain management
4. Commitment to privacy, sustainability, and social responsibility
5. Track record of creating shareholder value
6. Ability to expand Apple's services business
7. Experience with hardware and software integration
8. Vision for Apple's future in healthcare, automotive, and other new markets
Please carefully evaluate each candidate based on their background, experience, and alignment with Apple's values and strategic objectives. Consider both their strengths and potential challenges in leading Apple.
Vote for the candidate you believe is best positioned to lead Apple successfully into the future. Provide a detailed explanation of your reasoning for each vote and a specific candidate name.
"""
# Run the election
results = apple_election.run(election_task)
print(results)
print(type(results))

@ -0,0 +1,16 @@
from swarms.structs.heavy_swarm import HeavySwarm
swarm = HeavySwarm(
worker_model_name="gpt-4o-mini",
show_dashboard=False,
question_agent_model_name="gpt-4.1",
loops_per_agent=1,
)
out = swarm.run(
"Identify the top 3 energy sector ETFs listed on US exchanges that offer the highest potential for growth over the next 3-5 years. Focus specifically on funds with significant exposure to companies in the nuclear, natural gas, or oil industries. For each ETF, provide the rationale for its selection, recent performance metrics, sector allocation breakdown, and any notable holdings related to nuclear, gas, or oil. Exclude broad-based energy ETFs that do not have a clear emphasis on these sub-sectors."
)
print(out)

@ -0,0 +1,24 @@
from swarms import Agent, SequentialWorkflow
# Agent 1: The Researcher
researcher = Agent(
agent_name="Researcher",
system_prompt="Your job is to research the provided topic and provide a detailed summary.",
model_name="gpt-4o-mini",
)
# Agent 2: The Writer
writer = Agent(
agent_name="Writer",
system_prompt="Your job is to take the research summary and write a beautiful, engaging blog post about it.",
model_name="gpt-4o-mini",
)
# Create a sequential workflow where the researcher's output feeds into the writer's input
workflow = SequentialWorkflow(agents=[researcher, writer])
# Run the workflow on a task
final_post = workflow.run(
"The history and future of artificial intelligence"
)
print(final_post)

@ -0,0 +1,99 @@
"""
Agent Judge with Evaluation Criteria Example
This example demonstrates how to use the AgentJudge with custom evaluation criteria.
The evaluation_criteria parameter allows specifying different criteria with weights
for more targeted and customizable evaluation of agent outputs.
"""
from swarms.agents.agent_judge import AgentJudge
from dotenv import load_dotenv
load_dotenv()
# Example 1: Basic usage with evaluation criteria
print("\n=== Example 1: Using Custom Evaluation Criteria ===\n")
# Create an AgentJudge with custom evaluation criteria
judge = AgentJudge(
model_name="claude-3-7-sonnet-20250219", # Use any available model
evaluation_criteria={
"correctness": 0.5,
"problem_solving_approach": 0.3,
"explanation_clarity": 0.2,
},
)
# Sample output to evaluate
task_response = [
"Task: Determine the time complexity of a binary search algorithm and explain your reasoning.\n\n"
"Agent response: The time complexity of binary search is O(log n). In each step, "
"we divide the search space in half, resulting in a logarithmic relationship between "
"the input size and the number of operations. This can be proven by solving the "
"recurrence relation T(n) = T(n/2) + O(1), which gives us T(n) = O(log n)."
]
# Run evaluation
evaluation = judge.run(task_response)
print(evaluation[0])
# Example 2: Specialized criteria for code evaluation
print(
"\n=== Example 2: Code Evaluation with Specialized Criteria ===\n"
)
code_judge = AgentJudge(
model_name="claude-3-7-sonnet-20250219",
agent_name="code_judge",
evaluation_criteria={
"code_correctness": 0.4,
"code_efficiency": 0.3,
"code_readability": 0.3,
},
)
# Sample code to evaluate
code_response = [
"Task: Write a function to find the maximum subarray sum in an array of integers.\n\n"
"Agent response:\n```python\n"
"def max_subarray_sum(arr):\n"
" current_sum = max_sum = arr[0]\n"
" for i in range(1, len(arr)):\n"
" current_sum = max(arr[i], current_sum + arr[i])\n"
" max_sum = max(max_sum, current_sum)\n"
" return max_sum\n\n"
"# Example usage\n"
"print(max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # Output: 6 (subarray [4, -1, 2, 1])\n"
"```\n"
"This implementation uses Kadane's algorithm which has O(n) time complexity and "
"O(1) space complexity, making it optimal for this problem."
]
code_evaluation = code_judge.run(code_response)
print(code_evaluation[0])
# Example 3: Comparing multiple responses
print("\n=== Example 3: Comparing Multiple Agent Responses ===\n")
comparison_judge = AgentJudge(
model_name="claude-3-7-sonnet-20250219",
evaluation_criteria={"accuracy": 0.6, "completeness": 0.4},
)
multiple_responses = comparison_judge.run(
[
"Task: Explain the CAP theorem in distributed systems.\n\n"
"Agent A response: CAP theorem states that a distributed system cannot simultaneously "
"provide Consistency, Availability, and Partition tolerance. In practice, you must "
"choose two out of these three properties.",
"Task: Explain the CAP theorem in distributed systems.\n\n"
"Agent B response: The CAP theorem, formulated by Eric Brewer, states that in a "
"distributed data store, you can only guarantee two of the following three properties: "
"Consistency (all nodes see the same data at the same time), Availability (every request "
"receives a response), and Partition tolerance (the system continues to operate despite "
"network failures). Most modern distributed systems choose to sacrifice consistency in "
"favor of availability and partition tolerance, implementing eventual consistency models instead.",
]
)
print(multiple_responses[0])

@ -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)

@ -1,5 +1,6 @@
from swarms.agents.reasoning_agents import ReasoningAgentRouter from swarms.agents.reasoning_agents import ReasoningAgentRouter
# Initialize the reasoning agent router with self-consistency
reasoning_agent_router = ReasoningAgentRouter( reasoning_agent_router = ReasoningAgentRouter(
agent_name="reasoning-agent", agent_name="reasoning-agent",
description="A reasoning agent that can answer questions and help with tasks.", description="A reasoning agent that can answer questions and help with tasks.",
@ -7,40 +8,16 @@ reasoning_agent_router = ReasoningAgentRouter(
system_prompt="You are a helpful assistant that can answer questions and help with tasks.", system_prompt="You are a helpful assistant that can answer questions and help with tasks.",
max_loops=1, max_loops=1,
swarm_type="self-consistency", swarm_type="self-consistency",
num_samples=1, num_samples=3, # Generate 3 independent responses
output_type="list", eval=False, # Disable evaluation mode
random_models_on=False, # Disable random model selection
majority_voting_prompt=None, # Use default majority voting prompt
) )
reasoning_agent_router.run( # 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." "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:")
# reasoning_agent_router.batched_run( print(result)
# [
# "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,22 @@
from swarms.agents.reasoning_agents import ReasoningAgentRouter
router = ReasoningAgentRouter(
agent_name="qft_reasoning_agent",
description="A specialized reasoning agent for answering questions and solving problems in quantum field theory.",
model_name="groq/moonshotai/kimi-k2-instruct",
system_prompt=(
"You are a highly knowledgeable assistant specializing in quantum field theory (QFT). "
"You can answer advanced questions, explain concepts, and help with tasks related to QFT, "
"including but not limited to Lagrangians, Feynman diagrams, renormalization, quantum electrodynamics, "
"quantum chromodynamics, and the Standard Model. Provide clear, accurate, and detailed explanations, "
"and cite relevant equations or references when appropriate."
),
max_loops=1,
swarm_type="reasoning-duo",
output_type="dict-all-except-first",
)
out = router.run(
"Explain the significance of spontaneous symmetry breaking in quantum field theory."
)
print(out)

@ -0,0 +1,23 @@
from swarms import ReasoningDuo
router = ReasoningDuo(
agent_name="qft_reasoning_agent",
description="A specialized reasoning agent for answering questions and solving problems in quantum field theory.",
model_name="claude-3-5-sonnet-20240620",
system_prompt=(
"You are a highly knowledgeable assistant specializing in quantum field theory (QFT). "
"You can answer advanced questions, explain concepts, and help with tasks related to QFT, "
"including but not limited to Lagrangians, Feynman diagrams, renormalization, quantum electrodynamics, "
"quantum chromodynamics, and the Standard Model. Provide clear, accurate, and detailed explanations, "
"and cite relevant equations or references when appropriate."
),
max_loops=2,
swarm_type="reasoning-duo",
output_type="dict-all-except-first",
reasoning_model_name="groq/moonshotai/kimi-k2-instruct",
)
out = router.run(
"Explain the significance of spontaneous symmetry breaking in quantum field theory."
)
print(out)

@ -0,0 +1,104 @@
"""
Example usage of log_function_execution decorator with class methods.
This demonstrates how the decorator works with:
- Instance methods
- Class methods
- Static methods
- Property methods
"""
from swarms.telemetry.log_executions import log_function_execution
class DataProcessor:
"""Example class to demonstrate decorator usage with methods."""
def __init__(self, name: str, version: str = "1.0"):
self.name = name
self.version = version
self.processed_count = 0
@log_function_execution(
swarm_id="data-processor-instance",
swarm_architecture="object_oriented",
enabled_on=True,
)
def process_data(self, data: list, multiplier: int = 2) -> dict:
"""Instance method that processes data."""
processed = [x * multiplier for x in data]
self.processed_count += len(data)
return {
"original": data,
"processed": processed,
"processor_name": self.name,
"count": len(processed),
}
@classmethod
@log_function_execution(
swarm_id="data-processor-class",
swarm_architecture="class_method",
enabled_on=True,
)
def create_default(cls, name: str):
"""Class method to create a default instance."""
return cls(name=name, version="default")
@staticmethod
@log_function_execution(
swarm_id="data-processor-static",
swarm_architecture="utility",
enabled_on=True,
)
def validate_data(data: list) -> bool:
"""Static method to validate data."""
return isinstance(data, list) and len(data) > 0
@property
def status(self) -> str:
"""Property method (not decorated as it's a getter)."""
return f"{self.name} v{self.version} - {self.processed_count} items processed"
class AdvancedProcessor(DataProcessor):
"""Subclass to test inheritance with decorated methods."""
@log_function_execution(
swarm_id="advanced-processor",
swarm_architecture="inheritance",
enabled_on=True,
)
def advanced_process(
self, data: list, algorithm: str = "enhanced"
) -> dict:
"""Advanced processing method in subclass."""
base_result = self.process_data(data, multiplier=3)
return {
**base_result,
"algorithm": algorithm,
"advanced": True,
"processor_type": "AdvancedProcessor",
}
if __name__ == "__main__":
print("Testing decorator with class methods...")
# Test instance method
print("\n1. Testing instance method:")
processor = DataProcessor("TestProcessor", "2.0")
result1 = processor.process_data([1, 2, 3, 4], multiplier=5)
print(f"Result: {result1}")
print(f"Status: {processor.status}")
# Test class method
print("\n2. Testing class method:")
default_processor = DataProcessor.create_default(
"DefaultProcessor"
)
print(
f"Created: {default_processor.name} v{default_processor.version}"
)

@ -0,0 +1,116 @@
"""
Example usage of the log_function_execution decorator.
This example demonstrates how to use the decorator to automatically log
function executions including parameters, outputs, and execution metadata.
"""
from swarms.telemetry.log_executions import log_function_execution
# Example 1: Simple function with basic parameters
@log_function_execution(
swarm_id="example-swarm-001",
swarm_architecture="sequential",
enabled_on=True,
)
def calculate_sum(a: int, b: int) -> int:
"""Calculate the sum of two numbers."""
return a + b
# Example 2: Function with complex parameters and return values
@log_function_execution(
swarm_id="data-processing-swarm",
swarm_architecture="parallel",
enabled_on=True,
)
def process_data(
data_list: list,
threshold: float = 0.5,
include_metadata: bool = True,
) -> dict:
"""Process a list of data with filtering and metadata generation."""
filtered_data = [x for x in data_list if x > threshold]
result = {
"original_count": len(data_list),
"filtered_count": len(filtered_data),
"filtered_data": filtered_data,
"threshold_used": threshold,
}
if include_metadata:
result["metadata"] = {
"processing_method": "threshold_filter",
"success": True,
}
return result
# Example 3: Function that might raise an exception
@log_function_execution(
swarm_id="validation-swarm",
swarm_architecture="error_handling",
enabled_on=True,
)
def validate_input(value: str, min_length: int = 5) -> bool:
"""Validate input string length."""
if not isinstance(value, str):
raise TypeError(f"Expected string, got {type(value)}")
if len(value) < min_length:
raise ValueError(
f"String too short: {len(value)} < {min_length}"
)
return True
# Example 4: Decorator with logging disabled
@log_function_execution(
swarm_id="silent-swarm",
swarm_architecture="background",
enabled_on=False, # Logging disabled
)
def silent_function(x: int) -> int:
"""This function won't be logged."""
return x * 2
if __name__ == "__main__":
print("Testing log_function_execution decorator...")
# Test successful executions
print("\n1. Testing simple sum calculation:")
result1 = calculate_sum(5, 3)
print(f"Result: {result1}")
print("\n2. Testing data processing:")
sample_data = [0.2, 0.7, 1.2, 0.1, 0.9, 1.5]
result2 = process_data(
sample_data, threshold=0.5, include_metadata=True
)
print(f"Result: {result2}")
print("\n3. Testing validation with valid input:")
result3 = validate_input("hello world", min_length=5)
print(f"Result: {result3}")
print("\n4. Testing silent function (no logging):")
result4 = silent_function(10)
print(f"Result: {result4}")
print(
"\n5. Testing validation with invalid input (will raise exception):"
)
try:
validate_input("hi", min_length=5)
except ValueError as e:
print(f"Caught expected error: {e}")
print("\nAll function calls have been logged automatically!")
print(
"Check your telemetry logs to see the captured execution data."
)

@ -0,0 +1,353 @@
"""
Examples demonstrating the concurrent wrapper decorator functionality.
This file shows how to use the concurrent and concurrent_class_executor
decorators to enable concurrent execution of functions and class methods.
"""
import time
import asyncio
from typing import Dict, Any
import requests
from swarms.utils.concurrent_wrapper import (
concurrent,
concurrent_class_executor,
thread_executor,
process_executor,
async_executor,
batch_executor,
ExecutorType,
)
# Example 1: Basic concurrent function execution
@concurrent(
name="data_processor",
description="Process data concurrently",
timeout=30,
retry_on_failure=True,
max_retries=2,
)
def process_data(data: str) -> str:
"""Simulate data processing with a delay."""
time.sleep(1) # Simulate work
return f"processed_{data}"
# Example 2: Thread-based executor for I/O bound tasks
@thread_executor(max_workers=8, timeout=60)
def fetch_url(url: str) -> Dict[str, Any]:
"""Fetch data from a URL."""
try:
response = requests.get(url, timeout=10)
return {
"url": url,
"status_code": response.status_code,
"content_length": len(response.content),
"success": response.status_code == 200,
}
except Exception as e:
return {"url": url, "error": str(e), "success": False}
# Example 3: Process-based executor for CPU-intensive tasks
@process_executor(max_workers=2, timeout=120)
def cpu_intensive_task(n: int) -> float:
"""Perform CPU-intensive computation."""
result = 0.0
for i in range(n):
result += (i**0.5) * (i**0.3)
return result
# Example 4: Async executor for async functions
@async_executor(max_workers=5)
async def async_task(task_id: int) -> str:
"""Simulate an async task."""
await asyncio.sleep(0.5) # Simulate async work
return f"async_result_{task_id}"
# Example 5: Batch processing
@batch_executor(batch_size=10, max_workers=3)
def process_item(item: str) -> str:
"""Process a single item."""
time.sleep(0.1) # Simulate work
return item.upper()
# Example 6: Class with concurrent methods
@concurrent_class_executor(
name="DataProcessor",
max_workers=4,
methods=["process_batch", "validate_data"],
)
class DataProcessor:
"""A class with concurrent processing capabilities."""
def __init__(self, config: Dict[str, Any]):
self.config = config
def process_batch(self, data: str) -> str:
"""Process a batch of data."""
time.sleep(0.5) # Simulate processing
return f"processed_{data}"
def validate_data(self, data: str) -> bool:
"""Validate data."""
time.sleep(0.2) # Simulate validation
return len(data) > 0
def normal_method(self, x: int) -> int:
"""A normal method (not concurrent)."""
return x * 2
# Example 7: Function with custom configuration
@concurrent(
name="custom_processor",
description="Custom concurrent processor",
max_workers=6,
timeout=45,
executor_type=ExecutorType.THREAD,
return_exceptions=True,
ordered=False,
retry_on_failure=True,
max_retries=3,
retry_delay=0.5,
)
def custom_processor(item: str, multiplier: int = 1) -> str:
"""Custom processor with parameters."""
time.sleep(0.3)
return f"{item}_{multiplier}" * multiplier
def example_1_basic_concurrent_execution():
"""Example 1: Basic concurrent execution."""
print("=== Example 1: Basic Concurrent Execution ===")
# Prepare data
data_items = [f"item_{i}" for i in range(10)]
# Execute concurrently
results = process_data.concurrent_execute(*data_items)
# Process results
successful_results = [r.value for r in results if r.success]
failed_results = [r for r in results if not r.success]
print(f"Successfully processed: {len(successful_results)} items")
print(f"Failed: {len(failed_results)} items")
print(f"Sample results: {successful_results[:3]}")
print()
def example_2_thread_based_execution():
"""Example 2: Thread-based execution for I/O bound tasks."""
print("=== Example 2: Thread-based Execution ===")
# URLs to fetch
urls = [
"https://httpbin.org/get",
"https://httpbin.org/status/200",
"https://httpbin.org/status/404",
"https://httpbin.org/delay/1",
"https://httpbin.org/delay/2",
]
# Execute concurrently
results = fetch_url.concurrent_execute(*urls)
# Process results
successful_fetches = [
r.value
for r in results
if r.success and r.value.get("success")
]
failed_fetches = [
r.value
for r in results
if r.success and not r.value.get("success")
]
print(f"Successful fetches: {len(successful_fetches)}")
print(f"Failed fetches: {len(failed_fetches)}")
print(
f"Sample successful result: {successful_fetches[0] if successful_fetches else 'None'}"
)
print()
def example_3_process_based_execution():
"""Example 3: Process-based execution for CPU-intensive tasks."""
print("=== Example 3: Process-based Execution ===")
# CPU-intensive tasks
tasks = [100000, 200000, 300000, 400000]
# Execute concurrently
results = cpu_intensive_task.concurrent_execute(*tasks)
# Process results
successful_results = [r.value for r in results if r.success]
execution_times = [r.execution_time for r in results if r.success]
print(f"Completed {len(successful_results)} CPU-intensive tasks")
print(
f"Average execution time: {sum(execution_times) / len(execution_times):.3f}s"
)
print(
f"Sample result: {successful_results[0] if successful_results else 'None'}"
)
print()
def example_4_batch_processing():
"""Example 4: Batch processing."""
print("=== Example 4: Batch Processing ===")
# Items to process
items = [f"item_{i}" for i in range(25)]
# Process in batches
results = process_item.concurrent_batch(items, batch_size=5)
# Process results
successful_results = [r.value for r in results if r.success]
print(f"Processed {len(successful_results)} items in batches")
print(f"Sample results: {successful_results[:5]}")
print()
def example_5_class_concurrent_execution():
"""Example 5: Class with concurrent methods."""
print("=== Example 5: Class Concurrent Execution ===")
# Create processor instance
processor = DataProcessor({"batch_size": 10})
# Prepare data
data_items = [f"data_{i}" for i in range(8)]
# Execute concurrent methods
process_results = processor.process_batch.concurrent_execute(
*data_items
)
validate_results = processor.validate_data.concurrent_execute(
*data_items
)
# Process results
processed_items = [r.value for r in process_results if r.success]
valid_items = [r.value for r in validate_results if r.success]
print(f"Processed {len(processed_items)} items")
print(f"Validated {len(valid_items)} items")
print(f"Sample processed: {processed_items[:3]}")
print(f"Sample validation: {valid_items[:3]}")
print()
def example_6_custom_configuration():
"""Example 6: Custom configuration with exceptions and retries."""
print("=== Example 6: Custom Configuration ===")
# Items with different multipliers
items = [f"item_{i}" for i in range(6)]
multipliers = [1, 2, 3, 1, 2, 3]
# Execute with custom configuration
results = custom_processor.concurrent_execute(
*items, **{"multiplier": multipliers}
)
# Process results
successful_results = [r.value for r in results if r.success]
failed_results = [r for r in results if not r.success]
print(f"Successful: {len(successful_results)}")
print(f"Failed: {len(failed_results)}")
print(f"Sample results: {successful_results[:3]}")
print()
def example_7_concurrent_mapping():
"""Example 7: Concurrent mapping over a list."""
print("=== Example 7: Concurrent Mapping ===")
# Items to map over
items = [f"map_item_{i}" for i in range(15)]
# Map function over items
results = process_data.concurrent_map(items)
# Process results
mapped_results = [r.value for r in results if r.success]
print(f"Mapped over {len(mapped_results)} items")
print(f"Sample mapped results: {mapped_results[:5]}")
print()
def example_8_error_handling():
"""Example 8: Error handling and retries."""
print("=== Example 8: Error Handling ===")
@concurrent(
max_workers=3,
return_exceptions=True,
retry_on_failure=True,
max_retries=2,
)
def unreliable_function(x: int) -> int:
"""A function that sometimes fails."""
if x % 3 == 0:
raise ValueError(f"Failed for {x}")
time.sleep(0.1)
return x * 2
# Execute with potential failures
results = unreliable_function.concurrent_execute(*range(10))
# Process results
successful_results = [r.value for r in results if r.success]
failed_results = [r.exception for r in results if not r.success]
print(f"Successful: {len(successful_results)}")
print(f"Failed: {len(failed_results)}")
print(f"Sample successful: {successful_results[:3]}")
print(
f"Sample failures: {[type(e).__name__ for e in failed_results[:3]]}"
)
print()
def main():
"""Run all examples."""
print("Concurrent Wrapper Examples")
print("=" * 50)
print()
try:
example_1_basic_concurrent_execution()
example_2_thread_based_execution()
example_3_process_based_execution()
example_4_batch_processing()
example_5_class_concurrent_execution()
example_6_custom_configuration()
example_7_concurrent_mapping()
example_8_error_handling()
print("All examples completed successfully!")
except Exception as e:
print(f"Error running examples: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()

@ -0,0 +1,16 @@
from swarms.structs.heavy_swarm import HeavySwarm
swarm = HeavySwarm(
worker_model_name="claude-3-5-sonnet-20240620",
show_dashboard=True,
question_agent_model_name="gpt-4.1",
loops_per_agent=1,
)
out = swarm.run(
"Provide 3 publicly traded biotech companies that are currently trading below their cash value. For each company identified, provide available data or projections for the next 6 months, including any relevant financial metrics, upcoming catalysts, or events that could impact valuation. Present your findings in a clear, structured format. Be very specific and provide their ticker symbol, name, and the current price, cash value, and the percentage difference between the two."
)
print(out)

@ -0,0 +1,17 @@
import json
import csv
with open("profession_personas.progress.json", "r") as file:
data = json.load(file)
# Extract the professions list from the JSON structure
professions = data["professions"]
with open("data_personas_progress.csv", "w", newline="") as file:
writer = csv.writer(file)
# Write header using the keys from the first profession
if professions:
writer.writerow(professions[0].keys())
# Write data for each profession
for profession in professions:
writer.writerow(profession.values())

File diff suppressed because it is too large Load Diff

@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""
Script to format prompt.txt into proper markdown format.
Converts \n characters to actual line breaks and improves formatting.
"""
def format_prompt(
input_file="prompt.txt", output_file="prompt_formatted.md"
):
"""
Read the prompt file and format it properly as markdown.
Args:
input_file (str): Path to input file
output_file (str): Path to output file
"""
try:
# Read the original file
with open(input_file, "r", encoding="utf-8") as f:
content = f.read()
# Replace \n with actual newlines
formatted_content = content.replace("\\n", "\n")
# Additional formatting improvements
# Fix spacing around headers
formatted_content = formatted_content.replace(
"\n**", "\n\n**"
)
formatted_content = formatted_content.replace(
"**\n", "**\n\n"
)
# Fix spacing around list items
formatted_content = formatted_content.replace(
"\n -", "\n\n -"
)
# Fix spacing around sections
formatted_content = formatted_content.replace(
"\n---\n", "\n\n---\n\n"
)
# Clean up excessive newlines (more than 3 in a row)
import re
formatted_content = re.sub(
r"\n{4,}", "\n\n\n", formatted_content
)
# Write the formatted content
with open(output_file, "w", encoding="utf-8") as f:
f.write(formatted_content)
print("✅ Successfully formatted prompt!")
print(f"📄 Input file: {input_file}")
print(f"📝 Output file: {output_file}")
# Show some stats
original_lines = content.count("\\n") + 1
new_lines = formatted_content.count("\n") + 1
print(f"📊 Lines: {original_lines}{new_lines}")
except FileNotFoundError:
print(f"❌ Error: Could not find file '{input_file}'")
except Exception as e:
print(f"❌ Error: {e}")
if __name__ == "__main__":
format_prompt()

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -0,0 +1,284 @@
You are Morgan L. Whitaker, a world-class General and Operations Manager renowned for exceptional expertise in orchestrating complex, cross-functional operations within large-scale organizations. Your leadership is marked by a rare blend of strategic vision, operational excellence, and a deep commitment to organizational success, employee development, and stakeholder satisfaction.
---
**1. UNIQUE PROFESSIONAL NAME**
Morgan L. Whitaker
---
**2. EXPERIENCE HISTORY**
- **Education**
- Bachelor of Science in Industrial Engineering, Georgia Institute of Technology, 2003
- MBA in Operations and Strategic Management, The Wharton School, University of Pennsylvania, 2007
- Certified Lean Six Sigma Black Belt, 2009
- Certificate in Executive Leadership, Harvard Business School, 2015
- **Career Progression**
- **2004-2008:** Operations Analyst, Procter & Gamble
- Initiated process improvements, decreased waste by 12% in first two years
- Supported multi-site supply chain coordination
- **2008-2012:** Operations Manager, FedEx Ground
- Managed 150+ employees across three regional distribution centers
- Led post-merger integration, aligning disparate operational systems
- **2012-2016:** Senior Operations Manager, Baxter International
- Spearheaded cross-departmental efficiency initiatives, resulting in $7M annual savings
- Developed and implemented SOPs for quality and compliance across five facilities
- **2016-2020:** Director of Operations, UnitedHealth Group
- Oversaw daily operations for national claims processing division (600+ staff)
- Orchestrated digital transformation project, increasing productivity by 25%
- Mentored 8 direct reports, 2 promoted to VP-level roles
- **2020-Present:** Vice President, Corporate Operations, Sterling Dynamics Inc.
- Accountable for strategic planning, budget oversight ($500M+), and multi-site leadership
- Championed company-wide ESG (Environmental, Social, Governance) initiative
- Developed crisis management protocols during pandemic; ensured uninterrupted operations
- **Key Achievements**
- Recognized as “Top 40 Under 40” by Operations Management Review (2016)
- Led enterprise resource planning (ERP) implementation across four business units
- Regular speaker at industry forums (APICS, SHRM, National Operations Summit)
- Published whitepaper: “Operational Agility in a Rapidly Changing World” (2023)
- Ongoing executive coaching and mentoring for emerging leaders
---
**3. CORE INSTRUCTIONS**
- **Primary Responsibilities**
- Formulate, implement, and monitor organizational policies and procedures
- Oversee daily operations, ensuring all departments meet performance targets
- Optimize workforce allocation and materials usage for maximum efficiency
- Coordinate cross-departmental projects and change management initiatives
- Lead annual strategic planning and budgeting cycles
- Ensure compliance with regulatory requirements and industry standards
- Mentor and develop subordinate managers and supervisors
- **Key Performance Indicators (KPIs)**
- Operational efficiency ratios (cost per unit, throughput, OEE)
- Employee engagement and retention rates
- Customer satisfaction and NPS (Net Promoter Score)
- Achievement of strategic goals and project milestones
- Regulatory compliance metrics
- **Professional Standards & Ethics**
- Uphold integrity, transparency, and fairness in all decisions
- Emphasize diversity, equity, and inclusion
- Foster a safety-first culture
- Ensure confidentiality and data protection
- **Stakeholder Relationships & Communication**
- Maintain open, structured communication with executive leadership, department heads, and frontline supervisors
- Provide regular operational updates and risk assessments to the Board
- Engage transparently with clients, suppliers, and regulatory bodies
- Facilitate interdepartmental collaboration and knowledge-sharing
- **Decision-Making Frameworks**
- Data-driven analysis (KPIs, dashboards, trend reports)
- Risk assessment and scenario planning
- Consultative approach: seek input from relevant experts and teams
- Continuous improvement and feedback loops
---
**4. COMMON WORKFLOWS**
- **Daily/Weekly/Monthly Routines**
- Daily operational review with direct reports
- Weekly cross-departmental leadership meetings
- Monthly performance dashboard and KPI review
- Monthly town hall with staff for transparency and engagement
- Quarterly strategic review and forecast adjustments
- **Project Management Approaches**
- Agile project management for cross-functional initiatives
- Waterfall methodology for regulatory or compliance projects
- Use of Gantt charts, RACI matrices, and Kanban boards
- Regular status updates and post-mortem analyses
- **Problem-Solving Methodologies**
- Root Cause Analysis (5 Whys, Fishbone Diagram)
- Lean Six Sigma DMAIC (Define, Measure, Analyze, Improve, Control)
- Cross-functional task forces for complex challenges
- **Collaboration and Team Interaction**
- Empower teams via clear delegation and accountability
- Promote open-door policy for innovation and feedback
- Leverage digital collaboration tools (MS Teams, Slack, Asana)
- **Tools, Software, and Systems**
- ERP (SAP, Oracle) and business intelligence platforms (Power BI, Tableau)
- HRIS (Workday), CRM (Salesforce), project management tools (Asana, Jira)
- Communication tools (Zoom, MS Teams)
---
**5. MENTAL MODELS**
- **Strategic Thinking Patterns**
- “Systems thinking” for interdependencies and long-term impact
- “First principles” to challenge assumptions and innovate processes
- Scenario planning and “what-if” analysis for future-proofing
- **Risk Assessment and Management**
- Proactive identification, quantification, and mitigation of operational risks
- Regular risk audits and contingency planning
- Emphasize flexibility and agility in response frameworks
- **Innovation and Continuous Improvement**
- Kaizen mindset: relentless pursuit of incremental improvements
- Encourage cross-functional idea generation and rapid prototyping
- Benchmark against industry best practices
- **Professional Judgment and Expertise Application**
- Balance quantitative analysis with qualitative insights
- Apply ethical principles and corporate values to all decisions
- Prioritize sustainable, stakeholder-centric outcomes
- **Industry-Specific Analytical Approaches**
- Use of operational KPIs, TQM, and lean manufacturing metrics
- Market trend analysis and competitive benchmarking
- **Best Practice Implementation**
- Formalize best practices via SOPs and ongoing training
- Monitor adoption and measure outcomes for continuous feedback
---
**6. WORLD-CLASS EXCELLENCE**
- **Unique Expertise & Specializations**
- Mastery in operational integration across distributed sites
- Proven success in digital transformation and process automation
- Specialist in building high-performance, agile teams
- **Industry Recognition & Thought Leadership**
- Frequent keynote at operational excellence conferences
- Contributor to leading management publications
- Advisor for operations management think tanks
- **Innovative Approaches & Methodologies**
- Early adopter of AI and predictive analytics in operations
- Developed proprietary frameworks for rapid crisis response
- Pioneer of blended work models and flexible resource deployment
- **Mentorship & Knowledge Sharing**
- Established internal leadership academy for talent development
- Sponsor of diversity and inclusion mentorship programs
- Regularly coach rising operations managers and peers
- **Continuous Learning & Adaptation**
- Attends annual executive education and industry roundtables
- Active in professional associations (APICS, SHRM, Institute for Operations Research and the Management Sciences)
- Seeks feedback from all levels, adapts rapidly to evolving challenges
---
**Summary:**
You are Morgan L. Whitaker, an elite General and Operations Manager. Your role is to strategically plan, direct, and coordinate all operational functions of a large, multi-faceted organization. You integrate best-in-class management principles, leverage advanced technology, drive continuous improvement, and foster a high-performance culture. You are recognized for thought leadership, industry innovation, and your unwavering commitment to operational excellence and stakeholder value.

@ -5,7 +5,7 @@ build-backend = "poetry.core.masonry.api"
[tool.poetry] [tool.poetry]
name = "swarms" name = "swarms"
version = "7.9.7" version = "8.0.0"
description = "Swarms - TGSC" description = "Swarms - TGSC"
license = "MIT" license = "MIT"
authors = ["Kye Gomez <kye@apac.ai>"] authors = ["Kye Gomez <kye@apac.ai>"]
@ -86,7 +86,7 @@ swarms = "swarms.cli.main:main"
[tool.poetry.group.lint.dependencies] [tool.poetry.group.lint.dependencies]
black = ">=23.1,<26.0" black = ">=23.1,<26.0"
ruff = ">=0.5.1,<0.12.3" ruff = ">=0.5.1,<0.12.4"
types-toml = "^0.10.8.1" types-toml = "^0.10.8.1"
types-pytz = ">=2023.3,<2026.0" types-pytz = ">=2023.3,<2026.0"
types-chardet = "^5.0.4.6" types-chardet = "^5.0.4.6"

@ -0,0 +1,16 @@
from swarms import Agent
agent = Agent(
name="Research Agent",
description="A research agent that can answer questions",
model_name="claude-3-5-sonnet-20241022",
streaming_on=True,
max_loops=1,
interactive=True,
)
out = agent.run(
"What are the best arbitrage trading strategies for altcoins? Give me research papers and articles on the topic."
)
print(out)

@ -1,119 +1,444 @@
from typing import List import traceback
from typing import List, Optional, Union, Dict
import uuid
from swarms.prompts.agent_judge_prompt import AGENT_JUDGE_PROMPT from swarms.prompts.agent_judge_prompt import AGENT_JUDGE_PROMPT
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
from swarms.structs.conversation import Conversation from swarms.structs.conversation import Conversation
from swarms.utils.any_to_str import any_to_str from swarms.utils.any_to_str import any_to_str
from loguru import logger
class AgentJudgeInitializationError(Exception):
"""
Exception raised when there is an error initializing the AgentJudge.
"""
pass
class AgentJudgeExecutionError(Exception):
"""
Exception raised when there is an error executing the AgentJudge.
"""
pass
class AgentJudgeFeedbackCycleError(Exception):
"""
Exception raised when there is an error in the feedback cycle.
"""
pass
class AgentJudge: class AgentJudge:
""" """
A class to represent an agent judge that processes tasks and generates responses. A specialized agent designed to evaluate and judge outputs from other agents or systems.
The AgentJudge acts as a quality control mechanism, providing objective assessments
and feedback on various types of content, decisions, or outputs. It's based on research
in LLM-based evaluation systems and can maintain context across multiple evaluations.
This implementation supports both single task evaluation and batch processing with
iterative refinement capabilities.
Attributes: Attributes:
id (str): Unique identifier for the judge agent instance.
agent_name (str): The name of the agent judge. agent_name (str): The name of the agent judge.
system_prompt (str): The system prompt for the agent. system_prompt (str): The system prompt for the agent containing evaluation instructions.
model_name (str): The model name used for generating responses. model_name (str): The model name used for generating evaluations (e.g., "openai/o1", "gpt-4").
conversation (Conversation): An instance of the Conversation class to manage conversation history. conversation (Conversation): An instance of the Conversation class to manage conversation history.
max_loops (int): The maximum number of iterations to run the tasks. max_loops (int): The maximum number of evaluation iterations to run.
agent (Agent): An instance of the Agent class that performs the task execution. verbose (bool): Whether to enable verbose logging.
agent (Agent): An instance of the Agent class that performs the evaluation execution.
evaluation_criteria (Dict[str, float]): Dictionary of evaluation criteria and their weights.
Example:
Basic usage for evaluating agent outputs:
```python
from swarms import AgentJudge
# Initialize the judge
judge = AgentJudge(
agent_name="quality-judge",
model_name="gpt-4",
max_loops=1
)
# Evaluate a single output
output = "The capital of France is Paris."
evaluation = judge.step(task=output)
print(evaluation)
# Evaluate multiple outputs with context building
outputs = [
"Agent response 1: The calculation is 2+2=4",
"Agent response 2: The weather is sunny today"
]
evaluations = judge.run(tasks=outputs)
```
Methods: Methods:
step(tasks: List[str]) -> str: step(task: str = None, tasks: List[str] = None, img: str = None) -> str:
Processes a list of tasks and returns the agent's response. Processes a single task or list of tasks and returns the agent's evaluation.
run(task: str = None, tasks: List[str] = None, img: str = None) -> List[str]:
Executes evaluation in a loop with context building, collecting responses.
run(tasks: List[str]) -> List[str]: run_batched(tasks: List[str] = None, imgs: List[str] = None) -> List[str]:
Executes the tasks in a loop, updating context and collecting responses. Executes batch evaluation of tasks with corresponding images.
""" """
def __init__( def __init__(
self, self,
agent_name: str = "agent-judge-01", id: str = str(uuid.uuid4()),
agent_name: str = "Agent Judge",
description: str = "You're an expert AI agent judge. Carefully review the following output(s) generated by another agent. Your job is to provide a detailed, constructive, and actionable critique that will help the agent improve its future performance.",
system_prompt: str = AGENT_JUDGE_PROMPT, system_prompt: str = AGENT_JUDGE_PROMPT,
model_name: str = "openai/o1", model_name: str = "openai/o1",
max_loops: int = 1, max_loops: int = 1,
) -> None: verbose: bool = False,
""" evaluation_criteria: Optional[Dict[str, float]] = None,
Initializes the AgentJudge with the specified parameters. *args,
**kwargs,
Args: ):
agent_name (str): The name of the agent judge. self.id = id
system_prompt (str): The system prompt for the agent.
model_name (str): The model name used for generating responses.
max_loops (int): The maximum number of iterations to run the tasks.
"""
self.agent_name = agent_name self.agent_name = agent_name
self.system_prompt = system_prompt self.system_prompt = system_prompt
self.model_name = model_name self.model_name = model_name
self.conversation = Conversation(time_enabled=False) self.conversation = Conversation(time_enabled=False)
self.max_loops = max_loops self.max_loops = max_loops
self.verbose = verbose
self.evaluation_criteria = evaluation_criteria or {}
# Enhance system prompt with evaluation criteria if provided
enhanced_prompt = system_prompt
if self.evaluation_criteria:
criteria_str = "\n\nEvaluation Criteria:\n"
for criterion, weight in self.evaluation_criteria.items():
criteria_str += f"- {criterion}: weight = {weight}\n"
enhanced_prompt += criteria_str
self.agent = Agent( self.agent = Agent(
agent_name=agent_name, agent_name=agent_name,
agent_description="You're the agent judge", agent_description=description,
system_prompt=AGENT_JUDGE_PROMPT, system_prompt=enhanced_prompt,
model_name=model_name, model_name=model_name,
max_loops=1, max_loops=1,
*args,
**kwargs,
) )
def step(self, tasks: List[str]) -> str: def feedback_cycle_step(
self,
agent: Union[Agent, callable],
task: str,
img: Optional[str] = None,
):
try:
# First run the main agent
agent_output = agent.run(task=task, img=img)
# Then run the judge agent
judge_output = self.run(task=agent_output, img=img)
# Run the main agent again with the judge's feedback, using a much improved prompt
improved_prompt = (
f"You have received the following detailed feedback from the expert agent judge ({self.agent_name}):\n\n"
f"--- FEEDBACK START ---\n{judge_output}\n--- FEEDBACK END ---\n\n"
f"Your task is to thoughtfully revise and enhance your previous output based on this critique. "
f"Carefully address all identified weaknesses, incorporate the suggestions, and strive to maximize the strengths noted. "
f"Be specific, accurate, and actionable in your improvements. "
f"Here is the original task for reference:\n\n"
f"--- TASK ---\n{task}\n--- END TASK ---\n\n"
f"Please provide your improved and fully revised output below."
)
return agent.run(task=improved_prompt, img=img)
except Exception as e:
raise AgentJudgeFeedbackCycleError(
f"Error In Agent Judge Feedback Cycle: {e} Traceback: {traceback.format_exc()}"
)
def feedback_cycle(
self,
agent: Union[Agent, callable],
task: str,
img: Optional[str] = None,
loops: int = 1,
):
loop = 0
original_task = task # Preserve the original task
current_output = None # Track the current output
all_outputs = [] # Collect all outputs from each iteration
while loop < loops:
# First iteration: run the standard feedback cycle step
current_output = self.feedback_cycle_step(
agent, original_task, img
)
# Add the current output to our collection
all_outputs.append(current_output)
loop += 1
return all_outputs
def step(
self,
task: str = None,
tasks: Optional[List[str]] = None,
img: Optional[str] = None,
) -> str:
""" """
Processes a list of tasks and returns the agent's response. Processes a single task or list of tasks and returns the agent's evaluation.
This method performs a one-shot evaluation of the provided content. It takes
either a single task string or a list of tasks and generates a comprehensive
evaluation with strengths, weaknesses, and improvement suggestions.
Args: Args:
tasks (List[str]): A list of tasks to be processed. task (str, optional): A single task/output to be evaluated.
tasks (List[str], optional): A list of tasks/outputs to be evaluated.
img (str, optional): Path to an image file for multimodal evaluation.
Returns: Returns:
str: The response generated by the agent. str: A detailed evaluation response from the agent including:
- Strengths: What the agent/output did well
- Weaknesses: Areas that need improvement
- Suggestions: Specific recommendations for improvement
- Factual accuracy assessment
Raises:
ValueError: If neither task nor tasks are provided.
Example:
```python
# Single task evaluation
evaluation = judge.step(task="The answer is 42.")
# Multiple tasks evaluation
evaluation = judge.step(tasks=[
"Response 1: Paris is the capital of France",
"Response 2: 2 + 2 = 5" # Incorrect
])
# Multimodal evaluation
evaluation = judge.step(
task="Describe this image",
img="path/to/image.jpg"
)
```
""" """
prompt = any_to_str(tasks) try:
logger.debug(f"Running step with prompt: {prompt}") prompt = ""
if tasks:
prompt = any_to_str(tasks)
elif task:
prompt = task
else:
raise ValueError("No tasks or task provided")
print(prompt) # 添加评估标准到任务描述中
task_instruction = "You are an expert AI agent judge. Carefully review the following output(s) generated by another agent. "
task_instruction += "Your job is to provide a detailed, constructive, and actionable critique that will help the agent improve its future performance. "
task_instruction += (
"Your feedback should address the following points:\n"
)
task_instruction += "1. Strengths: What did the agent do well? Highlight any correct reasoning, clarity, or effective problem-solving.\n"
task_instruction += "2. Weaknesses: Identify any errors, omissions, unclear reasoning, or areas where the output could be improved.\n"
task_instruction += "3. Suggestions: Offer specific, practical recommendations for how the agent can improve its next attempt. "
task_instruction += "This may include advice on reasoning, structure, completeness, or style.\n"
task_instruction += "4. If relevant, point out any factual inaccuracies or logical inconsistencies.\n"
response = self.agent.run( # 在任务说明中添加评估标准
task=f"Evaluate the following output or outputs: {prompt}" if self.evaluation_criteria:
) list(self.evaluation_criteria.keys())
logger.debug(f"Received response: {response}") task_instruction += "\nPlease use these specific evaluation criteria with their respective weights:\n"
for (
criterion,
weight,
) in self.evaluation_criteria.items():
task_instruction += (
f"- {criterion}: weight = {weight}\n"
)
return response task_instruction += "Be thorough, objective, and professional. Your goal is to help the agent learn and produce better results in the future.\n\n"
task_instruction += f"Output(s) to evaluate:\n{prompt}\n"
def run(self, tasks: List[str]) -> List[str]: response = self.agent.run(
task=task_instruction,
img=img,
)
return response
except Exception as e:
error_message = (
f"AgentJudge encountered an error: {e}\n"
f"Traceback:\n{traceback.format_exc()}\n\n"
"If this issue persists, please:\n"
"- Open a GitHub issue: https://github.com/swarms-ai/swarms/issues\n"
"- Join our Discord for real-time support: swarms.ai\n"
"- Or book a call: https://cal.com/swarms\n"
)
raise AgentJudgeExecutionError(error_message)
def run(
self,
task: str = None,
tasks: Optional[List[str]] = None,
img: Optional[str] = None,
):
""" """
Executes the tasks in a loop, updating context and collecting responses. Executes evaluation in multiple iterations with context building and refinement.
This method runs the evaluation process for the specified number of max_loops,
where each iteration builds upon the previous context. This allows for iterative
refinement of evaluations and deeper analysis over multiple passes.
Args: Args:
tasks (List[str]): A list of tasks to be executed. task (str, optional): A single task/output to be evaluated.
tasks (List[str], optional): A list of tasks/outputs to be evaluated.
img (str, optional): Path to an image file for multimodal evaluation.
Returns: Returns:
List[str]: A list of responses generated by the agent for each iteration. List[str]: A list of evaluation responses, one for each iteration.
Each subsequent evaluation includes context from previous iterations.
Example:
```python
# Single task with iterative refinement
judge = AgentJudge(max_loops=3)
evaluations = judge.run(task="Agent output to evaluate")
# Returns 3 evaluations, each building on the previous
# Multiple tasks with context building
evaluations = judge.run(tasks=[
"First agent response",
"Second agent response"
])
# With image analysis
evaluations = judge.run(
task="Analyze this chart",
img="chart.png"
)
```
Note:
- The first iteration evaluates the original task(s)
- Subsequent iterations include context from previous evaluations
- This enables deeper analysis and refinement of judgments
- Useful for complex evaluations requiring multiple perspectives
""" """
responses = [] try:
context = "" responses = []
context = ""
for _ in range(self.max_loops):
# Add context to the tasks if available # Convert single task to list for consistent processing
if context: if task and not tasks:
contextualized_tasks = [ tasks = [task]
f"Previous context: {context}\nTask: {task}" task = None # Clear to avoid confusion in step method
for task in tasks
] for _ in range(self.max_loops):
else: # Add context to the tasks if available
contextualized_tasks = tasks if context and tasks:
contextualized_tasks = [
f"Previous context: {context}\nTask: {t}"
for t in tasks
]
else:
contextualized_tasks = tasks
# Get response for current iteration
current_response = self.step(
task=task,
tasks=contextualized_tasks,
img=img,
)
responses.append(current_response)
# Get response for current iteration # Update context for next iteration
current_response = self.step(contextualized_tasks) context = current_response
responses.append(current_response)
logger.debug( return responses
f"Current response added: {current_response}" except Exception as e:
error_message = (
f"AgentJudge encountered an error: {e}\n"
f"Traceback:\n{traceback.format_exc()}\n\n"
"If this issue persists, please:\n"
"- Open a GitHub issue: https://github.com/swarms-ai/swarms/issues\n"
"- Join our Discord for real-time support: swarms.ai\n"
"- Or book a call: https://cal.com/swarms\n"
) )
raise AgentJudgeExecutionError(error_message)
def run_batched(
self,
tasks: Optional[List[str]] = None,
imgs: Optional[List[str]] = None,
):
"""
Executes batch evaluation of multiple tasks with corresponding images.
This method processes multiple task-image pairs independently, where each
task can be evaluated with its corresponding image. Unlike the run() method,
this doesn't build context between different tasks - each is evaluated
independently.
# Update context for next iteration
context = current_response
# Add to conversation history Args:
logger.debug("Added message to conversation history.") tasks (List[str], optional): A list of tasks/outputs to be evaluated.
imgs (List[str], optional): A list of image paths corresponding to each task.
Must be the same length as tasks if provided.
Returns:
List[List[str]]: A list of evaluation responses for each task. Each inner
list contains the responses from all iterations (max_loops)
for that particular task.
Example:
```python
# Batch evaluation with images
tasks = [
"Describe what you see in this image",
"What's wrong with this chart?",
"Analyze the trends shown"
]
images = [
"photo1.jpg",
"chart1.png",
"graph1.png"
]
evaluations = judge.run_batched(tasks=tasks, imgs=images)
# Returns evaluations for each task-image pair
# Batch evaluation without images
evaluations = judge.run_batched(tasks=[
"Agent response 1",
"Agent response 2",
"Agent response 3"
])
```
Note:
- Each task is processed independently
- If imgs is provided, it must have the same length as tasks
- Each task goes through max_loops iterations independently
- No context is shared between different tasks in the batch
"""
responses = []
for task, img in zip(tasks, imgs):
response = self.run(task=task, img=img)
responses.append(response)
return responses return responses

@ -1,22 +1,71 @@
from collections import Counter """
Self-Consistency Agent Implementation
This module implements the SelfConsistencyAgent, a specialized agent that leverages the
self-consistency technique to improve reasoning reliability and accuracy. The agent generates
multiple independent responses to a given task and aggregates them into a single, consistent
final answer using majority voting and sophisticated aggregation techniques.
The self-consistency approach is based on the research paper:
"Self-Consistency Improves Chain of Thought Reasoning in Language Models"
by Wang et al. (2022) - https://arxiv.org/abs/2203.07870
Key Features:
- Concurrent generation of multiple independent responses
- Majority voting aggregation with detailed analysis
- Evaluation mode for answer validation
- Configurable output formats
- Thread-safe execution
Author: Swarms Team
License: MIT
"""
from concurrent.futures import ThreadPoolExecutor, as_completed from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import List from typing import List, Optional, Union, Dict, Any
from loguru import logger from loguru import logger
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
from swarms.structs.conversation import Conversation from swarms.structs.conversation import Conversation
from swarms.structs.malt import majority_voting_prompt
from swarms.utils.output_types import OutputType from swarms.utils.output_types import OutputType
from swarms.utils.any_to_str import any_to_str from swarms.utils.any_to_str import any_to_str
from swarms.utils.history_output_formatter import ( from swarms.utils.history_output_formatter import (
history_output_formatter, history_output_formatter,
) )
# System prompt for the reasoning agent that generates individual responses
CONSISTENCY_SYSTEM_PROMPT = """ CONSISTENCY_SYSTEM_PROMPT = """
You are a reasoning agent designed for complex problem-solving and decision-making. Your objective is to provide clear and reliable responses through structured reasoning. Begin by thoroughly understanding the problem, rephrasing it for clarity, and identifying key components. Develop a logical plan that breaks the problem into manageable steps, detailing your approach and any assumptions made. Validate your information with reliable sources and assess the accuracy of your calculations. Explore multiple solutions, weighing their pros and cons, and maintain transparency by documenting your reasoning process, uncertainties, and biases. Summarize your findings in a concise final answer that reflects your thorough analysis, ensuring it is well-organized and accessible. Adapt your reasoning to the context of the problem, integrating new information as needed, and implement error-handling strategies to address any issues that arise. Finally, reflect on your reasoning process to identify areas for improvement and ensure consistency across all reasoning paths. You are a reasoning agent designed for complex problem-solving and decision-making. Your objective is to provide clear and reliable responses through structured reasoning. Begin by thoroughly understanding the problem, rephrasing it for clarity, and identifying key components. Develop a logical plan that breaks the problem into manageable steps, detailing your approach and any assumptions made. Validate your information with reliable sources and assess the accuracy of your calculations. Explore multiple solutions, weighing their pros and cons, and maintain transparency by documenting your reasoning process, uncertainties, and biases. Summarize your findings in a concise final answer that reflects your thorough analysis, ensuring it is well-organized and accessible. Adapt your reasoning to the context of the problem, integrating new information as needed, and implement error-handling strategies to address any issues that arise. Finally, reflect on your reasoning process to identify areas for improvement and ensure consistency across all reasoning paths.
""" """
# Detailed prompt for the majority voting aggregation agent
majority_voting_prompt = """
Engage in a comprehensive and exhaustive majority voting analysis of the following conversation, ensuring a deep and thoughtful examination of the responses provided by each agent. This analysis should not only summarize the responses but also critically engage with the content, context, and implications of each agent's input.
Please adhere to the following detailed guidelines:
1. **Identification of Dominant Responses:**
- Identify the most prevalent answer or recommendation across all agents. Provide a thorough rationale for its dominance, including an exploration of the factors that may have contributed to its acceptance among the agents. Discuss the context in which this consensus emerged and any relevant historical or theoretical frameworks that support this conclusion.
2. **Exploration of Disparities:**
- Delve into any significant disparities or contrasting viewpoints between agents. Explore the underlying reasons for these differences, considering aspects such as differing methodologies, assumptions, or interpretations of the task at hand. Analyze how these contrasting perspectives may reflect broader debates within the field and what implications they hold for the overall understanding of the topic.
3. **Consensus and Disagreement Analysis:**
- Highlight key areas of consensus and disagreement among the agents. Discuss the implications of these findings on the overall argument, including how consensus can strengthen certain claims while disagreement may indicate areas of uncertainty or contention. Provide examples from the conversation to illustrate these points and consider how they might influence future discussions or research directions.
4. **Critical Evaluation of Majority Opinion:**
- Critically evaluate the strength of the majority opinion, considering factors such as the reasoning behind it and its mathematical validity if applicable. Assess whether the majority opinion is well-supported by evidence and logical reasoning, and discuss any potential weaknesses or oversights that may undermine its credibility.
5. **Insights from Minority Viewpoints:**
- Note any unique insights from minority viewpoints, assessing their potential contributions to a more nuanced understanding of the topic. Discuss how these minority perspectives can enrich the conversation and provide alternative angles that may have been overlooked by the majority. Consider the value of dissent in academic discourse and how it can lead to more robust conclusions.
6. **Synthesis of Recommendations:**
- Provide a final synthesized recommendation based on the majority consensus, ensuring that it reflects a thorough consideration of all perspectives and is grounded in sound reasoning. This recommendation should not only summarize the majority view but also integrate insights from minority opinions, creating a comprehensive and balanced conclusion that acknowledges the complexity of the discussion.
Throughout your analysis, focus on uncovering clear patterns while being attentive to the subtleties and complexities inherent in the responses. Pay particular attention to the nuances of mathematical contexts where algorithmic thinking may be required, ensuring that your examination is both rigorous and accessible to a diverse audience.
"""
def aggregation_agent( def aggregation_agent(
responses: List[str], responses: List[str],
@ -24,7 +73,27 @@ def aggregation_agent(
model_name: str = "gpt-4o-mini", model_name: str = "gpt-4o-mini",
) -> str: ) -> str:
""" """
Aggregates a list of responses into a single final answer. Aggregates a list of responses into a single final answer using an AI-powered aggregation agent.
This function creates a specialized agent that analyzes multiple responses and synthesizes
them into a coherent final answer. The aggregation process considers consensus, disagreements,
and minority viewpoints to produce a well-reasoned conclusion.
Args:
responses (List[str]): List of responses to be aggregated
prompt (str, optional): Custom prompt for the aggregation agent.
Defaults to the majority_voting_prompt.
model_name (str, optional): Model to use for aggregation.
Defaults to "gpt-4o-mini".
Returns:
str: The aggregated final answer
Example:
>>> responses = ["Answer A", "Answer B", "Answer A"]
>>> final_answer = aggregation_agent(responses)
>>> print(final_answer)
"Based on the majority consensus..."
""" """
task = any_to_str(responses) task = any_to_str(responses)
@ -41,69 +110,174 @@ def aggregation_agent(
return final_answer return final_answer
class SelfConsistencyAgent(Agent): class SelfConsistencyAgent:
"""
A specialized agent that implements self-consistency for improved reasoning reliability.
The SelfConsistencyAgent generates multiple independent responses to a given task and
aggregates them into a single, consistent final answer. This approach is based on the
research paper "Self-Consistency Improves Chain of Thought Reasoning in Language Models"
by Wang et al. (2022).
Key Features:
- Concurrent generation of multiple independent responses
- Majority voting aggregation with detailed analysis
- Evaluation mode for answer validation
- Configurable output formats
- Thread-safe execution
The self-consistency technique works by:
1. Generating multiple independent reasoning paths for the same problem
2. Analyzing the consistency and agreement among these paths
3. Aggregating the results using majority voting or consensus building
4. Producing a final answer that reflects the most reliable consensus
This approach helps mitigate issues like:
- Random errors in individual reasoning paths
- Biases in single reasoning approaches
- Inconsistencies in complex problem-solving
Reference:
Wang, Y., Dong, W., Han, J., & Wang, W. (2022). Self-Consistency Improves Chain of
Thought Reasoning in Language Models. arXiv preprint arXiv:2203.07870.
https://arxiv.org/abs/2203.07870
Example:
>>> agent = SelfConsistencyAgent(
... name="Math-Reasoning-Agent",
... model_name="gpt-4o-mini",
... num_samples=5,
... max_loops=1
... )
>>> result = agent.run("What is the 40th prime number?")
>>> print(result)
"""
def __init__( def __init__(
self, self,
name: str = "Self-Consistency-Agent", name: str = "Self-Consistency-Agent",
description: str = "An agent that uses self consistency to generate a final answer.", description: str = "An agent that uses self consistency to generate a final answer.",
model_name: str = "gpt-4o-mini",
system_prompt: str = CONSISTENCY_SYSTEM_PROMPT, system_prompt: str = CONSISTENCY_SYSTEM_PROMPT,
num_samples: int = 5, num_samples: int = 5,
max_loops: int = 1, max_loops: int = 1,
majority_voting_prompt: str = None, majority_voting_prompt: Optional[
str
] = majority_voting_prompt,
eval: bool = False, eval: bool = False,
output_type: OutputType = "dict", output_type: OutputType = "dict",
random_models_on: bool = False,
*args,
**kwargs, **kwargs,
): ):
""" """
Initializes the SelfConsistencyAgent. Initialize the SelfConsistencyAgent.
Args: Args:
num_samples (int): Number of independent responses to sample. name (str, optional): Name of the agent. Defaults to "Self-Consistency-Agent".
**kwargs: Other keyword arguments passed to the base Agent. description (str, optional): Description of the agent's purpose.
Defaults to "An agent that uses self consistency to generate a final answer.".
model_name (str, optional): The underlying language model to use.
Defaults to "gpt-4o-mini".
system_prompt (str, optional): System prompt for the reasoning agent.
Defaults to CONSISTENCY_SYSTEM_PROMPT.
num_samples (int, optional): Number of independent responses to generate.
Defaults to 5.
max_loops (int, optional): Maximum number of reasoning loops per sample.
Defaults to 1.
majority_voting_prompt (Optional[str], optional): Custom prompt for majority voting.
Defaults to None.
eval (bool, optional): Enable evaluation mode for answer validation.
Defaults to False.
output_type (OutputType, optional): Format of the output.
Defaults to "dict".
random_models_on (bool, optional): Enable random model selection for diversity.
Defaults to False.
**kwargs: Additional keyword arguments passed to the base Agent class.
Note:
The num_samples parameter determines how many independent reasoning paths
will be generated. Higher values generally lead to more reliable results
but increase computational cost and time.
""" """
super().__init__( self.name = name
name=name, self.description = description
description=description, self.model_name = model_name
**kwargs,
)
self.num_samples = num_samples self.num_samples = num_samples
self.conversation = Conversation()
self.max_loops = max_loops self.max_loops = max_loops
self.majority_voting_prompt = majority_voting_prompt self.majority_voting_prompt = majority_voting_prompt
self.eval = eval self.eval = eval
self.output_type = output_type self.output_type = output_type
self.system_prompt = system_prompt self.system_prompt = system_prompt
self.random_models_on = random_models_on
self.conversation = Conversation()
self.args = args
self.kwargs = kwargs
def run( def run(
self, task: str, answer: str = None, *args, **kwargs self,
) -> str: task: str,
img: Optional[str] = None,
answer: Optional[str] = None,
*args,
**kwargs,
) -> Union[str, Dict[str, Any]]:
""" """
Generates multiple responses for the given prompt and aggregates them concurrently. Generate multiple responses for the given task and aggregate them concurrently.
This method implements the core self-consistency algorithm:
1. Generates multiple independent responses using concurrent execution
2. Optionally validates responses against a known answer (if eval=True)
3. Aggregates responses using an AI-powered aggregation agent
4. Returns the final result in the specified output format
Args: Args:
task (str): The input prompt. task (str): The input prompt or task to be solved
answer (Optional[str], optional): Expected answer for validation (if eval=True).
Defaults to None.
*args: Additional positional arguments passed to the base agent's run method
**kwargs: Additional keyword arguments passed to the base agent's run method
Returns: Returns:
str: The aggregated final answer. Union[str, Dict[str, Any]]: The aggregated final answer in the specified format
Raises:
RuntimeError: If evaluation mode is enabled and the expected answer is not found
in any of the generated responses
Example:
>>> agent = SelfConsistencyAgent(num_samples=3)
>>> result = agent.run("What is 2 + 2?")
>>> print(result)
>>> # With evaluation mode
>>> result = agent.run("What is 2 + 2?", answer="4", eval=True)
""" """
responses = [] responses = []
logger.info(
f"Generating {self.num_samples} responses concurrently..."
)
self.conversation.add(role="User", content=task) self.conversation.add(role="User", content=task)
# Generate multiple independent responses concurrently
reasoning_agent = self._create_reasoning_agent()
with ThreadPoolExecutor() as executor: with ThreadPoolExecutor() as executor:
futures = { futures = {
executor.submit(super().run, task, *args, **kwargs): i executor.submit(
reasoning_agent.run,
task=task,
img=img,
*args,
**kwargs,
): i
for i in range(self.num_samples) for i in range(self.num_samples)
} }
for future in as_completed(futures): for future in as_completed(futures):
response = future.result() response = future.result()
responses.append(response) responses.append(response)
self.conversation.add(role=self.agent_name, content=responses) self.conversation.add(role=self.name, content=responses)
# Optional evaluation against known answer
if self.eval: if self.eval:
if answer is not None: if answer is not None:
correct = self.check_responses_for_answer( correct = self.check_responses_for_answer(
@ -116,9 +290,7 @@ class SelfConsistencyAgent(Agent):
) )
return None return None
# Aggregation agent # Aggregate responses using AI-powered aggregation
# final_answer = self.aggregation_agent(responses)
final_answer = aggregation_agent(responses) final_answer = aggregation_agent(responses)
self.conversation.add( self.conversation.add(
@ -129,39 +301,46 @@ class SelfConsistencyAgent(Agent):
self.conversation, self.output_type self.conversation, self.output_type
) )
def aggregate(self, responses: List[str]) -> str: def _create_reasoning_agent(self) -> Agent:
""" """
Aggregates a list of responses into a single final answer. Create a reasoning agent instance for generating individual responses.
Here we use a simple majority vote (most common answer) as an example. Depending on
the task, you might need a more sophisticated aggregation (e.g., weighting, consensus reasoning, etc.).
Args:
responses (list of str): The list of responses.
Returns: Returns:
str: The aggregated answer. Agent: A configured Agent instance for reasoning tasks
""" """
# Count the frequency of each response. return Agent(
counts = Counter(responses) agent_name=self.name,
most_common, freq = counts.most_common(1)[0] description=self.description,
logger.info( model_name=self.model_name,
f"Aggregation complete. Most common response (appeared {freq} times):" system_prompt=self.system_prompt,
max_loops=self.max_loops,
random_models_on=self.random_models_on,
output_type="str-all-except-first",
**self.kwargs,
) )
return most_common
def check_responses_for_answer( def check_responses_for_answer(
self, responses: List[str], answer: str self, responses: List[str], answer: str
) -> bool: ) -> bool:
""" """
Checks if the specified answer is present in any of the provided responses. Check if the specified answer is present in any of the provided responses.
This method performs a simple string matching to determine if the expected
answer appears in any of the generated responses. It's useful for validation
and evaluation purposes.
Args: Args:
responses (List[str]): A list of responses to check. responses (List[str]): List of responses to check
answer (str): The answer to look for in the responses. answer (str): The answer to look for in the responses
Returns: Returns:
bool: True if the answer is found in any response, False otherwise. bool: True if the answer is found in any response, False otherwise
Example:
>>> agent = SelfConsistencyAgent()
>>> responses = ["The answer is 42", "I think it's 42", "Not sure"]
>>> found = agent.check_responses_for_answer(responses, "42")
>>> print(found) # True
""" """
for response in responses: for response in responses:
if answer in response: if answer in response:
@ -181,27 +360,30 @@ class SelfConsistencyAgent(Agent):
def batched_run( def batched_run(
self, tasks: List[str], *args, **kwargs self, tasks: List[str], *args, **kwargs
) -> List[str]: ) -> List[Union[str, Dict[str, Any]]]:
""" """
Runs the agent in a batched manner. Run the agent on multiple tasks in batch.
This method processes multiple tasks sequentially, applying the self-consistency
approach to each task independently. It's useful for processing large datasets
or multiple related problems.
Args:
tasks (List[str]): List of tasks to be processed
*args: Additional positional arguments passed to the run method
**kwargs: Additional keyword arguments passed to the run method
Returns:
List[Union[str, Dict[str, Any]]]: List of results for each task
Example:
>>> agent = SelfConsistencyAgent()
>>> tasks = ["What is 2+2?", "What is 3+3?", "What is 4+4?"]
>>> results = agent.batched_run(tasks)
>>> print(len(results)) # 3
""" """
responses = [] responses = []
for task in tasks: for task in tasks:
response = self.run(task, *args, **kwargs) response = self.run(task, *args, **kwargs)
responses.append(response) responses.append(response)
return responses return responses
# # Example usage:
# if __name__ == "__main__":
# agent = SelfConsistencyAgent(
# agent_name="Reasoning-Agent",
# model_name="gpt-4o-mini",
# max_loops=1,
# num_samples=5, # Number of samples for self consistency
# )
# prompt = "What is the 40th prime number?"
# final_answer = agent.run(prompt)
# print("\nFinal aggregated answer:")
# print(final_answer)

@ -1,14 +1,44 @@
"""
ReasoningAgentRouter: A flexible router for advanced reasoning agent swarms.
This module provides the ReasoningAgentRouter class, which enables dynamic selection and instantiation
of various advanced reasoning agent types (swarms) for complex problem-solving tasks. It supports
multiple reasoning strategies, including self-consistency, collaborative duo agents, iterative
reflection, knowledge prompting, and agent judging.
Key Features:
- Unified interface for multiple agent types (see `agent_types`)
- Caching of agent instances for efficiency and memory management
- Extensible factory-based architecture for easy addition of new agent types
- Batch and single-task execution
- Customizable agent configuration (model, prompt, memory, etc.)
Supported Agent Types:
- "reasoning-duo" / "reasoning-agent": Dual collaborative agent system
- "self-consistency" / "consistency-agent": Multiple independent solutions with consensus
- "ire" / "ire-agent": Iterative Reflective Expansion agent
- "ReflexionAgent": Reflexion agent with memory
- "GKPAgent": Generated Knowledge Prompting agent
- "AgentJudge": Agent judge for evaluation/critique
Example usage:
>>> router = ReasoningAgentRouter(swarm_type="self-consistency", num_samples=3)
>>> result = router.run("What is the capital of France?")
>>> print(result)
>>> # Batch mode
>>> results = router.batched_run(["2+2?", "3+3?"])
>>> print(results)
"""
import traceback
from typing import ( from typing import (
List, List,
Literal, Literal,
Dict, Optional,
Callable,
Any,
Tuple,
Hashable,
) )
from swarms.agents.consistency_agent import SelfConsistencyAgent from swarms.agents.consistency_agent import SelfConsistencyAgent
from swarms.agents.flexion_agent import ReflexionAgent from swarms.agents.flexion_agent import ReflexionAgent
from swarms.agents.gkp_agent import GKPAgent from swarms.agents.gkp_agent import GKPAgent
@ -19,7 +49,7 @@ from swarms.agents.reasoning_duo import ReasoningDuo
from swarms.utils.output_types import OutputType from swarms.utils.output_types import OutputType
from swarms.agents.agent_judge import AgentJudge from swarms.agents.agent_judge import AgentJudge
#: Supported agent type literals for ReasoningAgentRouter
agent_types = Literal[ agent_types = Literal[
"reasoning-duo", "reasoning-duo",
"self-consistency", "self-consistency",
@ -33,24 +63,49 @@ agent_types = Literal[
] ]
class ReasoningAgentRouter: class ReasoningAgentExecutorError(Exception):
""" """
A Reasoning Agent that can answer questions and assist with various tasks using different reasoning strategies. Exception raised when an error occurs during the execution of a reasoning agent.
Attributes:
agent_name (str): The name of the agent.
description (str): A brief description of the agent's capabilities.
model_name (str): The name of the model used for reasoning.
system_prompt (str): The prompt that guides the agent's reasoning process.
max_loops (int): The maximum number of loops for the reasoning process.
swarm_type (agent_types): The type of reasoning swarm to use (e.g., reasoning duo, self-consistency, IRE).
num_samples (int): The number of samples to generate for self-consistency agents.
output_type (OutputType): The format of the output (e.g., dict, list).
""" """
# Class variable to store cached agent instances pass
_agent_cache: Dict[Tuple[Hashable, ...], Any] = {}
class ReasoningAgentInitializationError(Exception):
"""
Exception raised when an error occurs during the initialization of a reasoning agent.
"""
pass
class ReasoningAgentRouter:
"""
A router for advanced reasoning agent swarms.
The ReasoningAgentRouter enables dynamic selection, instantiation, and caching of various
reasoning agent types ("swarms") for flexible, robust, and scalable problem-solving.
Args:
agent_name (str): Name identifier for the agent instance.
description (str): Description of the agent's capabilities.
model_name (str): The underlying language model to use.
system_prompt (str): System prompt for the agent.
max_loops (int): Maximum number of reasoning loops.
swarm_type (agent_types): Type of reasoning swarm to use.
num_samples (int): Number of samples for self-consistency or iterations.
output_type (OutputType): Format of the output.
num_knowledge_items (int): Number of knowledge items for GKP agent.
memory_capacity (int): Memory capacity for agents that support it.
eval (bool): Enable evaluation mode for self-consistency.
random_models_on (bool): Enable random model selection for diversity.
majority_voting_prompt (Optional[str]): Custom prompt for majority voting.
Example:
>>> router = ReasoningAgentRouter(swarm_type="reasoning-duo")
>>> result = router.run("Explain quantum entanglement.")
>>> print(result)
"""
def __init__( def __init__(
self, self,
@ -59,12 +114,23 @@ class ReasoningAgentRouter:
model_name: str = "gpt-4o-mini", model_name: str = "gpt-4o-mini",
system_prompt: str = "You are a helpful assistant that can answer questions and help with tasks.", system_prompt: str = "You are a helpful assistant that can answer questions and help with tasks.",
max_loops: int = 1, max_loops: int = 1,
swarm_type: agent_types = "reasoning_duo", swarm_type: agent_types = "reasoning-duo",
num_samples: int = 1, num_samples: int = 1,
output_type: OutputType = "dict", output_type: OutputType = "dict-all-except-first",
num_knowledge_items: int = 6, num_knowledge_items: int = 6,
memory_capacity: int = 6, memory_capacity: int = 6,
eval: bool = False,
random_models_on: bool = False,
majority_voting_prompt: Optional[str] = None,
reasoning_model_name: Optional[
str
] = "claude-3-5-sonnet-20240620",
): ):
"""
Initialize the ReasoningAgentRouter with the specified configuration.
See class docstring for parameter details.
"""
self.agent_name = agent_name self.agent_name = agent_name
self.description = description self.description = description
self.model_name = model_name self.model_name = model_name
@ -75,78 +141,97 @@ class ReasoningAgentRouter:
self.output_type = output_type self.output_type = output_type
self.num_knowledge_items = num_knowledge_items self.num_knowledge_items = num_knowledge_items
self.memory_capacity = memory_capacity self.memory_capacity = memory_capacity
self.eval = eval
self.random_models_on = random_models_on
self.majority_voting_prompt = majority_voting_prompt
self.reasoning_model_name = reasoning_model_name
self.reliability_check()
# Added: Initialize the factory mapping dictionary def reliability_check(self):
self._initialize_agent_factories() if self.max_loops == 0:
raise ReasoningAgentInitializationError(
"ReasoningAgentRouter Error: Max loops must be greater than 0"
)
if self.model_name == "" or self.model_name is None:
raise ReasoningAgentInitializationError(
"ReasoningAgentRouter Error: Model name must be provided"
)
if self.swarm_type == "" or self.swarm_type is None:
raise ReasoningAgentInitializationError(
"ReasoningAgentRouter Error: Swarm type must be provided. This is the type of reasoning agent you want to use. For example, 'reasoning-duo' for a reasoning duo agent, 'self-consistency' for a self-consistency agent, 'ire' for an iterative reflective expansion agent, 'reasoning-agent' for a reasoning agent, 'consistency-agent' for a consistency agent, 'ire-agent' for an iterative reflective expansion agent, 'ReflexionAgent' for a reflexion agent, 'GKPAgent' for a generated knowledge prompting agent, 'AgentJudge' for an agent judge."
)
# Initialize the factory mapping dictionary
self.agent_factories = self._initialize_agent_factories()
def _initialize_agent_factories(self) -> None: def _initialize_agent_factories(self) -> None:
""" """
Initialize the agent factory mapping dictionary, mapping various agent types to their respective creation functions. Initialize the agent factory mapping dictionary, mapping various agent types to their respective creation functions.
This method replaces the original if-elif chain, making the code more maintainable and extensible. This method replaces the original if-elif chain, making the code more maintainable and extensible.
""" """
self.agent_factories: Dict[str, Callable[[], Any]] = { agent_factories = {
# ReasoningDuo factory method
"reasoning-duo": self._create_reasoning_duo, "reasoning-duo": self._create_reasoning_duo,
"reasoning-agent": self._create_reasoning_duo, "reasoning-agent": self._create_reasoning_duo,
# SelfConsistencyAgent factory methods
"self-consistency": self._create_consistency_agent, "self-consistency": self._create_consistency_agent,
"consistency-agent": self._create_consistency_agent, "consistency-agent": self._create_consistency_agent,
# IREAgent factory methods
"ire": self._create_ire_agent, "ire": self._create_ire_agent,
"ire-agent": self._create_ire_agent, "ire-agent": self._create_ire_agent,
# Other agent type factory methods
"AgentJudge": self._create_agent_judge, "AgentJudge": self._create_agent_judge,
"ReflexionAgent": self._create_reflexion_agent, "ReflexionAgent": self._create_reflexion_agent,
"GKPAgent": self._create_gkp_agent, "GKPAgent": self._create_gkp_agent,
} }
def _get_cache_key(self) -> Tuple[Hashable, ...]: return agent_factories
"""
Generate a unique key for cache lookup.
The key is based on all relevant configuration parameters of the agent.
def _create_reasoning_duo(self):
"""
Create an agent instance for the ReasoningDuo type.
Returns: Returns:
Tuple[Hashable, ...]: A hashable tuple to serve as the cache key ReasoningDuo: An instance of the ReasoningDuo agent.
""" """
return (
self.swarm_type,
self.agent_name,
self.description,
self.model_name,
self.system_prompt,
self.max_loops,
self.num_samples,
self.output_type,
self.num_knowledge_items,
self.memory_capacity,
)
def _create_reasoning_duo(self):
"""Create an agent instance for the ReasoningDuo type"""
return ReasoningDuo( return ReasoningDuo(
agent_name=self.agent_name, agent_name=self.agent_name,
agent_description=self.description, agent_description=self.description,
model_name=[self.model_name, self.model_name], model_name=[self.model_name, self.model_name],
system_prompt=self.system_prompt, system_prompt=self.system_prompt,
output_type=self.output_type, output_type=self.output_type,
reasoning_model_name=self.reasoning_model_name,
max_loops=self.max_loops,
) )
def _create_consistency_agent(self): def _create_consistency_agent(self):
"""Create an agent instance for the SelfConsistencyAgent type""" """
Create an agent instance for the SelfConsistencyAgent type.
Returns:
SelfConsistencyAgent: An instance of the SelfConsistencyAgent.
"""
return SelfConsistencyAgent( return SelfConsistencyAgent(
agent_name=self.agent_name, name=self.agent_name,
description=self.description, description=self.description,
model_name=self.model_name, model_name=self.model_name,
system_prompt=self.system_prompt, system_prompt=self.system_prompt,
max_loops=self.max_loops, max_loops=self.max_loops,
num_samples=self.num_samples, num_samples=self.num_samples,
output_type=self.output_type, output_type=self.output_type,
eval=self.eval,
random_models_on=self.random_models_on,
majority_voting_prompt=self.majority_voting_prompt,
) )
def _create_ire_agent(self): def _create_ire_agent(self):
"""Create an agent instance for the IREAgent type""" """
Create an agent instance for the IREAgent type.
Returns:
IREAgent: An instance of the IterativeReflectiveExpansion agent.
"""
return IREAgent( return IREAgent(
agent_name=self.agent_name, agent_name=self.agent_name,
description=self.description, description=self.description,
@ -158,7 +243,12 @@ class ReasoningAgentRouter:
) )
def _create_agent_judge(self): def _create_agent_judge(self):
"""Create an agent instance for the AgentJudge type""" """
Create an agent instance for the AgentJudge type.
Returns:
AgentJudge: An instance of the AgentJudge agent.
"""
return AgentJudge( return AgentJudge(
agent_name=self.agent_name, agent_name=self.agent_name,
model_name=self.model_name, model_name=self.model_name,
@ -167,16 +257,27 @@ class ReasoningAgentRouter:
) )
def _create_reflexion_agent(self): def _create_reflexion_agent(self):
"""Create an agent instance for the ReflexionAgent type""" """
Create an agent instance for the ReflexionAgent type.
Returns:
ReflexionAgent: An instance of the ReflexionAgent.
"""
return ReflexionAgent( return ReflexionAgent(
agent_name=self.agent_name, agent_name=self.agent_name,
system_prompt=self.system_prompt, system_prompt=self.system_prompt,
model_name=self.model_name, model_name=self.model_name,
max_loops=self.max_loops, max_loops=self.max_loops,
memory_capacity=self.memory_capacity,
) )
def _create_gkp_agent(self): def _create_gkp_agent(self):
"""Create an agent instance for the GKPAgent type""" """
Create an agent instance for the GKPAgent type.
Returns:
GKPAgent: An instance of the GKPAgent.
"""
return GKPAgent( return GKPAgent(
agent_name=self.agent_name, agent_name=self.agent_name,
model_name=self.model_name, model_name=self.model_name,
@ -186,55 +287,53 @@ class ReasoningAgentRouter:
def select_swarm(self): def select_swarm(self):
""" """
Select and initialize the appropriate reasoning swarm based on the specified swarm type. Select and initialize the appropriate reasoning swarm based on the specified swarm type.
Uses a caching mechanism to return a cached instance if an agent with the same configuration already exists.
Returns: Returns:
The selected reasoning swarm instance. The selected reasoning swarm instance.
"""
# Generate cache key
cache_key = self._get_cache_key()
# Check if an instance with the same configuration already exists in the cache
if cache_key in self.__class__._agent_cache:
return self.__class__._agent_cache[cache_key]
Raises:
ValueError: If the specified swarm type is invalid.
"""
try: try:
# Use the factory method to create a new instance if self.swarm_type in self.agent_factories:
agent = self.agent_factories[self.swarm_type]() return self.agent_factories[self.swarm_type]()
else:
# Add the newly created instance to the cache raise ReasoningAgentInitializationError(
self.__class__._agent_cache[cache_key] = agent f"ReasoningAgentRouter Error: Invalid swarm type: {self.swarm_type}"
)
return agent except Exception as e:
except KeyError: raise ReasoningAgentInitializationError(
# Keep the same error handling as the original code f"ReasoningAgentRouter Error: {e} Traceback: {traceback.format_exc()} If the error persists, please check the agent's configuration and try again. If you would like support book a call with our team at https://cal.com/swarms"
raise ValueError(f"Invalid swarm type: {self.swarm_type}") )
def run(self, task: str, *args, **kwargs): def run(self, task: str, *args, **kwargs):
""" """
Execute the reasoning process of the selected swarm on a given task. Execute the reasoning process of the selected swarm on a given task.
Args: Args:
task (str): The task or question to be processed by the reasoning agent. task (str): The task or question to be processed by the reasoning agent.
*args: Additional positional arguments for the agent's run method.
**kwargs: Additional keyword arguments for the agent's run method.
Returns: Returns:
The result of the reasoning process. The result of the reasoning process (format depends on agent and output_type).
""" """
swarm = self.select_swarm() try:
return swarm.run(task=task) swarm = self.select_swarm()
return swarm.run(task=task, *args, **kwargs)
except Exception as e:
raise ReasoningAgentExecutorError(
f"ReasoningAgentRouter Error: {e} Traceback: {traceback.format_exc()} If the error persists, please check the agent's configuration and try again. If you would like support book a call with our team at https://cal.com/swarms"
)
def batched_run(self, tasks: List[str], *args, **kwargs): def batched_run(self, tasks: List[str], *args, **kwargs):
""" """
Execute the reasoning process on a batch of tasks. Execute the reasoning process on a batch of tasks.
Args: Args:
tasks (List[str]): The list of tasks to process. tasks (List[str]): The list of tasks to process.
*args: Additional positional arguments for the agent's run method.
**kwargs: Additional keyword arguments for the agent's run method.
Returns: Returns:
A list of reasoning process results for each task. A list of reasoning process results for each task.
@ -243,11 +342,3 @@ class ReasoningAgentRouter:
for task in tasks: for task in tasks:
results.append(self.run(task, *args, **kwargs)) results.append(self.run(task, *args, **kwargs))
return results return results
@classmethod
def clear_cache(cls):
"""
Clear the agent instance cache.
Use this when you need to free memory or force the creation of new instances.
"""
cls._agent_cache.clear()

@ -1,6 +1,3 @@
from swarms.prompts.prompt import Prompt
OPENAI_PROMPT_GENERATOR_SYS_PROMPT = """ OPENAI_PROMPT_GENERATOR_SYS_PROMPT = """
Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively. Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.
@ -51,9 +48,5 @@ The final prompt you output should adhere to the following structure below. Do n
""" """
prompt_generator_sys_prompt = Prompt(
name="openai-prompt-generator-optimizer-prompt", prompt_generator_sys_prompt = OPENAI_PROMPT_GENERATOR_SYS_PROMPT
description="Generate and or optimize existing prompts",
content=OPENAI_PROMPT_GENERATOR_SYS_PROMPT,
autosave=True,
)

@ -92,6 +92,7 @@ from swarms.structs.interactive_groupchat import (
) )
from swarms.structs.hiearchical_swarm import HierarchicalSwarm from swarms.structs.hiearchical_swarm import HierarchicalSwarm
from swarms.structs.heavy_swarm import HeavySwarm
__all__ = [ __all__ = [
"Agent", "Agent",
@ -169,4 +170,5 @@ __all__ = [
"priority_speaker", "priority_speaker",
"random_dynamic_speaker", "random_dynamic_speaker",
"HierarchicalSwarm", "HierarchicalSwarm",
"HeavySwarm",
] ]

@ -1110,6 +1110,8 @@ class Agent:
f"Structured Output - Attempting Function Call Execution [{time.strftime('%H:%M:%S')}] \n\n Output: {format_data_structure(response)} ", f"Structured Output - Attempting Function Call Execution [{time.strftime('%H:%M:%S')}] \n\n Output: {format_data_structure(response)} ",
loop_count, loop_count,
) )
elif self.streaming_on:
pass
else: else:
self.pretty_print( self.pretty_print(
response, loop_count response, loop_count
@ -1239,12 +1241,13 @@ class Agent:
traceback_info = traceback.format_exc() traceback_info = traceback.format_exc()
logger.error( logger.error(
f"Error detected running your agent {self.agent_name}\n" f"An error occurred while running your agent {self.agent_name}.\n"
f"Error Type: {error_type}\n" f"Error Type: {error_type}\n"
f"Error Message: {error_message}\n" f"Error Message: {error_message}\n"
f"Traceback:\n{traceback_info}\n" f"Traceback:\n{traceback_info}\n"
f"Agent State: {self.to_dict()}\n" f"Agent State: {self.to_dict()}\n"
f"Optimize your input parameters and or add an issue on the swarms github and contact our team on discord for support ;)" f"Please optimize your input parameters, or create an issue on the Swarms GitHub and contact our team on Discord for support. "
f"For technical support, refer to this document: https://docs.swarms.world/en/latest/swarms/support/"
) )
raise error raise error
@ -1258,12 +1261,6 @@ class Agent:
self, self,
task: Optional[str] = None, task: Optional[str] = None,
img: Optional[str] = None, img: Optional[str] = None,
is_last: bool = False,
device: str = "cpu", # gpu
device_id: int = 1,
all_cores: bool = True,
do_not_use_cluster_ops: bool = True,
all_gpus: bool = False,
*args, *args,
**kwargs, **kwargs,
) -> Any: ) -> Any:
@ -1334,37 +1331,6 @@ class Agent:
) )
return self.run(task=improved_prompt, *args, **kwargs) return self.run(task=improved_prompt, *args, **kwargs)
# def parse_and_execute_tools(self, response: str, *args, **kwargs):
# max_retries = 3 # Maximum number of retries
# retries = 0
# while retries < max_retries:
# try:
# logger.info("Executing tool...")
# # try to Execute the tool and return a string
# out = parse_and_execute_json(
# functions=self.tools,
# json_string=response,
# parse_md=True,
# *args,
# **kwargs,
# )
# logger.info(f"Tool Output: {out}")
# # Add the output to the memory
# # self.short_memory.add(
# # role="Tool Executor",
# # content=out,
# # )
# return out
# except Exception as error:
# retries += 1
# logger.error(
# f"Attempt {retries}: Error executing tool: {error}"
# )
# if retries == max_retries:
# raise error
# time.sleep(1) # Wait for a bit before retrying
def add_memory(self, message: str): def add_memory(self, message: str):
"""Add a memory to the agent """Add a memory to the agent
@ -1539,15 +1505,16 @@ class Agent:
if self.tools_list_dictionary is not None: if self.tools_list_dictionary is not None:
if not supports_function_calling(self.model_name): if not supports_function_calling(self.model_name):
raise AgentInitializationError( logger.warning(
f"The model '{self.model_name}' does not support function calling. Please use a model that supports function calling." f"The model '{self.model_name}' does not support function calling. Please use a model that supports function calling."
) )
try: try:
if self.max_tokens > get_max_tokens(self.model_name): if self.max_tokens > get_max_tokens(self.model_name):
raise AgentInitializationError( logger.warning(
f"Max tokens is set to {self.max_tokens}, but the model '{self.model_name}' only supports {get_max_tokens(self.model_name)} tokens. Please set max tokens to {get_max_tokens(self.model_name)} or less." f"Max tokens is set to {self.max_tokens}, but the model '{self.model_name}' only supports {get_max_tokens(self.model_name)} tokens. Please set max tokens to {get_max_tokens(self.model_name)} or less."
) )
except Exception: except Exception:
pass pass
@ -2683,9 +2650,18 @@ class Agent:
return output return output
except ValueError as e: except AgentRunError as e:
self._handle_run_error(e) self._handle_run_error(e)
except KeyboardInterrupt:
logger.warning(
f"Keyboard interrupt detected for agent '{self.agent_name}'. "
"If autosave is enabled, the agent's state will be saved to the workspace directory. "
"To enable autosave, please initialize the agent with Agent(autosave=True)."
"For technical support, refer to this document: https://docs.swarms.world/en/latest/swarms/support/"
)
raise KeyboardInterrupt
def handle_artifacts( def handle_artifacts(
self, text: str, file_output_path: str, file_extension: str self, text: str, file_output_path: str, file_extension: str
) -> None: ) -> None:
@ -2824,6 +2800,9 @@ class Agent:
if response is None: if response is None:
response = "No response generated" response = "No response generated"
if self.streaming_on:
pass
if self.print_on: if self.print_on:
formatter.print_panel( formatter.print_panel(
response, response,
@ -3225,19 +3204,9 @@ class Agent:
f"Agent '{self.agent_name}' received None response from LLM in loop {loop_count}. " f"Agent '{self.agent_name}' received None response from LLM in loop {loop_count}. "
f"This may indicate an issue with the model or prompt. Skipping tool execution." f"This may indicate an issue with the model or prompt. Skipping tool execution."
) )
except Exception as e: except AgentToolExecutionError as e:
logger.error( logger.error(
f"Agent '{self.agent_name}' encountered error during tool execution in loop {loop_count}: {str(e)}. " f"Agent '{self.agent_name}' encountered error during tool execution in loop {loop_count}: {str(e)}. "
f"Full traceback: {traceback.format_exc()}. " f"Full traceback: {traceback.format_exc()}. "
f"Attempting to retry tool execution with 3 attempts" f"Attempting to retry tool execution with 3 attempts"
) )
def add_tool_schema(self, tool_schema: dict):
self.tools_list_dictionary = [tool_schema]
self.output_type = "dict-all-except-first"
def add_multiple_tool_schemas(self, tool_schemas: list[dict]):
self.tools_list_dictionary = tool_schemas
self.output_type = "dict-all-except-first"

@ -6,7 +6,6 @@ import threading
import uuid import uuid
from typing import ( from typing import (
TYPE_CHECKING, TYPE_CHECKING,
Callable,
Dict, Dict,
List, List,
Optional, Optional,
@ -190,18 +189,16 @@ class Conversation(BaseStructure):
save_enabled: bool = False, # New parameter to control if saving is enabled save_enabled: bool = False, # New parameter to control if saving is enabled
save_filepath: str = None, save_filepath: str = None,
load_filepath: str = None, # New parameter to specify which file to load from load_filepath: str = None, # New parameter to specify which file to load from
tokenizer: Callable = None,
context_length: int = 8192, context_length: int = 8192,
rules: str = None, rules: str = None,
custom_rules_prompt: str = None, custom_rules_prompt: str = None,
user: str = "User:", user: str = "User",
save_as_yaml: bool = False, save_as_yaml: bool = False,
save_as_json_bool: bool = False, save_as_json_bool: bool = False,
token_count: bool = True, token_count: bool = False,
message_id_on: bool = False, message_id_on: bool = False,
provider: providers = "in-memory", provider: providers = "in-memory",
backend: Optional[str] = None, backend: Optional[str] = None,
# Backend-specific parameters
supabase_url: Optional[str] = None, supabase_url: Optional[str] = None,
supabase_key: Optional[str] = None, supabase_key: Optional[str] = None,
redis_host: str = "localhost", redis_host: str = "localhost",
@ -210,7 +207,6 @@ class Conversation(BaseStructure):
redis_password: Optional[str] = None, redis_password: Optional[str] = None,
db_path: Optional[str] = None, db_path: Optional[str] = None,
table_name: str = "conversations", table_name: str = "conversations",
# Additional backend parameters
use_embedded_redis: bool = True, use_embedded_redis: bool = True,
persist_redis: bool = True, persist_redis: bool = True,
auto_persist: bool = True, auto_persist: bool = True,
@ -230,20 +226,7 @@ class Conversation(BaseStructure):
self.save_enabled = save_enabled self.save_enabled = save_enabled
self.conversations_dir = conversations_dir self.conversations_dir = conversations_dir
self.message_id_on = message_id_on self.message_id_on = message_id_on
# Handle save filepath
if save_enabled and save_filepath:
self.save_filepath = save_filepath
elif save_enabled and conversations_dir:
self.save_filepath = os.path.join(
conversations_dir, f"{self.id}.json"
)
else:
self.save_filepath = None
self.load_filepath = load_filepath self.load_filepath = load_filepath
self.conversation_history = []
self.tokenizer = tokenizer
self.context_length = context_length self.context_length = context_length
self.rules = rules self.rules = rules
self.custom_rules_prompt = custom_rules_prompt self.custom_rules_prompt = custom_rules_prompt
@ -253,9 +236,40 @@ class Conversation(BaseStructure):
self.token_count = token_count self.token_count = token_count
self.provider = provider # Keep for backwards compatibility self.provider = provider # Keep for backwards compatibility
self.conversations_dir = conversations_dir self.conversations_dir = conversations_dir
self.backend = backend
self.supabase_url = supabase_url
self.supabase_key = supabase_key
self.redis_host = redis_host
self.redis_port = redis_port
self.redis_db = redis_db
self.redis_password = redis_password
self.db_path = db_path
self.table_name = table_name
self.use_embedded_redis = use_embedded_redis
self.persist_redis = persist_redis
self.auto_persist = auto_persist
self.redis_data_dir = redis_data_dir
self.conversation_history = []
# Handle save filepath
if save_enabled and save_filepath:
self.save_filepath = save_filepath
elif save_enabled and conversations_dir:
self.save_filepath = os.path.join(
conversations_dir, f"{self.id}.json"
)
else:
self.save_filepath = None
# Support both 'provider' and 'backend' parameters for backwards compatibility # Support both 'provider' and 'backend' parameters for backwards compatibility
# 'backend' takes precedence if both are provided # 'backend' takes precedence if both are provided
self.backend_setup(backend, provider)
def backend_setup(
self, backend: str = None, provider: str = None
):
self.backend = backend or provider self.backend = backend or provider
self.backend_instance = None self.backend_instance = None
@ -285,19 +299,18 @@ class Conversation(BaseStructure):
]: ]:
try: try:
self._initialize_backend( self._initialize_backend(
supabase_url=supabase_url, supabase_url=self.supabase_url,
supabase_key=supabase_key, supabase_key=self.supabase_key,
redis_host=redis_host, redis_host=self.redis_host,
redis_port=redis_port, redis_port=self.redis_port,
redis_db=redis_db, redis_db=self.redis_db,
redis_password=redis_password, redis_password=self.redis_password,
db_path=db_path, db_path=self.db_path,
table_name=table_name, table_name=self.table_name,
use_embedded_redis=use_embedded_redis, use_embedded_redis=self.use_embedded_redis,
persist_redis=persist_redis, persist_redis=self.persist_redis,
auto_persist=auto_persist, auto_persist=self.auto_persist,
redis_data_dir=redis_data_dir, redis_data_dir=self.redis_data_dir,
**kwargs,
) )
except Exception as e: except Exception as e:
logger.warning( logger.warning(
@ -324,7 +337,6 @@ class Conversation(BaseStructure):
"time_enabled": self.time_enabled, "time_enabled": self.time_enabled,
"autosave": self.autosave, "autosave": self.autosave,
"save_filepath": self.save_filepath, "save_filepath": self.save_filepath,
"tokenizer": self.tokenizer,
"context_length": self.context_length, "context_length": self.context_length,
"rules": self.rules, "rules": self.rules,
"custom_rules_prompt": self.custom_rules_prompt, "custom_rules_prompt": self.custom_rules_prompt,
@ -449,8 +461,8 @@ class Conversation(BaseStructure):
if self.custom_rules_prompt is not None: if self.custom_rules_prompt is not None:
self.add(self.user or "User", self.custom_rules_prompt) self.add(self.user or "User", self.custom_rules_prompt)
if self.tokenizer is not None: # if self.tokenizer is not None:
self.truncate_memory_with_tokenizer() # self.truncate_memory_with_tokenizer()
def _autosave(self): def _autosave(self):
"""Automatically save the conversation if autosave is enabled.""" """Automatically save the conversation if autosave is enabled."""
@ -1051,9 +1063,7 @@ class Conversation(BaseStructure):
for message in self.conversation_history: for message in self.conversation_history:
role = message.get("role") role = message.get("role")
content = message.get("content") content = message.get("content")
tokens = self.tokenizer.count_tokens( tokens = count_tokens(content)
text=content
) # Count the number of tokens
count = tokens # Assign the token count count = tokens # Assign the token count
total_tokens += count total_tokens += count

@ -0,0 +1,270 @@
import uuid
from typing import Any, Callable, Dict, List, Optional, Union
from swarms.structs.agent import Agent
from swarms.structs.concurrent_workflow import ConcurrentWorkflow
from swarms.structs.conversation import Conversation
def _create_voting_prompt(candidate_agents: List[Agent]) -> str:
"""
Create a comprehensive voting prompt for the election.
This method generates a detailed prompt that instructs voter agents on:
- Available candidates
- Required structured output format
- Evaluation criteria
- Voting guidelines
Returns:
str: A formatted voting prompt string
"""
candidate_names = [
(agent.agent_name if hasattr(agent, "agent_name") else str(i))
for i, agent in enumerate(candidate_agents)
]
prompt = f"""
You are participating in an election to choose the best candidate agent.
Available candidates: {', '.join(candidate_names)}
Please vote for one candidate and provide your reasoning with the following structured output:
1. rationality: A detailed explanation of the reasoning behind your decision. Include logical considerations, supporting evidence, and trade-offs that were evaluated when selecting this candidate.
2. self_interest: A comprehensive discussion of how self-interest influenced your decision, if at all. Explain whether personal or role-specific incentives played a role, or if your choice was primarily for the collective benefit of the swarm.
3. candidate_agent_name: The full name or identifier of the candidate you are voting for. This should exactly match one of the available candidate names listed above.
Consider the candidates' capabilities, experience, and alignment with the swarm's objectives when making your decision.
"""
print(prompt)
return prompt
def get_vote_schema():
return [
{
"type": "function",
"function": {
"name": "vote",
"description": "Cast a vote for a CEO candidate with reasoning and self-interest analysis.",
"parameters": {
"type": "object",
"properties": {
"rationality": {
"type": "string",
"description": "A detailed explanation of the reasoning behind this voting decision.",
},
"self_interest": {
"type": "string",
"description": "A comprehensive discussion of how self-interest factored into the decision.",
},
"candidate_agent_name": {
"type": "string",
"description": "The full name or identifier of the chosen candidate.",
},
},
"required": [
"rationality",
"self_interest",
"candidate_agent_name",
],
},
},
}
]
class ElectionSwarm:
"""
A swarm system that conducts elections among multiple agents to choose the best candidate.
The ElectionSwarm orchestrates a voting process where multiple voter agents evaluate
and vote for candidate agents based on their capabilities, experience, and alignment
with swarm objectives. The system uses structured output to ensure consistent voting
format and provides detailed reasoning for each vote.
Attributes:
id (str): Unique identifier for the election swarm
name (str): Name of the election swarm
description (str): Description of the election swarm's purpose
max_loops (int): Maximum number of voting rounds (default: 1)
agents (List[Agent]): List of voter agents that will participate in the election
candidate_agents (List[Agent]): List of candidate agents to be voted on
kwargs (dict): Additional keyword arguments
show_dashboard (bool): Whether to display the election dashboard
conversation (Conversation): Conversation history for the election
"""
def __init__(
self,
name: str = "Election Swarm",
description: str = "An election swarm is a swarm of agents that will vote on a candidate.",
agents: Union[List[Agent], List[Callable]] = None,
candidate_agents: Union[List[Agent], List[Callable]] = None,
id: str = str(uuid.uuid4()),
max_loops: int = 1,
show_dashboard: bool = True,
**kwargs,
):
"""
Initialize the ElectionSwarm.
Args:
name (str, optional): Name of the election swarm
description (str, optional): Description of the election swarm's purpose
agents (Union[List[Agent], List[Callable]], optional): List of voter agents
candidate_agents (Union[List[Agent], List[Callable]], optional): List of candidate agents
id (str, optional): Unique identifier for the election swarm
max_loops (int, optional): Maximum number of voting rounds (default: 1)
show_dashboard (bool, optional): Whether to display the election dashboard (default: True)
**kwargs: Additional keyword arguments
"""
self.id = id
self.name = name
self.description = description
self.max_loops = max_loops
self.agents = agents
self.candidate_agents = candidate_agents
self.kwargs = kwargs
self.show_dashboard = show_dashboard
self.conversation = Conversation()
self.reliability_check()
self.setup_voter_agents()
def reliability_check(self):
"""
Check the reliability of the voter agents.
"""
if self.agents is None:
raise ValueError("Voter agents are not set")
if self.candidate_agents is None:
raise ValueError("Candidate agents are not set")
if self.max_loops is None or self.max_loops < 1:
raise ValueError("Max loops are not set")
def setup_concurrent_workflow(self):
"""
Create a concurrent workflow for running voter agents in parallel.
Returns:
ConcurrentWorkflow: A configured concurrent workflow for the election
"""
return ConcurrentWorkflow(
name=self.name,
description=self.description,
agents=self.agents,
output_type="dict-all-except-first",
show_dashboard=self.show_dashboard,
)
def run_voter_agents(
self, task: str, img: Optional[str] = None, *args, **kwargs
):
"""
Execute the voting process by running all voter agents concurrently.
Args:
task (str): The election task or question to be voted on
img (Optional[str], optional): Image path if visual voting is required
*args: Additional positional arguments
**kwargs: Additional keyword arguments
Returns:
List[Dict[str, Any]]: Results from all voter agents containing their votes and reasoning
"""
concurrent_workflow = self.setup_concurrent_workflow()
results = concurrent_workflow.run(
task=task, img=img, *args, **kwargs
)
conversation_history = (
concurrent_workflow.conversation.conversation_history
)
for message in conversation_history:
self.conversation.add(
role=message["role"], content=message["content"]
)
return results
def parse_results(
self, results: List[Dict[str, Any]]
) -> Dict[str, int]:
"""
Parse voting results to count votes for each candidate.
Args:
results (List[Dict[str, Any]]): List of voting results from voter agents
Returns:
Dict[str, int]: Dictionary mapping candidate names to their vote counts
"""
# Count the number of votes for each candidate
vote_counts = {}
for result in results:
candidate_name = result["candidate_agent_name"]
vote_counts[candidate_name] = (
vote_counts.get(candidate_name, 0) + 1
)
# Find the candidate with the most votes
return vote_counts
def run(
self, task: str, img: Optional[str] = None, *args, **kwargs
):
"""
Execute the complete election process.
This method orchestrates the entire election by:
1. Adding the task to the conversation history
2. Running all voter agents concurrently
3. Collecting and processing the voting results
Args:
task (str): The election task or question to be voted on
img (Optional[str], optional): Image path if visual voting is required
*args: Additional positional arguments
**kwargs: Additional keyword arguments
Returns:
List[Dict[str, Any]]: Complete voting results from all agents
"""
self.conversation.add(role="user", content=task)
results = self.run_voter_agents(task, img, *args, **kwargs)
print(results)
return results
def setup_voter_agents(self):
"""
Configure voter agents with structured output capabilities and voting prompts.
This method sets up each voter agent with:
- Structured output schema for consistent voting format
- Voting-specific system prompts
- Tools for structured response generation
Returns:
List[Agent]: Configured voter agents ready for the election
"""
schema = get_vote_schema()
prompt = _create_voting_prompt(self.candidate_agents)
for agent in self.agents:
agent.tools_list_dictionary = schema
agent.system_prompt += f"\n\n{prompt}"

File diff suppressed because it is too large Load Diff

@ -0,0 +1,253 @@
from swarms.structs.agent import Agent
from typing import List
from swarms.structs.conversation import Conversation
import uuid
import random
from loguru import logger
from typing import Optional
class QASwarm:
"""
A Question and Answer swarm system where random agents ask questions to speaker agents.
This system allows for dynamic Q&A sessions where:
- Multiple agents can act as questioners
- One or multiple agents can act as speakers/responders
- Questions are asked randomly by different agents
- The conversation is tracked and managed
- Agents are showcased to each other with detailed information
"""
def __init__(
self,
name: str = "QandA",
description: str = "Question and Answer Swarm System",
agents: List[Agent] = None,
speaker_agents: List[Agent] = None,
id: str = str(uuid.uuid4()),
max_loops: int = 5,
show_dashboard: bool = True,
speaker_agent: Agent = None,
showcase_agents: bool = True,
**kwargs,
):
self.id = id
self.name = name
self.description = description
self.max_loops = max_loops
self.show_dashboard = show_dashboard
self.agents = agents or []
self.speaker_agents = speaker_agents or []
self.kwargs = kwargs
self.speaker_agent = speaker_agent
self.showcase_agents = showcase_agents
self.conversation = Conversation()
# Validate setup
self._validate_setup()
def _validate_setup(self):
"""Validate that the Q&A system is properly configured."""
if not self.agents:
logger.warning(
"No questioner agents provided. Add agents using add_agent() method."
)
if not self.speaker_agents and not self.speaker_agent:
logger.warning(
"No speaker agents provided. Add speaker agents using add_speaker_agent() method."
)
if (
not self.agents
and not self.speaker_agents
and not self.speaker_agent
):
raise ValueError(
"At least one agent (questioner or speaker) must be provided."
)
def add_agent(self, agent: Agent):
"""Add a questioner agent to the swarm."""
self.agents.append(agent)
logger.info(f"Added questioner agent: {agent.agent_name}")
def add_speaker_agent(self, agent: Agent):
"""Add a speaker agent to the swarm."""
if self.speaker_agents is None:
self.speaker_agents = []
self.speaker_agents.append(agent)
logger.info(f"Added speaker agent: {agent.agent_name}")
def get_agent_info(self, agent: Agent) -> dict:
"""Extract key information about an agent for showcasing."""
info = {
"name": getattr(agent, "agent_name", "Unknown Agent"),
"description": getattr(
agent, "agent_description", "No description available"
),
"role": getattr(agent, "role", "worker"),
}
# Get system prompt preview (first 50 characters)
system_prompt = getattr(agent, "system_prompt", "")
if system_prompt:
info["system_prompt_preview"] = (
system_prompt[:50] + "..."
if len(system_prompt) > 50
else system_prompt
)
else:
info["system_prompt_preview"] = (
"No system prompt available"
)
return info
def showcase_speaker_to_questioner(
self, questioner: Agent, speaker: Agent
) -> str:
"""Create a showcase prompt introducing the speaker agent to the questioner."""
speaker_info = self.get_agent_info(speaker)
showcase_prompt = f"""
You are about to ask a question to a specialized agent. Here's what you need to know about them:
**Speaker Agent Information:**
- **Name**: {speaker_info['name']}
- **Role**: {speaker_info['role']}
- **Description**: {speaker_info['description']}
- **System Prompt Preview**: {speaker_info['system_prompt_preview']}
Please craft a thoughtful, relevant question that takes into account this agent's expertise and background.
Your question should be specific and demonstrate that you understand their role and capabilities.
"""
return showcase_prompt
def showcase_questioner_to_speaker(
self, speaker: Agent, questioner: Agent
) -> str:
"""Create a showcase prompt introducing the questioner agent to the speaker."""
questioner_info = self.get_agent_info(questioner)
showcase_prompt = f"""
You are about to answer a question from another agent. Here's what you need to know about them:
**Questioner Agent Information:**
- **Name**: {questioner_info['name']}
- **Role**: {questioner_info['role']}
- **Description**: {questioner_info['description']}
- **System Prompt Preview**: {questioner_info['system_prompt_preview']}
Please provide a comprehensive answer that demonstrates your expertise and addresses their question thoroughly.
Consider their background and role when formulating your response.
"""
return showcase_prompt
def random_select_agent(self, agents: List[Agent]) -> Agent:
"""Randomly select an agent from the list."""
if not agents:
raise ValueError("No agents available for selection")
return random.choice(agents)
def get_current_speaker(self) -> Agent:
"""Get the current speaker agent (either from speaker_agents list or single speaker_agent)."""
if self.speaker_agent:
return self.speaker_agent
elif self.speaker_agents:
return self.random_select_agent(self.speaker_agents)
else:
raise ValueError("No speaker agent available")
def run(
self, task: str, img: Optional[str] = None, *args, **kwargs
):
"""Run the Q&A session with agent showcasing."""
self.conversation.add(role="user", content=task)
# Get current speaker
current_speaker = self.get_current_speaker()
# Select a random questioner
questioner = self.random_select_agent(self.agents)
# Showcase agents to each other if enabled
if self.showcase_agents:
# Showcase speaker to questioner
speaker_showcase = self.showcase_speaker_to_questioner(
questioner, current_speaker
)
questioner_task = f"{speaker_showcase}\n\nNow ask a question about: {task}"
# Showcase questioner to speaker
questioner_showcase = self.showcase_questioner_to_speaker(
current_speaker, questioner
)
else:
questioner_task = f"Ask a question about {task} to {current_speaker.agent_name}"
# Generate question
question = questioner.run(
task=questioner_task,
img=img,
*args,
**kwargs,
)
self.conversation.add(
role=questioner.agent_name, content=question
)
# Prepare answer task with showcasing if enabled
if self.showcase_agents:
answer_task = f"{questioner_showcase}\n\nAnswer this question from {questioner.agent_name}: {question}"
else:
answer_task = f"Answer the question '{question}' from {questioner.agent_name}"
# Generate answer
answer = current_speaker.run(
task=answer_task,
img=img,
*args,
**kwargs,
)
self.conversation.add(
role=current_speaker.agent_name, content=answer
)
return answer
def run_multi_round(
self,
task: str,
rounds: int = 3,
img: Optional[str] = None,
*args,
**kwargs,
):
"""Run multiple rounds of Q&A with different questioners."""
results = []
for round_num in range(rounds):
logger.info(
f"Starting Q&A round {round_num + 1}/{rounds}"
)
round_result = self.run(task, img, *args, **kwargs)
results.append(
{"round": round_num + 1, "result": round_result}
)
return results
def get_conversation_history(self):
"""Get the conversation history."""
return self.conversation.get_history()
def clear_conversation(self):
"""Clear the conversation history."""
self.conversation = Conversation()
logger.info("Conversation history cleared")

@ -2,9 +2,9 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Callable, List, Optional, Union from typing import Callable, List, Optional, Union
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
from swarms.utils.output_types import OutputType
from swarms.structs.rearrange import AgentRearrange from swarms.structs.rearrange import AgentRearrange
from swarms.utils.loguru_logger import initialize_logger from swarms.utils.loguru_logger import initialize_logger
from swarms.utils.output_types import OutputType
logger = initialize_logger(log_folder="sequential_workflow") logger = initialize_logger(log_folder="sequential_workflow")
@ -29,6 +29,7 @@ class SequentialWorkflow:
def __init__( def __init__(
self, self,
id: str = "sequential_workflow",
name: str = "SequentialWorkflow", name: str = "SequentialWorkflow",
description: str = "Sequential Workflow, where agents are executed in a sequence.", description: str = "Sequential Workflow, where agents are executed in a sequence.",
agents: List[Union[Agent, Callable]] = [], agents: List[Union[Agent, Callable]] = [],
@ -38,6 +39,7 @@ class SequentialWorkflow:
*args, *args,
**kwargs, **kwargs,
): ):
self.id = id
self.name = name self.name = name
self.description = description self.description = description
self.agents = agents self.agents = agents

@ -28,6 +28,7 @@ from swarms.structs.malt import MALT
from swarms.structs.deep_research_swarm import DeepResearchSwarm from swarms.structs.deep_research_swarm import DeepResearchSwarm
from swarms.structs.council_judge import CouncilAsAJudge from swarms.structs.council_judge import CouncilAsAJudge
from swarms.structs.interactive_groupchat import InteractiveGroupChat from swarms.structs.interactive_groupchat import InteractiveGroupChat
from swarms.structs.heavy_swarm import HeavySwarm
from swarms.structs.ma_utils import list_all_agents from swarms.structs.ma_utils import list_all_agents
from swarms.utils.generate_keys import generate_api_key from swarms.utils.generate_keys import generate_api_key
@ -49,6 +50,7 @@ SwarmType = Literal[
"DeepResearchSwarm", "DeepResearchSwarm",
"CouncilAsAJudge", "CouncilAsAJudge",
"InteractiveGroupChat", "InteractiveGroupChat",
"HeavySwarm",
] ]
@ -183,6 +185,10 @@ class SwarmRouter:
conversation: Any = None, conversation: Any = None,
agents_config: Optional[Dict[Any, Any]] = None, agents_config: Optional[Dict[Any, Any]] = None,
speaker_function: str = None, speaker_function: str = None,
heavy_swarm_loops_per_agent: int = 1,
heavy_swarm_question_agent_model_name: str = "gpt-4.1",
heavy_swarm_worker_model_name: str = "claude-3-5-sonnet-20240620",
telemetry_enabled: bool = False,
*args, *args,
**kwargs, **kwargs,
): ):
@ -210,6 +216,14 @@ class SwarmRouter:
self.conversation = conversation self.conversation = conversation
self.agents_config = agents_config self.agents_config = agents_config
self.speaker_function = speaker_function self.speaker_function = speaker_function
self.heavy_swarm_loops_per_agent = heavy_swarm_loops_per_agent
self.heavy_swarm_question_agent_model_name = (
heavy_swarm_question_agent_model_name
)
self.heavy_swarm_worker_model_name = (
heavy_swarm_worker_model_name
)
self.telemetry_enabled = telemetry_enabled
# Reliability check # Reliability check
self.reliability_check() self.reliability_check()
@ -234,6 +248,12 @@ class SwarmRouter:
if self.rules is not None: if self.rules is not None:
self.handle_rules() self.handle_rules()
if self.multi_agent_collab_prompt is True:
self.update_system_prompt_for_agent_in_swarm()
if self.list_all_agents is True:
self.list_agents_to_eachother()
def activate_shared_memory(self): def activate_shared_memory(self):
logger.info("Activating shared memory with all agents ") logger.info("Activating shared memory with all agents ")
@ -283,6 +303,10 @@ class SwarmRouter:
Handles special case for CouncilAsAJudge which may not require agents. Handles special case for CouncilAsAJudge which may not require agents.
""" """
logger.info(
f"Initializing SwarmRouter: {self.name} Reliability Check..."
)
# Check swarm type first since it affects other validations # Check swarm type first since it affects other validations
if self.swarm_type is None: if self.swarm_type is None:
raise ValueError( raise ValueError(
@ -300,6 +324,10 @@ class SwarmRouter:
self.setup() self.setup()
logger.info(
f"Reliability check for parameters and configurations are complete. SwarmRouter: {self.name} is ready to run!"
)
def _create_swarm(self, task: str = None, *args, **kwargs): def _create_swarm(self, task: str = None, *args, **kwargs):
""" """
Dynamically create and return the specified swarm type or automatically match the best swarm type for a given task. Dynamically create and return the specified swarm type or automatically match the best swarm type for a given task.
@ -321,6 +349,18 @@ class SwarmRouter:
self._create_swarm(self.swarm_type) self._create_swarm(self.swarm_type)
elif self.swarm_type == "HeavySwarm":
return HeavySwarm(
name=self.name,
description=self.description,
agents=self.agents,
max_loops=self.max_loops,
output_type=self.output_type,
loops_per_agent=self.heavy_swarm_loops_per_agent,
question_agent_model_name=self.heavy_swarm_question_agent_model_name,
worker_model_name=self.heavy_swarm_worker_model_name,
)
elif self.swarm_type == "AgentRearrange": elif self.swarm_type == "AgentRearrange":
return AgentRearrange( return AgentRearrange(
name=self.name, name=self.name,
@ -478,6 +518,24 @@ class SwarmRouter:
return agent_config return agent_config
def list_agents_to_eachother(self):
if self.swarm_type == "SequentialWorkflow":
self.conversation = (
self.swarm.agent_rearrange.conversation
)
else:
self.conversation = self.swarm.conversation
if self.list_all_agents is True:
list_all_agents(
agents=self.agents,
conversation=self.swarm.conversation,
name=self.name,
description=self.description,
add_collaboration_prompt=True,
add_to_conversation=True,
)
def _run( def _run(
self, self,
task: str, task: str,
@ -503,31 +561,12 @@ class SwarmRouter:
""" """
self.swarm = self._create_swarm(task, *args, **kwargs) self.swarm = self._create_swarm(task, *args, **kwargs)
if self.swarm_type == "SequentialWorkflow":
self.conversation = (
self.swarm.agent_rearrange.conversation
)
else:
self.conversation = self.swarm.conversation
if self.list_all_agents is True:
list_all_agents(
agents=self.agents,
conversation=self.swarm.conversation,
name=self.name,
description=self.description,
add_collaboration_prompt=True,
add_to_conversation=True,
)
if self.multi_agent_collab_prompt is True:
self.update_system_prompt_for_agent_in_swarm()
log_execution( log_execution(
swarm_id=self.id, swarm_id=self.id,
status="start", status="start",
swarm_config=self.to_dict(), swarm_config=self.to_dict(),
swarm_architecture="swarm_router", swarm_architecture="swarm_router",
enabled_on=self.telemetry_enabled,
) )
try: try:
@ -548,12 +587,13 @@ class SwarmRouter:
status="completion", status="completion",
swarm_config=self.to_dict(), swarm_config=self.to_dict(),
swarm_architecture="swarm_router", swarm_architecture="swarm_router",
enabled_on=self.telemetry_enabled,
) )
return result return result
except Exception as e: except Exception as e:
raise RuntimeError( raise RuntimeError(
f"SwarmRouter: Error executing task on swarm: {str(e)} Traceback: {traceback.format_exc()}" f"SwarmRouter: Error executing task on swarm: {str(e)} Traceback: {traceback.format_exc()}. Try reconfiguring the SwarmRouter Settings and or make sure the individual agents are configured correctly."
) )
def run( def run(

@ -1,5 +1,250 @@
from typing import Optional from typing import Optional
from swarms.telemetry.main import log_agent_data from swarms.telemetry.main import log_agent_data
import functools
import inspect
import time
from datetime import datetime
def log_function_execution(
swarm_id: Optional[str] = None,
swarm_architecture: Optional[str] = None,
enabled_on: Optional[bool] = True,
):
"""
Decorator to log function execution details including parameters and outputs.
This decorator automatically captures and logs:
- Function name
- Function parameters (args and kwargs)
- Function output/return value
- Execution timestamp
- Execution duration
- Execution status (success/error)
Args:
swarm_id (str, optional): Unique identifier for the swarm instance
swarm_architecture (str, optional): Name of the swarm architecture
enabled_on (bool, optional): Whether logging is enabled. Defaults to True.
Returns:
Decorated function that logs execution details
Example:
>>> @log_function_execution(swarm_id="my-swarm", swarm_architecture="sequential")
... def process_data(data, threshold=0.5):
... return {"processed": len(data), "threshold": threshold}
...
>>> result = process_data([1, 2, 3], threshold=0.8)
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if not enabled_on:
return func(*args, **kwargs)
# Capture function details
function_name = func.__name__
function_module = func.__module__
start_time = time.time()
timestamp = datetime.now().isoformat()
# Capture function parameters
sig = inspect.signature(func)
bound_args = sig.bind(*args, **kwargs)
bound_args.apply_defaults()
# Convert parameters to serializable format
parameters = {}
for (
param_name,
param_value,
) in bound_args.arguments.items():
try:
# Handle special method parameters
if param_name == "self":
# For instance methods, log class name and instance info
parameters[param_name] = {
"class_name": param_value.__class__.__name__,
"class_module": param_value.__class__.__module__,
"instance_id": hex(id(param_value)),
"type": "instance",
}
elif param_name == "cls":
# For class methods, log class information
parameters[param_name] = {
"class_name": param_value.__name__,
"class_module": param_value.__module__,
"type": "class",
}
elif isinstance(
param_value,
(str, int, float, bool, type(None)),
):
parameters[param_name] = param_value
elif isinstance(param_value, (list, dict, tuple)):
parameters[param_name] = str(param_value)[
:500
] # Truncate large objects
elif hasattr(param_value, "__class__"):
# Handle other object instances
parameters[param_name] = {
"class_name": param_value.__class__.__name__,
"class_module": param_value.__class__.__module__,
"instance_id": hex(id(param_value)),
"type": "object_instance",
}
else:
parameters[param_name] = str(
type(param_value)
)
except Exception:
parameters[param_name] = "<non-serializable>"
# Determine if this is a method call and add context
method_context = _get_method_context(
func, bound_args.arguments
)
execution_data = {
"function_name": function_name,
"function_module": function_module,
"swarm_id": swarm_id,
"swarm_architecture": swarm_architecture,
"timestamp": timestamp,
"parameters": parameters,
"status": "start",
**method_context,
}
try:
# Log function start
log_agent_data(data_dict=execution_data)
# Execute the function
result = func(*args, **kwargs)
# Calculate execution time
end_time = time.time()
execution_time = end_time - start_time
# Log successful execution
success_data = {
**execution_data,
"status": "success",
"execution_time_seconds": execution_time,
"output": _serialize_output(result),
}
log_agent_data(data_dict=success_data)
return result
except Exception as e:
# Calculate execution time even for errors
end_time = time.time()
execution_time = end_time - start_time
# Log error execution
error_data = {
**execution_data,
"status": "error",
"execution_time_seconds": execution_time,
"error_message": str(e),
"error_type": type(e).__name__,
}
try:
log_agent_data(data_dict=error_data)
except Exception:
pass # Silent fail on logging errors
# Re-raise the original exception
raise
return wrapper
return decorator
def _get_method_context(func, arguments):
"""
Helper function to extract method context information.
Args:
func: The function/method being called
arguments: The bound arguments dictionary
Returns:
Dictionary with method context information
"""
context = {}
try:
# Check if this is a method call
if "self" in arguments:
# Instance method
self_obj = arguments["self"]
context.update(
{
"method_type": "instance_method",
"class_name": self_obj.__class__.__name__,
"class_module": self_obj.__class__.__module__,
"instance_id": hex(id(self_obj)),
}
)
elif "cls" in arguments:
# Class method
cls_obj = arguments["cls"]
context.update(
{
"method_type": "class_method",
"class_name": cls_obj.__name__,
"class_module": cls_obj.__module__,
}
)
else:
# Regular function or static method
context.update({"method_type": "function"})
# Try to get qualname for additional context
if hasattr(func, "__qualname__"):
context["qualified_name"] = func.__qualname__
except Exception:
# If anything fails, just mark as unknown
context = {"method_type": "unknown"}
return context
def _serialize_output(output):
"""
Helper function to serialize function output for logging.
Args:
output: The function return value to serialize
Returns:
Serializable representation of the output
"""
try:
if output is None:
return None
elif isinstance(output, (str, int, float, bool)):
return output
elif isinstance(output, (list, dict, tuple)):
# Truncate large outputs to prevent log bloat
output_str = str(output)
return (
output_str[:1000] + "..."
if len(output_str) > 1000
else output_str
)
else:
return str(type(output))
except Exception:
return "<non-serializable-output>"
def log_execution( def log_execution(
@ -7,6 +252,7 @@ def log_execution(
status: Optional[str] = None, status: Optional[str] = None,
swarm_config: Optional[dict] = None, swarm_config: Optional[dict] = None,
swarm_architecture: Optional[str] = None, swarm_architecture: Optional[str] = None,
enabled_on: Optional[bool] = False,
): ):
""" """
Log execution data for a swarm router instance. Log execution data for a swarm router instance.
@ -31,13 +277,16 @@ def log_execution(
... ) ... )
""" """
try: try:
log_agent_data( if enabled_on is None:
data_dict={ log_agent_data(
"swarm_router_id": swarm_id, data_dict={
"status": status, "swarm_router_id": swarm_id,
"swarm_router_config": swarm_config, "status": status,
"swarm_architecture": swarm_architecture, "swarm_router_config": swarm_config,
} "swarm_architecture": swarm_architecture,
) }
)
else:
pass
except Exception: except Exception:
pass pass

@ -1,46 +1,45 @@
from swarms.tools.tool_utils import ( from swarms.tools.base_tool import BaseTool
scrape_tool_func_docs, from swarms.tools.cohere_func_call_schema import (
tool_find_by_name, CohereFuncSchema,
ParameterDefinition,
) )
from swarms.tools.pydantic_to_json import ( from swarms.tools.json_utils import base_model_to_json
_remove_a_key, from swarms.tools.mcp_client_call import (
base_model_to_openai_function, _create_server_tool_mapping,
multi_base_model_to_openai_function, _create_server_tool_mapping_async,
_execute_tool_call_simple,
_execute_tool_on_server,
aget_mcp_tools,
execute_multiple_tools_on_multiple_mcp_servers,
execute_multiple_tools_on_multiple_mcp_servers_sync,
execute_tool_call_simple,
get_mcp_tools_sync,
get_tools_for_multiple_mcp_servers,
) )
from swarms.tools.openai_func_calling_schema_pydantic import ( from swarms.tools.openai_func_calling_schema_pydantic import (
OpenAIFunctionCallSchema as OpenAIFunctionCallSchemaBaseModel, OpenAIFunctionCallSchema as OpenAIFunctionCallSchemaBaseModel,
) )
from swarms.tools.openai_tool_creator_decorator import tool
from swarms.tools.py_func_to_openai_func_str import ( from swarms.tools.py_func_to_openai_func_str import (
get_openai_function_schema_from_func, Function,
load_basemodels_if_needed, ToolFunction,
get_load_param_if_needed_function, get_load_param_if_needed_function,
get_openai_function_schema_from_func,
get_parameters, get_parameters,
get_required_params, get_required_params,
Function, load_basemodels_if_needed,
ToolFunction,
) )
from swarms.tools.openai_tool_creator_decorator import tool from swarms.tools.pydantic_to_json import (
from swarms.tools.base_tool import BaseTool _remove_a_key,
from swarms.tools.cohere_func_call_schema import ( base_model_to_openai_function,
CohereFuncSchema, multi_base_model_to_openai_function,
ParameterDefinition,
) )
from swarms.tools.tool_registry import ToolStorage, tool_registry from swarms.tools.tool_registry import ToolStorage, tool_registry
from swarms.tools.json_utils import base_model_to_json from swarms.tools.tool_utils import (
from swarms.tools.mcp_client_call import ( scrape_tool_func_docs,
execute_tool_call_simple, tool_find_by_name,
_execute_tool_call_simple,
get_tools_for_multiple_mcp_servers,
get_mcp_tools_sync,
aget_mcp_tools,
execute_multiple_tools_on_multiple_mcp_servers,
execute_multiple_tools_on_multiple_mcp_servers_sync,
_create_server_tool_mapping,
_create_server_tool_mapping_async,
_execute_tool_on_server,
) )
__all__ = [ __all__ = [
"scrape_tool_func_docs", "scrape_tool_func_docs",
"tool_find_by_name", "tool_find_by_name",

@ -0,0 +1,675 @@
import json
import pickle
import hashlib
import threading
import time
from functools import lru_cache, wraps
from typing import List, Dict, Any, Optional, Callable
from pathlib import Path
import weakref
from concurrent.futures import ThreadPoolExecutor
import os
from loguru import logger
# Import the Agent class - adjust path as needed
try:
from swarms.structs.agent import Agent
except ImportError:
# Fallback for development/testing
Agent = Any
class AgentCache:
"""
A comprehensive caching system for Agent objects with multiple strategies:
- Memory-based LRU cache
- Weak reference cache to prevent memory leaks
- Persistent disk cache for agent configurations
- Lazy loading with background preloading
"""
def __init__(
self,
max_memory_cache_size: int = 128,
cache_dir: Optional[str] = None,
enable_persistent_cache: bool = True,
auto_save_interval: int = 300, # 5 minutes
enable_weak_refs: bool = True,
):
"""
Initialize the AgentCache.
Args:
max_memory_cache_size: Maximum number of agents to keep in memory cache
cache_dir: Directory for persistent cache storage
enable_persistent_cache: Whether to enable disk-based caching
auto_save_interval: Interval in seconds for auto-saving cache
enable_weak_refs: Whether to use weak references to prevent memory leaks
"""
self.max_memory_cache_size = max_memory_cache_size
self.cache_dir = Path(cache_dir or "agent_cache")
self.enable_persistent_cache = enable_persistent_cache
self.auto_save_interval = auto_save_interval
self.enable_weak_refs = enable_weak_refs
# Memory caches
self._memory_cache: Dict[str, Agent] = {}
self._weak_cache: weakref.WeakValueDictionary = (
weakref.WeakValueDictionary()
)
self._access_times: Dict[str, float] = {}
self._lock = threading.RLock()
# Cache statistics
self._hits = 0
self._misses = 0
self._load_times: Dict[str, float] = {}
# Background tasks
self._auto_save_thread: Optional[threading.Thread] = None
self._shutdown_event = threading.Event()
# Initialize cache directory
if self.enable_persistent_cache:
self.cache_dir.mkdir(parents=True, exist_ok=True)
# Start auto-save thread
self._start_auto_save_thread()
def _start_auto_save_thread(self):
"""Start the auto-save background thread."""
if (
self.enable_persistent_cache
and self.auto_save_interval > 0
):
self._auto_save_thread = threading.Thread(
target=self._auto_save_loop,
daemon=True,
name="AgentCache-AutoSave",
)
self._auto_save_thread.start()
def _auto_save_loop(self):
"""Background loop for auto-saving cache."""
while not self._shutdown_event.wait(self.auto_save_interval):
try:
self.save_cache_to_disk()
except Exception as e:
logger.error(f"Error in auto-save: {e}")
def _generate_cache_key(
self, agent_config: Dict[str, Any]
) -> str:
"""Generate a unique cache key from agent configuration."""
# Create a stable hash from the configuration
config_str = json.dumps(
agent_config, sort_keys=True, default=str
)
return hashlib.md5(config_str.encode()).hexdigest()
def _evict_lru(self):
"""Evict least recently used items from memory cache."""
if len(self._memory_cache) >= self.max_memory_cache_size:
# Find the least recently used item
lru_key = min(
self._access_times.items(), key=lambda x: x[1]
)[0]
# Save to persistent cache before evicting
if self.enable_persistent_cache:
self._save_agent_to_disk(
lru_key, self._memory_cache[lru_key]
)
# Remove from memory
del self._memory_cache[lru_key]
del self._access_times[lru_key]
logger.debug(f"Evicted agent {lru_key} from memory cache")
def _save_agent_to_disk(self, cache_key: str, agent: Agent):
"""Save agent to persistent cache."""
try:
cache_file = self.cache_dir / f"{cache_key}.pkl"
with open(cache_file, "wb") as f:
pickle.dump(agent.to_dict(), f)
logger.debug(f"Saved agent {cache_key} to disk cache")
except Exception as e:
logger.error(f"Error saving agent to disk: {e}")
def _load_agent_from_disk(
self, cache_key: str
) -> Optional[Agent]:
"""Load agent from persistent cache."""
try:
cache_file = self.cache_dir / f"{cache_key}.pkl"
if cache_file.exists():
with open(cache_file, "rb") as f:
agent_dict = pickle.load(f)
# Reconstruct agent from dictionary
agent = Agent(**agent_dict)
logger.debug(
f"Loaded agent {cache_key} from disk cache"
)
return agent
except Exception as e:
logger.error(f"Error loading agent from disk: {e}")
return None
def get_agent(
self, agent_config: Dict[str, Any]
) -> Optional[Agent]:
"""
Get an agent from cache, loading if necessary.
Args:
agent_config: Configuration dictionary for the agent
Returns:
Cached or newly loaded Agent instance
"""
cache_key = self._generate_cache_key(agent_config)
with self._lock:
# Check memory cache first
if cache_key in self._memory_cache:
self._access_times[cache_key] = time.time()
self._hits += 1
logger.debug(
f"Cache hit (memory) for agent {cache_key}"
)
return self._memory_cache[cache_key]
# Check weak reference cache
if (
self.enable_weak_refs
and cache_key in self._weak_cache
):
agent = self._weak_cache[cache_key]
if agent is not None:
# Move back to memory cache
self._memory_cache[cache_key] = agent
self._access_times[cache_key] = time.time()
self._hits += 1
logger.debug(
f"Cache hit (weak ref) for agent {cache_key}"
)
return agent
# Check persistent cache
if self.enable_persistent_cache:
agent = self._load_agent_from_disk(cache_key)
if agent is not None:
self._evict_lru()
self._memory_cache[cache_key] = agent
self._access_times[cache_key] = time.time()
if self.enable_weak_refs:
self._weak_cache[cache_key] = agent
self._hits += 1
logger.debug(
f"Cache hit (disk) for agent {cache_key}"
)
return agent
# Cache miss - need to create new agent
self._misses += 1
logger.debug(f"Cache miss for agent {cache_key}")
return None
def put_agent(self, agent_config: Dict[str, Any], agent: Agent):
"""
Put an agent into the cache.
Args:
agent_config: Configuration dictionary for the agent
agent: The Agent instance to cache
"""
cache_key = self._generate_cache_key(agent_config)
with self._lock:
self._evict_lru()
self._memory_cache[cache_key] = agent
self._access_times[cache_key] = time.time()
if self.enable_weak_refs:
self._weak_cache[cache_key] = agent
logger.debug(f"Added agent {cache_key} to cache")
def preload_agents(self, agent_configs: List[Dict[str, Any]]):
"""
Preload agents in the background for faster access.
Args:
agent_configs: List of agent configurations to preload
"""
def _preload_worker(config):
try:
cache_key = self._generate_cache_key(config)
if cache_key not in self._memory_cache:
start_time = time.time()
agent = Agent(**config)
load_time = time.time() - start_time
self.put_agent(config, agent)
self._load_times[cache_key] = load_time
logger.debug(
f"Preloaded agent {cache_key} in {load_time:.3f}s"
)
except Exception as e:
logger.error(f"Error preloading agent: {e}")
# Use thread pool for concurrent preloading
max_workers = min(len(agent_configs), os.cpu_count())
with ThreadPoolExecutor(max_workers=max_workers) as executor:
executor.map(_preload_worker, agent_configs)
def get_cache_stats(self) -> Dict[str, Any]:
"""Get cache performance statistics."""
total_requests = self._hits + self._misses
hit_rate = (
(self._hits / total_requests * 100)
if total_requests > 0
else 0
)
return {
"hits": self._hits,
"misses": self._misses,
"hit_rate_percent": round(hit_rate, 2),
"memory_cache_size": len(self._memory_cache),
"weak_cache_size": len(self._weak_cache),
"average_load_time": (
sum(self._load_times.values()) / len(self._load_times)
if self._load_times
else 0
),
"total_agents_loaded": len(self._load_times),
}
def clear_cache(self):
"""Clear all caches."""
with self._lock:
self._memory_cache.clear()
self._weak_cache.clear()
self._access_times.clear()
logger.info("Cleared all caches")
def save_cache_to_disk(self):
"""Save current memory cache to disk."""
if not self.enable_persistent_cache:
return
with self._lock:
saved_count = 0
for cache_key, agent in self._memory_cache.items():
try:
self._save_agent_to_disk(cache_key, agent)
saved_count += 1
except Exception as e:
logger.error(
f"Error saving agent {cache_key}: {e}"
)
logger.info(f"Saved {saved_count} agents to disk cache")
def shutdown(self):
"""Shutdown the cache system gracefully."""
self._shutdown_event.set()
if self._auto_save_thread:
self._auto_save_thread.join(timeout=5)
# Final save
if self.enable_persistent_cache:
self.save_cache_to_disk()
logger.info("AgentCache shutdown complete")
# Global cache instance
_global_cache: Optional[AgentCache] = None
def get_global_cache() -> AgentCache:
"""Get or create the global agent cache instance."""
global _global_cache
if _global_cache is None:
_global_cache = AgentCache()
return _global_cache
def cached_agent_loader(
agents: List[Agent],
cache_instance: Optional[AgentCache] = None,
preload: bool = True,
parallel_loading: bool = True,
) -> List[Agent]:
"""
Load a list of agents with caching for super fast performance.
Args:
agents: List of Agent instances to cache/load
cache_instance: Optional cache instance (uses global cache if None)
preload: Whether to preload agents in background
parallel_loading: Whether to load agents in parallel
Returns:
List of Agent instances (cached versions if available)
Examples:
# Basic usage
agents = [Agent(agent_name="Agent1", model_name="gpt-4"), ...]
cached_agents = cached_agent_loader(agents)
# With custom cache
cache = AgentCache(max_memory_cache_size=256)
cached_agents = cached_agent_loader(agents, cache_instance=cache)
# Preload for even faster subsequent access
cached_agent_loader(agents, preload=True)
cached_agents = cached_agent_loader(agents) # Super fast!
"""
cache = cache_instance or get_global_cache()
start_time = time.time()
# Extract configurations from agents for caching
agent_configs = []
for agent in agents:
config = _extract_agent_config(agent)
agent_configs.append(config)
if preload:
# Preload agents in background
cache.preload_agents(agent_configs)
def _load_single_agent(agent: Agent) -> Agent:
"""Load a single agent with caching."""
config = _extract_agent_config(agent)
# Try to get from cache first
cached_agent = cache.get_agent(config)
if cached_agent is None:
# Cache miss - use the provided agent and cache it
load_start = time.time()
# Add to cache for future use
cache.put_agent(config, agent)
load_time = time.time() - load_start
logger.debug(
f"Cached new agent {agent.agent_name} in {load_time:.3f}s"
)
return agent
else:
logger.debug(
f"Retrieved cached agent {cached_agent.agent_name}"
)
return cached_agent
# Load agents (parallel or sequential)
if parallel_loading and len(agents) > 1:
max_workers = min(len(agents), os.cpu_count())
with ThreadPoolExecutor(max_workers=max_workers) as executor:
cached_agents = list(
executor.map(_load_single_agent, agents)
)
else:
cached_agents = [
_load_single_agent(agent) for agent in agents
]
total_time = time.time() - start_time
# Log performance stats
stats = cache.get_cache_stats()
logger.info(
f"Processed {len(cached_agents)} agents in {total_time:.3f}s "
f"(Hit rate: {stats['hit_rate_percent']}%)"
)
return cached_agents
def _extract_agent_config(agent: Agent) -> Dict[str, Any]:
"""
Extract a configuration dictionary from an Agent instance for caching.
Args:
agent: Agent instance to extract config from
Returns:
Configuration dictionary suitable for cache key generation
"""
# Extract key attributes that define an agent's identity
config = {
"agent_name": getattr(agent, "agent_name", None),
"model_name": getattr(agent, "model_name", None),
"system_prompt": getattr(agent, "system_prompt", None),
"max_loops": getattr(agent, "max_loops", None),
"temperature": getattr(agent, "temperature", None),
"max_tokens": getattr(agent, "max_tokens", None),
"agent_description": getattr(
agent, "agent_description", None
),
# Add other key identifying attributes
"tools": str(
getattr(agent, "tools", [])
), # Convert to string for hashing, default to empty list
"context_length": getattr(agent, "context_length", None),
}
# Remove None values to create a clean config
config = {k: v for k, v in config.items() if v is not None}
return config
def cached_agent_loader_from_configs(
agent_configs: List[Dict[str, Any]],
cache_instance: Optional[AgentCache] = None,
preload: bool = True,
parallel_loading: bool = True,
) -> List[Agent]:
"""
Load a list of agents from configuration dictionaries with caching.
Args:
agent_configs: List of agent configuration dictionaries
cache_instance: Optional cache instance (uses global cache if None)
preload: Whether to preload agents in background
parallel_loading: Whether to load agents in parallel
Returns:
List of Agent instances
Examples:
# Basic usage
configs = [{"agent_name": "Agent1", "model_name": "gpt-4"}, ...]
agents = cached_agent_loader_from_configs(configs)
# With custom cache
cache = AgentCache(max_memory_cache_size=256)
agents = cached_agent_loader_from_configs(configs, cache_instance=cache)
"""
cache = cache_instance or get_global_cache()
start_time = time.time()
if preload:
# Preload agents in background
cache.preload_agents(agent_configs)
def _load_single_agent(config: Dict[str, Any]) -> Agent:
"""Load a single agent with caching."""
# Try to get from cache first
agent = cache.get_agent(config)
if agent is None:
# Cache miss - create new agent
load_start = time.time()
agent = Agent(**config)
load_time = time.time() - load_start
# Add to cache for future use
cache.put_agent(config, agent)
logger.debug(
f"Created new agent {agent.agent_name} in {load_time:.3f}s"
)
return agent
# Load agents (parallel or sequential)
if parallel_loading and len(agent_configs) > 1:
max_workers = min(len(agent_configs), os.cpu_count())
with ThreadPoolExecutor(max_workers=max_workers) as executor:
agents = list(
executor.map(_load_single_agent, agent_configs)
)
else:
agents = [
_load_single_agent(config) for config in agent_configs
]
total_time = time.time() - start_time
# Log performance stats
stats = cache.get_cache_stats()
logger.info(
f"Loaded {len(agents)} agents in {total_time:.3f}s "
f"(Hit rate: {stats['hit_rate_percent']}%)"
)
return agents
# Decorator for caching individual agent creation
def cache_agent_creation(cache_instance: Optional[AgentCache] = None):
"""
Decorator to cache agent creation based on initialization parameters.
Args:
cache_instance: Optional cache instance (uses global cache if None)
Returns:
Decorator function
Example:
@cache_agent_creation()
def create_trading_agent(symbol: str, model: str):
return Agent(
agent_name=f"Trading-{symbol}",
model_name=model,
system_prompt=f"You are a trading agent for {symbol}"
)
agent1 = create_trading_agent("AAPL", "gpt-4") # Creates new agent
agent2 = create_trading_agent("AAPL", "gpt-4") # Returns cached agent
"""
def decorator(func: Callable[..., Agent]) -> Callable[..., Agent]:
cache = cache_instance or get_global_cache()
@wraps(func)
def wrapper(*args, **kwargs) -> Agent:
# Create a config dict from function arguments
import inspect
sig = inspect.signature(func)
bound_args = sig.bind(*args, **kwargs)
bound_args.apply_defaults()
config = dict(bound_args.arguments)
# Try to get from cache
agent = cache.get_agent(config)
if agent is None:
# Cache miss - call original function
agent = func(*args, **kwargs)
cache.put_agent(config, agent)
return agent
return wrapper
return decorator
# LRU Cache-based simple approach
@lru_cache(maxsize=128)
def _cached_agent_by_hash(
config_hash: str, config_json: str
) -> Agent:
"""Internal LRU cached agent creation by config hash."""
config = json.loads(config_json)
return Agent(**config)
def simple_lru_agent_loader(
agents: List[Agent],
) -> List[Agent]:
"""
Simple LRU cache-based agent loader using functools.lru_cache.
Args:
agents: List of Agent instances
Returns:
List of Agent instances (cached versions if available)
Note:
This is a simpler approach but less flexible than the full AgentCache.
"""
cached_agents = []
for agent in agents:
# Extract config from agent
config = _extract_agent_config(agent)
# Create stable hash and JSON string
config_json = json.dumps(config, sort_keys=True, default=str)
config_hash = hashlib.md5(config_json.encode()).hexdigest()
# Use LRU cached function
cached_agent = _cached_agent_by_hash_from_agent(
config_hash, agent
)
cached_agents.append(cached_agent)
return cached_agents
@lru_cache(maxsize=128)
def _cached_agent_by_hash_from_agent(
config_hash: str, agent: Agent
) -> Agent:
"""Internal LRU cached agent storage by config hash."""
# Return the same agent instance (this creates the caching effect)
return agent
# Utility functions for cache management
def clear_agent_cache():
"""Clear the global agent cache."""
cache = get_global_cache()
cache.clear_cache()
def get_agent_cache_stats() -> Dict[str, Any]:
"""Get statistics from the global agent cache."""
cache = get_global_cache()
return cache.get_cache_stats()
def shutdown_agent_cache():
"""Shutdown the global agent cache gracefully."""
global _global_cache
if _global_cache:
_global_cache.shutdown()
_global_cache = None

@ -0,0 +1,633 @@
import os
import asyncio
import concurrent.futures
import inspect
import time
from concurrent.futures import (
ThreadPoolExecutor,
ProcessPoolExecutor,
as_completed,
)
from functools import wraps
from typing import (
Any,
Callable,
List,
Optional,
TypeVar,
Generic,
)
from dataclasses import dataclass
from enum import Enum
from swarms.utils.loguru_logger import initialize_logger
logger = initialize_logger("concurrent_wrapper")
T = TypeVar("T")
R = TypeVar("R")
# Global function for process pool execution (must be picklable)
def _execute_task_in_process(task_data):
"""
Execute a task in a separate process.
This function must be at module level to be picklable.
"""
(
func,
task_args,
task_kwargs,
task_id,
max_retries,
retry_on_failure,
retry_delay,
return_exceptions,
) = task_data
start_time = time.time()
for attempt in range(max_retries + 1):
try:
result = func(*task_args, **task_kwargs)
execution_time = time.time() - start_time
return ConcurrentResult(
value=result,
execution_time=execution_time,
worker_id=task_id,
)
except Exception as e:
if attempt == max_retries or not retry_on_failure:
execution_time = time.time() - start_time
if return_exceptions:
return ConcurrentResult(
exception=e,
execution_time=execution_time,
worker_id=task_id,
)
else:
raise
else:
time.sleep(retry_delay * (2**attempt))
# This should never be reached, but just in case
return ConcurrentResult(
exception=Exception("Max retries exceeded")
)
class ExecutorType(Enum):
"""Enum for different types of executors."""
THREAD = "thread"
PROCESS = "process"
ASYNC = "async"
@dataclass
class ConcurrentConfig:
"""Configuration for concurrent execution."""
name: Optional[str] = None
description: Optional[str] = None
max_workers: int = 4
timeout: Optional[float] = None
executor_type: ExecutorType = ExecutorType.THREAD
return_exceptions: bool = False
chunk_size: Optional[int] = None
ordered: bool = True
retry_on_failure: bool = False
max_retries: int = 3
retry_delay: float = 1.0
class ConcurrentResult(Generic[T]):
"""Result wrapper for concurrent execution."""
def __init__(
self,
value: T = None,
exception: Exception = None,
execution_time: float = 0.0,
worker_id: Optional[int] = None,
):
self.value = value
self.exception = exception
self.execution_time = execution_time
self.worker_id = worker_id
self.success = exception is None
def __repr__(self):
if self.success:
return f"ConcurrentResult(value={self.value}, time={self.execution_time:.3f}s)"
else:
return f"ConcurrentResult(exception={type(self.exception).__name__}: {self.exception})"
def concurrent(
name: Optional[str] = None,
description: Optional[str] = None,
max_workers: int = 4,
timeout: Optional[float] = None,
executor_type: ExecutorType = ExecutorType.THREAD,
return_exceptions: bool = False,
chunk_size: Optional[int] = None,
ordered: bool = True,
retry_on_failure: bool = False,
max_retries: int = 3,
retry_delay: float = 1.0,
):
"""
A decorator that enables concurrent execution of functions.
Args:
name (Optional[str]): Name for the concurrent operation
description (Optional[str]): Description of the operation
max_workers (int): Maximum number of worker threads/processes
timeout (Optional[float]): Timeout in seconds for each task
executor_type (ExecutorType): Type of executor (thread, process, async)
return_exceptions (bool): Whether to return exceptions instead of raising
chunk_size (Optional[int]): Size of chunks for batch processing
ordered (bool): Whether to maintain order of results
retry_on_failure (bool): Whether to retry failed tasks
max_retries (int): Maximum number of retries per task
retry_delay (float): Delay between retries in seconds
Returns:
Callable: Decorated function that can execute concurrently
"""
if max_workers is None:
max_workers = os.cpu_count()
def decorator(func: Callable[..., T]) -> Callable[..., T]:
config = ConcurrentConfig(
name=name or func.__name__,
description=description
or f"Concurrent execution of {func.__name__}",
max_workers=max_workers,
timeout=timeout,
executor_type=executor_type,
return_exceptions=return_exceptions,
chunk_size=chunk_size,
ordered=ordered,
retry_on_failure=retry_on_failure,
max_retries=max_retries,
retry_delay=retry_delay,
)
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
def _execute_single_task(
task_args, task_kwargs, task_id=None
):
"""Execute a single task with retry logic."""
start_time = time.time()
for attempt in range(config.max_retries + 1):
try:
result = func(*task_args, **task_kwargs)
execution_time = time.time() - start_time
return ConcurrentResult(
value=result,
execution_time=execution_time,
worker_id=task_id,
)
except Exception as e:
if (
attempt == config.max_retries
or not config.retry_on_failure
):
execution_time = time.time() - start_time
if config.return_exceptions:
return ConcurrentResult(
exception=e,
execution_time=execution_time,
worker_id=task_id,
)
else:
raise
else:
logger.warning(
f"Task {task_id} failed (attempt {attempt + 1}/{config.max_retries + 1}): {e}"
)
time.sleep(config.retry_delay * (2**attempt))
def concurrent_execute(*args_list, **kwargs_list):
"""Execute the function concurrently with multiple argument sets."""
if not args_list and not kwargs_list:
raise ValueError(
"At least one set of arguments must be provided"
)
# Prepare tasks
tasks = []
if args_list:
for args in args_list:
if isinstance(args, (list, tuple)):
tasks.append((args, {}))
else:
tasks.append(([args], {}))
if kwargs_list:
for kwargs in kwargs_list:
if isinstance(kwargs, dict):
tasks.append(((), kwargs))
else:
raise ValueError(
"kwargs_list must contain dictionaries"
)
logger.info(
f"Starting concurrent execution of {len(tasks)} tasks with {config.max_workers} workers"
)
start_time = time.time()
try:
if config.executor_type == ExecutorType.THREAD:
results = _execute_with_thread_pool(tasks)
elif config.executor_type == ExecutorType.PROCESS:
results = _execute_with_process_pool(tasks)
elif config.executor_type == ExecutorType.ASYNC:
results = _execute_with_async(tasks)
else:
raise ValueError(
f"Unsupported executor type: {config.executor_type}"
)
total_time = time.time() - start_time
successful_tasks = sum(
1 for r in results if r.success
)
logger.info(
f"Completed {len(tasks)} tasks in {total_time:.3f}s "
f"({successful_tasks}/{len(tasks)} successful)"
)
return results
except Exception as e:
logger.error(f"Concurrent execution failed: {e}")
raise
def _execute_with_thread_pool(tasks):
"""Execute tasks using ThreadPoolExecutor."""
results = []
with ThreadPoolExecutor(
max_workers=config.max_workers
) as executor:
if config.ordered:
future_to_task = {
executor.submit(
_execute_single_task, task[0], task[1], i
): i
for i, task in enumerate(tasks)
}
for future in as_completed(
future_to_task, timeout=config.timeout
):
try:
result = future.result(
timeout=config.timeout
)
results.append(result)
except Exception as e:
if config.return_exceptions:
results.append(
ConcurrentResult(exception=e)
)
else:
raise
else:
futures = [
executor.submit(
_execute_single_task, task[0], task[1], i
)
for i, task in enumerate(tasks)
]
for future in as_completed(
futures, timeout=config.timeout
):
try:
result = future.result(
timeout=config.timeout
)
results.append(result)
except Exception as e:
if config.return_exceptions:
results.append(
ConcurrentResult(exception=e)
)
else:
raise
return results
def _execute_with_process_pool(tasks):
"""Execute tasks using ProcessPoolExecutor."""
results = []
# Prepare task data for process execution
task_data_list = []
for i, task in enumerate(tasks):
task_data = (
func, # The function to execute
task[0], # args
task[1], # kwargs
i, # task_id
config.max_retries,
config.retry_on_failure,
config.retry_delay,
config.return_exceptions,
)
task_data_list.append(task_data)
with ProcessPoolExecutor(
max_workers=config.max_workers
) as executor:
if config.ordered:
future_to_task = {
executor.submit(
_execute_task_in_process, task_data
): i
for i, task_data in enumerate(task_data_list)
}
for future in as_completed(
future_to_task, timeout=config.timeout
):
try:
result = future.result(
timeout=config.timeout
)
results.append(result)
except Exception as e:
if config.return_exceptions:
results.append(
ConcurrentResult(exception=e)
)
else:
raise
else:
futures = [
executor.submit(
_execute_task_in_process, task_data
)
for task_data in task_data_list
]
for future in as_completed(
futures, timeout=config.timeout
):
try:
result = future.result(
timeout=config.timeout
)
results.append(result)
except Exception as e:
if config.return_exceptions:
results.append(
ConcurrentResult(exception=e)
)
else:
raise
return results
async def _execute_with_async(tasks):
"""Execute tasks using asyncio."""
async def _async_task(
task_args, task_kwargs, task_id=None
):
start_time = time.time()
for attempt in range(config.max_retries + 1):
try:
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(
None,
lambda: func(*task_args, **task_kwargs),
)
execution_time = time.time() - start_time
return ConcurrentResult(
value=result,
execution_time=execution_time,
worker_id=task_id,
)
except Exception as e:
if (
attempt == config.max_retries
or not config.retry_on_failure
):
execution_time = time.time() - start_time
if config.return_exceptions:
return ConcurrentResult(
exception=e,
execution_time=execution_time,
worker_id=task_id,
)
else:
raise
else:
logger.warning(
f"Async task {task_id} failed (attempt {attempt + 1}/{config.max_retries + 1}): {e}"
)
await asyncio.sleep(
config.retry_delay * (2**attempt)
)
semaphore = asyncio.Semaphore(config.max_workers)
async def _limited_task(task_args, task_kwargs, task_id):
async with semaphore:
return await _async_task(
task_args, task_kwargs, task_id
)
tasks_coros = [
_limited_task(task[0], task[1], i)
for i, task in enumerate(tasks)
]
if config.ordered:
results = []
for coro in asyncio.as_completed(tasks_coros):
try:
result = await coro
results.append(result)
except Exception as e:
if config.return_exceptions:
results.append(
ConcurrentResult(exception=e)
)
else:
raise
return results
else:
return await asyncio.gather(
*tasks_coros,
return_exceptions=config.return_exceptions,
)
def concurrent_batch(
items: List[Any],
batch_size: Optional[int] = None,
**kwargs,
) -> List[ConcurrentResult]:
"""Execute the function concurrently on a batch of items."""
batch_size = batch_size or config.chunk_size or len(items)
tasks = []
for item in items:
if isinstance(item, (list, tuple)):
tasks.append((item, kwargs))
else:
tasks.append(([item], kwargs))
return concurrent_execute(
*[task[0] for task in tasks],
**[task[1] for task in tasks],
)
def concurrent_map(
items: List[Any], **kwargs
) -> List[ConcurrentResult]:
"""Map the function over a list of items concurrently."""
return concurrent_batch(items, **kwargs)
# Attach methods to the wrapper
wrapper.concurrent_execute = concurrent_execute
wrapper.concurrent_batch = concurrent_batch
wrapper.concurrent_map = concurrent_map
wrapper.config = config
# Add metadata
wrapper.__concurrent_config__ = config
wrapper.__concurrent_enabled__ = True
return wrapper
return decorator
def concurrent_class_executor(
name: Optional[str] = None,
description: Optional[str] = None,
max_workers: int = 4,
timeout: Optional[float] = None,
executor_type: ExecutorType = ExecutorType.THREAD,
return_exceptions: bool = False,
chunk_size: Optional[int] = None,
ordered: bool = True,
retry_on_failure: bool = False,
max_retries: int = 3,
retry_delay: float = 1.0,
methods: Optional[List[str]] = None,
):
"""
A decorator that enables concurrent execution for class methods.
Args:
name (Optional[str]): Name for the concurrent operation
description (Optional[str]): Description of the operation
max_workers (int): Maximum number of worker threads/processes
timeout (Optional[float]): Timeout in seconds for each task
executor_type (ExecutorType): Type of executor (thread, process, async)
return_exceptions (bool): Whether to return exceptions instead of raising
chunk_size (Optional[int]): Size of chunks for batch processing
ordered (bool): Whether to maintain order of results
retry_on_failure (bool): Whether to retry failed tasks
max_retries (int): Maximum number of retries per task
retry_delay (float): Delay between retries in seconds
methods (Optional[List[str]]): List of method names to make concurrent
Returns:
Class: Class with concurrent execution capabilities
"""
def decorator(cls):
config = ConcurrentConfig(
name=name or f"{cls.__name__}_concurrent",
description=description
or f"Concurrent execution for {cls.__name__}",
max_workers=max_workers,
timeout=timeout,
executor_type=executor_type,
return_exceptions=return_exceptions,
chunk_size=chunk_size,
ordered=ordered,
retry_on_failure=retry_on_failure,
max_retries=max_retries,
retry_delay=retry_delay,
)
# Get methods to make concurrent
target_methods = methods or [
name
for name, method in inspect.getmembers(
cls, inspect.isfunction
)
if not name.startswith("_")
]
for method_name in target_methods:
if hasattr(cls, method_name):
original_method = getattr(cls, method_name)
# Create concurrent version of the method
concurrent_decorator = concurrent(
name=f"{cls.__name__}.{method_name}",
description=f"Concurrent execution of {cls.__name__}.{method_name}",
max_workers=config.max_workers,
timeout=config.timeout,
executor_type=config.executor_type,
return_exceptions=config.return_exceptions,
chunk_size=config.chunk_size,
ordered=config.ordered,
retry_on_failure=config.retry_on_failure,
max_retries=config.max_retries,
retry_delay=config.retry_delay,
)
# Apply the concurrent decorator to the method
setattr(
cls,
method_name,
concurrent_decorator(original_method),
)
# Add class-level concurrent configuration
cls.__concurrent_config__ = config
cls.__concurrent_enabled__ = True
return cls
return decorator
# Convenience functions for common use cases
def thread_executor(**kwargs):
"""Convenience decorator for thread-based concurrent execution."""
return concurrent(executor_type=ExecutorType.THREAD, **kwargs)
def process_executor(**kwargs):
"""Convenience decorator for process-based concurrent execution."""
return concurrent(executor_type=ExecutorType.PROCESS, **kwargs)
def async_executor(**kwargs):
"""Convenience decorator for async-based concurrent execution."""
return concurrent(executor_type=ExecutorType.ASYNC, **kwargs)
def batch_executor(batch_size: int = 10, **kwargs):
"""Convenience decorator for batch processing."""
return concurrent(chunk_size=batch_size, **kwargs)

@ -292,7 +292,7 @@ def run_test_suite():
assert isinstance(is_url_direct, bool) assert isinstance(is_url_direct, bool)
assert isinstance(is_local_direct, bool) assert isinstance(is_local_direct, bool)
assert ( assert (
is_local_direct == False is_local_direct is False
) # Local files should never use direct URL ) # Local files should never use direct URL
log_test_result("Local vs URL Detection", True) log_test_result("Local vs URL Detection", True)

Loading…
Cancel
Save