openrouter_rs/api/
models.rs

1use serde::{Deserialize, Serialize};
2use surf::http::headers::AUTHORIZATION;
3
4use crate::{error::OpenRouterError, types::ApiResponse, utils::handle_error};
5
6#[derive(Serialize, Deserialize, Debug)]
7pub struct Model {
8    id: String,
9    name: String,
10    created: f64,
11    description: String,
12    context_length: f64,
13    architecture: Architecture,
14    top_provider: TopProvider,
15    pricing: Pricing,
16    per_request_limits: Option<std::collections::HashMap<String, String>>,
17}
18
19impl Model {
20    pub fn id(&self) -> &str {
21        self.id.as_str()
22    }
23    pub fn display_name(&self) -> &str {
24        self.name.as_str()
25    }
26    pub fn max_token_count(&self) -> u32 {
27        self.context_length as u32
28    }
29    pub fn max_output_tokens(&self) -> Option<u32> {
30        self.top_provider
31            .max_completion_tokens
32            .map(|max_completion_tokens| max_completion_tokens as u32)
33    }
34}
35
36#[derive(Serialize, Deserialize, Debug)]
37pub struct Architecture {
38    modality: String,
39    tokenizer: String,
40    instruct_type: Option<String>,
41}
42
43#[derive(Serialize, Deserialize, Debug)]
44pub struct TopProvider {
45    context_length: Option<f64>,
46    max_completion_tokens: Option<f64>,
47    is_moderated: bool,
48}
49
50#[derive(Serialize, Deserialize, Debug)]
51pub struct Pricing {
52    prompt: String,
53    completion: String,
54    image: String,
55    request: String,
56    input_cache_read: String,
57    input_cache_write: String,
58    web_search: String,
59    internal_reasoning: String,
60}
61
62#[derive(Serialize, Deserialize, Debug)]
63pub struct Endpoint {
64    name: String,
65    context_length: f64,
66    pricing: EndpointPricing,
67    provider_name: String,
68    supported_parameters: Vec<String>,
69    quantization: Option<String>,
70    max_completion_tokens: Option<f64>,
71    max_prompt_tokens: Option<f64>,
72    status: Option<String>,
73}
74
75#[derive(Serialize, Deserialize, Debug)]
76pub struct EndpointPricing {
77    request: String,
78    image: String,
79    prompt: String,
80    completion: String,
81}
82
83#[derive(Serialize, Deserialize, Debug)]
84pub struct EndpointData {
85    id: String,
86    name: String,
87    created: f64,
88    description: String,
89    architecture: EndpointArchitecture,
90    endpoints: Vec<Endpoint>,
91}
92
93#[derive(Serialize, Deserialize, Debug)]
94pub struct EndpointArchitecture {
95    tokenizer: Option<String>,
96    instruct_type: Option<String>,
97    modality: Option<String>,
98}
99
100/// Returns a list of models available through the API
101///
102/// # Arguments
103///
104/// * `base_url` - The base URL of the OpenRouter API.
105/// * `api_key` - The API key for authentication.
106///
107/// # Returns
108///
109/// * `Result<Vec<Model>, OpenRouterError>` - A list of models or an error.
110pub async fn list_models(base_url: &str, api_key: &str) -> Result<Vec<Model>, OpenRouterError> {
111    let url = format!("{}/models", base_url);
112
113    let mut response = surf::get(url)
114        .header(AUTHORIZATION, format!("Bearer {}", api_key))
115        .await?;
116
117    if response.status().is_success() {
118        let model_list_response: ApiResponse<_> = response.body_json().await?;
119        Ok(model_list_response.data)
120    } else {
121        handle_error(response).await?;
122        unreachable!()
123    }
124}
125
126/// Returns details about the endpoints for a specific model
127///
128/// # Arguments
129///
130/// * `base_url` - The base URL of the OpenRouter API.
131/// * `api_key` - The API key for authentication.
132/// * `author` - The author of the model.
133/// * `slug` - The slug identifier for the model.
134///
135/// # Returns
136///
137/// * `Result<EndpointData, OpenRouterError>` - The endpoint data or an error.
138pub async fn list_model_endpoints(
139    base_url: &str,
140    api_key: &str,
141    author: &str,
142    slug: &str,
143) -> Result<EndpointData, OpenRouterError> {
144    let url = format!("{}/models/{}/{}", base_url, author, slug);
145
146    let mut response = surf::get(&url)
147        .header(AUTHORIZATION, format!("Bearer {}", api_key))
148        .await?;
149
150    if response.status().is_success() {
151        let endpoint_list_response: ApiResponse<_> = response.body_json().await?;
152        Ok(endpoint_list_response.data)
153    } else {
154        handle_error(response).await?;
155        unreachable!()
156    }
157}