openrouter_api 0.6.0

A Rust client library for the OpenRouter API
Documentation
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
use crate::error::{Error, Result};
use crate::types::{Provider, ProvidersResponse};
use crate::utils::cache::Cache;
use crate::utils::{
    retry::execute_with_retry_builder, retry::handle_response_json,
    retry::operations::GET_PROVIDERS,
};
use reqwest::Client;
use std::sync::{Arc, Mutex};

/// API client for provider-related operations
pub struct ProvidersApi {
    pub(crate) client: Client,
    pub(crate) config: crate::client::ApiConfig,
    pub(crate) cache: Arc<Mutex<Cache<String, ProvidersResponse>>>,
}

impl ProvidersApi {
    /// Creates a new ProvidersApi with the given reqwest client, configuration, and shared cache.
    ///
    /// The cache is shared across calls so that repeated requests hit the cache
    /// instead of the network. Callers should retain the same `Arc<Mutex<Cache<...>>>`
    /// instance across multiple `ProvidersApi` lifetimes.
    #[must_use = "returns an API client that should be used for API calls"]
    pub fn new(
        client: Client,
        config: &crate::client::ClientConfig,
        cache: Arc<Mutex<Cache<String, ProvidersResponse>>>,
    ) -> Result<Self> {
        Ok(Self {
            client,
            config: config.to_api_config()?,
            cache,
        })
    }

    /// Retrieves a list of all available providers
    ///
    /// Returns information about providers available through the OpenRouter API,
    /// including their policies and status information.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the `ProvidersResponse` with provider information
    /// or an `Error` if the request fails.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use openrouter_api::client::OpenRouterClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OpenRouterClient::from_env()?;
    ///
    ///     // Get all available providers
    ///     let providers_response = client.providers()?.get_providers().await?;
    ///
    ///     println!("Found {} providers", providers_response.count());
    ///
    ///     // Find a specific provider
    ///     if let Some(openai) = providers_response.find_by_slug("openai") {
    ///         println!("OpenAI provider found: {}", openai.name);
    ///         if openai.has_privacy_policy() {
    ///             println!("Privacy policy: {}", openai.privacy_policy_url.as_ref().unwrap());
    ///         }
    ///     }
    ///
    ///     // Group providers by domain
    ///     let domain_groups = providers_response.group_by_domain();
    ///     for (domain, providers) in domain_groups {
    ///         println!("Domain {}: {} providers", domain, providers.len());
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_providers(&self) -> Result<ProvidersResponse> {
        // Check cache first
        let cache_key = "providers".to_string();
        if let Ok(mut cache) = self.cache.lock() {
            if let Some(cached_response) = cache.get(&cache_key) {
                return Ok(cached_response);
            }
        }

        // Build the URL for the providers endpoint
        let url = self
            .config
            .base_url
            .join("providers")
            .map_err(|e| Error::ApiError {
                code: 400,
                message: format!("Invalid URL: {e}"),
                metadata: None,
            })?;

        // Execute request with retry logic
        let response = execute_with_retry_builder(&self.config.retry_config, GET_PROVIDERS, || {
            self.client
                .get(url.clone())
                .headers((*self.config.headers).clone())
        })
        .await?;

        // Handle response with consistent error parsing
        let providers_response =
            handle_response_json::<ProvidersResponse>(response, GET_PROVIDERS).await?;

        // Cache the response
        if let Ok(mut cache) = self.cache.lock() {
            cache.insert(cache_key, providers_response.clone());
        }

        Ok(providers_response)
    }

    /// Retrieves a specific provider by slug
    ///
    /// This is a convenience method that fetches all providers and returns
    /// the one matching the specified slug.
    ///
    /// # Arguments
    ///
    /// * `slug` - The slug identifier of the provider to retrieve
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the `Provider` information or an `Error`
    /// if the request fails or the provider is not found.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use openrouter_api::client::OpenRouterClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OpenRouterClient::from_env()?;
    ///
    ///     // Get a specific provider by slug
    ///     let openai = client.providers()?.get_provider_by_slug("openai").await?;
    ///
    ///     println!("Provider: {}", openai.name);
    ///     println!("Slug: {}", openai.slug);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_provider_by_slug(&self, slug: &str) -> Result<Provider> {
        // Validate input
        if slug.trim().is_empty() {
            return Err(Error::ConfigError(
                "Provider slug cannot be empty".to_string(),
            ));
        }

        let providers_response = self.get_providers().await?;

        providers_response
            .find_by_slug(slug)
            .cloned()
            .ok_or_else(|| {
                Error::ModelNotAvailable(format!("Provider with slug '{}' not found", slug))
            })
    }

    /// Retrieves a specific provider by name (case-insensitive)
    ///
    /// This is a convenience method that fetches all providers and returns
    /// the one matching the specified name.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the provider to retrieve (case-insensitive)
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the `Provider` information or an `Error`
    /// if the request fails or the provider is not found.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use openrouter_api::client::OpenRouterClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OpenRouterClient::from_env()?;
    ///
    ///     // Get a specific provider by name (case-insensitive)
    ///     let anthropic = client.providers()?.get_provider_by_name("anthropic").await?;
    ///
    ///     println!("Provider: {}", anthropic.name);
    ///     println!("Slug: {}", anthropic.slug);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_provider_by_name(&self, name: &str) -> Result<Provider> {
        // Validate input
        if name.trim().is_empty() {
            return Err(Error::ConfigError(
                "Provider name cannot be empty".to_string(),
            ));
        }

        let providers_response = self.get_providers().await?;

        providers_response
            .find_by_name(name)
            .cloned()
            .ok_or_else(|| {
                Error::ModelNotAvailable(format!("Provider with name '{}' not found", name))
            })
    }

    /// Retrieves providers that have a privacy policy
    ///
    /// This is a convenience method that filters providers to only include
    /// those that have a privacy policy URL.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing a vector of `Provider` instances that
    /// have privacy policies or an `Error` if the request fails.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use openrouter_api::client::OpenRouterClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OpenRouterClient::from_env()?;
    ///
    ///     // Get providers with privacy policies
    ///     let providers_with_privacy = client.providers()?
    ///         .get_providers_with_privacy_policy().await?;
    ///
    ///     println!("{} providers have privacy policies", providers_with_privacy.len());
    ///
    ///     for provider in providers_with_privacy {
    ///         println!("{}: {}", provider.name, provider.privacy_policy_url.unwrap());
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_providers_with_privacy_policy(&self) -> Result<Vec<Provider>> {
        let providers_response = self.get_providers().await?;
        Ok(providers_response
            .with_privacy_policy()
            .into_iter()
            .cloned()
            .collect())
    }

    /// Retrieves providers that have terms of service
    ///
    /// This is a convenience method that filters providers to only include
    /// those that have a terms of service URL.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing a vector of `Provider` instances that
    /// have terms of service or an `Error` if the request fails.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use openrouter_api::client::OpenRouterClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OpenRouterClient::from_env()?;
    ///
    ///     // Get providers with terms of service
    ///     let providers_with_tos = client.providers()?
    ///         .get_providers_with_terms_of_service().await?;
    ///
    ///     println!("{} providers have terms of service", providers_with_tos.len());
    ///
    ///     for provider in providers_with_tos {
    ///         println!("{}: {}", provider.name, provider.terms_of_service_url.unwrap());
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_providers_with_terms_of_service(&self) -> Result<Vec<Provider>> {
        let providers_response = self.get_providers().await?;
        Ok(providers_response
            .with_terms_of_service()
            .into_iter()
            .cloned()
            .collect())
    }

    /// Retrieves providers that have a status page
    ///
    /// This is a convenience method that filters providers to only include
    /// those that have a status page URL.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing a vector of `Provider` instances that
    /// have status pages or an `Error` if the request fails.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use openrouter_api::client::OpenRouterClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OpenRouterClient::from_env()?;
    ///
    ///     // Get providers with status pages
    ///     let providers_with_status = client.providers()?
    ///         .get_providers_with_status_page().await?;
    ///
    ///     println!("{} providers have status pages", providers_with_status.len());
    ///
    ///     for provider in providers_with_status {
    ///         println!("{}: {}", provider.name, provider.status_page_url.unwrap());
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_providers_with_status_page(&self) -> Result<Vec<Provider>> {
        let providers_response = self.get_providers().await?;
        Ok(providers_response
            .with_status_page()
            .into_iter()
            .cloned()
            .collect())
    }

    /// Retrieves all provider slugs sorted alphabetically
    ///
    /// This is a convenience method that returns all provider slugs
    /// in alphabetical order.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing a vector of provider slugs or an `Error`
    /// if the request fails.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use openrouter_api::client::OpenRouterClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OpenRouterClient::from_env()?;
    ///
    ///     // Get all provider slugs sorted alphabetically
    ///     let slugs = client.providers()?.get_provider_slugs().await?;
    ///
    ///     println!("Available provider slugs:");
    ///     for slug in slugs {
    ///         println!("  {}", slug);
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_provider_slugs(&self) -> Result<Vec<String>> {
        let providers_response = self.get_providers().await?;
        Ok(providers_response.sorted_slugs())
    }

    /// Retrieves all provider names sorted alphabetically
    ///
    /// This is a convenience method that returns all provider names
    /// in alphabetical order.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing a vector of provider names or an `Error`
    /// if the request fails.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use openrouter_api::client::OpenRouterClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OpenRouterClient::from_env()?;
    ///
    ///     // Get all provider names sorted alphabetically
    ///     let names = client.providers()?.get_provider_names().await?;
    ///
    ///     println!("Available provider names:");
    ///     for name in names {
    ///         println!("  {}", name);
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_provider_names(&self) -> Result<Vec<String>> {
        let providers_response = self.get_providers().await?;
        Ok(providers_response.sorted_names())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::{ClientConfig, RetryConfig, SecureApiKey};
    use crate::tests::test_helpers::test_client_config;
    use reqwest::Client;
    use std::time::Duration;

    fn default_providers_cache() -> Arc<Mutex<Cache<String, ProvidersResponse>>> {
        Arc::new(Mutex::new(Cache::new(Duration::from_secs(300))))
    }

    #[test]
    fn test_providers_api_new() {
        let config = test_client_config();
        let http_client = Client::new();

        let _providers_api = ProvidersApi::new(http_client, &config, default_providers_cache());
    }

    #[tokio::test]
    async fn test_providers_api_network_error() {
        let config = ClientConfig {
            api_key: Some(SecureApiKey::new("sk-test123456789012345678901234567890").unwrap()),
            base_url: url::Url::parse("https://invalid-url-that-does-not-exist.com/api/v1/")
                .unwrap(),
            timeout: std::time::Duration::from_secs(1),
            http_referer: None,
            site_title: None,
            user_id: None,
            retry_config: RetryConfig::default(),
            max_response_bytes: 10 * 1024 * 1024,
        };
        let http_client = Client::new();
        let providers_api =
            ProvidersApi::new(http_client, &config, default_providers_cache()).unwrap();

        // Test that network errors are properly handled
        let result = providers_api.get_providers().await;
        assert!(result.is_err());

        // Any error type is acceptable for network failure
        // The important thing is that it doesn't panic and returns an error
        match result.unwrap_err() {
            Error::HttpError(_) | Error::RateLimitExceeded(_) => {
                // Expected - network or rate limit error
            }
            other => {
                panic!(
                    "Expected HttpError or RateLimitExceeded for network failure, got: {:?}",
                    other
                );
            }
        }
    }

    #[tokio::test]
    async fn test_provider_convenience_methods_with_empty_response() {
        let config = ClientConfig {
            api_key: Some(SecureApiKey::new("sk-test123456789012345678901234567890").unwrap()),
            base_url: url::Url::parse("http://localhost:0/api/v1/").unwrap(),
            timeout: std::time::Duration::from_secs(1),
            ..test_client_config()
        };
        let http_client = Client::new();
        let providers_api =
            ProvidersApi::new(http_client, &config, default_providers_cache()).unwrap();

        // All convenience methods should handle network errors gracefully
        assert!(providers_api.get_provider_by_slug("openai").await.is_err());
        assert!(providers_api.get_provider_by_name("OpenAI").await.is_err());
        assert!(providers_api
            .get_providers_with_privacy_policy()
            .await
            .is_err());
        assert!(providers_api
            .get_providers_with_terms_of_service()
            .await
            .is_err());
        assert!(providers_api
            .get_providers_with_status_page()
            .await
            .is_err());
        assert!(providers_api.get_provider_slugs().await.is_err());
        assert!(providers_api.get_provider_names().await.is_err());
    }

    /// E2E test: verifies that a shared cache actually prevents duplicate network calls.
    /// Two ProvidersApi instances sharing the same Arc<Mutex<Cache>> should only hit
    /// the server once — the second call returns the cached value.
    #[tokio::test]
    async fn test_shared_cache_prevents_duplicate_network_calls() {
        use wiremock::{matchers, Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;

        // Respond with a minimal valid ProvidersResponse
        Mock::given(matchers::method("GET"))
            .and(matchers::path("/api/v1/providers"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "data": [{
                    "name": "TestProvider",
                    "slug": "test-provider",
                    "url": "https://test.example.com",
                    "privacy_policy_url": null,
                    "terms_of_service_url": null,
                    "status_page_url": null,
                    "context_length": 4096,
                    "max_completion_tokens": 2048
                }]
            })))
            .expect(1) // Assert mock is called exactly once
            .mount(&mock_server)
            .await;

        let config = ClientConfig {
            api_key: Some(SecureApiKey::new("sk-test123456789012345678901234567890").unwrap()),
            base_url: url::Url::parse(&format!("{}/api/v1/", mock_server.uri())).unwrap(),
            timeout: std::time::Duration::from_secs(5),
            ..test_client_config()
        };

        // Shared cache
        let cache = default_providers_cache();

        let http_client_1 = Client::new();
        let api1 = ProvidersApi::new(http_client_1, &config, cache.clone()).unwrap();

        let http_client_2 = Client::new();
        let api2 = ProvidersApi::new(http_client_2, &config, cache).unwrap();

        // First call hits the server
        let result1 = api1.get_providers().await;
        assert!(result1.is_ok(), "First call should succeed: {:?}", result1);
        assert_eq!(result1.unwrap().count(), 1);

        // Second call (different api instance, same cache) should use cache
        let result2 = api2.get_providers().await;
        assert!(
            result2.is_ok(),
            "Second call should succeed from cache: {:?}",
            result2
        );
        assert_eq!(result2.unwrap().count(), 1);

        // MockServer's .expect(1) will panic on drop if the mock was called more than once
    }
}