The official Rust SDK for the Rainy API by Enosis Labs - a unified interface for multiple AI providers including OpenAI, Anthropic, Google Gemini, and more.
- π― Full OpenAI Compatibility: Compatibility with the OpenAI SDK system.
- π Unified Multi-Provider API: Single interface for OpenAI, Google Gemini, Groq, Cerebras and others.
- π Type-Safe Authentication: Secure API key management with validation
- β‘ Async/Await: Full async support with Tokio runtime
- π Rich Metadata: Response times, provider info, token usage, credit tracking
- π‘οΈ Enhanced Error Handling: Comprehensive error types with retryability
- π Intelligent Retry: Exponential backoff with jitter for resilience
- π Rate Limiting: Optional governor-based rate limiting
- π§ Advanced Parameters: Support for reasoning_effort, response_format, tools, tool_choice
- π Rich Documentation: Complete API documentation with practical examples
Add this to your Cargo.toml:
[dependencies]
rainy-sdk = "0.2.5"
tokio = { version = "1.0", features = ["full"] }Or installation with cargo:
cargo add rainy-sdkRainy SDK v0.3.0 provides 100% OpenAI API compatibility while extending support to additional providers. Use Rainy SDK as a drop-in replacement for the official OpenAI SDK:
use rainy_sdk::{models, ChatCompletionRequest, ChatMessage, RainyClient};
// Works exactly like OpenAI SDK
let client = RainyClient::with_api_key("your-rainy-api-key")?;
let request = ChatCompletionRequest::new(
models::model_constants::OPENAI_GPT_4O, // or GOOGLE_GEMINI_2_5_PRO
vec![ChatMessage::user("Hello!")]
)
.with_temperature(0.7)
.with_response_format(models::ResponseFormat::JsonObject);
let (response, metadata) = client.chat_completion(request).await?;| Provider | Models | OpenAI Compatibility |
|---|---|---|
| OpenAI | openai/gpt-4o, openai/gpt-5 |
β Native |
google/gemini-2.5-pro, google/gemini-2.5-flash, google/gemini-2.5-flash-lite |
β Via compatibility layer | |
| Groq | groq/llama-3.1-8b-instant |
β OpenAI-compatible API |
| Cerebras | cerebras/llama3.1-8b |
β OpenAI-compatible API |
- Tool Calling: Function calling with
toolsandtool_choice - Structured Output: JSON Schema enforcement with
response_format - Reasoning Control:
reasoning_effortparameter for Gemini models - Log Probabilities:
logprobsandtop_logprobssupport - Streaming: OpenAI-compatible delta format streaming
Enable additional features as needed:
[dependencies]
rainy-sdk = { version = "0.2.5", features = ["rate-limiting", "tracing"] }Available features:
rate-limiting: Built-in rate limiting with thegovernorcrate.tracing: Request/response logging with thetracingcrate.
use rainy_sdk::{models, ChatCompletionRequest, ChatMessage, RainyClient};
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// Initialize client with your API key from environment variables
let api_key = std::env::var("RAINY_API_KEY").expect("RAINY_API_KEY not set");
let client = RainyClient::with_api_key(api_key)?;
// Simple chat completion
let response = client
.simple_chat(
models::model_constants::GPT_4O,
"Hello! Tell me a short story.",
)
.await?;
println!("Simple response: {}", response);
// Advanced usage with metadata
let request = ChatCompletionRequest::new(
models::model_constants::CLAUDE_SONNET_4,
vec![ChatMessage::user("Explain quantum computing in one sentence")],
)
.with_temperature(0.7)
.with_max_tokens(100);
let (response, metadata) = client.chat_completion(request).await?;
println!("\nAdvanced response: {}", response.choices[0].message.content);
println!("Provider: {:?}", metadata.provider.unwrap_or_default());
println!("Response time: {}ms", metadata.response_time.unwrap_or_default());
Ok(())
}The SDK uses API key authentication. It's recommended to load the key from an environment variable.
use rainy_sdk::RainyClient;
// Load API key from environment and create client
let api_key = std::env::var("RAINY_API_KEY").expect("RAINY_API_KEY not set");
let client = RainyClient::with_api_key(api_key)?;Verify the API status.
# use rainy_sdk::RainyClient;
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
# let client = RainyClient::with_api_key("dummy")?;
let health = client.health_check().await?;
println!("API Status: {}", health.status);
# Ok(())
# }Create a standard chat completion.
# use rainy_sdk::{RainyClient, ChatCompletionRequest, ChatMessage, models};
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
# let client = RainyClient::with_api_key("dummy")?;
let messages = vec![
ChatMessage::system("You are a helpful assistant."),
ChatMessage::user("Explain quantum computing in simple terms."),
];
let request = ChatCompletionRequest::new(models::model_constants::GPT_4O, messages)
.with_max_tokens(500)
.with_temperature(0.7);
let (response, metadata) = client.chat_completion(request).await?;
if let Some(choice) = response.choices.first() {
println!("Response: {}", choice.message.content);
}
# Ok(())
# }Receive the response as a stream of events.
# use rainy_sdk::{RainyClient, ChatCompletionRequest, ChatMessage, models};
# use futures::StreamExt;
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
# let client = RainyClient::with_api_key("dummy")?;
let request = ChatCompletionRequest::new(
models::model_constants::LLAMA_3_1_8B_INSTANT,
vec![ChatMessage::user("Write a haiku about Rust programming")],
)
.with_stream(true);
let mut stream = client.create_chat_completion_stream(request).await?;
while let Some(chunk) = stream.next().await {
match chunk {
Ok(response) => {
if let Some(choice) = response.choices.first() {
print!("{}", choice.message.content);
}
}
Err(e) => eprintln!("\nError in stream: {}", e),
}
}
# Ok(())
# }Get credit and usage statistics.
# use rainy_sdk::RainyClient;
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
# let client = RainyClient::with_api_key("dummy")?;
// Get credit stats
let credits = client.get_credit_stats(None).await?;
println!("Current credits: {}", credits.current_credits);
// Get usage stats for the last 7 days
let usage = client.get_usage_stats(Some(7)).await?;
println!("Total requests (last 7 days): {}", usage.total_requests);
# Ok(())
# }Manage API keys programmatically.
# use rainy_sdk::RainyClient;
# async fn example() -> Result<(), Box<dyn std::error::Error>> {
# let client = RainyClient::with_api_key("dummy")?;
// List all API keys
let keys = client.list_api_keys().await?;
for key in keys {
println!("Key ID: {} - Active: {}", key.id, key.is_active);
}
// Create a new API key
let new_key = client.create_api_key("My new key", Some(30)).await?;
println!("Created key: {}", new_key.key);
// Delete the API key
client.delete_api_key(&new_key.id.to_string()).await?;
# Ok(())
# }Explore the examples/ directory for comprehensive usage examples:
- Basic Usage (
examples/basic_usage.rs): Complete walkthrough of all SDK features. - Chat Completion (
examples/chat_completion.rs): Advanced chat completion patterns. - Error Handling (
examples/error_handling.rs): Demonstrates how to handle different error types.
Run examples with:
# Set your API key
export RAINY_API_KEY="your-api-key-here"
# Run basic usage example
cargo run --example basic_usage
# Run chat completion example
cargo run --example chat_completion-
API Key Management: This SDK utilizes the
secrecycrate to handle the API key, ensuring it is securely stored in memory and zeroed out upon being dropped. However, it is still crucial to manage theRainyClient's lifecycle carefully within your application to minimize exposure. -
Rate Limiting: The optional
rate-limitingfeature is intended as a client-side safeguard to prevent accidental overuse and to act as a "good citizen" towards the API. It is not a security mechanism and can be bypassed by a malicious actor. For robust abuse prevention, you must implement server-side monitoring, usage quotas, and API key management through your Enosis Labs dashboard. -
TLS Configuration: The client is hardened to use modern, secure TLS settings (TLS 1.2+ via the
rustlsbackend) and to only allow HTTPS connections, providing strong protection against network interception.
The SDK is built with a modular architecture:
src/
βββ client.rs # Main API client with request handling
βββ auth.rs # Authentication and authorization logic
βββ models.rs # Data structures and serialization
βββ error.rs # Comprehensive error handling
βββ retry.rs # Retry logic with exponential backoff
βββ endpoints/ # API endpoint implementations
β βββ chat.rs # Chat completion endpoints
β βββ health.rs # Health check and monitoring
β βββ keys.rs # API key operations
β βββ usage.rs # Usage statistics and billing
β βββ user.rs # User account management
βββ lib.rs # Public API and module exports
We welcome contributions! Please see our Contributing Guide for details on:
- Setting up your development environment
- Code style and standards
- Testing guidelines
- Submitting pull requests
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
- Website: enosislabs.com
- Email: hello@enosislabs.com
- GitHub: github.com/enosislabs
- Documentation: docs.rs/rainy-sdk
This SDK is developed by Enosis Labs and is not officially affiliated with any AI provider mentioned (OpenAI, Anthropic, Google, etc.). The Rainy API serves as an independent gateway service that provides unified access to multiple AI providers.
Made with β€οΈ by Enosis Labs