openrouter_api 0.7.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
#![allow(dead_code)]
use crate::error::{Error, Result};
use crate::types::analytics::{ActivityRequest, ActivityResponse, SortField, SortOrder};
use crate::utils::retry::operations::GET_ACTIVITY;
use crate::utils::{retry::execute_with_retry_builder, retry::handle_response_json};
use reqwest::Client;
use urlencoding::encode;

/// API endpoint for analytics and activity data.
pub struct AnalyticsApi {
    pub(crate) client: Client,
    pub(crate) config: crate::client::ApiConfig,
}

impl AnalyticsApi {
    /// Creates a new AnalyticsApi with the given reqwest client and configuration.
    #[must_use = "returns an API client that should be used for analytics operations"]
    pub fn new(client: Client, config: &crate::client::ClientConfig) -> Result<Self> {
        Ok(Self {
            client,
            config: config.to_api_config()?,
        })
    }

    /// Retrieves activity data for the authenticated user.
    ///
    /// This endpoint returns detailed usage and activity information including
    /// request costs, token usage, latency data, and feature usage statistics.
    ///
    /// # Arguments
    ///
    /// * `request` - ActivityRequest containing filtering and pagination parameters
    ///
    /// # Returns
    ///
    /// Returns an `ActivityResponse` containing:
    /// - List of activity data entries with detailed request information
    /// - Total count of entries matching query
    /// - Whether more results are available
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The request parameters are invalid (bad date format, invalid sort order, etc.)
    /// - The API request fails (network issues, authentication, etc.)
    /// - The response cannot be parsed
    /// - The server returns an error status code
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use openrouter_api::OpenRouterClient;
    /// use openrouter_api::types::analytics::{ActivityRequest, SortField, SortOrder};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OpenRouterClient::from_env()?;
    ///
    ///     // Get activity for last 7 days
    ///     let request = ActivityRequest::new()
    ///         .with_start_date("2024-01-01")
    ///         .with_end_date("2024-01-07")
    ///         .with_sort(SortField::CreatedAt)
    ///         .with_order(SortOrder::Descending)
    ///         .with_limit(100);
    ///
    ///     let response = client.analytics()?.get_activity(request).await?;
    ///
    ///     println!("Total requests: {}", response.data.len());
    ///     println!("Total cost: ${:.6}", response.total_cost());
    ///     println!("Total tokens: {}", response.total_tokens());
    ///     println!("Success rate: {:.1}%", response.success_rate());
    ///     println!("Streaming rate: {:.1}%", response.streaming_rate());
    ///
    ///     // Group by model
    ///     let model_groups = response.group_by_model();
    ///     for (model, activities) in model_groups {
    ///         let stats = response.model_stats(&model);
    ///         println!("Model {}: {} requests, ${:.6} total cost",
    ///                  model, stats.request_count, stats.total_cost);
    ///     }
    ///
    ///     // Feature usage percentages
    ///     let features = response.feature_usage_percentages();
    ///     println!("Web search usage: {:.1}%", features.web_search);
    ///     println!("Media usage: {:.1}%", features.media);
    ///     println!("Reasoning usage: {:.1}%", features.reasoning);
    ///     println!("Streaming usage: {:.1}%", features.streaming);
    ///
    ///     Ok(())
    /// }
    /// ```
    #[must_use = "returns an activity response that should be processed"]
    pub async fn get_activity(&self, request: ActivityRequest) -> Result<ActivityResponse> {
        // Validate the request parameters
        request.validate().map_err(Error::ConfigError)?;

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

        // Build query parameters
        let mut query_params = Vec::new();

        if let Some(start_date) = &request.start_date {
            query_params.push(("start_date", encode(start_date).to_string()));
        }

        if let Some(end_date) = &request.end_date {
            query_params.push(("end_date", encode(end_date).to_string()));
        }

        if let Some(model) = &request.model {
            query_params.push(("model", encode(model).to_string()));
        }

        if let Some(provider) = &request.provider {
            query_params.push(("provider", encode(provider).to_string()));
        }

        if let Some(sort) = &request.sort {
            query_params.push(("sort", encode(sort.as_str()).to_string()));
        }

        if let Some(order) = &request.order {
            query_params.push(("order", encode(order.as_str()).to_string()));
        }

        if let Some(limit) = request.limit {
            query_params.push(("limit", limit.to_string()));
        }

        if let Some(offset) = request.offset {
            query_params.push(("offset", offset.to_string()));
        }

        // Execute request with retry logic
        let response = execute_with_retry_builder(&self.config.retry_config, GET_ACTIVITY, || {
            let mut req_builder = self
                .client
                .get(url.clone())
                .headers((*self.config.headers).clone());

            // Add query parameters if any
            if !query_params.is_empty() {
                req_builder = req_builder.query(&query_params);
            }

            req_builder
        })
        .await?;

        // Handle response with consistent error parsing
        handle_response_json::<ActivityResponse>(response, GET_ACTIVITY).await
    }

    /// Retrieves activity data for a specific date range with default parameters.
    ///
    /// This is a convenience method that creates an ActivityRequest with the specified
    /// date range and uses sensible defaults for other parameters.
    ///
    /// # Arguments
    ///
    /// * `start_date` - Start date in YYYY-MM-DD format
    /// * `end_date` - End date in YYYY-MM-DD format
    ///
    /// # Returns
    ///
    /// Returns an `ActivityResponse` containing activity data for the specified date range.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use openrouter_api::OpenRouterClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OpenRouterClient::from_env()?;
    ///
    ///     // Get activity for the last 7 days
    ///     let response = client.analytics()?
    ///         .get_activity_by_date_range("2024-01-01", "2024-01-07")
    ///         .await?;
    ///
    ///     println!("Found {} requests", response.data.len());
    ///     println!("Total cost: ${:.6}", response.total_cost());
    ///
    ///     Ok(())
    /// }
    /// ```
    #[must_use = "returns the activity response that should be processed"]
    pub async fn get_activity_by_date_range(
        &self,
        start_date: &str,
        end_date: &str,
    ) -> Result<ActivityResponse> {
        let request = ActivityRequest::new()
            .with_start_date(start_date)
            .with_end_date(end_date)
            .with_sort(SortField::CreatedAt)
            .with_order(SortOrder::Descending);

        self.get_activity(request).await
    }

    /// Retrieves recent activity data (last 30 days) with default parameters.
    ///
    /// This is a convenience method that retrieves activity for the last 30 days
    /// with sensible defaults for sorting and pagination.
    ///
    /// # Returns
    ///
    /// Returns an `ActivityResponse` containing recent activity data.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use openrouter_api::OpenRouterClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OpenRouterClient::from_env()?;
    ///
    ///     // Get recent activity
    ///     let response = client.analytics()?.get_recent_activity().await?;
    ///
    ///     println!("Found {} recent requests", response.data.len());
    ///     println!("Success rate: {:.1}%", response.success_rate());
    ///
    ///     Ok(())
    /// }
    /// ```
    #[must_use = "returns the activity response that should be processed"]
    pub async fn get_recent_activity(&self) -> Result<ActivityResponse> {
        // Calculate date for recent activity
        let end_date = chrono::Utc::now().format("%Y-%m-%d").to_string();
        let start_date = (chrono::Utc::now()
            - chrono::Duration::days(crate::types::analytics::constants::DEFAULT_RECENT_DAYS))
        .format("%Y-%m-%d")
        .to_string();

        let request = ActivityRequest::new()
            .with_start_date(start_date)
            .with_end_date(end_date)
            .with_sort(SortField::CreatedAt)
            .with_order(SortOrder::Descending)
            .with_limit(crate::types::analytics::constants::MAX_LIMIT);

        self.get_activity(request).await
    }

    /// Retrieves activity data for a specific model.
    ///
    /// This is a convenience method that filters activity data by model name.
    ///
    /// # Arguments
    ///
    /// * `model` - The model name to filter by
    /// * `start_date` - Optional start date in YYYY-MM-DD format
    /// * `end_date` - Optional end date in YYYY-MM-DD format
    ///
    /// # Returns
    ///
    /// Returns an `ActivityResponse` containing activity data for the specified model.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use openrouter_api::OpenRouterClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OpenRouterClient::from_env()?;
    ///
    ///     // Get activity for a specific model
    ///     let response = client.analytics()?
    ///         .get_activity_by_model("anthropic/claude-3-opus", None, None)
    ///         .await?;
    ///
    ///     let stats = response.model_stats("anthropic/claude-3-opus");
    ///     println!("Model {}: {} requests", stats.model, stats.request_count);
    ///     println!("Total cost: ${:.6}", stats.total_cost);
    ///     println!("Success rate: {:.1}%", stats.success_rate);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_activity_by_model(
        &self,
        model: &str,
        start_date: Option<&str>,
        end_date: Option<&str>,
    ) -> Result<ActivityResponse> {
        let mut request = ActivityRequest::new()
            .with_model(model)
            .with_sort(SortField::CreatedAt)
            .with_order(SortOrder::Descending);

        if let Some(start) = start_date {
            request = request.with_start_date(start);
        }

        if let Some(end) = end_date {
            request = request.with_end_date(end);
        }

        self.get_activity(request).await
    }

    /// Retrieves activity data for a specific provider.
    ///
    /// This is a convenience method that filters activity data by provider name.
    ///
    /// # Arguments
    ///
    /// * `provider` - The provider name to filter by
    /// * `start_date` - Optional start date in YYYY-MM-DD format
    /// * `end_date` - Optional end date in YYYY-MM-DD format
    ///
    /// # Returns
    ///
    /// Returns an `ActivityResponse` containing activity data for the specified provider.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use openrouter_api::OpenRouterClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = OpenRouterClient::from_env()?;
    ///
    ///     // Get activity for a specific provider
    ///     let response = client.analytics()?
    ///         .get_activity_by_provider("Anthropic", None, None)
    ///         .await?;
    ///
    ///     let stats = response.provider_stats("Anthropic");
    ///     println!("Provider {}: {} requests", stats.provider, stats.request_count);
    ///     println!("Total cost: ${:.6}", stats.total_cost);
    ///     println!("Success rate: {:.1}%", stats.success_rate);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_activity_by_provider(
        &self,
        provider: &str,
        start_date: Option<&str>,
        end_date: Option<&str>,
    ) -> Result<ActivityResponse> {
        let mut request = ActivityRequest::new()
            .with_provider(provider)
            .with_sort(SortField::CreatedAt)
            .with_order(SortOrder::Descending);

        if let Some(start) = start_date {
            request = request.with_start_date(start);
        }

        if let Some(end) = end_date {
            request = request.with_end_date(end);
        }

        self.get_activity(request).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_analytics_api_new() {
        use crate::tests::test_helpers::test_client_config;

        let config = test_client_config();
        let client = Client::new();
        let analytics_api = AnalyticsApi::new(client, &config).unwrap();

        // Verify that the API config was created successfully
        // The API key should NOT be stored in the API config for security reasons
        // headers is now Arc<HeaderMap>, but Arc implements Deref so methods work the same
        assert!(!analytics_api.config.headers.is_empty());
        assert!(analytics_api.config.headers.contains_key("authorization"));
    }

    #[test]
    fn test_activity_request_builder() {
        let request = ActivityRequest::new()
            .with_start_date("2024-01-01")
            .with_end_date("2024-01-31")
            .with_model("test-model")
            .with_provider("test-provider")
            .with_sort(SortField::CreatedAt)
            .with_order(SortOrder::Descending)
            .with_limit(100)
            .with_offset(0);

        assert_eq!(request.start_date, Some("2024-01-01".to_string()));
        assert_eq!(request.end_date, Some("2024-01-31".to_string()));
        assert_eq!(request.model, Some("test-model".to_string()));
        assert_eq!(request.provider, Some("test-provider".to_string()));
        assert_eq!(request.sort, Some(SortField::CreatedAt));
        assert_eq!(request.order, Some(SortOrder::Descending));
        assert_eq!(request.limit, Some(100));
        assert_eq!(request.offset, Some(0));
    }

    #[test]
    fn test_query_parameter_encoding() {
        // Test that special characters in parameters are properly encoded
        let request = ActivityRequest::new()
            .with_model("model with spaces & symbols")
            .with_provider("provider/test");

        assert!(request.validate().is_ok());
        assert_eq!(
            request.model,
            Some("model with spaces & symbols".to_string())
        );
        assert_eq!(request.provider, Some("provider/test".to_string()));
    }

    #[test]
    fn test_analytics_api_base_url_resolves_correct_path() {
        use crate::tests::test_helpers::test_client_config;

        let config = test_client_config();
        let client = Client::new();
        let analytics_api = AnalyticsApi::new(client, &config).unwrap();
        let url = analytics_api.config.base_url.join("activity").unwrap();

        assert!(
            url.path().ends_with("/activity"),
            "Expected path ending with /activity, got: {}",
            url.path()
        );
        assert!(
            !url.path().contains("/api/v1/api/v1/"),
            "activity endpoint must not duplicate /api/v1/: {}",
            url.path()
        );
    }
}