diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 77570ace..9e576f87 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -307,6 +307,7 @@ nav: - Agents with Callable Tools: "swarms/examples/agent_with_tools.md" # - Agent With MCP Integration: "swarms/examples/agent_with_mcp.md" - Agent Output Types: "swarms/examples/agent_output_types.md" + - Agent with Structured Outputs: "swarms/examples/agent_structured_outputs.md" - Various Model Providers: - OpenAI: "swarms/examples/openai_example.md" - Anthropic: "swarms/examples/claude.md" @@ -331,14 +332,18 @@ nav: # - Quant Crypto Agent: "swarms/examples/quant_crypto_agent.md" - Multi-Agent Collaboration: - - Unique Swarms: "swarms/examples/unique_swarms.md" - - Swarms DAO: "swarms/examples/swarms_dao.md" - Hybrid Hierarchical-Cluster Swarm Example: "swarms/examples/hhcs_examples.md" - Group Chat Example: "swarms/examples/groupchat_example.md" - Sequential Workflow Example: "swarms/examples/sequential_example.md" - - ConcurrentWorkflow with VLLM Agents: "swarms/examples/vllm.md" - - External Agents: + - SwarmRouter Example: "swarms/examples/swarm_router.md" + - ConcurrentWorkflow Example: "swarms/examples/concurrent_workflow.md" + - MixtureOfAgents Example: "swarms/examples/mixture_of_agents.md" + - Unique Swarms: "swarms/examples/unique_swarms.md" + - Applications: + - Swarms DAO: "swarms/examples/swarms_dao.md" - Swarms of Browser Agents: "swarms/examples/swarms_of_browser_agents.md" + - ConcurrentWorkflow with VLLM Agents: "swarms/examples/vllm.md" + - Swarms API Examples: - Medical Swarm: "swarms/examples/swarms_api_medical.md" @@ -413,9 +418,9 @@ nav: # - PUT: "swarms_platform/telemetry/index.md" # - Swarms Wallet API: # - Overview: "swarms/wallet/api.md" - # - Tools API: - # - Overview: "swarms_platform/tools_api.md" - # - Add Tools: "swarms_platform/fetch_tools.md" + # - Tools API: + # - Overview: "swarms_platform/tools_api.md" + # - Add Tools: "swarms_platform/fetch_tools.md" # - Corporate: # - Culture: "corporate/culture.md" # - Hiring: "corporate/hiring.md" diff --git a/docs/swarms/examples/agent_structured_outputs.md b/docs/swarms/examples/agent_structured_outputs.md new file mode 100644 index 00000000..a980f1a8 --- /dev/null +++ b/docs/swarms/examples/agent_structured_outputs.md @@ -0,0 +1,199 @@ +# Agent Structured Outputs + +This example demonstrates how to use structured outputs with Swarms agents following OpenAI's function calling schema. By defining function schemas, you can specify exactly how agents should structure their responses, making it easier to parse and use the outputs in your applications. + +## Prerequisites + +- Python 3.7+ +- OpenAI API key +- Swarms library + +## Installation + +```bash +pip3 install -U swarms +``` + +## Environment Variables + +```plaintext +WORKSPACE_DIR="agent_workspace" +OPENAI_API_KEY="" +ANTHROPIC_API_KEY="" +``` + +## Understanding Function Schemas + +Function schemas in Swarms follow OpenAI's function calling format. Each function schema is defined as a dictionary with the following structure: + +```python +{ + "type": "function", + "function": { + "name": "function_name", + "description": "A clear description of what the function does", + "parameters": { + "type": "object", + "properties": { + # Define the parameters your function accepts + }, + "required": ["list", "of", "required", "parameters"] + } + } +} +``` + +## Code Example + +Here's an example showing how to use multiple function schemas with a Swarms agent: + +```python +from swarms import Agent +from swarms.prompts.finance_agent_sys_prompt import FINANCIAL_AGENT_SYS_PROMPT + +# Define multiple function schemas +tools = [ + { + "type": "function", + "function": { + "name": "get_stock_price", + "description": "Retrieve the current stock price and related information for a specified company.", + "parameters": { + "type": "object", + "properties": { + "ticker": { + "type": "string", + "description": "The stock ticker symbol of the company, e.g. AAPL for Apple Inc.", + }, + "include_history": { + "type": "boolean", + "description": "Whether to include historical price data.", + }, + "time": { + "type": "string", + "format": "date-time", + "description": "Optional time for stock data, in ISO 8601 format.", + }, + }, + "required": ["ticker", "include_history"] + }, + }, + }, + # Can pass in multiple function schemas as well + { + "type": "function", + "function": { + "name": "analyze_company_financials", + "description": "Analyze key financial metrics and ratios for a company.", + "parameters": { + "type": "object", + "properties": { + "ticker": { + "type": "string", + "description": "The stock ticker symbol of the company", + }, + "metrics": { + "type": "array", + "items": { + "type": "string", + "enum": ["PE_ratio", "market_cap", "revenue", "profit_margin"] + }, + "description": "List of financial metrics to analyze" + }, + "timeframe": { + "type": "string", + "enum": ["quarterly", "annual", "ttm"], + "description": "Timeframe for the analysis" + } + }, + "required": ["ticker", "metrics"] + } + } + } +] + +# Initialize the agent with multiple function schemas +agent = Agent( + agent_name="Financial-Analysis-Agent", + agent_description="Personal finance advisor agent that can fetch stock prices and analyze financials", + system_prompt=FINANCIAL_AGENT_SYS_PROMPT, + max_loops=1, + tools_list_dictionary=tools, # Pass in the list of function schemas + output_type="final" +) + +# Example usage with stock price query +stock_response = agent.run( + "What is the current stock price for Apple Inc. (AAPL)? Include historical data." +) +print("Stock Price Response:", stock_response) + +# Example usage with financial analysis query +analysis_response = agent.run( + "Analyze Apple's PE ratio and market cap using quarterly data." +) +print("Financial Analysis Response:", analysis_response) +``` + +## Schema Types and Properties + +The function schema supports various parameter types and properties: + +| Schema Type | Description | +|------------|-------------| +| Basic Types | `string`, `number`, `integer`, `boolean`, `array`, `object` | +| Format Specifications | `date-time`, `date`, `email`, etc. | +| Enums | Restrict values to a predefined set | +| Required vs Optional Parameters | Specify which parameters must be provided | +| Nested Objects and Arrays | Support for complex data structures | + +Example of a more complex schema: + +```python +{ + "type": "function", + "function": { + "name": "generate_investment_report", + "description": "Generate a comprehensive investment report", + "parameters": { + "type": "object", + "properties": { + "portfolio": { + "type": "object", + "properties": { + "stocks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "ticker": {"type": "string"}, + "shares": {"type": "number"}, + "entry_price": {"type": "number"} + } + } + }, + "risk_tolerance": { + "type": "string", + "enum": ["low", "medium", "high"] + }, + "time_horizon": { + "type": "integer", + "minimum": 1, + "maximum": 30, + "description": "Investment time horizon in years" + } + }, + "required": ["stocks", "risk_tolerance"] + }, + "report_type": { + "type": "string", + "enum": ["summary", "detailed", "risk_analysis"] + } + }, + "required": ["portfolio"] + } + } +} +``` + +This example shows how to structure complex nested objects, arrays, and various parameter types while following OpenAI's function calling schema. diff --git a/docs/swarms/examples/concurrent_workflow.md b/docs/swarms/examples/concurrent_workflow.md new file mode 100644 index 00000000..aac1e9e6 --- /dev/null +++ b/docs/swarms/examples/concurrent_workflow.md @@ -0,0 +1,248 @@ +# ConcurrentWorkflow Examples + +The ConcurrentWorkflow architecture enables parallel execution of multiple agents, allowing them to work simultaneously on different aspects of a task. This is particularly useful for complex tasks that can be broken down into independent subtasks. + +## Prerequisites + +- Python 3.7+ +- OpenAI API key or other supported LLM provider keys +- Swarms library + +## Installation + +```bash +pip3 install -U swarms +``` + +## Environment Variables + +```plaintext +WORKSPACE_DIR="agent_workspace" +OPENAI_API_KEY="" +ANTHROPIC_API_KEY="" +GROQ_API_KEY="" +``` + +## Basic Usage + +### 1. Initialize Specialized Agents + +```python +from swarms import Agent, ConcurrentWorkflow + +# Initialize market research agent +market_researcher = Agent( + agent_name="Market-Researcher", + system_prompt="""You are a market research specialist. Your tasks include: + 1. Analyzing market trends and patterns + 2. Identifying market opportunities and threats + 3. Evaluating competitor strategies + 4. Assessing customer needs and preferences + 5. Providing actionable market insights""", + model_name="gpt-4o", + max_loops=1, +) + +# Initialize financial analyst agent +financial_analyst = Agent( + agent_name="Financial-Analyst", + system_prompt="""You are a financial analysis expert. Your responsibilities include: + 1. Analyzing financial statements + 2. Evaluating investment opportunities + 3. Assessing risk factors + 4. Providing financial forecasts + 5. Recommending financial strategies""", + model_name="gpt-4o", + max_loops=1, +) + +# Initialize technical analyst agent +technical_analyst = Agent( + agent_name="Technical-Analyst", + system_prompt="""You are a technical analysis specialist. Your focus areas include: + 1. Analyzing price patterns and trends + 2. Evaluating technical indicators + 3. Identifying support and resistance levels + 4. Assessing market momentum + 5. Providing trading recommendations""", + model_name="gpt-4o", + max_loops=1, +) +``` + +### 2. Create and Run ConcurrentWorkflow + +```python +# Create list of agents +agents = [market_researcher, financial_analyst, technical_analyst] + +# Initialize the concurrent workflow +workflow = ConcurrentWorkflow( + name="market-analysis-workflow", + agents=agents, + max_loops=1, +) + +# Run the workflow +result = workflow.run( + "Analyze Tesla (TSLA) stock from market, financial, and technical perspectives" +) +``` + +## Advanced Usage + +### 1. Custom Agent Configuration + +```python +from swarms import Agent, ConcurrentWorkflow + +# Initialize agents with custom configurations +sentiment_analyzer = Agent( + agent_name="Sentiment-Analyzer", + system_prompt="You analyze social media sentiment...", + model_name="gpt-4o", + max_loops=1, + temperature=0.7, + streaming_on=True, + verbose=True, +) + +news_analyzer = Agent( + agent_name="News-Analyzer", + system_prompt="You analyze news articles and reports...", + model_name="gpt-4o", + max_loops=1, + temperature=0.5, + streaming_on=True, + verbose=True, +) + +# Create and run workflow +workflow = ConcurrentWorkflow( + name="sentiment-analysis-workflow", + agents=[sentiment_analyzer, news_analyzer], + max_loops=1, + verbose=True, +) + +result = workflow.run( + "Analyze the market sentiment for Bitcoin based on social media and news" +) +``` + +### 2. Error Handling and Logging + +```python +try: + workflow = ConcurrentWorkflow( + name="error-handled-workflow", + agents=agents, + max_loops=1, + verbose=True, + ) + + result = workflow.run("Complex analysis task") + + # Process results + for agent_result in result: + print(f"Agent {agent_result['agent']}: {agent_result['output']}") + +except Exception as e: + print(f"Error in workflow: {str(e)}") +``` + +## Best Practices + +1. Task Distribution: + - Break down complex tasks into independent subtasks + - Assign appropriate agents to each subtask + - Ensure tasks can be processed concurrently + +2. Agent Configuration: + - Use specialized agents for specific tasks + - Configure appropriate model parameters + - Set meaningful system prompts + +3. Resource Management: + - Monitor concurrent execution + - Handle rate limits appropriately + - Manage memory usage + +4. Error Handling: + - Implement proper error handling + - Log errors and exceptions + - Provide fallback mechanisms + +## Example Implementation + +Here's a complete example showing how to use ConcurrentWorkflow for a comprehensive market analysis: + +```python +import os +from swarms import Agent, ConcurrentWorkflow + +# Initialize specialized agents +market_analyst = Agent( + agent_name="Market-Analyst", + system_prompt="""You are a market analysis specialist focusing on: + 1. Market trends and patterns + 2. Competitive analysis + 3. Market opportunities + 4. Industry dynamics + 5. Growth potential""", + model_name="gpt-4o", + max_loops=1, +) + +financial_analyst = Agent( + agent_name="Financial-Analyst", + system_prompt="""You are a financial analysis expert specializing in: + 1. Financial statements analysis + 2. Ratio analysis + 3. Cash flow analysis + 4. Valuation metrics + 5. Risk assessment""", + model_name="gpt-4o", + max_loops=1, +) + +risk_analyst = Agent( + agent_name="Risk-Analyst", + system_prompt="""You are a risk assessment specialist focusing on: + 1. Market risks + 2. Operational risks + 3. Financial risks + 4. Regulatory risks + 5. Strategic risks""", + model_name="gpt-4o", + max_loops=1, +) + +# Create the concurrent workflow +workflow = ConcurrentWorkflow( + name="comprehensive-analysis-workflow", + agents=[market_analyst, financial_analyst, risk_analyst], + max_loops=1, + verbose=True, +) + +# Run the analysis +try: + result = workflow.run( + """Provide a comprehensive analysis of Apple Inc. (AAPL) including: + 1. Market position and competitive analysis + 2. Financial performance and health + 3. Risk assessment and mitigation strategies""" + ) + + # Process and display results + for agent_result in result: + print(f"\nAnalysis from {agent_result['agent']}:") + print(agent_result['output']) + print("-" * 50) + +except Exception as e: + print(f"Error during analysis: {str(e)}") +``` + +This comprehensive guide demonstrates how to effectively use the ConcurrentWorkflow architecture for parallel processing of complex tasks using multiple specialized agents. \ No newline at end of file diff --git a/docs/swarms/examples/mixture_of_agents.md b/docs/swarms/examples/mixture_of_agents.md new file mode 100644 index 00000000..3041ca92 --- /dev/null +++ b/docs/swarms/examples/mixture_of_agents.md @@ -0,0 +1,261 @@ +# MixtureOfAgents Examples + +The MixtureOfAgents architecture combines multiple specialized agents with an aggregator agent to process complex tasks. This architecture is particularly effective for tasks requiring diverse expertise and consensus-building among different specialists. + +## Prerequisites + +- Python 3.7+ +- OpenAI API key or other supported LLM provider keys +- Swarms library + +## Installation + +```bash +pip3 install -U swarms +``` + +## Environment Variables + +```plaintext +WORKSPACE_DIR="agent_workspace" +OPENAI_API_KEY="" +ANTHROPIC_API_KEY="" +GROQ_API_KEY="" +``` + +## Basic Usage + +### 1. Initialize Specialized Agents + +```python +from swarms import Agent, MixtureOfAgents + +# Initialize specialized agents +legal_expert = Agent( + agent_name="Legal-Expert", + system_prompt="""You are a legal expert specializing in contract law. Your responsibilities include: + 1. Analyzing legal documents and contracts + 2. Identifying potential legal risks + 3. Ensuring regulatory compliance + 4. Providing legal recommendations + 5. Drafting and reviewing legal documents""", + model_name="gpt-4o", + max_loops=1, +) + +financial_expert = Agent( + agent_name="Financial-Expert", + system_prompt="""You are a financial expert specializing in business finance. Your tasks include: + 1. Analyzing financial implications + 2. Evaluating costs and benefits + 3. Assessing financial risks + 4. Providing financial projections + 5. Recommending financial strategies""", + model_name="gpt-4o", + max_loops=1, +) + +business_expert = Agent( + agent_name="Business-Expert", + system_prompt="""You are a business strategy expert. Your focus areas include: + 1. Analyzing business models + 2. Evaluating market opportunities + 3. Assessing competitive advantages + 4. Providing strategic recommendations + 5. Planning business development""", + model_name="gpt-4o", + max_loops=1, +) + +# Initialize aggregator agent +aggregator = Agent( + agent_name="Decision-Aggregator", + system_prompt="""You are a decision aggregator responsible for: + 1. Synthesizing input from multiple experts + 2. Resolving conflicting viewpoints + 3. Prioritizing recommendations + 4. Providing coherent final decisions + 5. Ensuring comprehensive coverage of all aspects""", + model_name="gpt-4o", + max_loops=1, +) +``` + +### 2. Create and Run MixtureOfAgents + +```python +# Create list of specialist agents +specialists = [legal_expert, financial_expert, business_expert] + +# Initialize the mixture of agents +moa = MixtureOfAgents( + agents=specialists, + aggregator_agent=aggregator, + layers=3, +) + +# Run the analysis +result = moa.run( + "Analyze the proposed merger between Company A and Company B, considering legal, financial, and business aspects." +) +``` + +## Advanced Usage + +### 1. Custom Configuration with System Prompts + +```python +# Initialize MixtureOfAgents with custom aggregator prompt +moa = MixtureOfAgents( + agents=specialists, + aggregator_agent=aggregator, + aggregator_system_prompt="""As the decision aggregator, synthesize the analyses from all specialists into a coherent recommendation: + 1. Summarize key points from each specialist + 2. Identify areas of agreement and disagreement + 3. Weigh different perspectives + 4. Provide a balanced final recommendation + 5. Highlight key risks and opportunities""", + layers=3, +) + +result = moa.run("Evaluate the potential acquisition of StartupX") +``` + +### 2. Error Handling and Validation + +```python +try: + moa = MixtureOfAgents( + agents=specialists, + aggregator_agent=aggregator, + layers=3, + verbose=True, + ) + + result = moa.run("Complex analysis task") + + # Validate and process results + if result: + print("Analysis complete:") + print(result) + else: + print("Analysis failed to produce results") + +except Exception as e: + print(f"Error in analysis: {str(e)}") +``` + +## Best Practices + +1. Agent Selection and Configuration: + - Choose specialists with complementary expertise + - Configure appropriate system prompts + - Set suitable model parameters + +2. Aggregator Configuration: + - Define clear aggregation criteria + - Set appropriate weights for different opinions + - Configure conflict resolution strategies + +3. Layer Management: + - Set appropriate number of layers + - Monitor layer effectiveness + - Adjust based on task complexity + +4. Quality Control: + - Implement validation checks + - Monitor agent performance + - Ensure comprehensive coverage + +## Example Implementation + +Here's a complete example showing how to use MixtureOfAgents for a comprehensive business analysis: + +```python +import os +from swarms import Agent, MixtureOfAgents + +# Initialize specialist agents +market_analyst = Agent( + agent_name="Market-Analyst", + system_prompt="""You are a market analysis specialist focusing on: + 1. Market size and growth + 2. Competitive landscape + 3. Customer segments + 4. Market trends + 5. Entry barriers""", + model_name="gpt-4o", + max_loops=1, +) + +financial_analyst = Agent( + agent_name="Financial-Analyst", + system_prompt="""You are a financial analysis expert specializing in: + 1. Financial performance + 2. Valuation metrics + 3. Cash flow analysis + 4. Investment requirements + 5. ROI projections""", + model_name="gpt-4o", + max_loops=1, +) + +risk_analyst = Agent( + agent_name="Risk-Analyst", + system_prompt="""You are a risk assessment specialist focusing on: + 1. Market risks + 2. Operational risks + 3. Financial risks + 4. Regulatory risks + 5. Strategic risks""", + model_name="gpt-4o", + max_loops=1, +) + +# Initialize aggregator +aggregator = Agent( + agent_name="Strategic-Aggregator", + system_prompt="""You are a strategic decision aggregator responsible for: + 1. Synthesizing specialist analyses + 2. Identifying key insights + 3. Evaluating trade-offs + 4. Making recommendations + 5. Providing action plans""", + model_name="gpt-4o", + max_loops=1, +) + +# Create and configure MixtureOfAgents +try: + moa = MixtureOfAgents( + agents=[market_analyst, financial_analyst, risk_analyst], + aggregator_agent=aggregator, + aggregator_system_prompt="""Synthesize the analyses from all specialists to provide: + 1. Comprehensive situation analysis + 2. Key opportunities and risks + 3. Strategic recommendations + 4. Implementation considerations + 5. Success metrics""", + layers=3, + verbose=True, + ) + + # Run the analysis + result = moa.run( + """Evaluate the business opportunity for expanding into the electric vehicle market: + 1. Market potential and competition + 2. Financial requirements and projections + 3. Risk assessment and mitigation strategies""" + ) + + # Process and display results + print("\nComprehensive Analysis Results:") + print("=" * 50) + print(result) + print("=" * 50) + +except Exception as e: + print(f"Error during analysis: {str(e)}") +``` + +This comprehensive guide demonstrates how to effectively use the MixtureOfAgents architecture for complex analysis tasks requiring multiple expert perspectives and consensus-building. \ No newline at end of file diff --git a/docs/swarms/examples/swarm_router.md b/docs/swarms/examples/swarm_router.md new file mode 100644 index 00000000..50787621 --- /dev/null +++ b/docs/swarms/examples/swarm_router.md @@ -0,0 +1,240 @@ +# SwarmRouter Examples + +The SwarmRouter is a flexible routing system designed to manage different types of swarms for task execution. It provides a unified interface to interact with various swarm types, including `AgentRearrange`, `MixtureOfAgents`, `SpreadSheetSwarm`, `SequentialWorkflow`, and `ConcurrentWorkflow`. + +## Prerequisites + +- Python 3.7+ +- OpenAI API key or other supported LLM provider keys +- Swarms library + +## Installation + +```bash +pip3 install -U swarms +``` + +## Environment Variables + +```plaintext +WORKSPACE_DIR="agent_workspace" +OPENAI_API_KEY="" +ANTHROPIC_API_KEY="" +GROQ_API_KEY="" +``` + +## Basic Usage + +### 1. Initialize Specialized Agents + +```python +from swarms import Agent +from swarms.structs.swarm_router import SwarmRouter, SwarmType + +# Initialize specialized agents +data_extractor_agent = Agent( + agent_name="Data-Extractor", + system_prompt="You are a data extraction specialist...", + model_name="gpt-4o", + max_loops=1, +) + +summarizer_agent = Agent( + agent_name="Document-Summarizer", + system_prompt="You are a document summarization expert...", + model_name="gpt-4o", + max_loops=1, +) + +financial_analyst_agent = Agent( + agent_name="Financial-Analyst", + system_prompt="You are a financial analysis specialist...", + model_name="gpt-4o", + max_loops=1, +) +``` + +### 2. Create SwarmRouter with Sequential Workflow + +```python +sequential_router = SwarmRouter( + name="SequentialRouter", + description="Process tasks in sequence", + agents=[data_extractor_agent, summarizer_agent, financial_analyst_agent], + swarm_type=SwarmType.SequentialWorkflow, + max_loops=1 +) + +# Run a task +result = sequential_router.run("Analyze and summarize the quarterly financial report") +``` + +### 3. Create SwarmRouter with Concurrent Workflow + +```python +concurrent_router = SwarmRouter( + name="ConcurrentRouter", + description="Process tasks concurrently", + agents=[data_extractor_agent, summarizer_agent, financial_analyst_agent], + swarm_type=SwarmType.ConcurrentWorkflow, + max_loops=1 +) + +# Run a task +result = concurrent_router.run("Evaluate multiple aspects of the company simultaneously") +``` + +### 4. Create SwarmRouter with AgentRearrange + +```python +rearrange_router = SwarmRouter( + name="RearrangeRouter", + description="Dynamically rearrange agents for optimal task processing", + agents=[data_extractor_agent, summarizer_agent, financial_analyst_agent], + swarm_type=SwarmType.AgentRearrange, + flow=f"{data_extractor_agent.agent_name} -> {summarizer_agent.agent_name} -> {financial_analyst_agent.agent_name}", + max_loops=1 +) + +# Run a task +result = rearrange_router.run("Process and analyze company documents") +``` + +### 5. Create SwarmRouter with MixtureOfAgents + +```python +mixture_router = SwarmRouter( + name="MixtureRouter", + description="Combine multiple expert agents", + agents=[data_extractor_agent, summarizer_agent, financial_analyst_agent], + swarm_type=SwarmType.MixtureOfAgents, + max_loops=1 +) + +# Run a task +result = mixture_router.run("Provide comprehensive analysis of company performance") +``` + +## Advanced Features + +### 1. Error Handling and Logging + +```python +try: + result = router.run("Complex analysis task") + + # Retrieve and print logs + for log in router.get_logs(): + print(f"{log.timestamp} - {log.level}: {log.message}") +except Exception as e: + print(f"Error occurred: {str(e)}") +``` + +### 2. Custom Configuration + +```python +router = SwarmRouter( + name="CustomRouter", + description="Custom router configuration", + agents=[data_extractor_agent, summarizer_agent, financial_analyst_agent], + swarm_type=SwarmType.SequentialWorkflow, + max_loops=3, + autosave=True, + verbose=True, + output_type="json" +) +``` + +# Best Practices + +## Choose the appropriate swarm type based on your task requirements: + +| Swarm Type | Use Case | +|------------|----------| +| `SequentialWorkflow` | Tasks that need to be processed in order | +| `ConcurrentWorkflow` | Independent tasks that can be processed simultaneously | +| `AgentRearrange` | Tasks requiring dynamic agent organization | +| `MixtureOfAgents` | Complex tasks needing multiple expert perspectives | + +## Configure agents appropriately: + + | Configuration Aspect | Description | + |---------------------|-------------| + | Agent Names & Descriptions | Set meaningful and descriptive names that reflect the agent's role and purpose | + | System Prompts | Define clear, specific prompts that outline the agent's responsibilities and constraints | + | Model Parameters | Configure appropriate parameters like temperature, max_tokens, and other model-specific settings | + +## Implement proper error handling: + +| Error Handling Practice | Description | +|------------------------|-------------| +| Try-Except Blocks | Implement proper exception handling with try-except blocks | +| Log Monitoring | Regularly monitor and analyze system logs for potential issues | +| Edge Case Handling | Implement specific handling for edge cases and unexpected scenarios | + +## Optimize performance: + +| Performance Optimization | Description | +|------------------------|-------------| +| Concurrent Processing | Utilize parallel processing capabilities when tasks can be executed simultaneously | +| Max Loops Configuration | Set appropriate iteration limits based on task complexity and requirements | +| Resource Management | Continuously monitor and optimize system resource utilization | + +## Example Implementation + +Here's a complete example showing how to use SwarmRouter in a real-world scenario: + +```python +import os +from swarms import Agent +from swarms.structs.swarm_router import SwarmRouter, SwarmType + +# Initialize specialized agents +research_agent = Agent( + agent_name="ResearchAgent", + system_prompt="You are a research specialist...", + model_name="gpt-4o", + max_loops=1 +) + +analysis_agent = Agent( + agent_name="AnalysisAgent", + system_prompt="You are an analysis expert...", + model_name="gpt-4o", + max_loops=1 +) + +summary_agent = Agent( + agent_name="SummaryAgent", + system_prompt="You are a summarization specialist...", + model_name="gpt-4o", + max_loops=1 +) + +# Create router with sequential workflow +router = SwarmRouter( + name="ResearchAnalysisRouter", + description="Process research and analysis tasks", + agents=[research_agent, analysis_agent, summary_agent], + swarm_type=SwarmType.SequentialWorkflow, + max_loops=1, + verbose=True +) + +# Run complex task +try: + result = router.run( + "Research and analyze the impact of AI on healthcare, " + "providing a comprehensive summary of findings." + ) + print("Task Result:", result) + + # Print logs + for log in router.get_logs(): + print(f"{log.timestamp} - {log.level}: {log.message}") + +except Exception as e: + print(f"Error processing task: {str(e)}") +``` + +This comprehensive guide demonstrates how to effectively use the SwarmRouter in various scenarios, making it easier to manage and orchestrate multiple agents for complex tasks. \ No newline at end of file