Skip to main content

rig_extra/
get_openrouter_model_list.rs

1//! 获取openrouter中的模型列表
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
6pub struct Model {
7    pub slug: String,
8    #[serde(rename = "updated_at")]
9    pub updated_at: String,
10    #[serde(rename = "created_at")]
11    pub created_at: String,
12    pub name: String,
13    #[serde(rename = "short_name")]
14    pub short_name: String,
15    pub author: String,
16    pub description: String,
17    #[serde(rename = "context_length")]
18    pub context_length: i64,
19    #[serde(rename = "input_modalities")]
20    pub input_modalities: Vec<String>,
21    #[serde(rename = "output_modalities")]
22    pub output_modalities: Vec<String>,
23    #[serde(rename = "has_text_output")]
24    pub has_text_output: bool,
25    pub group: String,
26    pub permaslug: String,
27    #[serde(rename = "endpoint")]
28    #[serde(default)]
29    pub endpoint: Option<Endpoint>,
30}
31
32#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
33pub struct Endpoint {
34    pub name: String,
35    #[serde(rename = "context_length")]
36    pub context_length: i64,
37    #[serde(rename = "model_variant_slug")]
38    pub model_variant_slug: String,
39    #[serde(rename = "model_variant_permaslug")]
40    pub model_variant_permaslug: String,
41    #[serde(rename = "is_free")]
42    pub is_free: bool,
43}
44
45#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
46pub struct ModelsResponse {
47    pub data: Vec<Model>,
48}
49
50/// 获取 openrouter 模型列表
51pub async fn fetch_openrouter_model_list() -> Result<Vec<Model>, Box<dyn std::error::Error>> {
52    let client = reqwest::Client::new();
53    let resp = client
54        .get("https://openrouter.ai/api/frontend/models")
55        .header(
56            reqwest::header::USER_AGENT,
57            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",
58        )
59        .header(reqwest::header::ACCEPT, "application/json")
60        .send()
61        .await?;
62
63    if !resp.status().is_success() {
64        return Err(format!("request failed: {}", resp.status()).into());
65    }
66
67    let parsed: ModelsResponse = resp.json().await?;
68    Ok(parsed.data)
69}