swarms-rs Framework

repository·main·Indexed 41 days ago

https://github.com/the-swarm-corporation/swarms-rs

An enterprise-grade multi-agent orchestration framework written in Rust for high-performance, scalable, and reliable coordination of complex multi-agent systems. It supports LLM providers including OpenAI and Anthropic Claude, integrates with the Model Context Protocol (MCP) via STDIO and SSE transport, and features a ConcurrentWorkflow for parallel agent execution.

Tokens
23.1K
Snippets
79
Records
91
Agent score
50%

What's inside swarms-rs

  1. Overview of Binance Swarms Agent capabilities

    main

    The Binance Swarms Agent is a specialized implementation of the swarms-rs framework designed for cryptocurrency trading strategy analysis. It performs the following tasks:

    • Market Structure Analysis: Identifies support and resistance levels using recent price action and order book liquidity.
    • Order Book Liquidity Analysis: Assesses the strength of price levels by analyzing liquidity distribution.
    • Sentiment & Capital Flow Analysis: Monitors 24-hour volume patterns to detect institutional accumulation or distribution.
    • Market Depth Evaluation: Analyzes bid-ask spreads and market depth to assess trend continuation risks.
    • Strategy & Risk Management: Provides actionable recommendations (e.g., buying dips vs. waiting for breakouts) and defines specific stop-loss and take-profit targets based on user-defined risk tolerance.
  2. Understand the swarms-rs framework architecture

    main

    The swarms-rs architecture is organized into three progressive layers, allowing you to build everything from simple single-agent tools to complex distributed systems:

    1. Agent Layer: The foundation consisting of LLM Integration (OpenAI, DeepSeek, etc.), a Tool System (extensible via MCP and custom tools), Memory Management (short-term and long-term context), and State Management (handling configuration and runtime parameters).

    2. Multi-Agent Structure and Communication: Orchestrates how agents interact using Sequential Workflows (linear tasks), Concurrent Workflows (parallel execution), standardized Communication Protocols, Task Distribution, and Synchronization mechanisms.

    3. Cascading Multi-Agent Systems: The highest level of complexity involving Hierarchical Organizations (specialized roles), Swarm Intelligence (emergent behaviors from large-scale interactions), Dynamic Scaling, Fault Tolerance, and Resource Optimization.

  3. Use Model Context Protocol (MCP) tools with Agents

    main

    The swarms-rs library supports the Model Context Protocol (MCP), allowing agents to interact with external tools and real-world data via standardized interfaces.

    Supported MCP server types:

    • STDIO MCP Server: Connects to command-line tools that implement the MCP protocol.
    • SSE MCP Server: Connects to web-based MCP servers using Server-Sent Events.

    To add these to an agent, use the following methods during the agent building process:

    • .add_stdio_mcp_server(command, args): Adds a command-line based server.
    • .add_sse_mcp_server(name, url): Adds a web-based server via URL.
    // Adding a STDIO MCP server
    let agent = client
        .agent_builder()
        .add_stdio_mcp_server("uvx", ["mcp-hn"])
        .await
        .build();
    
    // Adding an SSE MCP server
    let agent = client
        .agent_builder()
        .add_sse_mcp_server("example-sse-mcp-server", "http://127.0.0.1:8000/sse")
        .await
        .build();
  4. How ConcurrentWorkflow works for parallel agent execution

    main

    A ConcurrentWorkflow allows you to execute multiple agents simultaneously to perform different parts of a task in parallel. This is useful for scenarios where specialized agents (e.g., a Market Analyst, a Strategy Specialist, and a Risk Assessor) can all work on the same input independently to produce a comprehensive result.

    To use it:

    1. Build specialized agents using an LLM client's agent_builder().
    2. Use ConcurrentWorkflow::builder() to define the workflow.
    3. Register the agents using .agents(vec![Box::new(agent1), Box::new(agent2), ...]).
    4. Call .run(input_string) to execute the workflow asynchronously.
    use swarms_rs::structs::concurrent_workflow::ConcurrentWorkflow;
    
    // ... agent setup ...
    
    let workflow = ConcurrentWorkflow::builder()
        .name("Trading Strategy Workflow")
        .metadata_output_dir("./temp/metadata")
        .description("A workflow for analyzing market data.")
        .agents(vec![
            Box::new(market_analysis_agent),
            Box::new(trade_strategy_agent),
            Box::new(risk_assessment_agent),
        ])
        .build();
    
    let result = workflow
        .run("Input prompt or data here")
        .await?;
  5. Execute multiple agents using ConcurrentWorkflow

    main

    The ConcurrentWorkflow allows you to execute multiple specialized agents simultaneously. This is useful for complex tasks where different agents handle different aspects of a problem (e.g., one for market analysis, one for strategy, and one for risk assessment).

    To use a ConcurrentWorkflow:

    1. Build multiple agents using agent_builder().
    2. Use ConcurrentWorkflow::builder() to define the workflow.
    3. Provide a .name(), .description(), and a vector of agents via .agents(vec![Box::new(agent1), ...]).
    4. Call .run(input) to execute the workflow.
    let workflow = ConcurrentWorkflow::builder()
        .name("Trading Workflow")
        .description("Analyzes market data using specialized agents.")
        .agents(vec![
            Box::new(market_analysis_agent),
            Box::new(trade_strategy_agent),
            Box::new(risk_assessment_agent),
        ])
        .build();
    
    let result = workflow.run("Market data input...").await?;
  6. Understand the swarms-rs architecture

    main

    The swarms-rs framework is built on a modular architecture designed for easy extension and customization. It consists of the following layers:

    • Agent Layer: Core agent implementations featuring memory management and tool integration.
    • LLM Provider Layer: Abstractions for various LLM providers (e.g., OpenAI, DeepSeek).
    • Tool System: An extensible framework for adding capabilities to agents.
    • MCP Integration: Support for Model Context Protocol (MCP) tools via STDIO and SSE interfaces.
    • Swarm Orchestration: Coordination of multiple agents for complex workflows.
    • Persistence Layer: Mechanisms for state management and recovery.
  7. Understand the Autonomous Testing Suite

    main

    The Autonomous Testing Suite is a self-managing quality monitoring system designed to run without manual intervention. It is triggered automatically on every Git push via GitHub Actions.

    Key Characteristics:

    • Automatic Execution: Runs by itself on every push.
    • Zero Configuration: Analyzes code without requiring manual setup.
    • Non-Intrusive: The tests reside in the /tests folder and analyze/report on code without modifying production logic.
    • Informational Nature: Results are primarily for guidance (Green = good, Red = review suggestions) and are not designed to block development workflows.

    The 4 Core Autonomous Tests:

    1. Health Check (test_suite_health): Validates that the testing infrastructure is functioning correctly.
    2. Coverage (test_coverage_analysis): Analyzes how much of the codebase is covered by tests.
    3. Scaffolding (test_integration_scaffolding): Automatically generates integration test templates based on detected API patterns.
    4. Security (test_security_safety): Scans the code for potential security vulnerabilities.
  8. Run and Debug Autonomous Tests

    main

    While tests run automatically on push, you can execute them manually for debugging or local validation using cargo test with specific test flags.

    Quick Start for New Developers

    cd swarms-rs
    ./scripts/validate_autonomous_tests.sh

    Running All Tests

    To run the full suite at once:

    cargo test --test test_suite_health --test test_coverage_analysis --test test_integration_scaffolding --test test_security_safety

    For faster execution using parallel jobs:

    cargo test --jobs 4 --test test_suite_health --test test_coverage_analysis --test test_integration_scaffolding --test test_security_safety

    Individual Test Commands

    Test CategoryCommand
    Health Checkscargo test --test test_suite_health
    Coverage Analysiscargo test --test test_coverage_analysis
    Integration Scaffoldingcargo test --test test_integration_scaffolding
    Security Scanningcargo test --test test_security_safety

    Debugging and Verbose Output

    If you need to see detailed output or inspect specific failures:

    • See all output (no capture): cargo test --test <test_name> -- --nocapture
    • Verbose mode: cargo test --test <test_name> --verbose
    • Run a specific test function: cargo test --test test_suite_health test_suite_discovery
    # Run all autonomous tests
    cargo test --test test_suite_health --test test_coverage_analysis --test test_integration_scaffolding --test test_security_safety
    
    # Quick health check
    cargo test --quiet --test test_suite_health
    
    # Debugging security scan with full output
    cargo test --test test_security_safety -- --nocapture
  9. Integrate custom tools with Claude agents

    main

    To give a Claude agent capabilities, implement the Tool and ToolDyn traits for your custom struct and register it using .add_tool() in the builder.

    use swarms_rs::agent::SwarmsAgentBuilder;
    use swarms_rs::llm::provider::anthropic::Anthropic;
    use swarms_rs::structs::tool::Tool;
    
    // Define a custom tool
    struct CalculatorTool;
    
    impl Tool for CalculatorTool {
        fn name(&self) -> &str { "calculator" }
        fn definition(&self) -> swarms_rs::llm::request::ToolDefinition {
            serde_json::json!({
                "name": "calculator",
                "description": "Perform mathematical calculations",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "expression": {
                            "type": "string",
                            "description": "Mathematical expression to evaluate"
                        }
                    },
                    "required": ["expression"]
                }
            }).into()
        }
    }
    
    impl swarms_rs::structs::tool::ToolDyn for CalculatorTool {
        fn call(&self, args: String) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<String, swarms_rs::structs::tool::ToolError>> + Send + '_>> {
            Box::pin(async move {
                // Implementation here
                Ok("42".to_string())
            })
        }
    }
    
    // Use with agent
    let agent = SwarmsAgentBuilder::new_with_model(Anthropic::from_env())
        .add_tool(CalculatorTool)
        .system_prompt("You can use the calculator tool for mathematical computations.")
        .build();
  10. Set up a development environment for swarms-rs

    main

    To contribute to or develop with swarms-rs, follow these steps to set up your local environment:

    1. Clone the repository:
      git clone https://github.com/The-Swarm-Corporation/swarms-rs
      cd swarms-rs
    2. Install development dependencies (specifically cargo-nextest for testing):
      cargo install cargo-nextest
    3. Run tests:
      cargo nextest run
    4. Run benchmarks:
      cargo bench
    git clone https://github.com/The-Swarm-Corporation/swarms-rs
    cd swarms-rs
    cargo install cargo-nextest
    cargo nextest run
    cargo bench
  11. Run project examples

    main

    The repository contains several examples in the swarms-rs/examples/ directory. You can run them using cargo run --example <name>.

    For example, to run the graph workflow:

    cargo run --example graph_workflow

    Note: Most examples require environment variables like DEEPSEEK_API_KEY and DEEPSEEK_BASE_URL to be set.