### Run Rust Examples Source: https://github.com/realmorrisliu/openrouter-rs/blob/main/CLAUDE.md Commands to execute various examples for the OpenRouter Rust SDK, including chat completion, streaming, reasoning tokens, model listing, and API key/credit management. ```bash # Basic chat completion cargo run --example send_chat_completion # Streaming chat completion cargo run --example stream_chat_completion # Reasoning tokens (new in 0.4.5) cargo run --example chat_with_reasoning cargo run --example stream_chat_with_reasoning # Get model list cargo run --example list_models # List models by category cargo run --example list_models_by_category # Filter models by parameters cargo run --example list_models_by_parameters # API key management cargo run --example list_api_keys cargo run --example get_current_api_key_info # Credit management cargo run --example get_credits ``` -------------------------------- ### Run OpenRouter Examples Locally using Bash Source: https://github.com/realmorrisliu/openrouter-rs/blob/main/README.md Provides bash commands to set the OpenRouter API key as an environment variable and then run various example Cargo projects. These examples demonstrate basic chat completion, reasoning tokens, and streaming responses. ```bash # Set your API key export OPENROUTER_API_KEY="your_key_here" # Basic chat completion cargo run --example send_chat_completion # Reasoning tokens demo cargo run --example chat_with_reasoning # Streaming responses cargo run --example stream_chat_completion # Run with reasoning cargo run --example stream_chat_with_reasoning ``` -------------------------------- ### Install OpenRouter Rust SDK Source: https://github.com/realmorrisliu/openrouter-rs/blob/main/README.md Instructions for adding the openrouter-rs crate and tokio to your project's Cargo.toml file for dependency management. ```toml [dependencies] openrouter-rs = "0.4.5" tokio = { version = "1", features = ["full"] } ``` -------------------------------- ### Rust Chat Completion with Reasoning Tokens Source: https://github.com/realmorrisliu/openrouter-rs/blob/main/CLAUDE.md Example of building a chat completion request with reasoning capabilities, setting `reasoning_effort` and `reasoning_max_tokens`, and then sending the request and printing the reasoning and answer from the response. ```rust use openrouter_rs::types::Effort; let request = ChatCompletionRequest::builder() .model("deepseek/deepseek-r1") .messages(vec![Message::new(Role::User, "What's bigger: 9.9 or 9.11?")]) .reasoning_effort(Effort::High) .reasoning_max_tokens(1000) .build()?; let response = client.send_chat_completion(&request).await?; println!("Reasoning: {}", response.choices[0].reasoning().unwrap_or("")); println!("Answer: {}", response.choices[0].content().unwrap_or("")); ``` -------------------------------- ### Comprehensive Error Handling in OpenRouter Rust SDK Source: https://github.com/realmorrisliu/openrouter-rs/blob/main/README.md Provides examples of how to handle various errors that may occur when interacting with the OpenRouter API, including moderation errors, general API errors, and other potential issues. ```rust use openrouter_rs::error::OpenRouterError; // Assuming 'client' and 'request' are already initialized as in the Quick Start example // let request = ChatCompletionRequest::builder()...build()?; // match client.send_chat_completion(&request).await { // Ok(response) => println!("Success!"), // Err(OpenRouterError::ModerationError { reasons, .. }) => { // eprintln!("Content flagged: {:?}", reasons); // } // Err(OpenRouterError::ApiError { code, message }) => { // eprintln!("API error {}: {}", code, message); // } // Err(e) => eprintln!("Other error: {}", e), // } ``` -------------------------------- ### Build and Test Rust Project Source: https://github.com/realmorrisliu/openrouter-rs/blob/main/CLAUDE.md Commands to build the Rust project, run unit tests, integration tests (requires API key), and all tests. ```bash # Build project cargo build # Run unit tests cargo test --test unit # Run integration tests (requires API key) OPENROUTER_API_KEY=your_key cargo test --test integration -- --nocapture # Run all tests cargo test ``` -------------------------------- ### Create OpenRouter Client in Rust Source: https://github.com/realmorrisliu/openrouter-rs/blob/main/CLAUDE.md Demonstrates how to create an instance of the `OpenRouterClient` using the builder pattern, setting the API key and other optional HTTP headers like `http-referer` and `x-title`. ```rust let client = OpenRouterClient::builder() .api_key("your_api_key") .http_referer("https://yourdomain.com") .x_title("Your App Name") .build()?; ``` -------------------------------- ### Using Smart Model Presets in OpenRouter Rust SDK Source: https://github.com/realmorrisliu/openrouter-rs/blob/main/README.md Demonstrates how to use predefined model presets (programming, reasoning, free) provided by the `OpenRouterConfig` to easily access curated groups of models. ```rust use openrouter_rs::config::OpenRouterConfig; let config = OpenRouterConfig::default(); // Three built-in presets: // • programming: Code generation and development // • reasoning: Advanced problem-solving models // • free: Free-tier models for experimentation println!("Available models: {:?}", config.get_resolved_models()); ``` -------------------------------- ### Basic Chat Completion with OpenRouter Rust SDK Source: https://github.com/realmorrisliu/openrouter-rs/blob/main/README.md Demonstrates how to create an OpenRouterClient, build a chat completion request with a specific model and user message, send the request, and print the response content. Requires an API key. ```rust use openrouter_rs::{OpenRouterClient, api::chat::*}; use openrouter_rs::types::Role; #[tokio::main] async fn main() -> Result<(), Box> { // Create client let client = OpenRouterClient::builder() .api_key("your_api_key") .build()?; // Send chat completion let request = ChatCompletionRequest::builder() .model("anthropic/claude-sonnet-4") .messages(vec![ Message::new(Role::User, "Explain Rust ownership in simple terms") ]) .build()?; let response = client.send_chat_completion(&request).await?; println!("{}", response.choices[0].content().unwrap_or("")); Ok(()) } ``` -------------------------------- ### Configure OpenRouter Client in Rust Source: https://github.com/realmorrisliu/openrouter-rs/blob/main/README.md Shows how to build and configure an `OpenRouterClient` instance with custom settings. This includes setting the API key, HTTP referer, a custom X-Title header, and an alternative base URL for the API endpoint. ```rust let client = OpenRouterClient::builder() .api_key("your_key") .http_referer("https://yourapp.com") .x_title("My AI App") .base_url("https://openrouter.ai/api/v1") // Custom endpoint .build()?; ``` -------------------------------- ### Real-time Streaming with OpenRouter Rust SDK Source: https://github.com/realmorrisliu/openrouter-rs/blob/main/README.md Illustrates how to stream chat completion responses using the `stream_chat_completion` method. It processes the stream chunk by chunk, printing the content as it arrives. ```rust use futures_util::StreamExt; // Assuming 'client' and 'request' are already initialized as in the Quick Start example // let request = ChatCompletionRequest::builder()...build()?; // let stream = client.stream_chat_completion(&request).await?; // stream // .filter_map(|event| async { event.ok() }) // .for_each(|chunk| async move { // if let Some(content) = chunk.choices[0].content() { // print!("{}", content); // Print as it arrives // } // }) // .await; ``` -------------------------------- ### Load API Key from Environment Variable (Rust) Source: https://github.com/realmorrisliu/openrouter-rs/blob/main/CLAUDE.md Demonstrates how to securely load an API key from environment variables using the `dotenvy_macro::dotenv!` macro, preventing hardcoding. ```Rust dotenvy_macro::dotenv!("OPENROUTER_API_KEY"); let api_key = std::env::var("OPENROUTER_API_KEY").expect("OPENROUTER_API_KEY must be set"); ``` -------------------------------- ### Advanced Reasoning with OpenRouter Rust SDK Source: https://github.com/realmorrisliu/openrouter-rs/blob/main/README.md Shows how to configure a chat completion request to utilize advanced reasoning capabilities by setting `reasoning_effort` and `reasoning_max_tokens`. It also demonstrates accessing both the reasoning output and the final answer from the response. ```rust use openrouter_rs::types::Effort; use openrouter_rs::api::chat::ChatCompletionRequest; // Assuming 'client' and 'request' are already initialized as in the Quick Start example // let request = ChatCompletionRequest::builder()...build()?; let request_with_reasoning = ChatCompletionRequest::builder() .model("deepseek/deepseek-r1") .messages(vec![Message::new(Role::User, "What's bigger: 9.9 or 9.11?")]) .reasoning_effort(Effort::High) // Enable deep reasoning .reasoning_max_tokens(2000) // Control reasoning depth .build()?; // let response = client.send_chat_completion(&request_with_reasoning).await?; // Access both reasoning and final answer // println!("🧠 Reasoning: {}", response.choices[0].reasoning().unwrap_or("")); // println!("šŸ’” Answer: {}", response.choices[0].content().unwrap_or("")); ``` -------------------------------- ### Format and Check Rust Code Source: https://github.com/realmorrisliu/openrouter-rs/blob/main/CLAUDE.md Commands for formatting Rust code using `cargo fmt`, checking code for compilation errors with `cargo check`, and performing linting with `cargo clippy`. ```bash # Format code cargo fmt # Check code cargo check # Clippy linting cargo clippy ``` -------------------------------- ### Stream Chat Completion with Reasoning in Rust Source: https://github.com/realmorrisliu/openrouter-rs/blob/main/README.md Illustrates how to stream chat completion responses from the OpenRouter API, specifically handling and displaying 'reasoning' tokens alongside the main content. It processes chunks from the stream, buffering and printing both reasoning and content as they arrive. ```rust let stream = client.stream_chat_completion( &ChatCompletionRequest::builder() .model("anthropic/claude-sonnet-4") .messages(vec![Message::new(Role::User, "Solve this step by step: 2x + 5 = 13")]) .reasoning_effort(Effort::High) .build()? ).await?; let mut reasoning_buffer = String::new(); let mut content_buffer = String::new(); stream.filter_map(|event| async { event.ok() }) .for_each(|chunk| async { if let Some(reasoning) = chunk.choices[0].reasoning() { reasoning_buffer.push_str(reasoning); print!("🧠"); // Show reasoning progress } if let Some(content) = chunk.choices[0].content() { content_buffer.push_str(content); print!("šŸ’¬"); // Show content progress } }).await; println!("\n🧠 Reasoning: {}", reasoning_buffer); println!("šŸ’” Answer: {}", content_buffer); ``` -------------------------------- ### Build Chat Completion Request in Rust Source: https://github.com/realmorrisliu/openrouter-rs/blob/main/CLAUDE.md Shows how to construct a `ChatCompletionRequest` using the builder pattern, specifying the model, messages, temperature, and max tokens. ```rust let request = ChatCompletionRequest::builder() .model("anthropic/claude-sonnet-4") .messages(vec![Message::new(Role::User, "Hello")]) .temperature(0.7) .max_tokens(200) .build()?; ``` -------------------------------- ### Filter Models by Category in Rust Source: https://github.com/realmorrisliu/openrouter-rs/blob/main/README.md Demonstrates how to list available models from the OpenRouter API, filtered by a specific category like 'Programming'. It utilizes the `list_models_by_category` method and expects a successful API response. ```rust use openrouter_rs::types::ModelCategory; let models = client .list_models_by_category(ModelCategory::Programming) .await?; println!("Found {} programming models", models.len()); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.