### Generate Getting Started Guide with Claude (Rust) Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/tutorials/09-documentation-generator.md This asynchronous Rust function creates a getting started guide by formulating a detailed prompt for the Claude API. The prompt incorporates project metadata and summaries of available examples, guiding the AI to produce a beginner-friendly guide with prerequisites, installation steps, and basic usage instructions. ```Rust async fn generate_getting_started_guide(&self, analysis: &ProjectAnalysis) -> Result> { let examples_summary = analysis.examples.iter() .take(3) // Use first 3 examples .map(|e| format!("Example: {} - {}", e.title, e.description)) .collect::>() .join("\n"); let prompt = format!( "Create a comprehensive getting started guide for this project:\n\n\ Project: {}\n\ Description: {}\n\ Language: {}\n\n\ Available Examples:\n{}\n\n\ The guide should include:\n\ 1. Prerequisites and system requirements\n\ 2. Installation steps\n\ 3. Basic configuration\n\ 4. Your first program/example\n\ 5. Common next steps\n\ 6. Where to find more help\n\n\ Make it beginner-friendly with clear step-by-step instructions.", analysis.metadata.name, analysis.metadata.description, analysis.metadata.language, examples_summary ); let guide = self.claude_client .query(&prompt) .send() .await?; Ok(guide) } ``` -------------------------------- ### Hello World Example with Claude AI SDK in Rust Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md A complete, basic example demonstrating how to initialize the Claude client, send a simple text query, and print the AI's response. ```Rust use claude_ai::{Client, Config}; #[tokio::main] async fn main() -> claude_ai::Result<()> { // Step 1: Create a client let client = Client::new(Config::default()); // Step 2: Send a query let response = client .query("Say hello and introduce yourself!") .send() .await?; // Step 3: Display the response println!("Claude says: {}", response); Ok(()) } ``` -------------------------------- ### Create Basic Rust Main File for Claude SDK Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md A minimal `main.rs` file demonstrating the basic setup for a `claude-sdk-rs` application, including `tokio::main` for async execution. ```Rust use claude_ai::{Client, Config}; #[tokio::main] async fn main() -> claude_ai::Result<()> { println!("Claude AI SDK is ready!"); Ok(()) } ``` -------------------------------- ### Run Basic Claude AI Query Example Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/tutorials/01-getting-started.md Command to compile and execute the Rust example that sends a basic query to Claude AI using `claude-sdk-rs`. ```bash cargo run ``` -------------------------------- ### Check and Install Rust Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/QUICK_START.md Instructions to verify your current Rust version and, if necessary, install or update Rust using the `rustup` script. ```bash # Check your Rust version rustc --version # If you need to install/update Rust curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` -------------------------------- ### Install and Authenticate Claude Code CLI Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/tutorials/01-getting-started.md Commands to install the Claude Code CLI tool and authenticate with your API key, which is a prerequisite for using the `claude-sdk-rs` SDK. ```bash curl -sSL https://claude.ai/install.sh | sh claude auth login ``` -------------------------------- ### Run claude-sdk-rs Examples from Command Line Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/QUICK_START.md This snippet provides bash commands to run various examples included with the `claude-sdk-rs` library. It helps users quickly explore different functionalities like basic usage, streaming, session management, and error handling. ```bash # Run different examples cargo run --example basic_usage cargo run --example streaming cargo run --example session_management cargo run --example error_handling ``` -------------------------------- ### Install and Use claude-sdk-rs CLI Binary Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/QUICK_START.md This snippet provides instructions for enabling and installing the `claude-sdk-rs` CLI binary. It includes the `Cargo.toml` feature flag and the `cargo install` command to make the interactive CLI available. ```toml claude-sdk-rs = { version = "1.0", features = ["cli"] } ``` ```bash cargo install claude-sdk-rs --features cli claude-sdk-rs ``` -------------------------------- ### Install and Verify Claude Code CLI Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md Instructions for installing the Claude Code CLI on macOS/Linux via curl and verifying its installation. Includes a note for Windows users. ```Bash # Install Claude CLI (macOS/Linux) curl -sSL https://claude.ai/install.sh | sh # Windows users: Download from https://github.com/anthropics/claude-code # Verify installation claude --version ``` -------------------------------- ### Create New Rust Project for Claude SDK Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md Steps to initialize a new Rust project and navigate into its directory, preparing it for `claude-sdk-rs` integration. ```Bash cargo new my-claude-app cd my-claude-app ``` -------------------------------- ### Configure `claude-sdk-rs` Client with Custom Settings Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/QUICK_START.md Rust example demonstrating how to create a `claude-sdk-rs` client with custom configurations, including specifying a model, setting a system prompt, and defining a timeout. ```rust use claude_sdk_rs::{Client, Config}; #[tokio::main] async fn main() -> Result<(), claude_sdk_rs::Error> { // Configure Claude with custom settings let config = Config::builder() .model("claude-3-sonnet-20240229") // Use specific model .system_prompt("You are a helpful coding assistant specialized in Rust.") .timeout_secs(30) .build()?; let client = Client::new(config); let response = client .query("What are the benefits of Rust's ownership system?") .send() .await?; println!("{}", response); Ok(()) } ``` -------------------------------- ### Send First Claude Query with `claude-sdk-rs` Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/QUICK_START.md A complete Rust example demonstrating how to initialize a `claude-sdk-rs` client with default settings, send a basic text query to Claude AI, and print the response. ```rust use claude_sdk_rs::{Client, Config}; #[tokio::main] async fn main() -> Result<(), claude_sdk_rs::Error> { println!("🤖 Welcome to claude-sdk-rs!"); // Create a client with default settings let client = Client::new(Config::default()); // Send a query to Claude let response = client .query("Hello Claude! Please introduce yourself in 2-3 sentences.") .send() .await?; println!("\nClaude's response:\n{}", response); Ok(()) } ``` -------------------------------- ### Rust Code Review Assistant with Claude AI Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md This Rust example demonstrates building a code review tool using the Claude AI SDK. It reads Rust code from a file, constructs a detailed prompt for Claude focusing on safety, performance, and idiomatic patterns, and then prints the AI's review. ```rust use claude_ai::{Client, Config}; use std::fs; #[tokio::main] async fn main() -> claude_ai::Result<()> { let client = Client::builder() .system_prompt("You are a Rust code reviewer. Focus on safety, performance, and idiomatic patterns.") .build(); // Read code from file let code = fs::read_to_string("src/main.rs")?; let prompt = format!( "Please review this Rust code and provide feedback:\n\n```rust\n{}\n```\n\nFocus on:\n1. Memory safety issues\n2. Performance improvements\n3. Idiomatic Rust patterns\n4. Error handling", code ); let review = client.query(&prompt).send().await?; println!("Code Review Results:\n{}", review); Ok(()) } ``` -------------------------------- ### Install and Authenticate Claude Code CLI Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/QUICK_START.md Steps to install the Claude Code CLI via npm or Homebrew, followed by the command to authenticate your CLI for use with the SDK. Includes a verification command. ```bash # Install via npm (recommended) npm install -g @anthropic-ai/claude-code # Or install via Homebrew on macOS brew install claude-code # After installation, authenticate: claude auth ``` ```bash claude --version ``` -------------------------------- ### Verify Rust Project Build and Run Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md Commands to compile and execute the newly created Rust project, ensuring all dependencies are correctly set up and the basic application runs. ```Bash cargo build cargo run ``` -------------------------------- ### Rust Claude AI Client Reuse Best Practice Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md This example highlights the best practice of reusing the Claude AI client instance across multiple queries to improve efficiency. It contrasts the efficient approach of creating a client once with the inefficient method of re-instantiating the client for each query. ```rust // Good: Create once, use many times let client = Client::new(Config::default()); for query in queries { let response = client.query(&query).send().await?; } // Bad: Creating new client for each query for query in queries { let client = Client::new(Config::default()); // Inefficient! let response = client.query(&query).send().await?; } ``` -------------------------------- ### Verify Claude CLI Installation Path Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/tutorials/01-getting-started.md Command to check if the `claude` CLI binary is installed and discoverable in the system's PATH, helping to diagnose 'Binary not found' errors. ```bash which claude # Should show the path to Claude CLI ``` -------------------------------- ### Rust Interactive CLI Assistant with Claude AI Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md This Rust example shows how to create an interactive command-line assistant using the Claude AI SDK. It maintains a session context, prompts the user for input, sends queries to Claude, and prints the AI's responses, allowing for a conversational experience. ```rust use claude_ai::{Client, Config}; use claude_ai_core::session::SessionId; use std::io::{self, Write}; #[tokio::main] async fn main() -> claude_ai::Result<()> { let client = Client::builder() .system_prompt("You are a helpful CLI assistant. Be concise and practical.") .build(); let session_id = SessionId::new(); println!("Claude CLI Assistant (type 'quit' to exit)\n"); loop { // Prompt for input print!("> "); io::stdout().flush()?; // Read user input let mut input = String::new(); io::stdin().read_line(&mut input)?; let input = input.trim(); // Check for exit if input == "quit" || input == "exit" { println!("Goodbye!"); break; } // Send to Claude with session context match client.query(input).session_id(&session_id).send().await { Ok(response) => println!("\n{}\n", response), Err(e) => eprintln!("Error: {}", e), } } Ok(()) } ``` -------------------------------- ### Rust Claude AI Response Modes Best Practices Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md This example demonstrates the different response modes available in the Claude AI Rust SDK. It shows how to retrieve simple text content, a full response with metadata (like cost and tokens), and a streaming response for real-time output or long generations, advising on when to use each mode. ```rust // Simple text response - when you just need the content let text = client.query("...").send().await?; // Full response - when you need metadata let full = client.query("...").send_full().await?; // Streaming - for long responses or real-time output let stream = client.query("...").stream().await?; ``` -------------------------------- ### Install and Authenticate Claude Code CLI Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/examples/README.md Instructions to install the Claude Code CLI and authenticate it, which is a prerequisite for running the `claude-sdk-rs` examples. ```bash # Install Claude Code CLI first # Then authenticate claude login ``` -------------------------------- ### Orchestrate User Guide Generation (Rust) Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/tutorials/09-documentation-generator.md This asynchronous Rust function manages the creation of a comprehensive user guide for a project. It sets up the necessary output directory structure and then calls helper functions to generate and write 'getting started' guides, tutorials for various use cases, and an FAQ section to Markdown files. ```Rust async fn generate_user_guide(&self, analysis: &ProjectAnalysis) -> Result<(), Box> { println!(" 📖 Generating user guide..."); let guides_dir = self.output_dir.join("docs").join("guides"); fs::create_dir_all(&guides_dir)?; // Generate getting started guide let getting_started = self.generate_getting_started_guide(analysis).await?; fs::write(guides_dir.join("getting-started.md"), getting_started)?; // Generate tutorials for different use cases let tutorials = self.generate_tutorials(analysis).await?; for (name, content) in tutorials { fs::write(guides_dir.join(format!("{}.md", name)), content)?; } // Generate FAQ let faq = self.generate_faq(analysis).await?; fs::write(guides_dir.join("faq.md"), faq)?; Ok(()) } ``` -------------------------------- ### Initialize Claude AI Client in Rust Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md Demonstrates how to create a `Client` instance for interacting with the Claude API, showing both default configuration and custom builder patterns for model and timeout settings. ```Rust // Default client let client = Client::new(Config::default()); // Custom configuration let client = Client::builder() .model("claude-sonnet-4-20250514") .timeout(60) .build(); ``` -------------------------------- ### Create New Rust Project Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/QUICK_START.md Commands to initialize a new Rust project using Cargo and navigate into the newly created project directory. ```bash cargo new my-claude-app cd my-claude-app ``` -------------------------------- ### Authenticate Claude CLI with API Key Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md Commands to log in to the Claude CLI using an API key and verify the authentication status. ```Bash # Login with your API key claude auth login # Verify authentication claude auth status ``` -------------------------------- ### Rust Batch Processing with Claude AI and Cost Tracking Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md This Rust example illustrates how to process multiple queries in a batch using the Claude AI SDK, while also tracking the total cost and token usage. It reads queries from a file, sends them to a specified Claude model (e.g., 'claude-haiku'), and aggregates cost and token metadata from the responses. ```rust use claude_ai::{Client, StreamFormat}; use std::fs::File; use std::io::{BufRead, BufReader}; #[tokio::main] async fn main() -> claude_ai::Result<()> { let client = Client::builder() .stream_format(StreamFormat::Json) .model("claude-haiku-3-20250307") // Cheaper model for batch processing .build(); // Read queries from file let file = File::open("queries.txt")?; let reader = BufReader::new(file); let mut total_cost = 0.0; let mut total_tokens = 0; for (i, line) in reader.lines().enumerate() { let query = line?; if query.trim().is_empty() { continue; } println!("Processing query {}: {}", i + 1, query); match client.query(&query).send_full().await { Ok(response) => { println!("Response: {}\n", response.content); // Track costs if let Some(metadata) = response.metadata { if let Some(cost) = metadata.cost_usd { total_cost += cost; } if let Some(tokens) = metadata.tokens_used { total_tokens += tokens.total_tokens.unwrap_or(0); } } } Err(e) => eprintln!("Error processing query {}: {}", i + 1, e), } } println!("\n--- Batch Processing Complete ---"); println!("Total cost: ${:.6}", total_cost); println!("Total tokens: {}", total_tokens); Ok(()) } ``` -------------------------------- ### Build and Send a Query (Rust) Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/tutorials/01-getting-started.md Illustrates the process of creating a query builder, sending the query to Claude AI, and awaiting the asynchronous response using `claude-sdk-rs`. ```rust let response = client.query("What is 2 + 2?").send().await?; ``` -------------------------------- ### Add claude-sdk-rs with Specific Features Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/tutorials/01-getting-started.md Examples of adding `claude-sdk-rs` to `Cargo.toml` with various feature flags, such as `sqlite` for persistence, `mcp` for MCP server support, `cli` for CLI binary, or `full` for all features. ```toml # With SQLite persistence claude-sdk-rs = { version = "0.1", features = ["sqlite"] } # With MCP support claude-sdk-rs = { version = "0.1", features = ["mcp"] } # With CLI binary claude-sdk-rs = { version = "0.1", features = ["cli"] } # All features claude-sdk-rs = { version = "0.1", features = ["full"] } ``` -------------------------------- ### Configure Claude AI Client Settings in Rust Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md Shows how to configure the `claude-sdk-rs` client using the `Config` builder, allowing customization of model, system prompt, stream format, and timeout duration. ```Rust let config = Config::builder() .model("claude-opus-4-20250514") .system_prompt("You are a helpful assistant") .stream_format(StreamFormat::Json) .timeout(Duration::from_secs(30)) .build()?; ``` -------------------------------- ### Add `claude-sdk-rs` and `tokio` Dependencies Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/QUICK_START.md Configuration for your `Cargo.toml` file to include `claude-sdk-rs` as the main dependency and `tokio` with full features for asynchronous operations. ```toml [dependencies] claude-sdk-rs = "1.0" tokio = { version = "1.40", features = ["full"] } ``` -------------------------------- ### Configure Claude Client in Rust Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md Demonstrates how to build a Claude client with custom settings such as model, system prompt, stream format, and timeout. It then queries Claude and displays the response along with metadata like session ID, cost, and token usage. ```Rust use claude_ai::{Client, StreamFormat}; use std::time::Duration; #[tokio::main] async fn main() -> claude_ai::Result<()> { // Build a client with specific settings let client = Client::builder() .model("claude-sonnet-4-20250514") // Faster model .system_prompt("You are a Rust programming expert. Be concise.") .stream_format(StreamFormat::Json) // Get structured responses .timeout(Duration::from_secs(45)) // 45 second timeout .build(); // Ask a Rust-specific question let response = client .query("What are the key differences between &str and String in Rust?") .send_full() // Get full response with metadata .await?; // Display response and metadata println!("Answer: {}", response.content); if let Some(metadata) = response.metadata { println!("\n--- Response Details ---"); println!("Session ID: {}", metadata.session_id); if let Some(cost) = metadata.cost_usd { println!("Cost: ${:.6}", cost); } if let Some(tokens) = metadata.tokens_used { println!("Tokens used: {} input, {} output", tokens.input_tokens.unwrap_or(0), tokens.output_tokens.unwrap_or(0) ); } } Ok(()) } ``` -------------------------------- ### Claude SDK Rust: Running Examples with Features Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/FEATURE_FLAGS.md This Bash script provides commands to run various examples included with `claude-sdk-rs`, demonstrating how to execute core examples and those requiring specific features like `cli` and `analytics`. It also shows how to list available examples. ```bash # Core examples (no features needed) cargo run --example basic_usage cargo run --example streaming cargo run --example session_management # CLI examples cargo run --example cli_interactive --features cli cargo run --example cli_analytics --features analytics # Check available examples find examples -name "*.rs" | grep -E "(cli_|analytics_)" ``` -------------------------------- ### Initialize claude-sdk-rs Client (Rust) Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/tutorials/01-getting-started.md Snippet showing the initialization of a new `claude-sdk-rs` client using the default configuration, which is the first step for interacting with Claude AI. ```rust let client = Client::new(Config::default()); ``` -------------------------------- ### Troubleshoot 'Claude binary not found' Error Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/QUICK_START.md This snippet provides commands to diagnose and resolve the 'Claude binary not found' error. It guides users to verify the Claude CLI installation and provides the command for reinstallation if needed. ```bash # Make sure Claude CLI is installed claude --version # If not found, reinstall with: npm install -g @anthropic-ai/claude-code ``` -------------------------------- ### Create Minimal Reproducible Example for Claude SDK for Rust Issues Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/TROUBLESHOOTING.md This Rust code provides a template for creating a minimal, self-contained example to reproduce issues encountered with the `claude-sdk-rs` client. It demonstrates how to initialize the client and handle potential errors, aiding in effective bug reporting. ```Rust // Create a minimal example that reproduces your issue use claude_ai::{Client, Config}; #[tokio::main] async fn main() -> Result<(), Box> { // Reproduce the issue with minimal code let client = Client::new(Config::default()); match client.query("Your problematic query here").send().await { Ok(response) => println!("Success: {}", response), Err(e) => { eprintln!("Error: {:?}", e); eprintln!("Error type: {}", std::any::type_name_of_val(&e)); } } Ok(()) } ``` -------------------------------- ### Add claude-sdk-rs and Tokio Dependencies Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md Configuration for `Cargo.toml` to include `claude-sdk-rs`, `tokio` (with full features), and optional `dotenv`, `serde`, `serde_json` for environment variables and JSON handling. ```TOML [dependencies] claude-sdk-rs = "1.0.0" tokio = { version = "1.40", features = ["full"] } # Optional: for environment variables dotenv = "0.15" # Optional: for JSON handling serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" ``` -------------------------------- ### Build Claude AI Query with Fluent API in Rust Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md Illustrates the fluent API for constructing queries to the Claude API, including setting a session ID before sending the request. ```Rust client.query("Your prompt here") .session_id("optional-session-id") .send() .await? ``` -------------------------------- ### Load client configuration from environment variables (Rust) Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md Shows how to create a `Client` instance by reading configuration parameters like model name and timeout from environment variables. This pattern provides flexibility and avoids hardcoding sensitive or environment-specific settings. ```Rust use claude_ai::{Client, StreamFormat}; use std::env; fn create_client_from_env() -> Client { Client::builder() .model(env::var("CLAUDE_MODEL").unwrap_or_else(|_| "claude-sonnet-4-20250514".to_string())) .timeout(env::var("CLAUDE_TIMEOUT") .ok() .and_then(|s| s.parse().ok()) .unwrap_or(30)) .build() } ``` -------------------------------- ### Examples of claude-sdk-rs CLI Commands Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/FEATURE_FLAGS.md Demonstrates various command-line operations including interactive mode, direct queries, session management, and configuration settings. ```bash claude-sdk-rs claude-sdk-rs query "What is Rust?" claude-sdk-rs sessions list claude-sdk-rs sessions new "My coding session" claude-sdk-rs config show claude-sdk-rs config set model claude-3-sonnet-20240229 ``` -------------------------------- ### Build and Install claude-sdk-rs CLI Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/FEATURE_FLAGS.md Commands to build the claude-sdk-rs project with CLI support and install the CLI binary globally for direct use. ```bash cargo build --features cli cargo install claude-sdk-rs --features cli claude-sdk-rs --help ``` -------------------------------- ### Rust Documentation Test Example Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/TESTING.md Shows how to embed executable examples directly within Rust documentation comments. These examples are automatically compiled and run as part of the test suite, ensuring documentation stays up-to-date and correct. ```rust /// # Example /// ``` /// use claude_ai::Client; /// let client = Client::new(Default::default()); /// ``` ``` -------------------------------- ### Update Claude Client Configuration with New Features Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/MIGRATION.md Provides a comprehensive example of updating a basic `claude-sdk-rs` client configuration to incorporate multiple new features, including appending system prompts, limiting conversation turns, setting granular allowed and disallowed tools, and controlling permission prompts. This showcases how to integrate the new functionalities into an existing setup. ```Rust use claude_sdk_rs::{Client, StreamFormat}; let client = Client::builder() .model("claude-3-sonnet-20240229") .system_prompt("You are a code reviewer.") .stream_format(StreamFormat::Json) .timeout_secs(60) .build(); ``` ```Rust use claude_sdk_rs::{Client, StreamFormat, ToolPermission}; let client = Client::builder() .model("claude-3-sonnet-20240229") .system_prompt("You are a code reviewer.") .append_system_prompt("Focus on security and performance.") // NEW .stream_format(StreamFormat::Json) .timeout_secs(60) .max_turns(10) // NEW: Limit review conversation .allowed_tools(vec![ // ENHANCED: Granular permissions ToolPermission::bash("git diff").to_cli_format(), ToolPermission::bash("cargo clippy").to_cli_format(), ToolPermission::mcp("filesystem", "read").to_cli_format(), ]) .disallowed_tools(vec![ // NEW: Block dangerous operations "Bash(rm)".to_string(), "Bash(sudo)".to_string(), ]) .skip_permissions(false) // NEW: Require explicit permissions .build(); ``` -------------------------------- ### Check and Update Rust Version Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md Commands to verify the installed Rust version and update it to the latest stable release using `rustup`. ```Bash # Check your Rust version rustc --version # Update Rust if needed rustup update stable ``` -------------------------------- ### Verify Claude CLI installation and version Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/TROUBLESHOOTING.md These bash commands verify that the Claude CLI is correctly installed and accessible in the system's PATH. `which claude` shows the binary location, and `claude --version` confirms its installed version. ```bash which claude claude --version ``` -------------------------------- ### Verify Claude CLI Installation and Authentication (Bash) Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/TROUBLESHOOTING.md Before running integration tests, ensure the Claude CLI is correctly installed and authenticated. Use `claude --version` to check installation and `claude auth` to confirm authentication status. ```Bash claude --version claude auth ``` -------------------------------- ### Troubleshoot 'Binary not found' Error for Claude CLI Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md This snippet provides commands to diagnose and resolve the 'Binary not found' error when using the Claude CLI. It shows how to verify the CLI installation and how to add its path to the system's PATH environment variable if necessary. ```bash # Verify Claude CLI is installed which claude # Add to PATH if needed export PATH="$PATH:/path/to/claude" ``` -------------------------------- ### Implement Robust Error Handling for Claude API in Rust Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md Provides an example of robust error handling for Claude API interactions. It demonstrates using a `match` statement to handle various `claude_ai::Error` types, including timeouts, authentication issues, and process failures. ```Rust use claude_ai::{Client, Config, Error}; use std::time::Duration; #[tokio::main] async fn main() { let client = Client::builder() .timeout(Duration::from_secs(5)) // Short timeout for demo .build(); match execute_query(&client).await { Ok(response) => println!("Success: {}", response), Err(e) => handle_error(e), } } async fn execute_query(client: &Client) -> claude_ai::Result { client .query("Explain quantum computing in detail") .send() .await } fn handle_error(error: Error) { match error { Error::Timeout => { eprintln!("Request timed out. Try a shorter query or increase timeout."); } Error::ClaudeNotAuthenticated => { eprintln!("Not authenticated. Run: claude auth login"); } Error::ClaudeNotFound => { eprintln!("Claude CLI not found. Please install it first."); } Error::ProcessFailed { exit_code, stderr } => { eprintln!("Claude returned an error (code {}): {}", exit_code, stderr); } Error::SerializationError(e) => { eprintln!("Failed to parse response: {}", e); } _ => { eprintln!("Unexpected error: {:?}", error); } } } ``` -------------------------------- ### Run First Claude Query Application Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/QUICK_START.md Command to compile and execute the Rust application that sends a query to Claude, demonstrating how to run your `claude-sdk-rs` project. ```bash cargo run ``` -------------------------------- ### Select appropriate Claude model based on task type (Rust) Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md Provides an example of how to choose a specific Claude model (Haiku, Sonnet, Opus) based on the task's requirements. This allows for optimization of cost and performance by selecting the most suitable model for simple, complex, or creative tasks. ```Rust enum TaskType { Simple, // Quick responses Complex, // Deep analysis Creative, // Creative writing } fn select_model(task: TaskType) -> &'static str { match task { TaskType::Simple => "claude-haiku-3-20250307", // Fast and cheap TaskType::Complex => "claude-sonnet-4-20250514", // Balanced TaskType::Creative => "claude-opus-4-20250514", // Most capable } } ``` -------------------------------- ### Send Claude Query using Builder Pattern Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/QUICK_START.md Illustrates the recommended builder pattern for sending queries, which offers greater flexibility for per-query customizations like sessions or formats. ```rust let response = client.query("Hello Claude!").send().await?; ``` -------------------------------- ### Resolve Claude CLI Authentication Failures Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md This snippet provides commands to check the authentication status and re-authenticate with the Claude CLI. It guides users through logging out and then logging back in to resolve authentication issues. ```bash # Check auth status claude auth status # Re-authenticate claude auth logout claude auth login ``` -------------------------------- ### Send a Basic Query to Claude AI (Rust) Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/tutorials/01-getting-started.md Demonstrates how to initialize the `claude-sdk-rs` client with default configuration and send a simple text query to Claude AI, printing the received response. ```rust use claude_sdk_rs::{Client, Config}; #[tokio::main] async fn main() -> Result<(), Box> { // Initialize the client with default configuration let client = Client::new(Config::default()); // Send a simple query let response = client.query("What is 2 + 2?").send().await?; println!("Response: {}", response); Ok(()) } ``` -------------------------------- ### Send Claude Query using Direct Method Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/QUICK_START.md Shows the simpler direct method for sending basic queries, primarily useful for straightforward interactions and backward compatibility. ```rust let response = client.send("Hello Claude!").await?; ``` -------------------------------- ### Manage Conversation Sessions with Claude in Rust Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md Illustrates how to maintain conversation context across multiple queries using session IDs. It shows starting a new session and sending follow-up messages within the same session to preserve continuity. ```Rust use claude_ai::{Client, Config}; use claude_ai_core::session::SessionId; #[tokio::main] async fn main() -> claude_ai::Result<()> { let client = Client::new(Config::default()); // Start a new session let session_id = SessionId::new(); // First message let response1 = client .query("My name is Alice and I'm learning Rust.") .session_id(&session_id) .send() .await?; println!("Claude: {}\n", response1); // Follow-up message in same session let response2 = client .query("What's my name and what am I learning?") .session_id(&session_id) .send() .await?; println!("Claude: {}", response2); Ok(()) } ``` -------------------------------- ### Enable Debug Output for Claude SDK in Rust Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md This Rust snippet shows how to enable debug logging for the `claude-ai` SDK. By setting the `RUST_LOG` environment variable and initializing `env_logger`, developers can get detailed debug information for troubleshooting. ```rust use claude_ai::{Client, Config}; // Set environment variable std::env::set_var("RUST_LOG", "claude_ai=debug"); // Initialize logging env_logger::init(); // Your code will now output debug information ``` -------------------------------- ### Clone and Setup Claude SDK Rust Repository (Bash) Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/TROUBLESHOOTING.md To begin development, clone the Claude SDK Rust repository from GitHub and navigate into the project directory. This is the initial step for setting up the development environment. ```Bash git clone https://github.com/bredmond1019/claude-sdk-rust.git cd claude-sdk-rust ``` -------------------------------- ### Increase Query Timeout (Rust) Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/tutorials/01-getting-started.md Example of configuring the `claude-sdk-rs` client to increase the operation timeout, which can prevent timeout errors for complex or long-running Claude AI queries. ```rust let config = Config::builder().timeout_secs(120).build(); // 2 minutes let client = Client::new(config); ``` -------------------------------- ### Configure Client with Builder Pattern (Rust) Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/tutorials/01-getting-started.md Demonstrates using the builder pattern to create a `Config` object for the `claude-sdk-rs` client, allowing customization of settings like stream format and timeout duration before sending a query. ```rust use claude_sdk_rs::{Client, Config, StreamFormat}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::builder() .stream_format(StreamFormat::Json) .timeout_secs(60) // 60 second timeout .build(); let client = Client::new(config); let response = client.query("Hello, Claude!").send().await?; println!("Response: {}", response); Ok(()) } ``` -------------------------------- ### Rust: Configure Claude Client for Deployment Automation Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/tutorials/05-tool-integration.md Illustrates setting up the `claude-sdk-rs` client as a deployment assistant. It defines a system prompt and allows Bash tools for pre-deployment checks (`cargo test`, `cargo clippy`), building (`cargo build`), Docker operations (`docker build`, `docker push`), and Kubernetes deployment (`kubectl apply`, `kubectl get pods`). The example then sends a query to prepare an application for deployment, including running tests, checking warnings, building, and pushing a Docker image. ```Rust use claude_sdk_rs::{Client, Config, ToolPermission}; async fn create_deployment_assistant() -> Result<(), Box> { let config = Config::builder() .system_prompt( "You are a deployment assistant. You can run builds, \ execute tests, and deploy applications safely." ) .allowed_tools(vec![ // Pre-deployment checks ToolPermission::bash("cargo test").to_cli_format(), ToolPermission::bash("cargo clippy -- -D warnings").to_cli_format(), // Build ToolPermission::bash("cargo build --release").to_cli_format(), // Docker operations (if using Docker) ToolPermission::bash("docker build").to_cli_format(), ToolPermission::bash("docker push").to_cli_format(), // Deployment commands ToolPermission::bash("kubectl apply").to_cli_format(), ToolPermission::bash("kubectl get pods").to_cli_format(), ]) .build(); let client = Client::new(config); let response = client .query( "Prepare this application for deployment: \ 1. Run all tests \ 2. Check for any clippy warnings \ 3. Build the release version \ 4. If everything passes, build and push Docker image" ) .send() .await?; println!("Deployment Process:\n{}", response); Ok(()) } ``` -------------------------------- ### Run Claude SDK Rust Examples with Cargo Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/README.md This bash snippet provides commands to run various examples from the `claude-sdk-rs` project. It includes commands for basic examples, new features like system prompts, and examples that require specific feature flags such as `sqlite` for session persistence or `cli` for interactive CLI usage. ```bash # Basic examples cargo run --example basic_usage cargo run --example streaming # New features - advanced configuration cargo run --example system_prompts cargo run --example advanced_permissions # Examples requiring features cargo run --example session_persistence --features sqlite cargo run --example cli_interactive --features cli ``` -------------------------------- ### Verify Claude SDK Rust Prerequisites Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/TROUBLESHOOTING.md Commands to check the Rust compiler version, confirm Claude CLI installation, and ensure authentication status before starting development with the Claude SDK for Rust. ```bash rustc --version # Should be 1.70+ claude --version # Should be installed claude auth # Should be authenticated ``` -------------------------------- ### Stream Real-time Responses from Claude in Rust Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md Shows how to stream responses from Claude, allowing real-time processing of generated content. It uses `StreamExt` to iterate over chunks and flushes stdout for immediate display. ```Rust use claude_ai::{Client, StreamFormat}; use futures::StreamExt; #[tokio::main] async fn main() -> claude_ai::Result<()> { let client = Client::builder() .stream_format(StreamFormat::StreamJson) .build(); println!("Asking Claude to write a story...\n"); let mut stream = client .query("Write a short story about a robot learning to paint") .stream() .await?; // Process each chunk as it arrives while let Some(result) = stream.next().await { match result { Ok(message) => { // Print without newline for smooth streaming print!("{}", message.content); // Flush to ensure immediate output use std::io::{self, Write}; io::stdout().flush().unwrap(); } Err(e) => eprintln!("\nStream error: {}", e), } } println!("\n\nStory complete!"); Ok(()) } ``` -------------------------------- ### Configure claude-sdk-rs Client for New Features Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/MIGRATION.md Illustrates how to configure the `claude-sdk-rs` client with new features like appending system prompts, setting maximum turns, disallowing specific tools, and skipping permission checks for testing purposes. ```rust #[tokio::test] async fn test_new_features() { let client = Client::builder() .append_system_prompt("Test mode") .max_turns(3) .disallowed_tools(vec!["Bash(rm)".to_string()]) .skip_permissions(true) .build(); assert!(client.is_ok()); } ``` -------------------------------- ### Create reusable prompt templates (Rust) Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md Defines a `PromptTemplate` struct for creating reusable prompt strings with variable substitution. This pattern simplifies prompt management and ensures consistency across different API calls. ```Rust struct PromptTemplate { template: String, } impl PromptTemplate { fn new(template: &str) -> Self { Self { template: template.to_string() } } fn render(&self, vars: &[(&str, &str)]) -> String { let mut result = self.template.clone(); for (key, value) in vars { result = result.replace(&format!("{{{}}}", key), value); } result } } // Usage let template = PromptTemplate::new( "Analyze this {language} code for {focus}:\n\n```\n{code}\n```" ); let prompt = template.render(&[ ("language", "Rust"), ("focus", "memory safety"), ("code", &code_snippet), ]); ``` -------------------------------- ### Run Claude SDK Rust Examples Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/examples/README.md Commands to execute individual examples of the `claude-sdk-rs` SDK, run the complete application in different modes (chat, dev, analysis), and run the test suite for the project. ```bash # Run individual examples cargo run --example 01_basic_sdk cargo run --example 02_sdk_sessions cargo run --example 03_streaming cargo run --example 04_tools cargo run --example 05_complete_app # Run the complete app with different modes cargo run --example 05_complete_app chat cargo run --example 05_complete_app dev cargo run --example 05_complete_app analysis # Run tests cargo test ``` -------------------------------- ### Increase Client Timeout for Claude SDK in Rust Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md This Rust snippet demonstrates how to configure the Claude client to increase the timeout duration. This is useful for complex queries that might require more time to process, preventing premature timeout errors. ```rust // Increase timeout for complex queries let client = Client::builder() .timeout(120) // 2 minutes .build(); ``` -------------------------------- ### Warm Up System Before Benchmarking (Bash) Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/PERFORMANCE.md Explains how to use the `--warm-up-time` flag with `cargo bench` to allow the system to stabilize before actual benchmark measurements begin, ensuring more consistent results. ```Bash cargo bench -- --warm-up-time 3 ``` -------------------------------- ### Retrieve Claude Response with Metadata Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/QUICK_START.md Rust example showing how to configure the client to receive responses in JSON format and use `send_full()` to obtain complete response data, including metadata like session ID, model, cost, and token usage. ```rust use claude_sdk_rs::{Client, StreamFormat}; #[tokio::main] async fn main() -> Result<(), claude_sdk_rs::Error> { // Enable JSON format to get metadata let client = Client::builder() .stream_format(StreamFormat::Json) .build(); // Use send_full() to get complete response with metadata let response = client .query("Write a haiku about programming") .send_full() .await?; println!("Response: {}", response.content); if let Some(metadata) = response.metadata { println!("\nMetadata:"); println!(" Session ID: {}", metadata.session_id); println!(" Model: {}", metadata.model); if let Some(cost) = metadata.cost_usd { println!(" Cost: ${:.6}", cost); } if let Some(tokens) = metadata.tokens_used { println!(" Tokens: {} input, {} output", tokens.input, tokens.output); } } Ok(()) } ``` -------------------------------- ### Git Repository Setup and Branching Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/CONTRIBUTING.md Commands for forking, cloning, and creating new branches for development on the `claude-sdk-rs` repository. ```bash git clone https://github.com/YOUR_USERNAME/claude-sdk-rs.git git checkout -b feature/your-feature-name ``` -------------------------------- ### Process multiple API queries concurrently (Rust) Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/GETTING_STARTED.md Demonstrates how to send multiple API queries in parallel using `futures::future::join_all`. This approach significantly improves performance when processing a batch of requests simultaneously, reducing overall latency. ```Rust use futures::future::join_all; async fn batch_query(client: &Client, queries: Vec) -> Vec> { let futures = queries.into_iter() .map(|q| client.query(&q).send()) .collect::>(); join_all(futures).await } ``` -------------------------------- ### Claude SDK Rust: Initial Dependency Configuration (Failing) Source: https://github.com/bredmond1019/claude-sdk-rs/blob/main/docs/FEATURE_FLAGS.md This TOML snippet shows the initial dependency configuration for `claude-sdk-rs` with the `mcp` feature, which is currently known to fail compilation due to unresolved imports and other issues. It serves as an example of a non-working setup. ```toml [dependencies] claude-sdk-rs = { version = "1.0", features = ["mcp"] } ```