openrouter-rs 0.11.1

A type-safe OpenRouter Rust SDK
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
use std::collections::HashMap;

use derive_builder::Builder;
use reqwest::Client as HttpClient;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use urlencoding::encode;

use crate::{
    error::OpenRouterError,
    transport::{request as transport_request, response as transport_response},
    types::{ApiResponse, Effort, ModelCategory, SupportedParameters},
};

#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct Model {
    pub id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub canonical_slug: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hugging_face_id: Option<String>,
    pub name: String,
    pub created: f64,
    #[serde(default)]
    pub description: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context_length: Option<f64>,
    pub architecture: Architecture,
    pub top_provider: TopProvider,
    pub pricing: Pricing,
    pub per_request_limits: Option<HashMap<String, String>>,
    #[serde(default)]
    pub supported_parameters: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub supported_voices: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_parameters: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expiration_date: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub knowledge_cutoff: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub links: Option<ModelLinks>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub benchmarks: Option<ModelBenchmarks>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning: Option<ModelReasoning>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct Architecture {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modality: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tokenizer: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub instruct_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub input_modalities: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output_modalities: Option<Vec<String>>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct TopProvider {
    pub context_length: Option<f64>,
    pub max_completion_tokens: Option<f64>,
    pub is_moderated: bool,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct Pricing {
    pub prompt: String,
    pub completion: String,
    pub image: Option<String>,
    pub request: Option<String>,
    pub input_cache_read: Option<String>,
    pub input_cache_write: Option<String>,
    pub web_search: Option<String>,
    pub internal_reasoning: Option<String>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct ModelLinks {
    pub details: String,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct AABenchmarkEntry {
    pub intelligence_index: Option<f64>,
    pub coding_index: Option<f64>,
    pub agentic_index: Option<f64>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct DABenchmarkEntry {
    pub arena: String,
    pub category: String,
    pub elo: f64,
    pub win_rate: f64,
    pub rank: u64,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct ModelBenchmarks {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub artificial_analysis: Option<AABenchmarkEntry>,
    #[serde(default)]
    pub design_arena: Vec<DABenchmarkEntry>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct ModelReasoning {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_effort: Option<Effort>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_enabled: Option<bool>,
    pub mandatory: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supported_efforts: Option<Vec<Effort>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supports_max_tokens: Option<bool>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct Endpoint {
    pub name: String,
    pub context_length: f64,
    pub pricing: EndpointPricing,
    pub provider_name: String,
    pub supported_parameters: Vec<String>,
    pub quantization: Option<String>,
    pub max_completion_tokens: Option<f64>,
    pub max_prompt_tokens: Option<f64>,
    pub status: Option<serde_json::Value>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct EndpointPricing {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image: Option<String>,
    pub prompt: String,
    pub completion: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct EndpointData {
    pub id: String,
    pub name: String,
    pub created: f64,
    pub description: String,
    pub architecture: EndpointArchitecture,
    pub endpoints: Vec<Endpoint>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub struct EndpointArchitecture {
    pub tokenizer: Option<String>,
    pub instruct_type: Option<String>,
    pub modality: Option<String>,
}

/// Extended query parameters for `GET /models`.
#[derive(Serialize, Deserialize, Debug, Clone, Default, Builder)]
#[builder(build_fn(error = "OpenRouterError"))]
#[non_exhaustive]
pub struct ListModelsParams {
    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub category: Option<ModelCategory>,
    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub supported_parameters: Option<SupportedParameters>,
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_modalities: Option<String>,
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort: Option<String>,
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub q: Option<String>,
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_modalities: Option<String>,
    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<u32>,
    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_price: Option<f64>,
    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_price: Option<f64>,
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arch: Option<String>,
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_authors: Option<String>,
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub providers: Option<String>,
    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub distillable: Option<bool>,
    #[builder(setter(strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub zdr: Option<bool>,
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub region: Option<String>,
}

impl ListModelsParams {
    pub fn builder() -> ListModelsParamsBuilder {
        ListModelsParamsBuilder::default()
    }

    fn is_empty(&self) -> bool {
        self.category.is_none()
            && self.supported_parameters.is_none()
            && self.output_modalities.is_none()
            && self.sort.is_none()
            && self.q.is_none()
            && self.input_modalities.is_none()
            && self.context.is_none()
            && self.min_price.is_none()
            && self.max_price.is_none()
            && self.arch.is_none()
            && self.model_authors.is_none()
            && self.providers.is_none()
            && self.distillable.is_none()
            && self.zdr.is_none()
            && self.region.is_none()
    }
}

/// Returns a list of models available through the API
///
/// # Arguments
///
/// * `base_url` - The base URL of the OpenRouter API.
/// * `api_key` - The API key for authentication.
/// * `category` - Optional category filter for the models.
/// * `supported_parameters` - Optional supported-parameter filter for the models.
///
/// # Returns
///
/// * `Result<Vec<Model>, OpenRouterError>` - A list of models or an error.
pub async fn list_models(
    base_url: &str,
    api_key: &str,
    category: Option<ModelCategory>,
    supported_parameters: Option<SupportedParameters>,
) -> Result<Vec<Model>, OpenRouterError> {
    let http_client = crate::transport::new_client()?;
    let params = ListModelsParams {
        category,
        supported_parameters,
        ..Default::default()
    };
    list_models_with_params_and_client(&http_client, base_url, api_key, Some(&params)).await
}

pub(crate) async fn list_models_with_client(
    http_client: &HttpClient,
    base_url: &str,
    api_key: &str,
    category: Option<ModelCategory>,
    supported_parameters: Option<SupportedParameters>,
) -> Result<Vec<Model>, OpenRouterError> {
    let params = ListModelsParams {
        category,
        supported_parameters,
        ..Default::default()
    };
    list_models_with_params_and_client(http_client, base_url, api_key, Some(&params)).await
}

/// Returns a list of models using the full upstream filter surface.
pub async fn list_models_with_params(
    base_url: &str,
    api_key: &str,
    params: Option<&ListModelsParams>,
) -> Result<Vec<Model>, OpenRouterError> {
    let http_client = crate::transport::new_client()?;
    list_models_with_params_and_client(&http_client, base_url, api_key, params).await
}

pub(crate) async fn list_models_with_params_and_client(
    http_client: &HttpClient,
    base_url: &str,
    api_key: &str,
    params: Option<&ListModelsParams>,
) -> Result<Vec<Model>, OpenRouterError> {
    let url = format!("{base_url}/models");
    let req =
        transport_request::with_bearer_auth(transport_request::get(http_client, &url), api_key);
    let response = match params {
        Some(params) if !params.is_empty() => req.query(params).send().await?,
        _ => req.send().await?,
    };

    if response.status().is_success() {
        let model_list_response: ApiResponse<_> =
            transport_response::parse_json_response(response, "model list").await?;
        Ok(model_list_response.data)
    } else {
        transport_response::handle_error(response).await?;
        unreachable!()
    }
}

/// Returns metadata about a specific model.
pub async fn get_model(
    base_url: &str,
    api_key: &str,
    author: &str,
    slug: &str,
) -> Result<Model, OpenRouterError> {
    let http_client = crate::transport::new_client()?;
    get_model_with_client(&http_client, base_url, api_key, author, slug).await
}

pub(crate) async fn get_model_with_client(
    http_client: &HttpClient,
    base_url: &str,
    api_key: &str,
    author: &str,
    slug: &str,
) -> Result<Model, OpenRouterError> {
    let encoded_author = encode(author);
    let encoded_slug = encode(slug);
    let url = format!("{base_url}/model/{encoded_author}/{encoded_slug}");

    let response =
        transport_request::with_bearer_auth(transport_request::get(http_client, &url), api_key)
            .send()
            .await?;

    if response.status().is_success() {
        let model_response: ApiResponse<_> =
            transport_response::parse_json_response(response, "model").await?;
        Ok(model_response.data)
    } else {
        transport_response::handle_error(response).await?;
        unreachable!()
    }
}

/// Returns details about the endpoints for a specific model
///
/// # Arguments
///
/// * `base_url` - The base URL of the OpenRouter API.
/// * `api_key` - The API key for authentication.
/// * `author` - The author of the model.
/// * `slug` - The slug identifier for the model.
///
/// # Returns
///
/// * `Result<EndpointData, OpenRouterError>` - The endpoint data or an error.
pub async fn list_model_endpoints(
    base_url: &str,
    api_key: &str,
    author: &str,
    slug: &str,
) -> Result<EndpointData, OpenRouterError> {
    let http_client = crate::transport::new_client()?;
    list_model_endpoints_with_client(&http_client, base_url, api_key, author, slug).await
}

pub(crate) async fn list_model_endpoints_with_client(
    http_client: &HttpClient,
    base_url: &str,
    api_key: &str,
    author: &str,
    slug: &str,
) -> Result<EndpointData, OpenRouterError> {
    let encoded_author = encode(author);
    let encoded_slug = encode(slug);
    let url = format!("{base_url}/models/{encoded_author}/{encoded_slug}/endpoints");

    let response =
        transport_request::with_bearer_auth(transport_request::get(http_client, &url), api_key)
            .send()
            .await?;

    if response.status().is_success() {
        let endpoint_list_response: ApiResponse<_> =
            transport_response::parse_json_response(response, "model endpoint list").await?;
        Ok(endpoint_list_response.data)
    } else {
        transport_response::handle_error(response).await?;
        unreachable!()
    }
}