### Start Onboarding Process Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/cli/cli_examples.md Starts an interactive setup process to configure your environment. ```bash swarms onboarding ``` -------------------------------- ### Setup Swarms Environment Source: https://github.com/kyegomez/swarms/blob/master/docs/contributors/environment_setup.md Choose between automated setup using a script or manual dependency installation with Poetry. ```bash # Setup (choose one) ./scripts/setup.sh # Automated setup (recommended) poetry install --with dev # Manual dependency install ``` -------------------------------- ### Full AgentRegistry Example Setup Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/agent_registry.md Imports necessary classes for setting up and using the AgentRegistry, including Agent and various AI models. ```python from swarms.structs.agent_registry import AgentRegistry from swarms import Agent, OpenAIChat, Anthropic ``` -------------------------------- ### Environment Variable Setup Source: https://github.com/kyegomez/swarms/blob/master/docs/contributors/environment_setup.md Instructions for setting up environment variables for local development, including copying an example file or creating a new .env file. ```bash # Copy example environment file cp .env.example .env # if it exists # Or create your own .env file touch .env ``` -------------------------------- ### Install Pytest Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/framework/test.md Install pytest using pip. This is the first step to start using the framework. ```bash pip install pytest ``` -------------------------------- ### API Integration Example Setup Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/cron_job.md Initializes an Agent for news analysis, setting the stage for potential API integrations within a CronJob. ```python import requests from swarms import Agent, CronJob import json # Create agent agent = Agent( agent_name="News-Analyst", system_prompt="Analyze news and provide summaries.", model_name="gpt-5.4", max_loops=1 ) ``` -------------------------------- ### Quick Setup with Default Transforms Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/transforms.md Provides a simple way to create a default set of transforms with sensible configurations for a specified model. Use this for a quick start. ```python from swarms.structs.transforms import create_default_transforms # Create with sensible defaults transforms = create_default_transforms( enabled=True, model_name="claude-3-sonnet" ) ``` -------------------------------- ### Financial Advisor Agent Example Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/agents/index.md Create and run a financial advisor agent. This example demonstrates initializing an agent with specific prompts and running a task to get investment advice. ```python from swarms import Agent # Create a basic financial advisor agent financial_agent = Agent( agent_name="Financial-Advisor", agent_description="Personal finance and investment advisor", system_prompt="""You are an expert financial advisor with deep knowledge of: - Investment strategies and portfolio management - Risk assessment and mitigation - Market analysis and trends - Financial planning and budgeting Provide clear, actionable advice while considering risk tolerance.""", model_name="gpt-5.4", max_loops=1, temperature=0.3, output_type="str" ) # Run the agent response = financial_agent.run("What are the best investment strategies for a 30-year-old?") print(response) ``` -------------------------------- ### Install and Serve Documentation Source: https://github.com/kyegomez/swarms/blob/master/docs/contributors/environment_setup.md Install project dependencies and serve the documentation locally using MkDocs. ```bash pip install -r docs/requirements.txt cd docs mkdocs serve ``` -------------------------------- ### Manual Swarms Setup with Poetry Source: https://github.com/kyegomez/swarms/blob/master/docs/contributors/environment_setup.md Alternative setup for manual control. Requires Python 3.10+, Git, and Poetry. Installs project dependencies including development ones. ```bash git clone https://github.com/kyegomez/swarms.git cd swarms poetry install --with dev ``` -------------------------------- ### Automated Swarms Setup Script Source: https://github.com/kyegomez/swarms/blob/master/docs/contributors/environment_setup.md Recommended for new contributors. Clones the repository, makes the setup script executable, and runs it to automate environment setup. ```bash git clone https://github.com/kyegomez/swarms.git cd swarms chmod +x scripts/setup.sh ./scripts/setup.sh ``` -------------------------------- ### Install uv and Swarms Source: https://github.com/kyegomez/swarms/blob/master/CONTRIBUTING.md Instructions for installing the uv package manager and then installing Swarms using uv. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh uv pip install swarms ``` -------------------------------- ### Install Swarms using uv Source: https://github.com/kyegomez/swarms/blob/master/README.md Recommended installation method using the fast Python package installer, uv. ```bash uv pip install swarms ``` -------------------------------- ### setup-check Command Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/cli/cli_reference.md Run a comprehensive environment setup check to verify your Swarms installation and configuration. ```APIDOC ## setup-check Command Run a comprehensive environment setup check to verify your Swarms installation and configuration. ```bash swarms setup-check [--verbose] ``` ### Arguments - `--verbose`: Enable detailed debug output showing version detection methods. This command performs the following checks: - **Python Version**: Verifies Python 3.10+ compatibility - **Swarms Version**: Checks current version and compares with latest available - **API Keys**: Verifies presence of common API keys in environment variables - **Dependencies**: Ensures required packages are available - **Environment File**: Checks for .env file existence and content - **Workspace Directory**: Verifies WORKSPACE_DIR environment variable ### Examples ```bash # Basic setup check swarms setup-check # Verbose setup check with debug information swarms setup-check --verbose ``` ``` -------------------------------- ### ReasoningDuo Examples Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/agents/reasoning_agent_router.md Configure the ReasoningAgentRouter for ReasoningDuo, supporting both standard models and vision-capable models for image analysis. Includes basic setup and image processing examples. ```python # Basic ReasoningDuo router = ReasoningAgentRouter( swarm_type="reasoning-duo", model_name="gpt-5.4", reasoning_model_name="claude-3-5-sonnet-20240620" ) ``` ```python # ReasoningDuo with image support router = ReasoningAgentRouter( swarm_type="reasoning-duo", model_name="gpt-5.4", 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" ) ``` -------------------------------- ### Initialize and Run HeavySwarm Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/heavy_swarm.md Quick start example demonstrating how to initialize a HeavySwarm instance with a name, description, and worker model, then run an analysis task. ```python from swarms.structs.heavy_swarm import HeavySwarm # Initialize HeavySwarm swarm = HeavySwarm( name="Research Team", description="Multi-agent analysis system", worker_model_name="gpt-5.4", show_dashboard=True ) # Run analysis result = swarm.run("Analyze the impact of AI on healthcare") print(result) ``` -------------------------------- ### Install UV and Swarms Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/install/install.md Install UV first using the provided script, then use UV to install Swarms for faster package management. ```bash # Install UV first curl -LsSf https://astral.sh/uv/install.sh | sh # Install swarms using UV uv pip install swarms ``` -------------------------------- ### Install Dependencies from requirements.txt Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/framework/test.md Install all project dependencies listed in the requirements.txt file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Quick Start with Preset Agents Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/debate_with_judge.md Initializes the DebateWithJudge swarm with pre-configured agents for a quick setup. Use this for immediate debates without custom agent configuration. ```python from swarms import DebateWithJudge # Create debate system with built-in optimized agents debate = DebateWithJudge(preset_agents=True, max_loops=3) # Run a debate result = debate.run("Should universal basic income be implemented?") print(result) ``` -------------------------------- ### Install MkDocs and Material Theme Source: https://github.com/kyegomez/swarms/blob/master/docs/contributors/docs.md Install MkDocs and the Material for MkDocs theme using pip. This is a prerequisite for local documentation development. ```bash pip install mkdocs mkdocs-material ``` -------------------------------- ### Setup and Help Commands Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/cli/cli_reference.md Use these commands for initial environment checks, onboarding, and accessing general help. ```bash # Environment setup swarms setup-check --verbose swarms onboarding # Get help swarms --help ``` -------------------------------- ### Basic Agent Setup and Execution Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/agent_mcp.md Demonstrates the fundamental setup of an agent, including specifying its name, MCP URL, output type, and maximum number of loops. It also shows how to execute a query. ```python # Basic setup from swarms import Agent agent = Agent( agent_name="Your-Agent", mcp_url="http://localhost:8000/mcp", output_type="json", max_loops=2 ) # Execute task result = agent.run("Your query here") # Common patterns crypto_query = "Get Bitcoin price" analysis_query = "Analyze Tesla stock performance" research_query = "Research recent AI developments" ``` -------------------------------- ### Swarms Setup Check Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/cli/cli_reference.md Perform a comprehensive environment setup check for Swarms installation and configuration. Use the --verbose flag for detailed debug output. ```bash swarms setup-check ``` ```bash swarms setup-check --verbose ``` -------------------------------- ### Quick Start: Initialize and Run Framework Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/hierarchical_structured_communication_framework.md Initializes specialized agents and the main framework, then runs a workflow for content analysis. Requires importing all necessary agent classes and the framework. ```python from swarms.structs.hierarchical_structured_communication_framework import ( HierarchicalStructuredCommunicationFramework, HierarchicalStructuredCommunicationGenerator, HierarchicalStructuredCommunicationEvaluator, HierarchicalStructuredCommunicationRefiner, HierarchicalStructuredCommunicationSupervisor ) # Create specialized agents generator = HierarchicalStructuredCommunicationGenerator( agent_name="ContentGenerator" ) evaluator = HierarchicalStructuredCommunicationEvaluator( agent_name="QualityEvaluator" ) refiner = HierarchicalStructuredCommunicationRefiner( agent_name="ContentRefiner" ) supervisor = HierarchicalStructuredCommunicationSupervisor( agent_name="WorkflowSupervisor" ) # Create the framework framework = HierarchicalStructuredCommunicationFramework( name="MyFramework", supervisor=supervisor, generators=[generator], evaluators=[evaluator], refiners=[refiner], max_loops=3 ) # Run the workflow result = framework.run("Create a comprehensive analysis of AI trends in 2024") ``` -------------------------------- ### Create .env file from example Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/install/env.md Copy the .env.example template to a new .env file. This new file will be populated with actual sensitive values. ```bash cp .env.example .env ``` -------------------------------- ### Get Available Models Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/utils/fallback_models.md Retrieve the ordered list of available models, starting with the primary model. ```python models = agent.get_available_models() print(models) # ['gpt-4o', 'gpt-4o-mini', 'gpt-3.5-turbo'] ``` -------------------------------- ### Example of Getting Task Results Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/async_subagent.md Iterate through the collected results, printing the outcome for each task, distinguishing between successful results and exceptions. ```python results = registry.get_results() for task_id, value in results.items(): if isinstance(value, Exception): print(f"{task_id} failed: {value}") else: print(f"{task_id} result: {value[:100]}...") ``` -------------------------------- ### Initialize and Run MentorshipSession Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/orchestration_methods.md Shows how to set up and execute a MentorshipSession. This involves creating mentor and mentee agents and configuring session parameters. ```python from swarms.agents import Agent from swarms.structs.multi_agent_debates import MentorshipSession # Create agents mentor = Agent(name="Mentor") mentee = Agent(name="Mentee") # Initialize mentorship mentorship = MentorshipSession( mentor=mentor, mentee=mentee, session_count=3, include_feedback=True ) # Run session result = mentorship.run("Career development in AI research") ``` -------------------------------- ### Basic Server Setup with AOP Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/aop.md Demonstrates setting up a basic agent server using AOP and adding individual agents with custom system prompts and configurations. Ensure agents are imported and configured before adding them to the AOP instance. ```python from swarms import Agent from swarms.structs.aop import AOP # Create specialized agents research_agent = Agent( agent_name="Research-Agent", agent_description="Expert in research, data collection, and information gathering", model_name="anthropic/claude-sonnet-4-5", max_loops=1, top_p=None, dynamic_temperature_enabled=True, system_prompt="""You are a research specialist. Your role is to: 1. Gather comprehensive information on any given topic 2. Analyze data from multiple sources 3. Provide well-structured research findings 4. Cite sources and maintain accuracy 5. Present findings in a clear, organized manner Always provide detailed, factual information with proper context.""", ) analysis_agent = Agent( agent_name="Analysis-Agent", agent_description="Expert in data analysis, pattern recognition, and generating insights", model_name="anthropic/claude-sonnet-4-5", max_loops=1, top_p=None, dynamic_temperature_enabled=True, system_prompt="""You are an analysis specialist. Your role is to: 1. Analyze data and identify patterns 2. Generate actionable insights 3. Create visualizations and summaries 4. Provide statistical analysis 5. Make data-driven recommendations Focus on extracting meaningful insights from information.""", ) # Create AOP instance deployer = AOP( server_name="MyAgentServer", port=8000, verbose=True, log_level="INFO" ) # Add agents individually deployer.add_agent(research_agent) deployer.add_agent(analysis_agent) # Start the server deployer.run() ``` -------------------------------- ### Example .env File Configuration Source: https://github.com/kyegomez/swarms/blob/master/docs/contributors/environment_setup.md Common environment variables for API keys, development settings, and database configuration. ```bash # .env file OPENAI_API_KEY=your_openai_api_key_here ANTHROPIC_API_KEY=your_anthropic_api_key_here GROQ_API_KEY=your_groq_api_key_here # Development settings DEBUG=true LOG_LEVEL=INFO # Optional: Database settings DATABASE_URL=sqlite:///swarms.db ``` -------------------------------- ### Calculate Mean Function Source: https://github.com/kyegomez/swarms/blob/master/CONTRIBUTING.md Example of a function with a docstring following Google Python Style Guide, including Args, Returns, and Raises sections. ```python def calculate_mean(values: List[float]) -> float: """ Calculates the mean of a list of numbers. Args: values (List[float]): A list of numerical values. Returns: float: The mean of the input values. Raises: ValueError: If the input list is empty. """ if not values: raise ValueError("The input list is empty.") return sum(values) / len(values) ``` -------------------------------- ### Full MCP Agent Example with News and Filesystem Tools Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms_rs/agents.md A complete example demonstrating an agent configured with both Hacker News (STDIO MCP) and a file system browser (SSE MCP) tool. It shows how to run queries against these tools and print their responses. ```rust use std::env; use anyhow::Result; use swarms_rs::{llm::provider::openai::OpenAI, structs::agent::Agent}; #[tokio::main] async fn main() -> Result<()> { dotenv::dotenv().ok(); tracing_subscriber::registry() .with(tracing_subscriber::EnvFilter::from_default_env()) .with( tracing_subscriber::fmt::layer() .with_line_number(true) .with_file(true), ) .init(); let api_key = env::var("OPENAI_API_KEY").expect("OPENAI_API_KEY must be set"); let client = OpenAI::new(api_key).set_model("gpt-4-turbo"); let agent = client .agent_builder() .system_prompt("You are a helpful assistant with access to news and file system tools.") .agent_name("SwarmsAgent") .user_name("User") // Add Hacker News tool .add_stdio_mcp_server("uvx", ["mcp-hn"]) .await // Add filesystem tool // To set up: uvx mcp-proxy --sse-port=8000 -- npx -y @modelcontextprotocol/server-filesystem ~ .add_sse_mcp_server("file-browser", "http://127.0.0.1:8000/mcp") .await .retry_attempts(2) .max_loops(3) .build(); // Use the news tool let news_response = agent .run("Get the top 3 stories of today from Hacker News".to_owned()) .await?; println!("NEWS RESPONSE:\n{}", news_response); // Use the filesystem tool let fs_response = agent.run("List files in my home directory".to_owned()).await?; println!("FILESYSTEM RESPONSE:\n{}", fs_response); Ok(()) } ``` -------------------------------- ### Set Up Virtual Environment Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/framework/test.md Create and activate a virtual environment for managing Python dependencies. ```bash python -m venv venv source venv/bin/activate # On Windows use `venv\Scripts\activate` ``` -------------------------------- ### Integrate Custom API Agent with Swarms Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/agents/external_party_agents.md Define a custom Swarms Agent to interact with any REST or GraphQL API. This example uses the requests library for a GET request. ```python from swarms import Agent as SwarmsAgent import requests # Custom API Agent class APIAgent(SwarmsAgent): def run(self, task: str) -> str: # Parse task for API endpoint and parameters endpoint, params = task.split(", ") response = requests.get(endpoint, params={"q": params}) return response.text # Example usage: api_swarms_agent = APIAgent() output = api_swarms_agent.run("https://api.example.com/search, python") print(output) ``` -------------------------------- ### Basic Agent Handoff Setup and Execution Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/agent.md Demonstrates how to create specialized agents and a coordinator agent that delegates tasks to them. Use this to set up a multi-agent system where tasks are automatically routed to the most suitable agent. ```python from swarms.structs.agent import Agent # Create specialized agents research_agent = Agent( agent_name="ResearchAgent", agent_description="Specializes in researching topics and providing detailed, factual information", model_name="gpt-5.4", max_loops=1, system_prompt="You are a research specialist. Provide detailed, well-researched information about any topic, citing sources when possible.", ) code_agent = Agent( agent_name="CodeExpertAgent", agent_description="Expert in writing, reviewing, and explaining code across multiple programming languages", model_name="gpt-5.4", max_loops=1, system_prompt="You are a coding expert. Write, review, and explain code with a focus on best practices and clean code principles.", ) writing_agent = Agent( agent_name="WritingAgent", agent_description="Skilled in creative and technical writing, content creation, and editing", model_name="gpt-5.4", max_loops=1, system_prompt="You are a writing specialist. Create, edit, and improve written content while maintaining appropriate tone and style.", ) # Create a coordinator agent with handoffs enabled coordinator = Agent( agent_name="CoordinatorAgent", agent_description="Coordinates tasks and delegates to specialized agents", model_name="gpt-5.4", max_loops=1, handoffs=[research_agent, code_agent, writing_agent], system_prompt="You are a coordinator agent. Analyze tasks and delegate them to the most appropriate specialized agent using the handoff_task tool. You can delegate to multiple agents if needed.", output_type="all", ) # Run task - will be automatically delegated to appropriate agent(s) task = "Call all the agents available to you and ask them how they are doing" result = coordinator.run(task=task) print(result) ``` -------------------------------- ### HeavySwarm Grok Mode Quick Start Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/heavy_swarm.md Initialize and run a HeavySwarm with Grok agents enabled for general analysis. This setup is suitable for tasks requiring multi-agent decomposition and synthesis. ```python from swarms.structs.heavy_swarm import HeavySwarm # Enable Grok 4.20 Heavy architecture swarm = HeavySwarm( name="Grok Analysis Team", description="Multi-agent analysis with Grok-style agents", worker_model_name="gpt-5.4", question_agent_model_name="gpt-5.4", use_grok_agents=True, show_dashboard=True, ) # Captain Swarm decomposes the task, Harper/Benjamin/Lucas # work in parallel, then Captain synthesizes with conflict resolution result = swarm.run("Evaluate whether Tesla should expand into commercial trucking") print(result) ``` -------------------------------- ### Conversation Configuration Examples Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/conversation.md Illustrates different ways to configure the Conversation struct for various use cases, from basic in-memory storage to production-ready setups with file persistence and advanced features. ```python # Basic configuration: Simple in-memory storage conv_basic = Conversation( name="basic_chat", token_count=True, message_id_on=True ) # Development configuration: With time tracking and autosave conv_dev = Conversation( name="dev_chat", time_enabled=True, token_count=True, message_id_on=True, autosave=True, export_method="json" ) # Production configuration: Full features with file persistence conv_prod = Conversation( name="prod_chat", system_prompt="You are a helpful assistant", time_enabled=True, token_count=True, message_id_on=True, autosave=True, export_method="json", dynamic_context_window=True, caching=True, conversations_dir="/app/conversations" ) # Analytics configuration: For data analysis and reporting conv_analytics = Conversation( name="analytics_chat", token_count=True, export_method="yaml", autosave=True, dynamic_context_window=True ) ``` -------------------------------- ### SequentialWorkflow Example Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/index.md Illustrates setting up a SequentialWorkflow to execute agents in a defined order. This is suitable for processes with clear, dependent steps. ```python from swarms import Agent, SequentialWorkflow # Initialize agents for a 3-step process # 1. Generate an idea idea_generator = Agent(agent_name="IdeaGenerator", system_prompt="Generate a unique startup idea.", model_name="gpt-5.4") # 2. Validate the idea validator = Agent(agent_name="Validator", system_prompt="Take this startup idea and analyze its market viability.", model_name="gpt-5.4") # 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-5.4") # Create the sequential workflow workflow = SequentialWorkflow(agents=[idea_generator, validator, pitch_creator]) # Run the workflow elevator_pitch = workflow.run() print(elevator_pitch) ``` -------------------------------- ### Get Agent Configurations Only Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/auto_swarm_builder.md Initializes a swarm with the execution type set to 'return-agents' to retrieve agent configurations without executing the full swarm. Useful for inspecting or modifying agent setups. ```python from swarms.structs.auto_swarm_builder import AutoSwarmBuilder # Initialize to return agent configurations swarm = AutoSwarmBuilder( name="Marketing Swarm", description="A swarm for marketing strategy development", execution_type="return-agents" ) # Get agent configurations without executing agent_configs = swarm.run( "Create a comprehensive marketing strategy for a new tech product launch" ) print("Generated agents:") for agent in agent_configs["agents"]: print(f"- {agent['agent_name']}: {agent['description']}") ``` -------------------------------- ### Access and Manage Swarm Conversation Data Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/custom_swarm.md Provides examples of interacting with the swarm's conversation object to retrieve history, search for specific messages, export data, and get message statistics. ```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() ``` -------------------------------- ### Initialize and Run a Financial Analysis Agent Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/tools/build_tool.md Demonstrates initializing an Agent with specific tools, system prompts, and parameters, then running it to perform a financial analysis task. Ensure the necessary tool functions (get_stock_price, get_crypto_price, calculate_portfolio_performance) are defined and accessible. ```python from swarms import Agent # Initialize the financial analysis agent agent = Agent( agent_name="Financial-Analysis-Agent", system_prompt=( "You are a professional financial analyst agent. Use the provided tools to " "analyze stocks, cryptocurrencies, and investment performance. Provide " "clear, accurate financial insights and recommendations. Always format " "responses in markdown for better readability." ), model_name="gpt-5.4", max_loops=3, autosave=True, dashboard=False, verbose=True, streaming_on=True, dynamic_temperature_enabled=True, saved_state_path="financial_agent.json", tools=[get_stock_price, get_crypto_price, calculate_portfolio_performance], user_name="financial_analyst", retry_attempts=3, context_length=200000, ) # Run the agent response = agent("Analyze the current price of Apple stock and Bitcoin, then calculate the performance of a $10,000 investment in each over the past 2 years.") print(response) ``` -------------------------------- ### Quick Start DebateWithJudge with Preset Agents Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/debate_with_judge.md Initialize DebateWithJudge using preset agents for a quick setup. Specify the model name and output type for the debate. This method requires no manual agent configuration. ```python from swarms import DebateWithJudge # Create the DebateWithJudge system with preset agents debate_system = DebateWithJudge( preset_agents=True, max_loops=3, model_name="gpt-5.4", # Specify model for preset agents output_type="str-all-except-first", verbose=True, ) # Define the debate topic topic = ( "Should artificial intelligence be regulated by governments? " "Discuss the balance between innovation and safety." ) # Run the debate result = debate_system.run(task=topic) print(result) # Get the final refined answer final_answer = debate_system.get_final_answer() print(final_answer) ``` -------------------------------- ### Using Different LLM Providers Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/advisor_swarm.md Illustrates initializing AdvisorSwarm with models from different providers, leveraging LiteLLM's compatibility. Examples show using OpenAI models and mixing providers. ```python from swarms import AdvisorSwarm # OpenAI models swarm = AdvisorSwarm( executor_model_name="gpt-5.4-mini", advisor_model_name="gpt-5.4", ) # Mix providers swarm = AdvisorSwarm( executor_model_name="gpt-5.4-mini", advisor_model_name="claude-opus-4-6", ) ``` -------------------------------- ### Basic Agent Usage with Skills Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/agents/agent_skills.md Demonstrates how to create an Agent instance and load skills from a specified directory. The agent will automatically follow the instructions defined in the skill files. ```python from swarms import Agent # Create agent with skills agent = Agent( agent_name="Financial Analyst", model_name="gpt-4o", skills_dir="./example_skills", # Point to your skills directory max_loops=1 ) # Agent automatically follows skill instructions response = agent.run("Perform a DCF valuation for Apple") ``` -------------------------------- ### Basic Agent Usage with Minimal Configuration Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/agent.md The simplest way to use an agent with minimal configuration, requiring only a model name and `max_loops`. Perfect for getting started quickly with basic text generation tasks. ```python from swarms import Agent # Simple agent with minimal configuration agent = Agent( model_name="gpt-5.4", max_loops=1, ) response = agent.run("What is the capital of France?") print(response) ``` -------------------------------- ### Install Poetry on Windows Source: https://github.com/kyegomez/swarms/blob/master/docs/contributors/environment_setup.md Installs Poetry using PowerShell by downloading and executing the installation script. ```powershell (Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | python - ``` -------------------------------- ### Quick Start: Basic Agent with OpenAI Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms_rs/agents.md Initialize and run a basic AI agent using the OpenAI provider. Ensure environment variables are loaded and tracing is configured for debugging. ```rust use std::env; use anyhow::Result; use swarms_rs::{llm::provider::openai::OpenAI, structs::agent::Agent}; #[tokio::main] async fn main() -> Result<()> { // Load environment variables from .env file dotenv::dotenv().ok(); // Initialize tracing for better debugging tracing_subscriber::registry() .with(tracing_subscriber::EnvFilter::from_default_env()) .with( tracing_subscriber::fmt::layer() .with_line_number(true) .with_file(true), ) .init(); // Set up your LLM client let api_key = env::var("OPENAI_API_KEY").expect("OPENAI_API_KEY must be set"); let client = OpenAI::new(api_key).set_model("gpt-4-turbo"); // Create a basic agent let agent = client .agent_builder() .system_prompt("You are a helpful assistant.") .agent_name("BasicAgent") .user_name("User") .build(); // Run the agent with a user query let response = agent .run("Tell me about Rust programming.".to_owned()) .await?; println!("{}", response); Ok(()) } ``` -------------------------------- ### Basic Financial Analysis Swarm Setup Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/spreadsheet_swarm.md Demonstrates initializing a SpreadSheetSwarm with a list of pre-configured Agent objects for a financial analysis task. The swarm is then run with a specific task. ```python from swarms import Agent from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm # Example 1: Using pre-configured agents agents = [ Agent( agent_name="Research-Agent", agent_description="Specialized in market research and analysis", model_name="claude-sonnet-4-20250514", dynamic_temperature_enabled=True, max_loops=1, streaming_on=False, ), Agent( agent_name="Technical-Agent", agent_description="Expert in technical analysis and trading strategies", model_name="claude-sonnet-4-20250514", dynamic_temperature_enabled=True, max_loops=1, streaming_on=False, ), Agent( agent_name="Risk-Agent", agent_description="Focused on risk assessment and portfolio management", model_name="claude-sonnet-4-20250514", dynamic_temperature_enabled=True, max_loops=1, streaming_on=False, ), ] # Initialize the SpreadSheetSwarm with agents swarm = SpreadSheetSwarm( name="Financial-Analysis-Swarm", description="A swarm of specialized financial analysis agents", agents=agents, max_loops=1, autosave=False, ) # Run all agents with the same task task = "What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis." result = swarm.run(task=task) print(result) ``` -------------------------------- ### Install Rustworkx for Backend Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/graph_workflow.md Install the rustworkx library using pip. If installation fails due to missing Rust compiler, follow the provided curl command to install Rustup first. ```bash # Install rustworkx pip install rustworkx # If installation fails due to missing Rust compiler curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh pip install rustworkx ``` -------------------------------- ### Set Up Environment Variables Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/agents/index.md Create a .env file to store your API keys and workspace directory. This is necessary for the framework to authenticate and manage agent workspaces. ```bash OPENAI_API_KEY="your-openai-api-key" ANTHROPIC_API_KEY="your-anthropic-api-key" WORKSPACE_DIR="agent_workspace" ``` -------------------------------- ### Install Swarms with Dockerfile Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/install/install.md This snippet shows how to install the swarms package and its dependencies within a Dockerfile. It updates apt-get, installs build tools, and then uses pip to install the swarm-models and swarms packages. ```docker RUN apt-get update && apt-get install -y \ build-essential \ gcc \ g++ \ gfortran \ && rm -rf /var/lib/apt/lists/* # Install swarms package RUN pip3 install -U swarm-models RUN pip3 install -U swarms # Copy the application COPY . . ``` -------------------------------- ### Automated Setup Script Source: https://github.com/kyegomez/swarms/blob/master/docs/contributors/environment_setup.md Execute the automated setup script to handle common setup problems and verification checks. ```bash chmod +x scripts/setup.sh ./scripts/setup.sh ``` -------------------------------- ### Initialize and Run NegotiationSession Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/orchestration_methods.md Illustrates the setup and execution of a NegotiationSession. This requires defining negotiating parties, a mediator, and negotiation parameters. ```python from swarms.agents import Agent from swarms.structs.multi_agent_debates import NegotiationSession # Create agents mediator = Agent(name="Mediator") party1 = Agent(name="Company1") party2 = Agent(name="Company2") # Initialize negotiation negotiation = NegotiationSession( parties=[party1, party2], mediator=mediator, negotiation_rounds=4, include_concessions=True ) # Run negotiation result = negotiation.run("Merger terms negotiation") ``` -------------------------------- ### Install uv Package Manager Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms_rs/agents.md Installs the uv package manager using a curl script. This is a prerequisite for installing MCP tools. ```bash curl -sSf https://raw.githubusercontent.com/astral-sh/uv/main/install.sh | sh ``` -------------------------------- ### Initialize and Run a Concurrent Workflow Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/concurrentworkflow.md Demonstrates the basic setup of agents and a ConcurrentWorkflow, followed by running a single task and printing the results. Ensure agents are defined before initializing the workflow. ```python agents = [ Agent( agent_name="Research-Agent", system_prompt="You are a research specialist focused on gathering information.", model_name="gpt-4", max_loops=1, ), Agent( agent_name="Analysis-Agent", system_prompt="You are an analysis expert who synthesizes information.", model_name="gpt-4", max_loops=1, ), Agent( agent_name="Summary-Agent", system_prompt="You are a summarization expert who creates concise reports.", model_name="gpt-4", max_loops=1, ) ] workflow = ConcurrentWorkflow( name="Research Analysis Workflow", description="Concurrent execution of research, analysis, and summarization tasks", agents=agents, auto_save=True, output_type="dict-all-except-first", show_dashboard=False ) task = "What are the environmental impacts of electric vehicles?" result = workflow.run(task) print(result) ``` -------------------------------- ### Development Installation with virtualenv Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/install/install.md Set up a Python virtual environment, activate it, and install Swarms in editable mode. Supports both headless and desktop installations. ```bash # Clone the repository and navigate to the root directory: git clone https://github.com/kyegomez/swarms.git cd swarms # Setup Python environment and activate it: python3 -m venv venv source venv/bin/activate pip install --upgrade pip # Install Swarms: # - Headless install: pip install -e . # - Desktop install: pip install -e .[desktop] ``` -------------------------------- ### Create a Simple Agent Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/cli/cli_reference.md Creates a basic agent with a name, description, system prompt, task, and temperature setting. ```bash swarms agent \ --name "Code Reviewer" \ --description "AI code review assistant" \ --system-prompt "You are an expert code reviewer..." \ --task "Review this Python code for best practices" \ --temperature 0.1 ``` -------------------------------- ### Development Installation with Anaconda Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/install/install.md Create and activate an Anaconda environment, clone the repository, and install Swarms in editable mode. Supports both headless and desktop installations. ```bash # Create and activate an Anaconda environment: conda create -n swarms python=3.10 conda activate swarms # Clone the repository and navigate to the root directory: git clone https://github.com/kyegomez/swarms.git cd swarms # Install Swarms: # - Headless install: pip install -e . # - Desktop install: pip install -e .[desktop] ``` -------------------------------- ### start_server() Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/aop.md Initiate the MCP server to start processing requests and managing agents. ```APIDOC ## start_server() Start the MCP server. ``` -------------------------------- ### Install Swarms Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/agents/openai_assistant.md Install the swarms library using pip. ```bash pip install swarms ``` -------------------------------- ### Initialize Agent with Tools Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/agents/structured_outputs.md Initialize an Agent instance, providing a name, description, system prompt, and a dictionary of defined tools. ```python from swarms import Agent agent = Agent( agent_name="Your-Agent-Name", agent_description="Agent description", system_prompt="Your system prompt", tools_list_dictionary=tools ) ``` -------------------------------- ### Install pytest-cov Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/framework/test.md Install the pytest-cov plugin to measure code coverage. ```bash pip install pytest-cov ``` -------------------------------- ### Development Installation with Poetry (Environment) Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/install/install.md Clone the Swarms repository, set up a Python environment using Poetry, and install Swarms in editable mode. Supports both headless and desktop installations. ```bash # Clone the repository and navigate to the root directory: git clone https://github.com/kyegomez/swarms.git cd swarms # Setup Python environment and activate it: poetry env use python3.10 poetry shell # Install Swarms: # - Headless install: poetry install # - Desktop install: poetry install --extras "desktop" ``` -------------------------------- ### Create .env.example Template Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/install/env.md Create a template file for environment variables, including required and optional configurations. This file should not contain actual sensitive values. ```bash # Required Configuration OPENAI_API_KEY="" ANTHROPIC_API_KEY="" GROQ_API_KEY="" WORKSPACE_DIR="agent_workspace" # Optional Configuration SWARMS_VERBOSE_GLOBAL="False" ``` -------------------------------- ### System Prompt Integration Example Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/agents/agent_skills.md Illustrates how agent skills are integrated into the agent's system prompt, including the skill's name, description, and full instructions. ```text [Your original system_prompt] # Available Skills ## financial-analysis **Description**: Perform comprehensive financial analysis... # Financial Analysis Skill [Full instructions from SKILL.md] --- ## code-review **Description**: Perform comprehensive code reviews... [Full instructions from SKILL.md] ``` -------------------------------- ### Serve MkDocs Locally Source: https://github.com/kyegomez/swarms/blob/master/docs/contributors/docs.md Use the `mkdocs serve` command to build and serve the documentation locally. This allows you to preview changes before submitting a pull request. Access the preview at `http://127.0.0.1:8000`. ```bash mkdocs serve # Open http://127.0.0.1:8000 to verify output ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/kyegomez/swarms/blob/master/docs/contributors/environment_setup.md Installs pre-commit hooks for the project, including commit message hooks. ```bash pre-commit install pre-commit install --hook-type commit-msg ``` -------------------------------- ### Build Custom MCP Server with Tools Source: https://github.com/kyegomez/swarms/blob/master/docs/swarms/structs/agent_mcp.md Demonstrates how to initialize a FastMCP server and define tools for fetching cryptocurrency prices and analyzing market sentiment. Use this to create custom agents with specific functionalities. ```python from mcp.server.fastmcp import FastMCP import requests from typing import Optional import asyncio # Initialize MCP server mcp = FastMCP("crypto_analysis_server") @mcp.tool( name="get_crypto_price", description="Fetch current cryptocurrency price with market data", ) def get_crypto_price( symbol: str, currency: str = "USD", include_24h_change: bool = True ) -> dict: """ Get real-time cryptocurrency price and market data. Args: symbol: Cryptocurrency symbol (e.g., BTC, ETH) currency: Target currency for price (default: USD) include_24h_change: Include 24-hour price change data """ try: url = f"https://api.coingecko.com/api/v3/simple/price" params = { "ids": symbol.lower(), "vs_currencies": currency.lower(), "include_24hr_change": include_24h_change } response = requests.get(url, params=params, timeout=10) response.raise_for_status() data = response.json() return { "symbol": symbol.upper(), "price": data[symbol.lower()][currency.lower()], "currency": currency.upper(), "change_24h": data[symbol.lower()].get("24h_change", 0), "timestamp": "2024-01-15T10:30:00Z" } except Exception as e: return {"error": f"Failed to fetch price: {str(e)}"} @mcp.tool( name="analyze_market_sentiment", description="Analyze cryptocurrency market sentiment from social media", ) def analyze_market_sentiment(symbol: str, timeframe: str = "24h") -> dict: """Analyze market sentiment for a cryptocurrency.""" # Implement sentiment analysis logic return { "symbol": symbol, "sentiment_score": 0.75, "sentiment": "Bullish", "confidence": 0.85, "timeframe": timeframe } if __name__ == "__main__": mcp.run(transport="streamable-http") ```