1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
use crate::{
auth::AuthConfig,
error::{ApiErrorResponse, RainyError, Result},
models::*,
retry::{retry_with_backoff, RetryConfig},
};
use eventsource_stream::Eventsource;
use futures::{Stream, StreamExt};
use reqwest::{
header::{HeaderMap, HeaderValue, AUTHORIZATION, USER_AGENT},
Client, Response,
};
use secrecy::ExposeSecret;
use serde::Deserialize;
use std::pin::Pin;
use std::time::Instant;
#[cfg(feature = "rate-limiting")]
use governor::{
clock::DefaultClock,
state::{InMemoryState, NotKeyed},
Quota, RateLimiter,
};
/// 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
///
/// ```rust,no_run
/// 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(())
/// }
/// ```
pub struct RainyClient {
/// The underlying `reqwest::Client` used for making HTTP requests.
client: Client,
/// The authentication configuration for the client.
auth_config: AuthConfig,
/// The retry configuration for handling failed requests.
retry_config: RetryConfig,
/// An optional rate limiter to control the request frequency.
/// This is only available when the `rate-limiting` feature is enabled.
#[cfg(feature = "rate-limiting")]
rate_limiter: Option<RateLimiter<NotKeyed, InMemoryState, DefaultClock>>,
}
impl RainyClient {
pub(crate) fn root_url(&self, path: &str) -> String {
let normalized = if path.starts_with('/') {
path.to_string()
} else {
format!("/{path}")
};
format!(
"{}{}",
self.auth_config.base_url.trim_end_matches('/'),
normalized
)
}
pub(crate) fn api_v1_url(&self, path: &str) -> String {
let normalized = if path.starts_with('/') {
path.to_string()
} else {
format!("/{path}")
};
format!(
"{}/api/v1{}",
self.auth_config.base_url.trim_end_matches('/'),
normalized
)
}
/// 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.
pub fn with_api_key(api_key: impl Into<String>) -> Result<Self> {
let auth_config = AuthConfig::new(api_key);
Self::with_config(auth_config)
}
/// 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.
pub fn with_config(auth_config: AuthConfig) -> Result<Self> {
// Validate configuration
auth_config.validate()?;
// Build HTTP client
let mut headers = HeaderMap::new();
headers.insert(
AUTHORIZATION,
HeaderValue::from_str(&format!("Bearer {}", auth_config.api_key.expose_secret()))
.map_err(|e| RainyError::Authentication {
code: "INVALID_API_KEY".to_string(),
message: format!("Invalid API key format: {}", e),
retryable: false,
})?,
);
headers.insert(
USER_AGENT,
HeaderValue::from_str(&auth_config.user_agent).map_err(|e| RainyError::Network {
message: format!("Invalid user agent: {}", e),
retryable: false,
source_error: None,
})?,
);
let client = Client::builder()
.use_rustls_tls()
.min_tls_version(reqwest::tls::Version::TLS_1_2)
.https_only(true)
.timeout(auth_config.timeout())
.default_headers(headers)
.build()
.map_err(|e| RainyError::Network {
message: format!("Failed to create HTTP client: {}", e),
retryable: false,
source_error: Some(e.to_string()),
})?;
let retry_config = RetryConfig::new(auth_config.max_retries);
#[cfg(feature = "rate-limiting")]
let rate_limiter = Some(RateLimiter::direct(Quota::per_second(
std::num::NonZeroU32::new(10).unwrap(),
)));
Ok(Self {
client,
auth_config,
retry_config,
#[cfg(feature = "rate-limiting")]
rate_limiter,
})
}
/// 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.
pub fn with_retry_config(mut self, retry_config: RetryConfig) -> Self {
self.retry_config = retry_config;
self
}
/// 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.
pub async fn get_available_models(&self) -> Result<AvailableModels> {
#[derive(Deserialize)]
struct ModelListItem {
id: String,
}
#[derive(Deserialize)]
struct ModelsData {
data: Vec<ModelListItem>,
}
#[derive(Deserialize)]
struct Envelope {
data: ModelsData,
}
let url = self.api_v1_url("/models");
let operation = || async {
let response = self.client.get(&url).send().await?;
let envelope: Envelope = self.handle_response(response).await?;
let mut providers = std::collections::HashMap::<String, Vec<String>>::new();
for item in envelope.data.data {
let provider = item
.id
.split_once('/')
.map(|(p, _)| p.to_string())
.unwrap_or_else(|| "rainy".to_string());
providers.entry(provider).or_default().push(item.id);
}
let total_models = providers.values().map(std::vec::Vec::len).sum();
let mut active_providers = providers.keys().cloned().collect::<Vec<_>>();
active_providers.sort();
Ok(AvailableModels {
providers,
total_models,
active_providers,
})
};
if self.auth_config.enable_retry {
retry_with_backoff(&self.retry_config, operation).await
} else {
operation().await
}
}
/// 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.
pub async fn chat_completion(
&self,
request: ChatCompletionRequest,
) -> Result<(ChatCompletionResponse, RequestMetadata)> {
#[cfg(feature = "rate-limiting")]
if let Some(ref limiter) = self.rate_limiter {
limiter.until_ready().await;
}
let url = self.api_v1_url("/chat/completions");
let start_time = Instant::now();
let operation = || async {
let response = self.client.post(&url).json(&request).send().await?;
let metadata = self.extract_metadata(&response, start_time);
let chat_response: ChatCompletionResponse = self.handle_response(response).await?;
Ok((chat_response, metadata))
};
if self.auth_config.enable_retry {
retry_with_backoff(&self.retry_config, operation).await
} else {
operation().await
}
}
/// Creates a streaming chat completion based on the provided request.
///
/// # Arguments
///
/// * `request` - A `ChatCompletionRequest` containing the model, messages, and other parameters.
///
/// # Returns
///
/// A `Result` containing a stream of `ChatCompletionChunk`s on success, or a `RainyError` on failure.
pub async fn chat_completion_stream(
&self,
mut request: ChatCompletionRequest,
) -> Result<Pin<Box<dyn Stream<Item = Result<ChatCompletionChunk>> + Send>>> {
// Ensure stream is set to true
request.stream = Some(true);
#[cfg(feature = "rate-limiting")]
if let Some(ref limiter) = self.rate_limiter {
limiter.until_ready().await;
}
let url = self.api_v1_url("/chat/completions");
// Note: Retries are more complex with streams, so we only retry the initial connection
let operation = || async {
let response = self
.client
.post(&url)
.json(&request)
.send()
.await
.map_err(|e| RainyError::Network {
message: format!("Failed to send request: {}", e),
retryable: true,
source_error: Some(e.to_string()),
})?;
self.handle_stream_response(response).await
};
if self.auth_config.enable_retry {
retry_with_backoff(&self.retry_config, operation).await
} else {
operation().await
}
}
/// Creates a Responses API completion (`POST /api/v1/responses`) in raw mode.
pub async fn create_response(
&self,
request: ResponsesRequest,
) -> Result<(ResponsesApiResponse, RequestMetadata)> {
#[cfg(feature = "rate-limiting")]
if let Some(ref limiter) = self.rate_limiter {
limiter.until_ready().await;
}
let url = self.api_v1_url("/responses");
let start_time = Instant::now();
let operation = || async {
let response = self.client.post(&url).json(&request).send().await?;
let metadata = self.extract_metadata(&response, start_time);
let api_response: ResponsesApiResponse = self.handle_response(response).await?;
Ok((api_response, metadata))
};
if self.auth_config.enable_retry {
retry_with_backoff(&self.retry_config, operation).await
} else {
operation().await
}
}
/// Creates a Responses API completion in envelope mode (`X-Rainy-Response-Mode: envelope`).
pub async fn create_response_envelope(
&self,
request: ResponsesRequest,
) -> Result<(RainyEnvelope<ResponsesApiResponse>, RequestMetadata)> {
#[cfg(feature = "rate-limiting")]
if let Some(ref limiter) = self.rate_limiter {
limiter.until_ready().await;
}
let url = self.api_v1_url("/responses");
let start_time = Instant::now();
let operation = || async {
let response = self
.client
.post(&url)
.header("X-Rainy-Response-Mode", "envelope")
.json(&request)
.send()
.await?;
let metadata = self.extract_metadata(&response, start_time);
let api_response: RainyEnvelope<ResponsesApiResponse> =
self.handle_response(response).await?;
Ok((api_response, metadata))
};
if self.auth_config.enable_retry {
retry_with_backoff(&self.retry_config, operation).await
} else {
operation().await
}
}
/// Creates a streaming Responses API completion and returns SSE events.
pub async fn create_response_stream(
&self,
mut request: ResponsesRequest,
) -> Result<Pin<Box<dyn Stream<Item = Result<ResponsesStreamEvent>> + Send>>> {
request.stream = Some(true);
#[cfg(feature = "rate-limiting")]
if let Some(ref limiter) = self.rate_limiter {
limiter.until_ready().await;
}
let url = self.api_v1_url("/responses");
let operation = || async {
let response = self
.client
.post(&url)
.json(&request)
.send()
.await
.map_err(|e| RainyError::Network {
message: format!("Failed to send request: {}", e),
retryable: true,
source_error: Some(e.to_string()),
})?;
let status = response.status();
if !status.is_success() {
return Err(self
.handle_response::<ResponsesApiResponse>(response)
.await
.err()
.unwrap());
}
let stream = response
.bytes_stream()
.eventsource()
.filter_map(|event| async move {
match event {
Ok(event) => {
if event.data.trim() == "[DONE]" {
return None;
}
match serde_json::from_str::<ResponsesStreamEvent>(&event.data) {
Ok(payload) => Some(Ok(payload)),
Err(e) => Some(Err(RainyError::Serialization {
message: e.to_string(),
source_error: Some(e.to_string()),
})),
}
}
Err(e) => Some(Err(RainyError::Network {
message: format!("SSE parsing error: {e}"),
retryable: true,
source_error: Some(e.to_string()),
})),
}
});
Ok(Box::pin(stream)
as Pin<
Box<dyn Stream<Item = Result<ResponsesStreamEvent>> + Send>,
>)
};
if self.auth_config.enable_retry {
retry_with_backoff(&self.retry_config, operation).await
} else {
operation().await
}
}
/// Retrieves `/api/v1/models/catalog` entries including `rainy_capabilities` metadata.
pub async fn get_models_catalog(&self) -> Result<Vec<ModelCatalogItem>> {
#[derive(Deserialize)]
struct ModelsCatalogData {
data: Vec<ModelCatalogItem>,
}
#[derive(Deserialize)]
struct Envelope {
data: ModelsCatalogData,
}
let url = self.api_v1_url("/models/catalog");
let operation = || async {
let response = self.client.get(&url).send().await?;
let envelope: Envelope = self.handle_response(response).await?;
Ok(envelope.data.data)
};
if self.auth_config.enable_retry {
retry_with_backoff(&self.retry_config, operation).await
} else {
operation().await
}
}
/// Retrieves catalog and filters/sorts models using SDK selector criteria.
pub async fn select_models(
&self,
criteria: ModelSelectionCriteria,
) -> Result<Vec<ModelCatalogItem>> {
let catalog = self.get_models_catalog().await?;
Ok(crate::models::select_models(&catalog, &criteria))
}
/// Builds provider-aware reasoning payload from a catalog entry and preference.
pub fn build_reasoning_config(
&self,
model: &ModelCatalogItem,
preference: &ReasoningPreference,
) -> Option<serde_json::Value> {
crate::models::build_reasoning_config(model, preference)
}
/// 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.
pub async fn simple_chat(
&self,
model: impl Into<String>,
prompt: impl Into<String>,
) -> Result<String> {
let request = ChatCompletionRequest::new(model, vec![ChatMessage::user(prompt)]);
let (response, _) = self.chat_completion(request).await?;
Ok(response
.choices
.into_iter()
.next()
.map(|choice| choice.message.content)
.unwrap_or_default())
}
/// Handles the HTTP response, deserializing the body into a given type `T` on success,
/// or mapping the error to a `RainyError` on failure.
///
/// This is an internal method used by the various endpoint functions.
pub(crate) async fn handle_response<T>(&self, response: Response) -> Result<T>
where
T: serde::de::DeserializeOwned,
{
let status = response.status();
let headers = response.headers().clone();
let request_id = headers
.get("x-request-id")
.and_then(|v| v.to_str().ok())
.map(String::from);
if status.is_success() {
let text = response.text().await?;
serde_json::from_str(&text).map_err(|e| RainyError::Serialization {
message: format!("Failed to parse response: {}", e),
source_error: Some(e.to_string()),
})
} else {
let text = response.text().await.unwrap_or_default();
// Try to parse structured error response
if let Ok(error_response) = serde_json::from_str::<ApiErrorResponse>(&text) {
let error = error_response.error;
self.map_api_error(error, status.as_u16(), request_id)
} else {
// Fallback to generic error
Err(RainyError::Api {
code: status.canonical_reason().unwrap_or("UNKNOWN").to_string(),
message: if text.is_empty() {
format!("HTTP {}", status.as_u16())
} else {
text
},
status_code: status.as_u16(),
retryable: status.is_server_error(),
request_id,
})
}
}
}
/// Handles the HTTP response for streaming requests.
pub(crate) async fn handle_stream_response(
&self,
response: Response,
) -> Result<Pin<Box<dyn Stream<Item = Result<ChatCompletionChunk>> + Send>>> {
let status = response.status();
let request_id = response
.headers()
.get("x-request-id")
.and_then(|v| v.to_str().ok())
.map(String::from);
if status.is_success() {
let stream = response
.bytes_stream()
.eventsource()
.map(move |event| match event {
Ok(event) => {
if event.data == "[DONE]" {
return None;
}
match serde_json::from_str::<ChatCompletionChunk>(&event.data) {
Ok(chunk) => Some(Ok(chunk)),
Err(e) => Some(Err(RainyError::Serialization {
message: format!("Failed to parse stream chunk: {}", e),
source_error: Some(e.to_string()),
})),
}
}
Err(e) => Some(Err(RainyError::Network {
message: format!("Stream error: {}", e),
retryable: true,
source_error: Some(e.to_string()),
})),
})
.take_while(|x| futures::future::ready(x.is_some()))
.map(|x| x.unwrap());
Ok(Box::pin(stream))
} else {
let text = response.text().await.unwrap_or_default();
// Try to parse structured error response
if let Ok(error_response) = serde_json::from_str::<ApiErrorResponse>(&text) {
let error = error_response.error;
self.map_api_error(error, status.as_u16(), request_id)
} else {
Err(RainyError::Api {
code: status.canonical_reason().unwrap_or("UNKNOWN").to_string(),
message: if text.is_empty() {
format!("HTTP {}", status.as_u16())
} else {
text
},
status_code: status.as_u16(),
retryable: status.is_server_error(),
request_id,
})
}
}
}
/// Extracts request metadata from the HTTP response headers.
///
/// This is an internal method.
fn extract_metadata(&self, response: &Response, start_time: Instant) -> RequestMetadata {
let headers = response.headers();
RequestMetadata {
response_time: Some(start_time.elapsed().as_millis() as u64),
provider: headers
.get("x-provider")
.and_then(|v| v.to_str().ok())
.map(String::from),
tokens_used: headers
.get("x-tokens-used")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse().ok()),
credits_used: headers
.get("x-credits-used")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse().ok()),
credits_remaining: headers
.get("x-credits-remaining")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse().ok()),
request_id: headers
.get("x-request-id")
.and_then(|v| v.to_str().ok())
.map(String::from),
compat_warnings: headers
.get("x-rainy-compat-warnings")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse().ok()),
response_mode: headers
.get("x-rainy-response-mode")
.and_then(|v| v.to_str().ok())
.map(String::from),
billing_plan: headers
.get("x-rainy-billing-plan")
.and_then(|v| v.to_str().ok())
.map(String::from),
rainy_credits_charged: headers
.get("x-rainy-credits-charged")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse().ok()),
rainy_markup_percent: headers
.get("x-rainy-markup-percent")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse().ok()),
rainy_daily_credits_remaining: headers
.get("x-rainy-daily-credits-remaining")
.and_then(|v| v.to_str().ok())
.map(String::from),
}
}
/// Maps a structured API error response to a `RainyError`.
///
/// This is an internal method.
fn map_api_error<T>(
&self,
error: crate::error::ApiErrorDetails,
status_code: u16,
request_id: Option<String>,
) -> Result<T> {
let retryable = error.retryable.unwrap_or(status_code >= 500);
let rainy_error = match error.code.as_str() {
"INVALID_API_KEY" | "EXPIRED_API_KEY" => RainyError::Authentication {
code: error.code,
message: error.message,
retryable: false,
},
"INSUFFICIENT_CREDITS" => {
// Extract credit info from details if available
let (current_credits, estimated_cost, reset_date) =
if let Some(details) = error.details {
let current = details
.get("current_credits")
.and_then(|v| v.as_f64())
.unwrap_or(0.0);
let cost = details
.get("estimated_cost")
.and_then(|v| v.as_f64())
.unwrap_or(0.0);
let reset = details
.get("reset_date")
.and_then(|v| v.as_str())
.map(String::from);
(current, cost, reset)
} else {
(0.0, 0.0, None)
};
RainyError::InsufficientCredits {
code: error.code,
message: error.message,
current_credits,
estimated_cost,
reset_date,
}
}
"RATE_LIMIT_EXCEEDED" => {
let retry_after = error
.details
.as_ref()
.and_then(|d| d.get("retry_after"))
.and_then(|v| v.as_u64());
RainyError::RateLimit {
code: error.code,
message: error.message,
retry_after,
current_usage: None,
}
}
"INVALID_REQUEST" | "MISSING_REQUIRED_FIELD" | "INVALID_MODEL" => {
RainyError::InvalidRequest {
code: error.code,
message: error.message,
details: error.details,
}
}
"PROVIDER_ERROR" | "PROVIDER_UNAVAILABLE" => {
let provider = error
.details
.as_ref()
.and_then(|d| d.get("provider"))
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string();
RainyError::Provider {
code: error.code,
message: error.message,
provider,
retryable,
}
}
_ => RainyError::Api {
code: error.code,
message: error.message,
status_code,
retryable,
request_id: request_id.clone(),
},
};
Err(rainy_error)
}
/// Returns a reference to the current authentication configuration.
pub fn auth_config(&self) -> &AuthConfig {
&self.auth_config
}
/// Returns the base URL being used by the client.
pub fn base_url(&self) -> &str {
&self.auth_config.base_url
}
/// Returns a reference to the underlying `reqwest::Client`.
///
/// This is intended for internal use by the endpoint modules.
pub(crate) fn http_client(&self) -> &Client {
&self.client
}
/// 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
///
/// ```rust,no_run
/// # use rainy_sdk::RainyClient;
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// 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);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn list_available_models(&self) -> Result<AvailableModels> {
self.get_available_models().await
}
/// Retrieves the Cowork profile for the current user.
///
/// This includes subscription plan details, usage statistics, and feature flags.
///
/// # Returns
///
/// A `Result` containing a `CoworkProfile` struct on success, or a `RainyError` on failure.
#[cfg(feature = "cowork")]
#[deprecated(
note = "Cowork endpoints are legacy and not supported by Rainy API v3. Migrate to v3 session/org endpoints."
)]
pub async fn get_cowork_profile(&self) -> Result<crate::cowork::CoworkProfile> {
let url = self.api_v1_url("/cowork/profile");
let operation = || async {
let response = self.client.get(&url).send().await?;
self.handle_response(response).await
};
if self.auth_config.enable_retry {
retry_with_backoff(&self.retry_config, operation).await
} else {
operation().await
}
}
// Legacy methods for backward compatibility
/// Makes a generic HTTP request to the API.
///
/// This is an internal method kept for compatibility with endpoint implementations.
pub(crate) async fn make_request<T: serde::de::DeserializeOwned>(
&self,
method: reqwest::Method,
endpoint: &str,
body: Option<serde_json::Value>,
) -> Result<T> {
#[cfg(feature = "rate-limiting")]
if let Some(ref limiter) = self.rate_limiter {
limiter.until_ready().await;
}
let url = self.api_v1_url(endpoint);
let headers = self.auth_config.build_headers()?;
let mut request = self.client.request(method, &url).headers(headers);
if let Some(body) = body {
request = request.json(&body);
}
let response = request.send().await?;
self.handle_response(response).await
}
}
impl std::fmt::Debug for RainyClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RainyClient")
.field("base_url", &self.auth_config.base_url)
.field("timeout", &self.auth_config.timeout_seconds)
.field("max_retries", &self.retry_config.max_retries)
.finish()
}
}