Skip to main content

agent_engine/runtime/openai/
registry.rs

1//! Provider registry — catalog of known OpenAI-compatible endpoints.
2//!
3//! Connection/credential metadata (base URLs, key discovery) is broker-owned
4//! (`agent_core::auth::static_providers` / `agent_core::auth::broker`). This
5//! module keeps the engine-side model catalog and produces credential-free
6//! routing data: no function here returns or accepts an API key.
7
8use super::types::ProviderConfig;
9use agent_core::auth::broker;
10use serde::Deserialize;
11
12#[derive(Debug)]
13pub struct ProviderSpec {
14    pub key: &'static str,
15    pub name: &'static str,
16    pub base_url: &'static str,
17    pub env_vars: &'static [&'static str],
18    pub default_model: &'static str,
19    pub models: &'static [(&'static str, &'static str, &'static str)], // (id, label, tier)
20}
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct ProviderModelInfo {
24    pub id: String,
25    pub name: Option<String>,
26}
27
28#[derive(Debug, Deserialize)]
29struct ProviderModelsResponse {
30    data: Vec<ProviderModelsItem>,
31}
32
33#[derive(Debug, Deserialize)]
34struct ProviderModelsItem {
35    id: String,
36    #[serde(default)]
37    name: Option<String>,
38}
39
40pub fn parse_provider_models_response(
41    body: &str,
42) -> Result<Vec<ProviderModelInfo>, serde_json::Error> {
43    let response: ProviderModelsResponse = serde_json::from_str(body)?;
44    Ok(response
45        .data
46        .into_iter()
47        .filter(|item| !item.id.trim().is_empty())
48        .map(|item| ProviderModelInfo {
49            id: item.id,
50            name: item.name.filter(|name| !name.trim().is_empty()),
51        })
52        .collect())
53}
54
55pub fn providers() -> &'static [ProviderSpec] {
56    static PROVIDERS: std::sync::LazyLock<Vec<ProviderSpec>> = std::sync::LazyLock::new(|| {
57        vec![
58            ProviderSpec {
59                key: "groq",
60                name: "Groq",
61                base_url: "https://api.groq.com/openai/v1",
62                env_vars: &["GROQ_API_KEY"],
63                default_model: "llama-3.3-70b-versatile",
64                models: &[
65                    ("llama-3.3-70b-versatile", "Llama 3.3 70B", "S"),
66                    ("llama-3.1-8b-instant", "Llama 3.1 8B", "B"),
67                    (
68                        "meta-llama/llama-4-scout-17b-16e-instruct",
69                        "Llama 4 Scout",
70                        "A",
71                    ),
72                    (
73                        "meta-llama/llama-4-maverick-17b-128e-instruct",
74                        "Llama 4 Maverick",
75                        "S",
76                    ),
77                ],
78            },
79            ProviderSpec {
80                key: "cerebras",
81                name: "Cerebras",
82                base_url: "https://api.cerebras.ai/v1",
83                env_vars: &["CEREBRAS_API_KEY"],
84                default_model: "llama3.1-8b",
85                models: &[
86                    ("qwen-3-235b-a22b-instruct-2507", "Qwen3 235B", "S+"),
87                    ("llama3.1-8b", "Llama 3.1 8B", "B"),
88                ],
89            },
90            ProviderSpec {
91                key: "nvidia",
92                name: "NVIDIA NIM",
93                base_url: "https://integrate.api.nvidia.com/v1",
94                env_vars: &["NVIDIA_API_KEY"],
95                default_model: "meta/llama-3.3-70b-instruct",
96                models: &[
97                    (
98                        "qwen/qwen3-coder-480b-a35b-instruct",
99                        "Qwen3 Coder 480B",
100                        "S+",
101                    ),
102                    (
103                        "mistralai/mistral-large-3-675b-instruct-2512",
104                        "Mistral Large 675B",
105                        "A+",
106                    ),
107                    ("meta/llama-3.3-70b-instruct", "Llama 3.3 70B", "A"),
108                    (
109                        "meta/llama-4-maverick-17b-128e-instruct",
110                        "Llama 4 Maverick",
111                        "S",
112                    ),
113                    ("meta/llama-4-scout-17b-16e-instruct", "Llama 4 Scout", "A"),
114                    (
115                        "nvidia/llama-3.1-nemotron-ultra-253b-v1",
116                        "Nemotron Ultra 253B",
117                        "A+",
118                    ),
119                    (
120                        "mistralai/devstral-2-123b-instruct-2512",
121                        "Devstral 2 123B",
122                        "S+",
123                    ),
124                    ("minimaxai/minimax-m2.5", "MiniMax M2.5", "S+"),
125                    ("stepfun-ai/step-3.5-flash", "Step 3.5 Flash", "S+"),
126                ],
127            },
128            ProviderSpec {
129                key: "sambanova",
130                name: "SambaNova",
131                base_url: "https://api.sambanova.ai/v1",
132                env_vars: &["SAMBANOVA_API_KEY"],
133                default_model: "Meta-Llama-3.3-70B-Instruct",
134                models: &[
135                    ("QwQ-32B", "QwQ 32B", "A+"),
136                    ("Meta-Llama-3.3-70B-Instruct", "Llama 3.3 70B", "S"),
137                    ("Meta-Llama-3.1-8B-Instruct", "Llama 3.1 8B", "B"),
138                    ("DeepSeek-R1", "DeepSeek R1", "S+"),
139                    ("DeepSeek-R1-Distill-Llama-70B", "R1 Distill 70B", "A"),
140                    ("Qwen3-32B", "Qwen3 32B", "A"),
141                ],
142            },
143            ProviderSpec {
144                key: "openrouter",
145                name: "OpenRouter",
146                base_url: "https://openrouter.ai/api/v1",
147                env_vars: &["OPENROUTER_API_KEY"],
148                default_model: "meta-llama/llama-3.3-70b-instruct",
149                models: &[
150                    ("qwen/qwen3-coder", "Qwen3 Coder", "S+"),
151                    ("meta-llama/llama-3.3-70b-instruct", "Llama 3.3 70B", "S"),
152                    ("deepseek/deepseek-chat-v3-0324", "DeepSeek V3", "S"),
153                    ("google/gemma-3-27b-it", "Gemma 3 27B", "A"),
154                    (
155                        "mistralai/mistral-small-3.1-24b-instruct",
156                        "Mistral Small 3.1",
157                        "A",
158                    ),
159                ],
160            },
161            ProviderSpec {
162                key: "google",
163                name: "Google AI Studio",
164                base_url: "https://generativelanguage.googleapis.com/v1beta/openai",
165                env_vars: &["GOOGLE_API_KEY"],
166                default_model: "gemini-2.5-flash",
167                models: &[
168                    ("gemini-2.5-flash", "Gemini 2.5 Flash", "A+"),
169                    ("gemini-2.0-flash", "Gemini 2.0 Flash", "B+"),
170                    ("gemma-3-27b-it", "Gemma 3 27B", "A"),
171                ],
172            },
173            ProviderSpec {
174                key: "deepinfra",
175                name: "DeepInfra",
176                base_url: "https://api.deepinfra.com/v1/openai",
177                env_vars: &["DEEPINFRA_API_KEY", "DEEPINFRA_TOKEN"],
178                default_model: "meta-llama/Llama-3.3-70B-Instruct",
179                models: &[
180                    ("meta-llama/Llama-3.3-70B-Instruct", "Llama 3.3 70B", "S"),
181                    ("Qwen/Qwen2.5-Coder-32B-Instruct", "Qwen2.5 Coder 32B", "A"),
182                    ("deepseek-ai/DeepSeek-V3-0324", "DeepSeek V3", "S"),
183                ],
184            },
185            ProviderSpec {
186                key: "huggingface",
187                name: "HuggingFace",
188                base_url: "https://router.huggingface.co/v1",
189                env_vars: &["HUGGINGFACE_API_KEY", "HF_TOKEN"],
190                default_model: "meta-llama/Llama-3.3-70B-Instruct",
191                models: &[
192                    ("meta-llama/Llama-3.3-70B-Instruct", "Llama 3.3 70B", "S"),
193                    ("Qwen/Qwen2.5-72B-Instruct", "Qwen2.5 72B", "A"),
194                ],
195            },
196            ProviderSpec {
197                key: "fireworks",
198                name: "Fireworks AI",
199                base_url: "https://api.fireworks.ai/inference/v1",
200                env_vars: &["FIREWORKS_API_KEY"],
201                default_model: "accounts/fireworks/models/llama-v3p3-70b-instruct",
202                models: &[
203                    (
204                        "accounts/fireworks/models/llama-v3p3-70b-instruct",
205                        "Llama 3.3 70B",
206                        "S",
207                    ),
208                    (
209                        "accounts/fireworks/models/qwen2p5-coder-32b-instruct",
210                        "Qwen2.5 Coder 32B",
211                        "A",
212                    ),
213                ],
214            },
215            ProviderSpec {
216                key: "hyperbolic",
217                name: "Hyperbolic",
218                base_url: "https://api.hyperbolic.xyz/v1",
219                env_vars: &["HYPERBOLIC_API_KEY"],
220                default_model: "meta-llama/Llama-3.3-70B-Instruct",
221                models: &[
222                    ("meta-llama/Llama-3.3-70B-Instruct", "Llama 3.3 70B", "S"),
223                    ("Qwen/Qwen2.5-Coder-32B-Instruct", "Qwen2.5 Coder 32B", "A"),
224                    ("deepseek-ai/DeepSeek-V3-0324", "DeepSeek V3", "S"),
225                ],
226            },
227            ProviderSpec {
228                key: "scaleway",
229                name: "Scaleway",
230                base_url: "https://api.scaleway.ai/v1",
231                env_vars: &["SCALEWAY_API_KEY"],
232                default_model: "llama-3.3-70b-instruct",
233                models: &[
234                    ("llama-3.3-70b-instruct", "Llama 3.3 70B", "S"),
235                    ("qwen3-235b-a22b", "Qwen3 235B", "S+"),
236                ],
237            },
238            ProviderSpec {
239                key: "siliconflow",
240                name: "SiliconFlow",
241                base_url: "https://api.siliconflow.cn/v1",
242                env_vars: &["SILICONFLOW_API_KEY"],
243                default_model: "Qwen/Qwen3-8B",
244                models: &[
245                    ("Qwen/Qwen3-8B", "Qwen3 8B", "A-"),
246                    ("deepseek-ai/DeepSeek-R1", "DeepSeek R1", "S+"),
247                ],
248            },
249            ProviderSpec {
250                key: "together",
251                name: "Together AI",
252                base_url: "https://api.together.xyz/v1",
253                env_vars: &["TOGETHER_API_KEY"],
254                default_model: "meta-llama/Llama-3.3-70B-Instruct-Turbo",
255                models: &[
256                    (
257                        "meta-llama/Llama-3.3-70B-Instruct-Turbo",
258                        "Llama 3.3 70B",
259                        "S",
260                    ),
261                    ("Qwen/Qwen2.5-Coder-32B-Instruct", "Qwen2.5 Coder 32B", "A"),
262                    ("deepseek-ai/DeepSeek-V3", "DeepSeek V3", "S"),
263                ],
264            },
265            ProviderSpec {
266                key: "chutes",
267                name: "Chutes AI",
268                base_url: "https://llm.chutes.ai/v1",
269                env_vars: &["CHUTES_API_KEY"],
270                default_model: "deepseek-ai/DeepSeek-V3-0324",
271                models: &[("deepseek-ai/DeepSeek-V3-0324", "DeepSeek V3", "S")],
272            },
273            ProviderSpec {
274                key: "codestral",
275                name: "Codestral (Mistral)",
276                base_url: "https://api.mistral.ai/v1",
277                env_vars: &["CODESTRAL_API_KEY"],
278                default_model: "codestral-latest",
279                models: &[("codestral-latest", "Codestral", "B+")],
280            },
281            ProviderSpec {
282                key: "perplexity",
283                name: "Perplexity",
284                base_url: "https://api.perplexity.ai",
285                env_vars: &["PERPLEXITY_API_KEY", "PPLX_API_KEY"],
286                default_model: "llama-3.1-sonar-large-128k-online",
287                models: &[("llama-3.1-sonar-large-128k-online", "Sonar Large", "A+")],
288            },
289            ProviderSpec {
290                key: "ovhcloud",
291                name: "OVHcloud",
292                base_url: "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1",
293                env_vars: &["OVH_AI_ENDPOINTS_ACCESS_TOKEN"],
294                default_model: "Meta-Llama-3.3-70B-Instruct",
295                models: &[
296                    ("Meta-Llama-3.3-70B-Instruct", "Llama 3.3 70B", "S"),
297                    ("Qwen/QwQ-32B", "QwQ 32B", "A+"),
298                ],
299            },
300            ProviderSpec {
301                key: "kimi",
302                name: "Kimi (Moonshot AI)",
303                base_url: "https://api.moonshot.ai/v1",
304                env_vars: &["MOONSHOT_API_KEY", "KIMI_API_KEY"],
305                default_model: "kimi-k2.7-code",
306                models: &[
307                    ("kimi-k2.7-code", "Kimi K2.7 Code", "S+"),
308                    ("kimi-k2.7-code-highspeed", "Kimi K2.7 Code Highspeed", "S"),
309                    ("kimi-k3", "Kimi K3", "S+"),
310                    ("kimi-k2.6", "Kimi K2.6", "S"),
311                ],
312            },
313        ]
314    });
315    &PROVIDERS
316}
317
318/// Look up a provider by key. Returns routing data only when the broker
319/// reports a credential is available; the key itself never leaves the broker.
320pub fn resolve_provider(key: &str) -> Option<(ProviderConfig, &'static str)> {
321    let specs = providers();
322    let spec = specs.iter().find(|s| s.key == key)?;
323    if !broker::static_key_configured(spec.key) {
324        return None;
325    }
326    Some((
327        ProviderConfig {
328            base_url: spec.base_url.to_string(),
329            model: spec.default_model.to_string(),
330            provider: spec.key.to_string(),
331        },
332        spec.default_model,
333    ))
334}
335
336/// Resolve a provider + specific model to credential-free routing data.
337pub fn resolve_provider_model(key: &str, model: &str) -> Option<ProviderConfig> {
338    // Special case: local provider — dynamic (non-secret) URL configuration.
339    if key == "local" {
340        return Some(resolve_local(model));
341    }
342    let specs = providers();
343    let spec = specs.iter().find(|s| s.key == key)?;
344    if !broker::static_key_configured(spec.key) {
345        return None;
346    }
347    Some(ProviderConfig {
348        base_url: spec.base_url.to_string(),
349        model: model.to_string(),
350        provider: spec.key.to_string(),
351    })
352}
353
354/// Resolve `"provider/model"` shorthand.
355pub fn resolve_shorthand(s: &str) -> Option<ProviderConfig> {
356    let (provider_key, model) = s.split_once('/')?;
357    resolve_provider_model(provider_key, model)
358}
359
360/// Resolve `"openai-codex/model"` shorthand if Codex OAuth is configured.
361pub fn resolve_codex_shorthand(s: &str) -> Option<ProviderConfig> {
362    let (provider_key, model) = s.split_once('/')?;
363    if provider_key != "openai-codex" {
364        return None;
365    }
366    Some(ProviderConfig {
367        base_url: "https://chatgpt.com/backend-api".to_string(),
368        // Credentials are resolved immediately before the request through the
369        // credential broker. Routing metadata never carries secrets.
370        model: model.to_string(),
371        provider: "openai-codex".to_string(),
372    })
373}
374
375/// Resolve a local model endpoint (Ollama, LM Studio, vLLM, llama.cpp, etc.)
376///
377/// URL resolution (non-secret): `provider.local.url` config → `LOCAL_ENDPOINT`
378/// env → `http://localhost:11434/v1`. Any optional key stays broker-owned and
379/// is applied at request time by the broker proxy.
380fn resolve_local(model: &str) -> ProviderConfig {
381    ProviderConfig {
382        base_url: broker::local_endpoint_url(),
383        model: model.to_string(),
384        provider: "local".to_string(),
385    }
386}
387
388pub async fn fetch_provider_models(provider_key: &str) -> Result<Vec<ProviderModelInfo>, String> {
389    let spec = providers()
390        .iter()
391        .find(|spec| spec.key == provider_key)
392        .ok_or_else(|| format!("unknown provider: {provider_key}"))?;
393    // The broker applies the credential; this path never sees the key.
394    let response = broker::global_broker()
395        .proxy(broker::ProxyRequest {
396            provider: spec.key.to_string(),
397            method: broker::ProxyMethod::Get,
398            path: "/models".to_string(),
399            body: None,
400            stream: false,
401            body_bytes: None,
402        })
403        .await
404        .map_err(|e| e.to_string())?;
405    if !(200..300).contains(&response.status) {
406        return Err(format!("model list failed: HTTP {}", response.status));
407    }
408    parse_provider_models_response(&response.body)
409        .map_err(|e| format!("failed to parse model list: {e}"))
410}
411
412/// List all providers with (non-secret) key status.
413pub fn list_providers() -> Vec<(&'static str, &'static str, bool, usize)> {
414    providers()
415        .iter()
416        .map(|s| {
417            let has_key = broker::static_key_configured(s.key);
418            (s.key, s.name, has_key, s.models.len())
419        })
420        .collect()
421}
422
423/// List models for a provider.
424pub fn list_models(key: &str) -> Option<Vec<(&'static str, &'static str, &'static str)>> {
425    let specs = providers();
426    let spec = specs.iter().find(|s| s.key == key)?;
427    Some(spec.models.to_vec())
428}
429
430/// Find all providers with a broker-available credential.
431pub fn configured_providers() -> Vec<(&'static str, &'static str, &'static str)> {
432    providers()
433        .iter()
434        .filter(|s| broker::static_key_configured(s.key))
435        .map(|s| (s.key, s.name, s.default_model))
436        .collect()
437}
438
439#[cfg(test)]
440mod model_list_tests {
441    use super::*;
442
443    /// Cross-registry invariant: every engine provider joins onto a broker
444    /// static-provider spec with identical connection metadata, so the URL a
445    /// route uses is exactly the URL the broker pins for the credential.
446    #[test]
447    fn engine_registry_matches_broker_static_provider_table() {
448        for spec in providers() {
449            let core = agent_core::auth::static_provider(spec.key).unwrap_or_else(|| {
450                panic!(
451                    "engine provider '{}' missing from broker static table",
452                    spec.key
453                )
454            });
455            assert_eq!(
456                spec.base_url, core.base_url,
457                "base_url drift for {}",
458                spec.key
459            );
460            assert_eq!(
461                spec.env_vars, core.env_vars,
462                "env_vars drift for {}",
463                spec.key
464            );
465            assert_eq!(spec.name, core.name, "name drift for {}", spec.key);
466        }
467        assert_eq!(
468            providers().len(),
469            agent_core::auth::static_providers::STATIC_PROVIDERS.len(),
470            "broker table and engine catalog must cover the same providers"
471        );
472    }
473
474    /// Routing data is credential-free by construction: `ProviderConfig` has
475    /// no field that could hold a key, and local resolution keeps only the
476    /// non-secret endpoint URL.
477    #[test]
478    fn resolve_local_carries_endpoint_but_no_credential() {
479        let cfg = resolve_provider_model("local", "llama3").expect("local always resolves");
480        assert_eq!(cfg.provider, "local");
481        assert_eq!(cfg.model, "llama3");
482        assert!(!cfg.base_url.is_empty());
483        let debug = format!("{cfg:?}");
484        assert!(
485            !debug.to_lowercase().contains("api_key"),
486            "no key field may exist: {debug}"
487        );
488    }
489
490    #[test]
491    fn parses_openrouter_models_response() {
492        let json = r#"{
493            "data": [
494                { "id": "qwen/qwen3-coder", "name": "Qwen: Qwen3 Coder" },
495                { "id": "openai/gpt-oss-120b" }
496            ]
497        }"#;
498
499        let models = parse_provider_models_response(json).expect("parse models");
500        assert_eq!(models.len(), 2);
501        assert_eq!(models[0].id, "qwen/qwen3-coder");
502        assert_eq!(models[0].name.as_deref(), Some("Qwen: Qwen3 Coder"));
503        assert_eq!(models[1].id, "openai/gpt-oss-120b");
504        assert_eq!(models[1].name, None);
505    }
506}