RainyClient

Struct RainyClient 

Source
pub struct RainyClient { /* private fields */ }
Expand description

The main client for interacting with the Rainy API.

RainyClient provides a convenient and high-level interface for making requests to the various endpoints of the Rainy API. It handles authentication, rate limiting, and retries automatically.

§Examples

use rainy_sdk::{RainyClient, Result};

#[tokio::main]
async fn main() -> Result<()> {
    // Create a client using an API key from an environment variable
    let api_key = std::env::var("RAINY_API_KEY").expect("RAINY_API_KEY not set");
    let client = RainyClient::with_api_key(api_key)?;

    // Use the client to make API calls
    let models = client.get_available_models().await?;
    println!("Available models: {:?}", models);

    Ok(())
}

Implementations§

Source§

impl RainyClient

Source

pub fn with_api_key(api_key: impl Into<String>) -> Result<Self>

Creates a new RainyClient with the given API key.

This is the simplest way to create a client. It uses default settings for the base URL, timeout, and retries.

§Arguments
  • api_key - Your Rainy API key.
§Returns

A Result containing the new RainyClient or a RainyError if initialization fails.

Source

pub fn with_config(auth_config: AuthConfig) -> Result<Self>

Creates a new RainyClient with a custom AuthConfig.

This allows for more advanced configuration, such as setting a custom base URL or timeout.

§Arguments
  • auth_config - The authentication configuration to use.
§Returns

A Result containing the new RainyClient or a RainyError if initialization fails.

Source

pub fn with_retry_config(self, retry_config: RetryConfig) -> Self

Sets a custom retry configuration for the client.

This allows you to override the default retry behavior.

§Arguments
  • retry_config - The new retry configuration.
§Returns

The RainyClient instance with the updated retry configuration.

Source

pub async fn get_available_models(&self) -> Result<AvailableModels>

Retrieves the list of available models and providers from the API.

§Returns

A Result containing an AvailableModels struct on success, or a RainyError on failure.

Source

pub async fn chat_completion( &self, request: ChatCompletionRequest, ) -> Result<(ChatCompletionResponse, RequestMetadata)>

Creates a chat completion based on the provided request.

§Arguments
  • request - A ChatCompletionRequest containing the model, messages, and other parameters.
§Returns

A Result containing a tuple of (ChatCompletionResponse, RequestMetadata) on success, or a RainyError on failure.

Source

pub async fn simple_chat( &self, model: impl Into<String>, prompt: impl Into<String>, ) -> Result<String>

Creates a simple chat completion with a single user prompt.

This is a convenience method for simple use cases where you only need to send a single prompt to a model and get a text response.

§Arguments
  • model - The name of the model to use for the completion.
  • prompt - The user’s prompt.
§Returns

A Result containing the String response from the model, or a RainyError on failure.

Source

pub fn auth_config(&self) -> &AuthConfig

Returns a reference to the current authentication configuration.

Source

pub fn base_url(&self) -> &str

Returns the base URL being used by the client.

Source

pub async fn list_available_models(&self) -> Result<AvailableModels>

Retrieves the list of available models from the API.

This method returns information about all models that are currently available through the Rainy API, including their compatibility status and supported parameters.

§Returns

A Result containing a AvailableModels struct with model information.

§Example
let client = RainyClient::with_api_key("your-api-key")?;
let models = client.list_available_models().await?;

println!("Total models: {}", models.total_models);
for (provider, model_list) in &models.providers {
    println!("Provider {}: {:?}", provider, model_list);
}
Source§

impl RainyClient

Source

pub async fn create_chat_completion( &self, request: ChatCompletionRequest, ) -> Result<ChatCompletionResponse>

Create a chat completion

This endpoint sends a chat completion request to the Rainy API.

§Arguments
  • request - The chat completion request parameters
§Returns

Returns the chat completion response from the AI model.

§Example
let client = RainyClient::with_api_key("user-api-key")?;

let messages = vec![
    ChatMessage::user("Hello, how are you?"),
];

let request = ChatCompletionRequest::new("gemini-pro", messages)
    .with_max_tokens(150)
    .with_temperature(0.7);

let response = client.create_chat_completion(request).await?;

if let Some(choice) = response.choices.first() {
    println!("Response: {}", choice.message.content);
}
Source

pub async fn create_chat_completion_stream( &self, request: ChatCompletionRequest, ) -> Result<Pin<Box<dyn Stream<Item = Result<ChatCompletionStreamResponse>> + Send>>>

Create a chat completion with streaming

This method provides streaming support for chat completions.

§Arguments
  • request - The chat completion request parameters
§Returns

Returns a stream of chat completion responses.

§Example
let client = RainyClient::with_api_key("user-api-key")?;

let messages = vec![
    ChatMessage::user("Tell me a story"),
];

let request = ChatCompletionRequest::new("llama-3.1-8b-instant", messages)
    .with_max_tokens(500)
    .with_temperature(0.8)
    .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() {
                if let Some(content) = &choice.delta.content {
                    print!("{}", content);
                }
            }
        }
        Err(e) => eprintln!("Error: {}", e),
    }
}
Source§

impl RainyClient

Source

pub async fn health_check(&self) -> Result<HealthCheck>

Performs a basic health check on the Rainy API.

This method is useful for quickly verifying that the API is up and running.

§Returns

A Result containing a HealthCheck struct with basic health information.

§Example
let client = RainyClient::with_api_key("user-api-key")?;
let health = client.health_check().await?;
println!("API Status: {}", health.status);
Source

pub async fn detailed_health_check(&self) -> Result<HealthCheck>

Performs a detailed health check on the Rainy API and its underlying services.

This method provides more in-depth information, including the status of the database, Redis, and connections to AI providers.

§Returns

A Result containing a HealthCheck struct with detailed service status.

§Example
let client = RainyClient::with_api_key("user-api-key")?;
let health = client.detailed_health_check().await?;
println!("Database status: {}", health.services.database);
println!("Providers status: {}", health.services.providers);
Source§

impl RainyClient

Source

pub async fn create_api_key( &self, description: &str, expires_in_days: Option<u32>, ) -> Result<ApiKey>

Create a new API key

This endpoint requires user authentication with a master API key.

§Arguments
  • description - Description of what this API key will be used for
  • expires_in_days - Optional expiration time in days
§Returns

Returns the created API key information.

§Example
let client = RainyClient::with_api_key("master-api-key")?;

let api_key = client.create_api_key(
    "Production API key",
    Some(365)
).await?;

println!("Created API key: {}", api_key.key);
Source

pub async fn list_api_keys(&self) -> Result<Vec<ApiKey>>

List all API keys for the current user

This endpoint requires user authentication.

§Returns

Returns a vector of all API keys owned by the authenticated user.

§Example
let client = RainyClient::with_api_key("user-api-key")?;

let keys = client.list_api_keys().await?;
for key in keys {
    println!("Key: {} - Active: {}", key.key, key.is_active);
}
Source

pub async fn update_api_key( &self, key_id: &str, updates: Value, ) -> Result<ApiKey>

Update an API key

This endpoint requires user authentication.

§Arguments
  • key_id - The UUID of the API key to update
  • updates - JSON object containing the fields to update
§Returns

Returns the updated API key information.

§Example
use serde_json::json;

let client = RainyClient::with_api_key("user-api-key")?;

let updates = json!({
    "description": "Updated description"
});

let updated_key = client.update_api_key(
    "550e8400-e29b-41d4-a716-446655440000",
    updates
).await?;
Source

pub async fn delete_api_key(&self, key_id: &str) -> Result<()>

Delete an API key

This endpoint requires user authentication.

§Arguments
  • key_id - The UUID of the API key to delete
§Example
let client = RainyClient::with_api_key("user-api-key")?;

client.delete_api_key("550e8400-e29b-41d4-a716-446655440000").await?;
println!("API key deleted successfully");
Source§

impl RainyClient

Source

pub async fn get_credit_stats(&self, days: Option<u32>) -> Result<CreditInfo>

Get credit statistics

This endpoint returns information about the user’s credit usage.

§Arguments
  • days - Optional number of days to look back (default: 30)
§Returns

Returns credit information including balance, usage, and allocation.

§Example
let client = RainyClient::with_api_key("user-api-key")?;

let credits = client.get_credit_stats(Some(7)).await?;
println!("Current credits: {}", credits.current_credits);
println!("Estimated cost: {}", credits.estimated_cost);
Source

pub async fn get_usage_stats(&self, days: Option<u32>) -> Result<UsageStats>

Get usage statistics

This endpoint returns detailed usage statistics.

§Arguments
  • days - Optional number of days to look back (default: 30)
§Returns

Returns comprehensive usage statistics including daily usage and recent transactions.

§Example
let client = RainyClient::with_api_key("user-api-key")?;

let usage = client.get_usage_stats(Some(30)).await?;
println!("Total requests: {}", usage.total_requests);
println!("Total tokens: {}", usage.total_tokens);

for daily in &usage.daily_usage {
    println!("{}: {} credits used", daily.date, daily.credits_used);
}
Source§

impl RainyClient

Source

pub async fn get_user_account(&self) -> Result<User>

Get current user account information

This endpoint requires user authentication with an API key.

§Returns

Returns information about the authenticated user.

§Example
let client = RainyClient::with_api_key("user-api-key")?;

let user = client.get_user_account().await?;
println!("Current credits: {}", user.current_credits);

Trait Implementations§

Source§

impl Debug for RainyClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,