OpenRouter Rust SDK
A type-safe, async Rust SDK for the OpenRouter API - Access 200+ AI models with ease
π Documentation | π― Examples | π¦ Crates.io
π What makes this special?
- π Type Safety: Leverages Rust's type system for compile-time error prevention
- β‘ Async/Await: Built on
tokiofor high-performance concurrent operations - π§ Reasoning Tokens: Industry-leading chain-of-thought reasoning support
- π οΈ Tool Calling: Function calling with typed tools and automatic JSON schema generation
- πΌοΈ Vision Support: Multi-modal content for image analysis with vision models
- π‘ Streaming: Real-time response streaming with
futures - π§© Unified Streaming Events: One event model across chat/responses/messages streams
- ποΈ Builder Pattern: Ergonomic client and request construction
- βοΈ Smart Presets: Curated model groups for programming, reasoning, and free tiers
- π― Complete Coverage: All OpenRouter API endpoints supported
π Quick Start
Installation
Add to your Cargo.toml:
[]
= "0.5.2"
= { = "1", = ["full"] }
30-Second Example
use ;
async
β¨ Key Features
π§ Domain-Oriented Client Surface
Use domain accessors for clearer API boundaries:
use PaginationOptions;
let response = client.chat.create.await?;
let models = client.models.list.await?;
let pagination = with_offset_and_limit;
let keys = client
.management
.list_api_keys
.await?;
Available domains:
client.chat()client.responses()client.messages()client.models()client.management()client.legacy()(requireslegacy-completionsfeature)
π§© Unified Streaming Events
use StreamExt;
use UnifiedStreamEvent;
let mut stream = client.chat.stream_unified.await?;
while let Some = stream.next.await
π§± Legacy Completions (Feature-Gated)
Legacy POST /completions support is isolated behind legacy-completions and explicit legacy namespace.
[]
= { = "0.5.2", = ["legacy-completions"] }
use ;
let request = builder
.model
.prompt
.build?;
let response = client.legacy.completions.create.await?;
Migration mapping:
api::completion::CompletionRequest->api::legacy::completion::CompletionRequestclient.send_completion_request(&request)->client.legacy().completions().create(&request)- Recommended modern path:
api::chat::ChatCompletionRequest+client.chat().create(...)
π 0.6 Naming/Pagination Migration
Full migration guide: MIGRATION.md
models().count()->models().get_model_count()models().list_for_user()->models().list_user_models()management().exchange_code_for_api_key(...)->management().create_api_key_from_auth_code(...)management().list_guardrails(offset, limit)->management().list_guardrails(Some(PaginationOptions::with_offset_and_limit(offset, limit)))management().list_api_keys(offset, include_disabled)->management().list_api_keys(Some(PaginationOptions::with_offset(offset)), include_disabled)
0.5.x transitional bridge (pre-0.6.0) keeps deprecated compatibility aliases with warnings:
Deprecated (0.5.x) |
Replacement |
|---|---|
OpenRouterClientBuilder::provisioning_key(...) |
OpenRouterClientBuilder::management_key(...) |
OpenRouterClient::set_provisioning_key(...) |
OpenRouterClient::set_management_key(...) |
OpenRouterClient::clear_provisioning_key() |
OpenRouterClient::clear_management_key() |
api::completion::* |
api::legacy::completion::* |
client.send_completion_request(&request) |
client.legacy().completions().create(&request) |
models().count() |
models().get_model_count() |
models().list_for_user() |
models().list_user_models() |
management().exchange_code_for_api_key(...) |
management().create_api_key_from_auth_code(...) |
list_api_keys(Some(offset_f64), ...) |
list_api_keys(Some(PaginationOptions::with_offset(offset_u32)), ...) |
Migration validation commands for contributors:
π§ Advanced Reasoning Support
Leverage chain-of-thought processing with reasoning tokens:
use Effort;
let request = builder
.model
.messages
.reasoning_effort // Enable deep reasoning
.reasoning_max_tokens // Control reasoning depth
.build?;
let response = client.chat.create.await?;
// Access both reasoning and final answer
println!;
println!;
π οΈ Tool Calling (Function Calling)
Define tools and let models call functions:
use Tool;
use json;
// Define a tool
let calculator = builder
.name
.description
.parameters
.build?;
// Send request with tools
let request = builder
.model
.messages
.tools
.build?;
let response = client.chat.create.await?;
// Handle tool calls
if let Some = response.choices.tool_calls
π§ Typed Tools with Auto Schema Generation
Use Rust structs for type-safe tool definitions:
use ;
use JsonSchema;
use ;
// Auto-generates JSON schema from struct
let request = builder
.model
.messages
.
.build?;
πΌοΈ Multi-Modal Vision Support
Send images for analysis with vision models:
use ContentPart;
let request = builder
.model
.messages
.build?;
π‘ Real-time Streaming
Process responses as they arrive:
use StreamExt;
let stream = client.chat.stream.await?;
stream
.filter_map
.for_each
.await;
βοΈ Smart Model Presets
Use curated model collections:
use OpenRouterConfig;
let config = default;
// Three built-in presets:
// β’ programming: Code generation and development
// β’ reasoning: Advanced problem-solving models
// β’ free: Free-tier models for experimentation
println!;
π‘οΈ Comprehensive Error Handling
use ;
match client.chat.create.await
π OAuth PKCE Flow
use ;
let client = builder
.api_key
.build?;
let create = builder
.callback_url
.code_challenge
.code_challenge_method
.build?;
let auth_code = client.management.create_auth_code.await?;
let key = client.management
.create_api_key_from_auth_code
.await?;
π API Coverage
| Feature | Status | Module |
|---|---|---|
| Domain-Oriented Client API | β | OpenRouterClient |
| Chat Completions | β | api::chat |
Legacy Text Completions (legacy-completions) |
β | api::legacy::completion |
| Tool Calling | β | api::chat |
| Typed Tools | β | types::typed_tool |
| Multi-Modal/Vision | β | api::chat |
| Reasoning Tokens | β | api::chat |
| Streaming Responses | β | api::chat |
| Unified Streaming Events | β | types::stream |
| Streaming Tool Calls | β | types::stream |
| Responses API | β | api::responses |
| Anthropic Messages API | β | api::messages |
| Provider/Activity Discovery | β | api::discovery |
| Guardrails | β | api::guardrails |
| Model Information | β | api::models |
| API Key Management | β | api::api_keys |
| Credit Management | β | api::credits |
| Authentication | β | api::auth |
/activity requires a management key; in this SDK set it with .management_key(...).
/guardrails* endpoints also require a management key; in this SDK set it with .management_key(...).
Management-key examples in this repo use OPENROUTER_MANAGEMENT_KEY.
π― More Examples
Filter Models by Category
use ModelCategory;
let models = client
.models
.list_by_category
.await?;
println!;
Advanced Client Configuration
let client = builder
.api_key
.http_referer
.x_title
.base_url // Custom endpoint
.build?;
Streaming with Reasoning
let stream = client.chat.stream.await?;
let mut reasoning_buffer = Stringnew;
let mut content_buffer = Stringnew;
stream.filter_map
.for_each.await;
println!;
println!;
π Documentation & Resources
- π API Documentation - Complete API reference
- π― Examples Repository - Comprehensive usage examples
- π§ Configuration Guide - Model presets and configuration
- β‘ OpenRouter API Docs - Official OpenRouter documentation
Run Examples Locally
# Set your API key
# Basic chat completion
# Domain-oriented chat client
# Tool calling (function calling)
# Typed tools with JSON schema generation
# Reasoning tokens demo
# Streaming responses
# Run with reasoning
# Streaming with tool calls
# Domain-oriented management client
# Legacy text completions (feature-gated)
Run CLI (Foundation)
# Show CLI help
# Show resolved profile/config/auth sources
CLI config priority is deterministic:
- flags (
--api-key,--management-key,--base-url) - environment (
OPENROUTER_API_KEY,OPENROUTER_MANAGEMENT_KEY,OPENROUTER_BASE_URL) - profile values in
profiles.toml - defaults
See crates/openrouter-cli/README.md for full config/profile conventions.
π€ Community & Support
π Found a Bug?
Please open an issue with:
- Your Rust version (
rustc --version) - SDK version you're using
- Minimal code example
- Expected vs actual behavior
π‘ Feature Requests
We love hearing your ideas! Start a discussion to:
- Suggest new features
- Share use cases
- Get help with implementation
π οΈ Contributing
Contributions are welcome! Please see our contributing guidelines:
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Follow the existing code style
- Submit a pull request
β Show Your Support
If this SDK helps your project, consider:
- β Starring the repository
- π¦ Sharing on social media
- π Writing about your experience
- π€ Contributing improvements
π Requirements
- Rust: 1.85+ (2024 edition)
- Tokio: 1.0+ (for async runtime)
- OpenRouter API Key: Get yours here
πΊοΈ Roadmap
- WebSocket Support - Real-time bidirectional communication
- Retry Strategies - Automatic retry with exponential backoff
- Caching Layer - Response caching for improved performance
- CLI Tool - Command-line interface for quick testing (foundation landed; command groups in progress)
- Middleware System - Request/response interceptors
π License
This project is licensed under the MIT License - see the LICENSE file for details.
β οΈ Disclaimer
This is a third-party SDK not officially affiliated with OpenRouter. Use at your own discretion.
π Release History
Version 0.5.2 (Latest)
- π§ Added: Domain-oriented SDK surface and major OpenRouter coverage expansion (
messages, discovery/activity, guardrails, auth code flow) - π οΈ Added:
openrouter-cli v0.1foundation with discovery, management, and usage/billing command groups - π Added: 0.5.x deprecation bridge + published
0.5.x -> 0.6.0migration guide and migration smoke harness - π Added: Unified streaming abstraction across chat/responses/messages and normalized API error model
- β
Improved: Live integration suite stability (standard
.envloading, configurable test models, resilient assertions)
Version 0.5.1
- π§© New: Multipart text
cache_controlhelpers (text_with_cache_control,cacheable_text,cacheable_text_with_ttl) - π§ Improved: Reasoning effort now supports
xhigh,minimal, andnone - π‘οΈ Security: Upgraded
bytesto1.11.1(GHSA-434x-w66g-qw3r) - π§ Fixed: Examples now load API keys at runtime to avoid compile-time
.envfailures in CI
Version 0.5.0
- π New: Streaming tool calls support with
ToolAwareStream- automatically accumulates partial tool call fragments - π§ New:
PartialToolCallandPartialFunctionCalltypes for incremental streaming data - π‘ New:
StreamEventenum for structured streaming events (ContentDelta,ReasoningDelta,Done,Error) - π οΈ New:
stream_chat_completion_tool_aware()convenience method on client
Version 0.4.7
- π οΈ New: Comprehensive tool calling (function calling) support with parallel tool calls
- π§ New: Typed tools with automatic JSON schema generation via
schemars - πΌοΈ New: Multi-modal content support for vision models (images with detail levels)
- π Fixed: Gemini model compatibility (added missing fields)
Version 0.4.6
-
π Fixed: Grok model deserialization error (Issue #6)
-
β Added:
indexandlogprobsfields to Choice structs -
π§ͺ Added: Grok model integration test and unit tests for response parsing
-
π§ New: Complete reasoning tokens implementation with chain-of-thought support
-
βοΈ Updated: Model presets restructured to
programming/reasoning/freecategories -
π Enhanced: Professional-grade documentation with comprehensive examples
-
ποΈ Improved: Configuration system with better model management
Version 0.4.5
- Added: Support for listing models by supported parameters
- Note: OpenRouter API limitations on simultaneous category and parameter filtering
Version 0.4.4
- Added: Support for listing models by category
- Thanks to OpenRouter team for the API enhancement!
Made with β€οΈ for the Rust community
β Star us on GitHub | π¦ Find us on Crates.io | π Read the Docs