Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
OpenRouter API Client Library
A production-ready Rust client for the OpenRouter API with comprehensive security, ergonomic design, and extensive testing. The library uses a type‑state builder pattern for compile-time configuration validation, ensuring robust and secure API interactions.
Features
🏗️ Architecture & Safety
- Type‑State Builder Pattern: Compile-time configuration validation ensures all required settings are provided before making requests
- Secure Memory Management: API keys are automatically zeroed on drop using the
zeroizecrate for enhanced security - Comprehensive Error Handling: Centralized error management with safe error message redaction to prevent sensitive data leakage
- Modular Organization: Clean separation of concerns across modules for models, API endpoints, types, and utilities
🚀 Ergonomic API Design
- Convenient Constructors: Quick setup with
from_api_key(),from_env(),quick(), andproduction()methods - Flexible Configuration: Fluent builder pattern with timeout, retry, and header configuration
- Environment Integration: Automatic API key loading from
OPENROUTER_API_KEYorOR_API_KEYenvironment variables
🔒 Security & Reliability
- Standardized Error Handling: Enterprise-grade retry logic with exponential backoff and jitter across all endpoints
- Memory Safety: Secure API key handling with automatic memory zeroing
- Response Redaction: Automatic sanitization of error messages to prevent sensitive data exposure
- Bounded Response Reading: Strict, configurable size limits on response body reading to prevent OOM attacks (default 10MB)
- Streaming Safety: Buffer limits and backpressure handling for streaming responses
- Input Validation: Comprehensive validation of requests and parameters
- Automatic Retries: Configurable retry behavior for network failures and rate limiting
- Production Reliability: Enterprise-grade error handling with exponential backoff and jitter
🌐 OpenRouter API Support
- Chat Completions: Full support for OpenRouter's chat completion API with streaming
- Text Completions: Traditional text completion endpoint with customizable parameters
- Tool Calling: Define and invoke function tools with proper validation
- Structured Outputs: JSON Schema validation for structured response formats
- Web Search: Type-safe web search API integration
- Provider Preferences: Configure model routing, fallbacks, and provider selection
- Analytics API: Comprehensive activity data retrieval with filtering and pagination
- Providers API: Provider information management with search and filtering
- Enhanced Models API: Advanced model discovery with filtering, sorting, and search
- Multimodal Support: Audio and File (PDF) input support
- Policy Controls: Granular routing control with allow/deny lists and Zero Data Retention (ZDR)
📡 Model Context Protocol (MCP)
- MCP Client: Full JSON-RPC client implementation for the Model Context Protocol
- Resource Access: Retrieve resources from MCP servers
- Tool Invocation: Execute tools provided by MCP servers
- Context Integration: Seamless context sharing between applications and LLMs
- Concurrency Control: Semaphore-based limiting for concurrent requests
- Secure ID Generation: UUID v4 usage for request tracking
🧪 Quality & Testing
- 100% Test Coverage: 162 comprehensive unit and integration tests
- CI/CD Pipeline: Automated quality gates with formatting, linting, security audits, and documentation checks
- Production Ready: Extensive error handling, standardized retry logic, and timeout management
Getting Started
Installation
Add the following to your project's Cargo.toml:
# With optional tracing support for better error logging
Available Features:
rustls(default): Use rustls for TLSnative-tls: Use system TLStracing: Enhanced error logging with tracing support
Ensure that you have Rust installed (tested with Rust v1.83.0) and that you're using Cargo for building and testing.
Quick Start Examples
Simple Chat Completion
use ;
use ;
async
Multimodal Chat (Audio & PDF)
use ;
use ;
async
Routing Shortcuts & Web Search
use ;
use ;
async
Production Configuration
use ;
async
Custom Configuration
use ;
use Duration;
async
Provider Preferences Example
use ;
use ;
use ;
use json;
async
Model Context Protocol (MCP) Client Example
use ;
use ;
async
Text Completion Example
use ;
use CompletionRequest;
use json;
async
Streaming Chat Example
use ;
use ;
use StreamExt;
use Write;
async
Analytics API Example
use ;
use ;
async
Providers API Example
use ;
use ;
async
Enhanced Models API Example
use ;
use ;
async
Model Context Protocol (MCP) Client
The library includes a client implementation for the Model Context Protocol, which is an open protocol that standardizes how applications provide context to LLMs.
Key features of the MCP client include:
- JSON-RPC Communication: Implements the JSON-RPC 2.0 protocol for MCP
- Resource Access: Retrieve resources from MCP servers
- Tool Invocation: Call tools provided by MCP servers
- Prompt Execution: Execute prompts on MCP servers
- Server Capabilities: Discover and leverage server capabilities
- Proper Authentication: Handle initialization and authentication flows
// Create an MCP client connected to a server
let client = new?;
// Initialize with client capabilities
let server_capabilities = client.initialize.await?;
// Access resources from the server
let resource = client.get_resource.await?;
See the Model Context Protocol specification for more details.
Implementation Status
This is a production-ready library with comprehensive functionality:
✅ Core Features (Completed)
- Client Framework: Type‑state builder pattern with compile‑time validation
- Security: Secure API key handling with memory zeroing and error redaction
- Chat Completions: Full OpenRouter chat API support with streaming
- Text Completions: Traditional text completion endpoint
- Web Search: Integrated web search capabilities
- Tool Calling: Function calling with validation
- Structured Outputs: JSON Schema validation
- Provider Preferences: Model routing and fallback configuration
- Analytics API: Comprehensive activity data retrieval with filtering and pagination
- Providers API: Provider information management with search and filtering
- Enhanced Models API: Advanced model discovery with filtering, sorting, and search
- Credits API: Account credit and usage tracking
- Generation API: Generation metadata and cost tracking
- Model Context Protocol: Complete MCP client implementation
✅ Quality Infrastructure (Completed)
- 100% Test Coverage: 162 comprehensive unit and integration tests
- Security Auditing: Automated security vulnerability scanning
- CI/CD Pipeline: GitHub Actions with quality gates
- Documentation: Complete API documentation with examples
- Developer Experience: Contributing guidelines, issue templates, PR templates
- Error Handling Standardization: Enterprise-grade retry logic across all endpoints
✅ Ergonomic Improvements (Completed)
- Convenience Constructors:
from_env(),from_api_key(),production(),quick() - Flexible Configuration: Timeout, retry, and header management
- Error Handling: Comprehensive error types with context and automatic retries
- Memory Safety: Automatic sensitive data cleanup
- Advanced Filtering: Sophisticated query builders for analytics, providers, and models
- Convenience Methods: Helper methods for common operations like domain extraction
- Production Reliability: Exponential backoff with jitter, rate limit handling, and consistent retry behavior
- Retry-After Support: Respects server-provided retry guidance (headers) for rate limiting
🔄 Future Enhancements
- Circuit Breaker Pattern: Prevent cascading failures
- Retry Budget Management: Prevent excessive retries in high-throughput scenarios
- Performance Optimizations: Connection pooling and caching
- Extended MCP Features: Additional MCP protocol capabilities
- Generation API Enhancements: Additional generation endpoints and features
Contributing
Contributions are welcome! Please open an issue or submit a pull request with your ideas or fixes. Follow the code style guidelines and ensure that all tests pass.
License
Distributed under either the MIT license or the Apache License, Version 2.0. See LICENSE for details.
OpenRouter API Rust Crate Documentation
Version: 0.1.6 • License: MIT / Apache‑2.0
The openrouter_api crate is a comprehensive client for interacting with the OpenRouter API and Model Context Protocol servers. It provides strongly‑typed endpoints for chat completions, text completions, web search, and MCP connections. The crate is built using asynchronous Rust and leverages advanced patterns for safe and flexible API usage.
Table of Contents
- Core Concepts
- Installation
- Architecture & Module Overview
- Client Setup & Type‑State Pattern
- API Endpoints
- Error Handling
- Best Practices
- Examples
- Additional Resources
Core Concepts
-
Type‑State Client Configuration: The client is built using a type‑state pattern to ensure that required parameters are set before making any API calls.
-
Provider Preferences: Strongly-typed configuration for model routing, fallbacks, and provider selection.
-
Asynchronous Streaming: Support for streaming responses via asynchronous streams.
-
Model Context Protocol: Client implementation for connecting to MCP servers to access resources, tools, and prompts.
-
Error Handling & Validation: Comprehensive error handling with detailed context and validation utilities.
Architecture & Module Overview
The crate is organized into several modules:
client: Type-state client implementation with builder patternapi: API endpoint implementations (chat, completions, web search, etc.)models: Domain models for structured outputs, provider preferences, toolstypes: Type definitions for requests and responsesmcp: Model Context Protocol client implementationerror: Centralized error handlingutils: Utility functions and helpers
Client Setup & Type‑State Pattern
// Quick setup (recommended for most use cases)
let client = from_env?;
// Production setup with optimized settings
let client = production?;
// Full control with type-state pattern
let client = new
.with_base_url?
.with_timeout
.with_http_referer
.with_api_key?;
API Endpoints
Chat Completions
// Basic chat completion
let response = client.chat?.chat_completion.await?;
Tool Calling
// Define a function tool
let weather_tool = Function ;
// Make a request with tool calling enabled
let response = client.chat?.chat_completion.await?;
Model Context Protocol
// Create an MCP client
let mcp_client = new?;
// Initialize with client capabilities
let server_capabilities = mcp_client.initialize.await?;
// Access a resource from the MCP server
let resource = mcp_client.get_resource.await?;
Error Handling
The library provides enterprise-grade error handling with automatic retries and consistent behavior across all endpoints.
Standardized Retry Logic
All API endpoints automatically retry failed requests with:
- Exponential Backoff: Starting at 500ms, doubling up to 10 seconds maximum
- Jitter: ±25% random variation to prevent thundering herd effects
- Smart Status Codes: Retries on rate limiting (429) and server errors (500, 502, 503, 504)
- Configurable Limits: Customizable maximum retries and backoff settings
use ;
// Custom retry configuration
let client = from_env?
.with_retry_config?;
// Automatic retries happen transparently
let response = client.chat?.chat_completion.await?;
Error Types
match client.chat?.chat_completion.await
Retry Behavior
The library automatically handles:
- Network Timeouts: Retries with increasing delays
- Rate Limiting: Respects HTTP 429 with exponential backoff
- Server Errors: Retries 5xx errors to handle temporary failures
- Connection Issues: Retries connection failures and DNS errors
All retry attempts are logged with operation context for debugging:
Retrying chat_completion request (1/3) after 625 ms (base: 500 ms, jitter: 25.00%) due to status code 429
Retrying chat_completion request (2/3) after 1250 ms (base: 1000 ms, jitter: 25.00%) due to status code 429
Best Practices
-
Use the Type‑State Pattern: Let the compiler ensure your client is properly configured.
-
Configure Retry Behavior: Adjust retry settings based on your application's needs:
let client = from_env? .with_retries? // More retries for resilience .without_retries?; // Disable for testing -
Set Appropriate Timeouts & Headers: Configure reasonable timeouts and identify your application.
-
Handle Errors Appropriately: Implement proper error handling for each error type. The automatic retry logic handles most transient failures.
-
Use Provider Preferences: Configure provider routing for optimal model selection.
-
Monitor Retry Behavior: Watch retry logs in production to identify patterns and adjust configuration.
-
Secure Your API Keys: Store keys in environment variables or secure storage.