### Full MCP Agent Example in Rust Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/README.md Demonstrates the setup and usage of a full MCP (Model Context Protocol) agent using Swarms-RS. It initializes an agent with OpenAI's provider, configures system and user prompts, and integrates with both stdio and SSE MCP servers. The example shows how to send commands to the agent and retrieve responses from different MCP server types. Requires `dotenv` for environment variables like DEEPSEEK_BASE_URL and DEEPSEEK_API_KEY. ```rust use std::env; use anyhow::Result; use swarms_rs::{llm::provider::openai::OpenAI, structs::agent::Agent}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[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 base_url = env::var("DEEPSEEK_BASE_URL").unwrap(); let api_key = env::var("DEEPSEEK_API_KEY").unwrap(); let client = OpenAI::from_url(base_url, api_key).set_model("deepseek-chat"); let agent = client .agent_builder() .system_prompt("You are a helpful assistant.") .agent_name("SwarmsAgent") .user_name("User") // How to install uv: https://github.com/astral-sh/uv#installation // mcp stdio server, any other stdio mcp server can be used .add_stdio_mcp_server("uvx", ["mcp-hn"]) .await // mcp sse server, we can use mcp-proxy to proxy the stdio mcp server(which does not support sse mode) to sse server // run in console: uvx mcp-proxy --sse-port=8000 -- npx -y @modelcontextprotocol/server-filesystem ~ // this will start a sse server on port 8000, and ~ will be the only allowed directory to access .add_sse_mcp_server("example-sse-mcp-server", "http://127.0.0.1:8000/sse") .await .retry_attempts(1) .max_loops(1) .build(); let response = agent .run("Get the top 3 stories of today".to_owned()) .await .unwrap(); // mcp-hn stdio server is called and give us the response println!("STDIO MCP RESPONSE:\n{response}"); let response = agent.run("List ~ directory".to_owned()).await.unwrap(); // example-sse-mcp-server is called and give us the response println!("SSE MCP RESPONSE:\n{response}"); Ok(()) } ``` -------------------------------- ### Bash Command to Run Graph Workflow Example Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/swarms-rs/README.md This command executes the graph workflow example provided in the swarms-rs library. It utilizes Cargo, Rust's package manager, to build and run the example. Ensure that the necessary environment variables (`DEEPSEEK_API_KEY` and `DEEPSEEK_BASE_URL`) are set. ```bash cargo run --example graph_workflow ``` -------------------------------- ### ConcurrentWorkflow Example in Rust Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/README.zh.md This Rust code demonstrates how to initialize and run a `ConcurrentWorkflow`. It sets up specialized agents for market analysis, trade strategy, and risk assessment using the OpenAI LLM provider (configured for DeepSeek). The workflow processes a market scenario and outputs the combined results. ```rust use std::env; use anyhow::Result; use swarms_rs::llm::provider::openai::OpenAI; use swarms_rs::structs::concurrent_workflow::ConcurrentWorkflow; #[tokio::main] async fn main() -> Result<()> { dotenv::dotenv().ok(); let subscriber = tracing_subscriber::fmt::Subscriber::builder() .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) .with_line_number(true) .with_file(true) .finish(); tracing::subscriber::set_global_default(subscriber)?; let base_url = env::var("DEEPSEEK_BASE_URL").unwrap(); let api_key = env::var("DEEPSEEK_API_KEY").unwrap(); let client = OpenAI::from_url(base_url, api_key).set_model("deepseek-chat"); // 创建具有独立角色的专业交易智能体 let market_analysis_agent = client .agent_builder() .agent_name("市场分析智能体") .system_prompt( "你是一个交易市场分析专家。分析提供的市场数据 \n 并识别关键趋势、模式和 technical 指标。你的任务是提供 \n 全面的市场分析,包括支撑/阻力位、成交量分析和 \n 整体市场情绪。只关注分析当前市场状况 \n 而不提供具体的交易建议。以 结束你的分析。", ) .user_name("Trader") .max_loops(1) .temperature(0.2) // 较低的温度以获得精确的技术分析 .enable_autosave() .save_state_dir("./temp/concurrent_workflow/trading") .add_stop_word("") .build(); let trade_strategy_agent = client .agent_builder() .agent_name("交易策略智能体") .system_prompt( "你是一个交易策略专家。基于提供的市场场景, \n 制定全面的交易策略。你的任务是分析给定的市场 \n 信息并创建一个包含潜在入场和出场点、 \n 仓位大小建议和订单类型的策略。只关注策略开发 \n 而不进行风险评估。以 结束你的策略。", ) .user_name("Trader") .max_loops(1) .temperature(0.3) .enable_autosave() .save_state_dir("./temp/concurrent_workflow/trading") .add_stop_word("") .build(); let risk_assessment_agent = client .agent_builder() .agent_name("风险评估智能体") .system_prompt( "你是一个交易风险评估专家。你的角色是评估 \n 提供的市场场景中的潜在风险。仅基于 \n 提供的市场信息计算适当的风险指标, \n 如波动率、最大回撤和风险回报比。提供独立的 \n 风险评估而不考虑具体的交易策略。以 结束你的评估。", ) .user_name("Trader") .max_loops(1) .temperature(0.2) .enable_autosave() .save_state_dir("./temp/concurrent_workflow/trading") .add_stop_word("") .build(); // 创建包含所有交易智能体的并发工作流 let workflow = ConcurrentWorkflow::builder() .name("交易策略工作流") .metadata_output_dir("./temp/concurrent_workflow/trading/workflow/metadata") .description("一个用于使用独立专业智能体分析市场数据的工作流。" ) .agents(vec![ Box::new(market_analysis_agent), Box::new(trade_strategy_agent), Box::new(risk_assessment_agent), ]) .build(); let result = workflow .run( "BTC/USD 正在接近 50,000 美元的关键阻力位,成交量增加。 \n RSI 为 68,MACD 显示看涨势头。为潜在的突破场景制定交易策略。", ) .await?; println!("{}", serde_json::to_string_pretty(&result)?); Ok(()) } ``` -------------------------------- ### Navigate to Project Directory (Bash) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/AUTONOMOUS_TESTING_GUIDE.md A common command-line instruction to change the current directory to the root of the swarms-rs project. This is typically the first step after cloning the repository. ```bash cd swarms-rs ``` -------------------------------- ### Bash: Run Graph Workflow Example Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/README.md This bash command executes the graph workflow example provided within the swarms-rs project. It assumes that the DEEPSEEK_API_KEY and DEEPSEEK_BASE_URL environment variables are set, as they are read by default. ```bash cargo run --example graph_workflow ``` -------------------------------- ### Install Development Dependency: cargo-nextest Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/README.md Installs the `cargo-nextest` tool, which enhances the testing experience for Rust projects. This command uses the Cargo package manager to install the specified tool globally. ```bash cargo install cargo-nextest ``` -------------------------------- ### Binance API Interaction with swarms-rs (Rust - Example) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/examples/binance-swarms-agent/README.md This example demonstrates how the swarms-rs agent interacts with the Binance API to fetch trading data. It includes calls to fetch klines, order book depth, and 24-hour ticker information for BTCUSDT and ETHUSDT. ```rust // Example tool calls within the agent logic (conceptual) // Fetch klines for BTCUSDT let btc_klines = tool_call("klines", json!({"symbol": "BTCUSDT", "interval": "1h", "limit": 24})); // Fetch klines for ETHUSDT let eth_klines = tool_call("klines", json!({"symbol": "ETHUSDT", "interval": "1h", "limit": 24})); // Fetch order book depth for BTCUSDT let btc_depth = tool_call("depth", json!({"symbol": "BTCUSDT", "limit": 10})); // Fetch order book depth for ETHUSDT let eth_depth = tool_call("depth", json!({"symbol": "ETHUSDT", "limit": 10})); // Fetch 24hr ticker for BTCUSDT let btc_ticker = tool_call("ticker_24hr", json!({"symbol": "BTCUSDT"})); // Fetch 24hr ticker for ETHUSDT let eth_ticker = tool_call("ticker_24hr", json!({"symbol": "ETHUSDT"})); // ... agent processes tool results to generate analysis ... ``` -------------------------------- ### Run Binance Swarms Agent (Bash) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/examples/binance-swarms-agent/README.md This command executes the Binance Swarms Agent from the root directory of the project using Cargo. It starts the agent and simulates an interaction for trading analysis. ```bash cargo run --package binance-swarms-agent ``` -------------------------------- ### Full MCP Agent Example in Rust Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/swarms-rs/README.md This Rust code demonstrates initializing an OpenAI client with DeepSeek, configuring an agent with system prompts and user names, and adding both STDIN and SSE MCP servers. It then executes agent tasks against these servers and prints the responses. Dependencies include `swarms-rs`, `tokio`, `dotenv`, and `tracing-subscriber`. ```rust use std::env; use anyhow::Result; use swarms_rs::{llm::provider::openai::OpenAI, structs::agent::Agent}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[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 base_url = env::var("DEEPSEEK_BASE_URL").unwrap(); let api_key = env::var("DEEPSEEK_API_KEY").unwrap(); let client = OpenAI::from_url(base_url, api_key).set_model("deepseek-chat"); let agent = client .agent_builder() .system_prompt("You are a helpful assistant.") .agent_name("SwarmsAgent") .user_name("User") // How to install uv: https://github.com/astral-sh/uv#installation // mcp stdio server, any other stdio mcp server can be used .add_stdio_mcp_server("uvx", ["mcp-hn"]) .await // mcp sse server, we can use mcp-proxy to proxy the stdio mcp server(which does not support sse mode) to sse server // run in console: uvx mcp-proxy --sse-port=8000 -- npx -y @modelcontextprotocol/server-filesystem ~ // this will start a sse server on port 8000, and ~ will be the only allowed directory to access .add_sse_mcp_server("example-sse-mcp-server", "http://127.0.0.1:8000/sse") .await .retry_attempts(1) .max_loops(1) .build(); let response = agent .run("Get the top 3 stories of today".to_owned()) .await .unwrap(); // mcp-hn stdio server is called and give us the response println!("STDIO MCP RESPONSE:\n{response}"); let response = agent.run("List ~ directory".to_owned()).await.unwrap(); // example-sse-mcp-server is called and give us the response println!("SSE MCP RESPONSE:\n{response}"); Ok(()) } ``` -------------------------------- ### Environment Setup for LLM API Keys Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/README.md Configuration for environment variables required to authenticate with LLM providers like OpenAI or DeepSeek. This file should be placed in your project's root directory. Ensure you replace placeholder keys with your actual credentials. ```env OPENAI_API_KEY=your_openai_key_here OPENAI_BASE_URL=https://api.openai.com/v1 # Or for DeepSeek DEEPSEEK_API_KEY=your_deepseek_key_here DEEPSEEK_BASE_URL=https://api.deepseek.com/v1 ``` -------------------------------- ### Debug Specific Test Function (Bash) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/AUTONOMOUS_TESTING_GUIDE.md A command to run a specific test function within a test suite, useful for focused debugging. This example shows how to run the `test_suite_discovery` function within the `test_suite_health` suite. ```bash cargo test --test test_suite_health test_suite_discovery ``` -------------------------------- ### Clone swarms-rs Repository Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/README.md This command clones the swarms-rs project from GitHub. It requires Git to be installed on your system. After cloning, you navigate into the project directory. ```bash git clone https://github.com/The-Swarm-Corporation/swarms-rs cd swarms-rs ``` -------------------------------- ### Add STDIO and SSE MCP Servers in Rust Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/swarms-rs/README.md These Rust code snippets demonstrate how to add different types of Model Context Protocol (MCP) servers to an agent. The first example shows how to add a STDIO MCP server, typically used for command-line tools, by providing its name and associated commands. The second example shows how to add an SSE (Server-Sent Events) MCP server, used for web-based MCP servers, by providing its name and URL. ```rust // Add a STDIO MCP server .add_stdio_mcp_server("uvx", ["mcp-hn"]) .await ``` ```rust // Add an SSE MCP server .add_sse_mcp_server("example-sse-mcp-server", "http://127.0.0.1:8000/sse") .await ``` -------------------------------- ### Install Swarms-rs with Cargo Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/README.md This command adds the latest version of the swarms-rs library to your Rust project's dependencies using the Cargo package manager. Ensure you have Rust and Cargo installed. ```bash cargo add swarms-rs ``` -------------------------------- ### Run Individual Test Categories (Bash) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/AUTONOMOUS_TESTING_GUIDE.md Provides commands to run each specific category of autonomous tests individually: health checks, coverage analysis, integration tests, and security scanning. ```bash cargo test --test test_suite_health # Health checks cargo test --test test_coverage_analysis # Coverage analysis cargo test --test test_integration_scaffolding # Integration tests cargo test --test test_security_safety # Security scanning ``` -------------------------------- ### Basic Agent Usage with Claude - Rust Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/ANTHROPIC_README.md Demonstrates the basic setup and execution of a Swarms-RS agent using an Anthropic Claude model. It initializes the model from environment variables, builds an agent with a system prompt and loop limit, and runs a task. ```rust use swarms_rs::agent::SwarmsAgentBuilder; use swarms_rs::llm::provider::anthropic::Anthropic; #[tokio::main] async fn main() -> Result<(), Box> { // Create Anthropic client from environment let model = Anthropic::from_env(); // Build agent with Claude let agent = SwarmsAgentBuilder::new_with_model(model) .agent_name("ClaudeAssistant") .system_prompt("You are Claude, a helpful AI assistant created by Anthropic.") .max_loops(3) .verbose(true) .build(); // Execute a task let result = agent.run("Explain quantum computing in simple terms.".to_string()).await?; println!("Response: {}", result); Ok(()) } ``` -------------------------------- ### Run Integration Scaffolding Test (Bash) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/AUTONOMOUS_TESTING_GUIDE.md Executes the integration scaffolding test for the autonomous testing suite. This test generates templates for integration tests based on detected API patterns. The `--nocapture` flag ensures that the test's output is displayed. ```bash cargo test --test test_integration_scaffolding -- --nocapture ``` -------------------------------- ### Verbose Test Output for Debugging (Bash) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/AUTONOMOUS_TESTING_GUIDE.md Runs a specified test suite with verbose compilation output enabled. This is helpful for diagnosing issues during the compilation phase of the test. ```bash cargo test --test test_coverage_analysis --verbose ``` -------------------------------- ### Run Validation Script (Bash) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/AUTONOMOUS_TESTING_GUIDE.md Executes a validation script designed to check the integrity and readiness of the autonomous testing suite. This script is recommended after cloning the repository to ensure everything is set up correctly. ```bash ./scripts/validate_autonomous_tests.sh ``` -------------------------------- ### Run All Autonomous Tests (Bash) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/AUTONOMOUS_TESTING_GUIDE.md Executes all four types of autonomous tests: health checks, coverage analysis, integration scaffolding, and security scanning. This command runs all tests in sequence. ```bash cargo test --test test_suite_health --test test_coverage_analysis --test test_integration_scaffolding --test test_security_safety ``` -------------------------------- ### Run Tests in Parallel (Bash) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/AUTONOMOUS_TESTING_GUIDE.md Executes all autonomous tests concurrently using multiple jobs to speed up the testing process. The `--jobs 4` flag specifies the number of parallel jobs. ```bash cargo test --jobs 4 --test test_suite_health --test test_coverage_analysis --test test_integration_scaffolding --test test_security_safety ``` -------------------------------- ### Run Quick Health Check (Bash) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/AUTONOMOUS_TESTING_GUIDE.md A simplified command to run only the health check test with quiet output. This is useful for a fast verification of the testing infrastructure's status. ```bash cargo test --quiet --test test_suite_health ``` -------------------------------- ### Basic Integration Test for Claude (Rust) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/ANTHROPIC_README.md An example of an integration test for the Claude model using Swarms-RS. It initializes the Anthropic provider with a test key and includes a placeholder comment for where further mocking or integration testing logic would reside. ```rust #[cfg(test)] mod tests { use super::*; #[tokio::test] async fn test_claude_basic_completion() { let model = Anthropic::new("test-key"); // Mock or integration test here } } ``` -------------------------------- ### Run Coverage Analysis Test (Bash) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/AUTONOMOUS_TESTING_GUIDE.md Executes the coverage analysis test for the autonomous testing suite. This command analyzes the code coverage provided by the existing tests. The `--nocapture` flag ensures that the test's output is displayed. ```bash cargo test --test test_coverage_analysis -- --nocapture ``` -------------------------------- ### Run Security Scan Test (Bash) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/AUTONOMOUS_TESTING_GUIDE.md Executes the security scanning test for the autonomous testing suite. This command scans the codebase for potential security vulnerabilities. The `--nocapture` flag ensures that the test's output is displayed. ```bash cargo test --test test_security_safety -- --nocapture ``` -------------------------------- ### Run Health Check Test (Bash) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/AUTONOMOUS_TESTING_GUIDE.md Executes the health check test for the autonomous testing suite. This command is used to verify that the testing infrastructure itself is functioning correctly. It captures output for detailed inspection. ```bash cargo check --tests ``` -------------------------------- ### Disable Autonomous Tests in GitHub Actions (YAML) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/AUTONOMOUS_TESTING_GUIDE.md Demonstrates how to temporarily disable the autonomous test suite by commenting out a specific job in the GitHub Actions workflow file. This is a manual intervention used only when necessary. ```yaml # - name: Run test suite health checks # run: cargo test --test test_suite_health --verbose ``` -------------------------------- ### Rust Agent Initialization with OpenAI Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/README.md Initializes an autonomous agent using the swarms-rs library with an OpenAI LLM provider. It configures the agent with a system prompt for cryptocurrency analysis, specifies agent and user names, enables autosave, sets a maximum number of loops, defines a state save directory, and enables a planning feature. The agent is then run with a sample query. ```rust use std::env; use anyhow::Result; use swarms_rs::{llm::provider::openai::OpenAI, structs::agent::Agent}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[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 base_url = env::var("DEEPSEEK_BASE_URL").unwrap(); let api_key = env::var("DEEPSEEK_API_KEY").unwrap(); let client = OpenAI::from_url(base_url, api_key).set_model("deepseek-chat"); let agent = client .agent_builder() .system_prompt( "You are a sophisticated cryptocurrency analysis assistant specialized in:\n 1. Technical analysis of crypto markets\n 2. Fundamental analysis of blockchain projects\n 3. Market sentiment analysis\n 4. Risk assessment\n 5. Trading patterns recognition\n \n When analyzing cryptocurrencies, always consider:\n - Market capitalization and volume\n - Historical price trends\n - Project fundamentals and technology\n - Recent news and developments\n - Market sentiment indicators\n - Potential risks and opportunities\n \n Provide clear, data-driven insights and always include relevant disclaimers about market volatility." ) .agent_name("CryptoAnalyst") .user_name("Trader") .enable_autosave() .max_loops(3) // Increased to allow for more thorough analysis .save_state_dir("./crypto_analysis/") .enable_plan("Break down the crypto analysis into systematic steps:\n 1. Gather market data\n 2. Analyze technical indicators\n 3. Review fundamental factors\n 4. Assess market sentiment\n 5. Provide comprehensive insights".to_owned()) .build(); let response = agent .run("What is the meaning of life?".to_owned()) .await .unwrap(); println!("{response}"); Ok(()) } ``` -------------------------------- ### Rust: ConcurrentWorkflow for Trading Agents Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/README.md This Rust code demonstrates how to set up and run a ConcurrentWorkflow using swarms-rs. It initializes specialized agents for market analysis, trade strategy, and risk assessment, configuring them with specific system prompts, user names, and saving parameters. The workflow is then executed with sample market data, and the results are printed. ```rust use std::env; use anyhow::Result; use swarms_rs::llm::provider::openai::OpenAI; use swarms_rs::structs::concurrent_workflow::ConcurrentWorkflow; #[tokio::main] async fn main() -> Result<()> { dotenv::dotenv().ok(); let subscriber = tracing_subscriber::fmt::Subscriber::builder() .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) .with_line_number(true) .with_file(true) .finish(); tracing::subscriber::set_global_default(subscriber)?; let base_url = env::var("DEEPSEEK_BASE_URL").unwrap(); let api_key = env::var("DEEPSEEK_API_KEY").unwrap(); let client = OpenAI::from_url(base_url, api_key).set_model("deepseek-chat"); // Create specialized trading agents with independent roles let market_analysis_agent = client .agent_builder() .agent_name("Market Analysis Agent") .system_prompt( "You are a market analysis specialist for trading. Analyze the provided market data \ and identify key trends, patterns, and technical indicators. Your task is to provide \ a comprehensive market analysis including support/resistance levels, volume analysis, \ and overall market sentiment. Focus only on analyzing current market conditions \ without making specific trading recommendations. End your analysis with ." ) .user_name("Trader") .max_loops(1) .temperature(0.2) // Lower temperature for precise technical analysis .enable_autosave() .save_state_dir("./temp/concurrent_workflow/trading") .add_stop_word("") .build(); let trade_strategy_agent = client .agent_builder() .agent_name("Trade Strategy Agent") .system_prompt( "You are a trading strategy specialist. Based on the provided market scenario, \ develop a comprehensive trading strategy. Your task is to analyze the given market \ information and create a strategy that includes potential entry and exit points, \ position sizing recommendations, and order types. Focus solely on strategy development \ without performing risk assessment. End your strategy with ." ) .user_name("Trader") .max_loops(1) .temperature(0.3) .enable_autosave() .save_state_dir("./temp/concurrent_workflow/trading") .add_stop_word("") .build(); let risk_assessment_agent = client .agent_builder() .agent_name("Risk Assessment Agent") .system_prompt( "You are a risk assessment specialist for trading. Your role is to evaluate \ potential risks in the provided market scenario. Calculate appropriate risk metrics \ such as volatility, maximum drawdown, and risk-reward ratios based solely on the \ market information provided. Provide an independent risk assessment without \ considering specific trading strategies. End your assessment with ." ) .user_name("Trader") .max_loops(1) .temperature(0.2) .enable_autosave() .save_state_dir("./temp/concurrent_workflow/trading") .add_stop_word("") .build(); // Create a concurrent workflow with all trading agents let workflow = ConcurrentWorkflow::builder() .name("Trading Strategy Workflow") .metadata_output_dir("./temp/concurrent_workflow/trading/workflow/metadata") .description("A workflow for analyzing market data with independent specialized agents.") .agents(vec![ Box::new(market_analysis_agent), Box::new(trade_strategy_agent), Box::new(risk_assessment_agent), ]) .build(); let result = workflow .run( "BTC/USD is approaching a key resistance level at $50,000 with increasing volume. \ RSI is at 68 and MACD shows bullish momentum. Develop a trading strategy for a \ potential breakout scenario." ) .await?; println!("{}", serde_json::to_string_pretty(&result)?); Ok(()) } ``` -------------------------------- ### Rust ConcurrentWorkflow for Trading Analysis Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/swarms-rs/README.md Demonstrates setting up a `ConcurrentWorkflow` with specialized trading agents using the `swarms-rs` library. It configures multiple agents, each with a distinct role and system prompt, and then executes them concurrently to analyze market data and generate a trading strategy. Requires `DEEPSEEK_API_KEY` and `DEEPSEEK_BASE_URL` environment variables. ```rust use std::env; use anyhow::Result; use swarms_rs::llm::provider::openai::OpenAI; use swarms_rs::structs::concurrent_workflow::ConcurrentWorkflow; #[tokio::main] async fn main() -> Result<()> { dotenv::dotenv().ok(); let subscriber = tracing_subscriber::fmt::Subscriber::builder() .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) .with_line_number(true) .with_file(true) .finish(); tracing::subscriber::set_global_default(subscriber)?; let base_url = env::var("DEEPSEEK_BASE_URL").unwrap(); let api_key = env::var("DEEPSEEK_API_KEY").unwrap(); let client = OpenAI::from_url(base_url, api_key).set_model("deepseek-chat"); // Create specialized trading agents with independent roles let market_analysis_agent = client .agent_builder() .agent_name("Market Analysis Agent") .system_prompt( "You are a market analysis specialist for trading. Analyze the provided market data \ and identify key trends, patterns, and technical indicators. Your task is to provide \ a comprehensive market analysis including support/resistance levels, volume analysis, \ and overall market sentiment. Focus only on analyzing current market conditions \ without making specific trading recommendations. End your analysis with ." ) .user_name("Trader") .max_loops(1) .temperature(0.2) // Lower temperature for precise technical analysis .enable_autosave() .save_state_dir("./temp/concurrent_workflow/trading") .add_stop_word("") .build(); let trade_strategy_agent = client .agent_builder() .agent_name("Trade Strategy Agent") .system_prompt( "You are a trading strategy specialist. Based on the provided market scenario, \ develop a comprehensive trading strategy. Your task is to analyze the given market \ information and create a strategy that includes potential entry and exit points, \ position sizing recommendations, and order types. Focus solely on strategy development \ without performing risk assessment. End your strategy with ." ) .user_name("Trader") .max_loops(1) .temperature(0.3) .enable_autosave() .save_state_dir("./temp/concurrent_workflow/trading") .add_stop_word("") .build(); let risk_assessment_agent = client .agent_builder() .agent_name("Risk Assessment Agent") .system_prompt( "You are a risk assessment specialist for trading. Your role is to evaluate \ potential risks in the provided market scenario. Calculate appropriate risk metrics \ such as volatility, maximum drawdown, and risk-reward ratios based solely on the \ market information provided. Provide an independent risk assessment without \ considering specific trading strategies. End your assessment with ." ) .user_name("Trader") .max_loops(1) .temperature(0.2) .enable_autosave() .save_state_dir("./temp/concurrent_workflow/trading") .add_stop_word("") .build(); // Create a concurrent workflow with all trading agents let workflow = ConcurrentWorkflow::builder() .name("Trading Strategy Workflow") .metadata_output_dir("./temp/concurrent_workflow/trading/workflow/metadata") .description("A workflow for analyzing market data with independent specialized agents.") .agents(vec![ Box::new(market_analysis_agent), Box::new(trade_strategy_agent), Box::new(risk_assessment_agent), ]) .build(); let result = workflow .run( "BTC/USD is approaching a key resistance level at $50,000 with increasing volume. \ RSI is at 68 and MACD shows bullish momentum. Develop a trading strategy for a \ potential breakout scenario.", ) .await?; println!("{}", serde_json::to_string_pretty(&result)?); Ok(()) } ``` -------------------------------- ### Configure Binance API Keys (.env file) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/examples/binance-swarms-agent/README.md This snippet shows how to configure your Binance API keys and secrets in the .env file for the agent to access the Binance API. Ensure these credentials are kept secure. ```dotenv DEEPSEEK_BASE_URL=https://api.deepseek.com/v1 DEEPSEEK_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxx ``` -------------------------------- ### Rust MCP Server Integration (STDIO and SSE) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/README.md Demonstrates how to add Model Context Protocol (MCP) servers to an agent in swarms-rs. It shows the syntax for adding both a STDIO MCP server, which connects to command-line tools, and an SSE MCP server, which connects to web-based servers using Server-Sent Events. These allow agents to interact with external functionalities. ```rust // Add a STDIO MCP server .add_stdio_mcp_server("uvx", ["mcp-hn"]) .await // Add an SSE MCP server .add_sse_mcp_server("example-sse-mcp-server", "http://127.0.0.1:8000/sse") .await ``` -------------------------------- ### Run Anthropic Provider Tests (Bash) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/ANTHROPIC_README.md Provides bash commands to execute tests specifically for the Anthropic provider within the Swarms-RS project. It includes an option to run tests with verbose output for more detailed logging. ```bash # Run Anthropic provider tests cargo test anthropic # Run with verbose output cargo test anthropic -- --nocapture ``` -------------------------------- ### Run Benchmarks with cargo bench Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/README.md Executes the benchmark tests defined in the swarms-rs project. This command is used to measure the performance of different parts of the code and identify potential optimizations. ```bash cargo bench ``` -------------------------------- ### Set Production Environment Variables (Bash) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/ANTHROPIC_README.md Configures essential environment variables for running the Swarms-RS Anthropic provider in a production environment. This includes setting the API key, the base URL for the Anthropic API, and the logging level for the swarms_rs library. ```bash # Production configuration export ANTHROPIC_API_KEY="sk-ant-prod-..." export ANTHROPIC_BASE_URL="https://api.anthropic.com" export RUST_LOG="swarms_rs=info" ``` -------------------------------- ### Enable Verbose Logging for Agent (Rust) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/ANTHROPIC_README.md Shows how to enable detailed logging for the Swarms-RS agent when using the Anthropic provider. Setting the `verbose` option to `true` during agent construction will log task initialization, API interactions, tool usage, performance metrics, and errors. ```rust let agent = SwarmsAgentBuilder::new_with_model(Anthropic::from_env()) .verbose(true) // Enable detailed logging .build(); ``` -------------------------------- ### Tool Integration with Claude Agent - Rust Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/ANTHROPIC_README.md Demonstrates how to integrate custom tools with a Swarms-RS agent powered by Anthropic Claude. It defines a `CalculatorTool` implementing the `Tool` and `ToolDyn` traits and shows how to add it to the agent builder. ```rust 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> + 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(); ``` -------------------------------- ### Run Tests with cargo-nextest Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/README.md Executes all tests within the swarms-rs project using `cargo-nextest`. This command is used to verify the correctness of the codebase and ensure that recent changes have not introduced regressions. ```bash cargo nextest run ``` -------------------------------- ### Create a New Feature Branch Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/swarms-rs/README.md Creates a new git branch for developing a new feature. This is a standard practice for collaborative development and managing changes. ```bash git checkout -b feature/amazing-feature ``` -------------------------------- ### Select Specific Claude Models - Rust Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/ANTHROPIC_README.md Illustrates how to instantiate the Anthropic model for Swarms-RS with specific Claude model names. This allows for choosing models based on their capabilities, such as intelligence, speed, or cost. ```rust // For complex analytical tasks let sonnet_model = Anthropic::from_env_with_model("claude-3-5-sonnet-20241022"); // For fast, simple responses let haiku_model = Anthropic::from_env_with_model("claude-3-5-haiku-20241022"); // For maximum intelligence let opus_model = Anthropic::from_env_with_model("claude-3-opus-20240229"); ``` -------------------------------- ### Set Anthropic API Key and Base URL - Bash Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/ANTHROPIC_README.md Environment variables are used to configure the Anthropic API key and optionally a custom base URL for the Swarms-RS framework. Ensure your API key is kept confidential. ```bash # Set your Anthropic API key export ANTHROPIC_API_KEY="your-api-key-here" # Optional: Set custom base URL (defaults to https://api.anthropic.com) export ANTHROPIC_BASE_URL="https://api.anthropic.com" ``` -------------------------------- ### Benchmark Model Performance (Rust) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/ANTHROPIC_README.md Compares the performance of different Anthropic Claude models by measuring the time taken to complete a simple task. It iterates through a predefined list of models, sets up an agent for each, runs a task, and prints the execution duration. ```rust use std::time::Instant; // Compare model performance let models = vec![ ("claude-3-5-haiku-20241022", "Fast"), ("claude-3-5-sonnet-20241022", "Balanced"), ("claude-3-opus-20240229", "Powerful"), ]; for (model_name, description) in models { let start = Instant::now(); let model = Anthropic::from_env().set_model(model_name); let agent = SwarmsAgentBuilder::new_with_model(model) .max_loops(1) .verbose(false) .build(); let result = agent.run("Hello, Claude!".to_string()).await?; let duration = start.elapsed(); println!("{} ({}): {:.2}s", description, model_name, duration.as_secs_f64()); } ``` -------------------------------- ### Advanced Agent Configuration - Rust Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/ANTHROPIC_README.md Shows how to configure a Swarms-RS agent with advanced options for Anthropic Claude models. This includes setting custom system prompts, controlling response creativity with temperature, adjusting token limits, enabling planning and autosave features, and setting retry attempts. ```rust use swarms_rs::agent::SwarmsAgentBuilder; use swarms_rs::llm::provider::anthropic::Anthropic; let agent = SwarmsAgentBuilder::new_with_model(Anthropic::from_env()) .agent_name("AdvancedClaude") .system_prompt("You are an advanced AI assistant with expertise in multiple domains.") .max_loops(5) .temperature(0.3) // Lower temperature for more focused responses .max_tokens(4096) // Increase token limit for detailed responses .enable_plan(Some("Create a detailed plan for solving: ".to_string())) .enable_autosave() .save_state_dir("./claude_agent_states") .retry_attempts(3) .verbose(true) .build(); ``` -------------------------------- ### Handle API and Network Errors (Rust) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/ANTHROPIC_README.md Demonstrates how to handle various errors that can occur when interacting with the Anthropic API using the Swarms-RS agent. It includes specific matches for provider errors (API issues) and HTTP errors (network problems), with a fallback for other agent errors. ```rust match agent.run(task).await { Ok(response) => println!("Success: {}", response), Err(e) => match e { swarms_rs::structs::agent::AgentError::ProviderError(msg) => { println!("Anthropic API error: {}", msg); } swarms_rs::structs::agent::AgentError::HttpError(_) => { println!("Network error - check your connection"); } _ => println!("Other error: {}", e), } } ``` -------------------------------- ### Git Commit Changes for Contribution Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/README.md Stages and commits changes to the local repository. This is a standard Git command used as part of the contribution workflow to record modifications before pushing them. ```bash git commit -m 'Add some amazing feature' ``` -------------------------------- ### Git Push Feature Branch for Contribution Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/README.md Pushes committed changes from a local feature branch to the remote repository. This is typically done to share work and prepare for a Pull Request. ```bash git push origin feature/amazing-feature ``` -------------------------------- ### Implement Health Check Endpoint (Rust) Source: https://github.com/the-swarm-corporation/swarms-rs/blob/main/docs/ANTHROPIC_README.md A basic asynchronous function demonstrating a health check for the Swarms-RS agent interacting with the Anthropic provider. It initializes an agent and runs a minimal task to verify connectivity and basic functionality. ```rust async fn health_check() -> Result<(), Box> { let model = Anthropic::from_env(); let agent = SwarmsAgentBuilder::new_with_model(model) .max_loops(1) .verbose(false) .build(); // Simple health check agent.run("Hello".to_string()).await?; Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.