Skip to main content

llm_codegen/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use proc_macro2::{Ident, TokenStream};
4use quote::{ToTokens, format_ident, quote};
5use serde::Deserialize;
6use std::borrow::Cow;
7use std::collections::{BTreeMap, HashMap, HashSet};
8use std::fmt::Write;
9use std::path::Path;
10use utils::ReasoningEffort;
11
12/// Output of the code generator.
13pub struct GeneratedOutput {
14    /// The generated Rust source (for `generated.rs`).
15    pub rust_source: String,
16    /// Per-provider markdown documentation keyed by provider identifier.
17    ///
18    /// Keys are provider `dev_ids` (e.g. `"anthropic"`, `"ollama"`) and values
19    /// are markdown strings suitable for `#![doc = include_str!(...)]`.
20    pub provider_docs: BTreeMap<String, String>,
21}
22
23#[derive(Debug, thiserror::Error)]
24pub enum CodegenError {
25    #[error("read: {0}")]
26    Read(#[from] std::io::Error),
27    #[error("parse: {0}")]
28    Parse(#[from] serde_json::Error),
29    #[error("Provider '{0}' not found in models.dev data")]
30    ProviderNotFound(String),
31    #[error("Configured model '{model_id}' was not found in provider '{provider_id}'")]
32    ConfiguredModelNotFound { provider_id: String, model_id: String },
33    #[error("Configured model '{model_id}' is duplicated for provider '{provider_id}'")]
34    DuplicateConfiguredModel { provider_id: String, model_id: String },
35    #[error("Configured model '{model_id}' is not tool-capable in provider '{provider_id}'")]
36    ConfiguredModelUnavailable { provider_id: String, model_id: String },
37    #[error("Model '{model_id}' declares unsupported reasoning effort '{effort}'")]
38    UnsupportedReasoningEffort { model_id: String, effort: String },
39    #[error("Model '{model_id}' declares unsupported wire shape '{shape}'")]
40    UnsupportedWireShape { model_id: String, shape: String },
41    #[error("Model '{model_id}' must declare both an endpoint and wire shape")]
42    IncompleteTransport { model_id: String },
43}
44
45pub fn generate(models_json_path: &Path) -> Result<GeneratedOutput, CodegenError> {
46    let json_bytes = std::fs::read_to_string(models_json_path)?;
47    let data: ModelsDevData = serde_json::from_str(&json_bytes)?;
48
49    let provider_models = build_provider_models(&data)?;
50    let ctx = CodegenCtx { provider_models };
51    Ok(GeneratedOutput { rust_source: emit_generated_source(&ctx), provider_docs: emit_provider_docs(&ctx) })
52}
53
54type ModelsDevData = HashMap<String, ProviderData>;
55
56#[derive(Debug, Deserialize)]
57struct ProviderData {
58    #[serde(default)]
59    models: HashMap<String, ModelData>,
60}
61
62#[derive(Debug, Deserialize)]
63struct ModelData {
64    id: String,
65    name: String,
66    #[serde(default)]
67    tool_call: Option<bool>,
68    #[serde(default)]
69    reasoning: Option<bool>,
70    #[serde(default)]
71    reasoning_options: Vec<ReasoningOption>,
72    #[serde(default)]
73    cost: Option<CostData>,
74    #[serde(default)]
75    limit: Option<LimitData>,
76    #[serde(default)]
77    modalities: Option<ModalitiesData>,
78    #[serde(default)]
79    provider: Option<ModelProviderData>,
80}
81
82/// Per-model transport override.
83#[derive(Debug, Deserialize)]
84struct ModelProviderData {
85    #[serde(default)]
86    api: Option<String>,
87    #[serde(default)]
88    shape: Option<String>,
89}
90
91#[derive(Debug, Deserialize)]
92#[serde(tag = "type", rename_all = "snake_case")]
93enum ReasoningOption {
94    Effort { values: Vec<Option<String>> },
95    Toggle,
96    BudgetTokens,
97}
98
99#[derive(Debug, Deserialize, Default)]
100struct ModalitiesData {
101    #[serde(default)]
102    input: Vec<String>,
103}
104
105#[derive(Debug, Clone, PartialEq, Deserialize)]
106struct CostData {
107    #[serde(default)]
108    input: f64,
109    #[serde(default)]
110    output: f64,
111    #[serde(default)]
112    cache_read: Option<f64>,
113    #[serde(default)]
114    cache_write: Option<f64>,
115}
116
117#[derive(Debug, Deserialize)]
118struct LimitData {
119    #[serde(default)]
120    context: u32,
121}
122
123impl CostData {
124    fn has_prompt_caching(&self) -> bool {
125        self.cache_read.is_some() || self.cache_write.is_some()
126    }
127}
128
129/// Provider configuration for codegen, for catalog and local providers alike.
130struct ProviderConfig {
131    /// Unique provider key used in `provider_models` map (e.g. "codex")
132    dev_id: &'static str,
133    /// models.dev provider ID to read models from (defaults to `dev_id` when `None`)
134    source_dev_id: Option<&'static str>,
135    /// Additional models.dev keys whose models are merged into this provider
136    extra_source_ids: &'static [&'static str],
137    /// When set, the provider exposes only these models (e.g. subscription-gated providers).
138    explicit_models: Option<&'static [ExplicitModel]>,
139    /// Our Rust enum name (e.g. "Gemini")
140    enum_name: &'static str,
141    /// Our internal provider name used for parsing (e.g. "gemini")
142    parser_name: &'static str,
143    /// OpenTelemetry `GenAI` semantic-convention provider name.
144    genai_provider_name: &'static str,
145    /// Human-readable provider name (e.g. "AWS Bedrock")
146    display_name: &'static str,
147    /// Env var our code actually checks (None for providers with complex credential chains)
148    env_var: Option<&'static str>,
149    /// OAuth provider ID for providers that require OAuth login (e.g. "codex")
150    oauth_provider_id: Option<&'static str>,
151    /// Fallback levels when source metadata does not declare granular efforts.
152    fallback_reasoning_levels: &'static [ReasoningEffort],
153    /// Which models can turn reasoning off.
154    reasoning_off: ReasoningOff,
155    /// When false (subscription-billed providers), models carry no pricing.
156    per_token_pricing: bool,
157    /// When true, a model's `provider.api`/`provider.shape` metadata is read as a
158    /// per-model transport override. Off elsewhere because most providers publish
159    /// unrelated data (npm package names) under the same key.
160    use_model_transport: bool,
161    /// Transports for models whose metadata declares none.
162    transport_overrides: &'static [TransportOverride],
163    model_ids: ModelIds,
164}
165
166/// How `LlmModel::{Enum}` identifies a provider's models.
167#[derive(Clone, Copy, PartialEq, Eq)]
168enum ModelIds {
169    /// A generated `{Enum}Model` catalog enum.
170    Catalog,
171    /// A generated `{Enum}FoundationModel` catalog enum inside a hand-written
172    /// `{Enum}Model` wrapper (defined outside of codegen) that adds a
173    /// `Profile(String)` fall-through plus any provider-specific parsing policy.
174    /// Used for Bedrock to accept arbitrary inference profile IDs at runtime
175    /// while keeping ARNs out of model identity.
176    Hybrid,
177    /// A model name supplied at runtime (`LlmModel::{Enum}(String)`), with no
178    /// catalog enum.
179    Runtime,
180}
181
182/// Mirrors `ReasoningOff` in `llm::catalog`.
183#[derive(Debug, Clone, Copy)]
184enum ReasoningOff {
185    Always,
186    Effort,
187    ModelTransport,
188    Never,
189}
190
191/// Mirrors `llm::ReasoningDisabledSupport`.
192#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
193enum ReasoningDisabledSupport {
194    #[default]
195    Unsupported,
196    Effort,
197    Toggle,
198}
199
200/// Mirrors `llm::ReasoningControl`.
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202enum ReasoningControl {
203    Effort,
204    Budget,
205    BudgetAndEffort,
206}
207
208struct TransportOverride {
209    matches: ModelMatch,
210    transport: TransportInfo,
211}
212
213enum ModelMatch {
214    Prefixes(&'static [&'static str]),
215    /// IDs containing the text anywhere, so inference-profile IDs such as
216    /// `us.anthropic.claude-…` match along with their foundation model.
217    Contains(&'static str),
218}
219
220impl TransportOverride {
221    fn for_model(&self, model_id: &str) -> Option<TransportInfo> {
222        let matches = match self.matches {
223            ModelMatch::Prefixes(prefixes) => prefixes.iter().any(|prefix| model_id.starts_with(prefix)),
224            ModelMatch::Contains(text) => model_id.contains(text),
225        };
226        matches.then(|| self.transport.clone())
227    }
228}
229
230impl ProviderConfig {
231    /// Shorthand for providers with default `source_dev_id`, `explicit_models`, and `oauth_provider_id`.
232    const fn standard(
233        dev_id: &'static str,
234        enum_name: &'static str,
235        parser_name: &'static str,
236        display_name: &'static str,
237        env_var: Option<&'static str>,
238    ) -> Self {
239        Self {
240            dev_id,
241            source_dev_id: None,
242            extra_source_ids: &[],
243            explicit_models: None,
244            enum_name,
245            parser_name,
246            genai_provider_name: parser_name,
247            display_name,
248            env_var,
249            oauth_provider_id: None,
250            fallback_reasoning_levels: &[ReasoningEffort::Low, ReasoningEffort::Medium, ReasoningEffort::High],
251            reasoning_off: ReasoningOff::Always,
252            per_token_pricing: true,
253            use_model_transport: false,
254            transport_overrides: &[],
255            model_ids: ModelIds::Catalog,
256        }
257    }
258
259    const fn local(
260        enum_name: &'static str,
261        parser_name: &'static str,
262        genai_provider_name: &'static str,
263        display_name: &'static str,
264    ) -> Self {
265        Self {
266            genai_provider_name,
267            reasoning_off: ReasoningOff::Never,
268            model_ids: ModelIds::Runtime,
269            ..Self::standard(parser_name, enum_name, parser_name, display_name, None)
270        }
271    }
272
273    fn is_local(&self) -> bool {
274        self.model_ids == ModelIds::Runtime
275    }
276
277    /// Inner catalog-enum name. For hybrid providers the outer `{enum_name}Model`
278    /// is a wrapper; the catalog enum is `{enum_name}FoundationModel`.
279    fn inner_enum_name(&self) -> String {
280        if self.model_ids == ModelIds::Hybrid {
281            format!("{}FoundationModel", self.enum_name)
282        } else {
283            format!("{}Model", self.enum_name)
284        }
285    }
286
287    /// Outer enum name as referenced by `LlmModel::{enum_name}(...)`.
288    fn outer_enum_name(&self) -> String {
289        format!("{}Model", self.enum_name)
290    }
291
292    /// The models.dev key to look up in the JSON data.
293    fn json_key(&self) -> &'static str {
294        self.source_dev_id.unwrap_or(self.dev_id)
295    }
296}
297
298const PROVIDERS: &[ProviderConfig] = &[
299    ProviderConfig::standard("anthropic", "Anthropic", "anthropic", "Anthropic", Some("ANTHROPIC_API_KEY")),
300    ProviderConfig {
301        source_dev_id: Some("azure"),
302        genai_provider_name: "azure.ai.openai",
303        reasoning_off: ReasoningOff::Effort,
304        ..ProviderConfig::standard(
305            "azure-foundry",
306            "AzureFoundry",
307            "azure-foundry",
308            "Microsoft Foundry",
309            Some("AZURE_OPENAI_API_KEY"),
310        )
311    },
312    ProviderConfig {
313        source_dev_id: Some("openai"),
314        explicit_models: Some(CODEX_SUBSCRIPTION_MODELS),
315        genai_provider_name: "openai",
316        oauth_provider_id: Some("codex"),
317        fallback_reasoning_levels: &[
318            ReasoningEffort::Low,
319            ReasoningEffort::Medium,
320            ReasoningEffort::High,
321            ReasoningEffort::Xhigh,
322        ],
323        per_token_pricing: false,
324        ..ProviderConfig::standard("codex", "Codex", "codex", "Codex", None)
325    },
326    ProviderConfig {
327        reasoning_off: ReasoningOff::Effort,
328        ..ProviderConfig::standard("deepseek", "DeepSeek", "deepseek", "DeepSeek", Some("DEEPSEEK_API_KEY"))
329    },
330    ProviderConfig {
331        source_dev_id: Some("fireworks-ai"),
332        reasoning_off: ReasoningOff::Effort,
333        ..ProviderConfig::standard("fireworks", "Fireworks", "fireworks", "Fireworks AI", Some("FIREWORKS_API_KEY"))
334    },
335    ProviderConfig {
336        genai_provider_name: "gcp.gemini",
337        ..ProviderConfig::standard("google", "Gemini", "gemini", "Gemini", Some("GEMINI_API_KEY"))
338    },
339    ProviderConfig {
340        genai_provider_name: "moonshot_ai",
341        reasoning_off: ReasoningOff::Effort,
342        ..ProviderConfig::standard("moonshotai", "Moonshot", "moonshot", "Moonshot", Some("MOONSHOT_API_KEY"))
343    },
344    ProviderConfig::standard("openai", "Openai", "openai", "OpenAI", Some("OPENAI_API_KEY")),
345    ProviderConfig::standard("openrouter", "OpenRouter", "openrouter", "OpenRouter", Some("OPENROUTER_API_KEY")),
346    ProviderConfig::standard("xiaomi", "Xiaomi", "xiaomi", "Xiaomi", Some("XIAOMI_API_KEY")),
347    ProviderConfig {
348        extra_source_ids: &["zai-coding-plan"],
349        reasoning_off: ReasoningOff::Effort,
350        ..ProviderConfig::standard("zai", "ZAi", "zai", "ZAI", Some("ZAI_API_KEY"))
351    },
352    ProviderConfig {
353        genai_provider_name: "aws.bedrock",
354        reasoning_off: ReasoningOff::ModelTransport,
355        use_model_transport: true,
356        transport_overrides: &[
357            TransportOverride {
358                matches: ModelMatch::Prefixes(&["us.openai.gpt-6-", "us.openai.gpt-6.1-sol"]),
359                transport: TransportInfo::OpenAiResponses {
360                    base_url_template: Cow::Borrowed("https://bedrock-runtime.${AWS_REGION}.amazonaws.com/openai/v1"),
361                },
362            },
363            TransportOverride {
364                matches: ModelMatch::Contains("anthropic.claude-"),
365                transport: TransportInfo::AnthropicMessages,
366            },
367        ],
368        model_ids: ModelIds::Hybrid,
369        ..ProviderConfig::standard("amazon-bedrock", "Bedrock", "bedrock", "AWS Bedrock", None)
370    },
371    ProviderConfig::local("Ollama", "ollama", "ollama", "Ollama"),
372    ProviderConfig::local("LlamaCpp", "llamacpp", "llama.cpp", "LlamaCpp"),
373];
374
375struct ExplicitModel {
376    id: &'static str,
377    context_window: u32,
378}
379
380impl ExplicitModel {
381    const fn new(id: &'static str, context_window: u32) -> Self {
382        Self { id, context_window }
383    }
384}
385
386const CODEX_SUBSCRIPTION_MODELS: &[ExplicitModel] = &[
387    ExplicitModel::new("gpt-6.1-sol", 272_000),
388    ExplicitModel::new("gpt-6.1-terra", 500_000),
389    ExplicitModel::new("gpt-6-sol", 272_000),
390    ExplicitModel::new("gpt-6-astra", 272_000),
391    ExplicitModel::new("gpt-6-luna", 272_000),
392    ExplicitModel::new("gpt-5.6-sol", 272_000),
393    ExplicitModel::new("gpt-5.6-terra", 272_000),
394    ExplicitModel::new("gpt-5.6-luna", 272_000),
395    ExplicitModel::new("gpt-5.5", 272_000),
396];
397
398#[derive(Debug, Clone)]
399struct ModelInfo {
400    variant_name: String,
401    model_id: String,
402    display_name: String,
403    context_window: u32,
404    reasoning: ReasoningMetadata,
405    input_modalities: Vec<String>,
406    pricing: Option<CostData>,
407    supports_prompt_caching: bool,
408    transport: Option<TransportInfo>,
409}
410
411#[derive(Debug, Clone)]
412struct ReasoningMetadata {
413    levels: Vec<ReasoningEffort>,
414    disabled_support: ReasoningDisabledSupport,
415    control: ReasoningControl,
416}
417
418#[derive(Default)]
419struct ListedReasoningOptions<'a> {
420    efforts: Option<Vec<&'a str>>,
421    disabled_support: ReasoningDisabledSupport,
422    budget_tokens: bool,
423}
424
425impl<'a> ListedReasoningOptions<'a> {
426    fn new(options: &'a [ReasoningOption]) -> Self {
427        let mut listed = Self::default();
428        for option in options {
429            match option {
430                ReasoningOption::Effort { values } => {
431                    let efforts = listed.efforts.get_or_insert_with(Vec::new);
432                    for value in values.iter().flatten() {
433                        match value.as_str() {
434                            "none" => listed.disabled_support = ReasoningDisabledSupport::Effort,
435                            "default" => {}
436                            effort => efforts.push(effort),
437                        }
438                    }
439                }
440                ReasoningOption::Toggle => {
441                    if listed.disabled_support == ReasoningDisabledSupport::Unsupported {
442                        listed.disabled_support = ReasoningDisabledSupport::Toggle;
443                    }
444                }
445                ReasoningOption::BudgetTokens => listed.budget_tokens = true,
446            }
447        }
448        listed
449    }
450}
451
452#[derive(Debug, Clone, PartialEq, Eq)]
453enum TransportInfo {
454    OpenAiResponses { base_url_template: Cow<'static, str> },
455    AnthropicMessages,
456}
457
458type ProviderModels = BTreeMap<&'static str, Vec<ModelInfo>>;
459
460struct CodegenCtx {
461    provider_models: ProviderModels,
462}
463
464/// Providers with a fixed model list read from models.dev.
465fn catalog_providers() -> impl Iterator<Item = &'static ProviderConfig> {
466    PROVIDERS.iter().filter(|cfg| !cfg.is_local())
467}
468
469fn build_provider_models(data: &ModelsDevData) -> Result<ProviderModels, CodegenError> {
470    let mut provider_models = ProviderModels::new();
471
472    for cfg in catalog_providers() {
473        let json_key = cfg.json_key();
474        let provider_data = data.get(json_key).ok_or_else(|| CodegenError::ProviderNotFound(json_key.to_string()))?;
475
476        validate_provider_config(cfg, provider_data)?;
477        let mut models: Vec<ModelInfo> = collect_models_from(cfg, &provider_data.models)?;
478
479        for &extra_key in cfg.extra_source_ids {
480            if let Some(extra_data) = data.get(extra_key) {
481                let extra = collect_models_from(cfg, &extra_data.models)?;
482                let existing_ids: std::collections::HashSet<String> =
483                    models.iter().map(|m| m.model_id.clone()).collect();
484                models.extend(extra.into_iter().filter(|m| !existing_ids.contains(&m.model_id)));
485            }
486        }
487
488        models.sort_by(|a, b| a.model_id.cmp(&b.model_id));
489        provider_models.insert(cfg.dev_id, models);
490    }
491
492    Ok(provider_models)
493}
494
495fn validate_provider_config(cfg: &ProviderConfig, provider: &ProviderData) -> Result<(), CodegenError> {
496    let Some(explicit_models) = cfg.explicit_models else {
497        return Ok(());
498    };
499    let mut seen = HashSet::new();
500    for &ExplicitModel { id: model_id, .. } in explicit_models {
501        if !seen.insert(model_id) {
502            return Err(CodegenError::DuplicateConfiguredModel {
503                provider_id: cfg.dev_id.to_string(),
504                model_id: model_id.to_string(),
505            });
506        }
507        let Some(model) = provider.models.get(model_id) else {
508            return Err(CodegenError::ConfiguredModelNotFound {
509                provider_id: cfg.dev_id.to_string(),
510                model_id: model_id.to_string(),
511            });
512        };
513        if model.tool_call != Some(true) {
514            return Err(CodegenError::ConfiguredModelUnavailable {
515                provider_id: cfg.dev_id.to_string(),
516                model_id: model_id.to_string(),
517            });
518        }
519    }
520    Ok(())
521}
522
523fn collect_models_from(
524    cfg: &ProviderConfig,
525    models: &HashMap<String, ModelData>,
526) -> Result<Vec<ModelInfo>, CodegenError> {
527    let explicit_model = |id: &str| cfg.explicit_models.and_then(|models| models.iter().find(|m| m.id == id));
528    models
529        .values()
530        .filter(|m| m.tool_call == Some(true))
531        .filter(|m| !is_alias(&m.id))
532        .filter(|m| cfg.explicit_models.is_none() || explicit_model(&m.id).is_some())
533        .map(|m| {
534            let input_modalities =
535                m.modalities.as_ref().map_or_else(|| vec!["text".to_string()], |md| md.input.clone());
536            let context_window = explicit_model(&m.id)
537                .map_or_else(|| m.limit.as_ref().map_or(0, |l| l.context), |explicit| explicit.context_window);
538            let pricing = m.cost.clone().filter(|_| cfg.per_token_pricing);
539            Ok(ModelInfo {
540                variant_name: model_id_to_variant(&m.id),
541                model_id: m.id.clone(),
542                display_name: m.name.clone(),
543                context_window,
544                reasoning: reasoning_for_model(cfg, m)?,
545                input_modalities,
546                supports_prompt_caching: m.cost.as_ref().is_some_and(CostData::has_prompt_caching),
547                pricing,
548                transport: transport_for_model(cfg, m)?,
549            })
550        })
551        .collect()
552}
553
554fn transport_for_model(cfg: &ProviderConfig, model: &ModelData) -> Result<Option<TransportInfo>, CodegenError> {
555    if !cfg.use_model_transport {
556        return Ok(None);
557    }
558    let (api, shape) =
559        model.provider.as_ref().map_or((None, None), |provider| (provider.api.as_ref(), provider.shape.as_deref()));
560
561    match (api, shape) {
562        (None, None) => Ok(cfg.transport_overrides.iter().find_map(|transport| transport.for_model(&model.id))),
563        (Some(base_url_template), Some("responses")) => {
564            Ok(Some(TransportInfo::OpenAiResponses { base_url_template: Cow::Owned(base_url_template.clone()) }))
565        }
566        (_, Some(shape)) if shape != "responses" => {
567            Err(CodegenError::UnsupportedWireShape { model_id: model.id.clone(), shape: shape.to_string() })
568        }
569        _ => Err(CodegenError::IncompleteTransport { model_id: model.id.clone() }),
570    }
571}
572
573fn reasoning_for_model(cfg: &ProviderConfig, model: &ModelData) -> Result<ReasoningMetadata, CodegenError> {
574    let listed = ListedReasoningOptions::new(&model.reasoning_options);
575    let reasoning = model.reasoning.unwrap_or(false);
576    let disabled_support = if reasoning && cfg.explicit_models.is_none() {
577        listed.disabled_support
578    } else {
579        ReasoningDisabledSupport::Unsupported
580    };
581
582    let control = match (listed.budget_tokens, listed.efforts.as_ref().is_some_and(|efforts| !efforts.is_empty())) {
583        (true, true) => ReasoningControl::BudgetAndEffort,
584        (true, false) => ReasoningControl::Budget,
585        (false, _) => ReasoningControl::Effort,
586    };
587
588    let levels = if reasoning { reasoning_levels(cfg, model, &listed, disabled_support)? } else { Vec::new() };
589    Ok(ReasoningMetadata { levels, disabled_support, control })
590}
591
592fn reasoning_levels(
593    cfg: &ProviderConfig,
594    model: &ModelData,
595    listed: &ListedReasoningOptions<'_>,
596    disabled_support: ReasoningDisabledSupport,
597) -> Result<Vec<ReasoningEffort>, CodegenError> {
598    let mut levels = match &listed.efforts {
599        None => cfg.fallback_reasoning_levels.to_vec(),
600        Some(efforts) => efforts
601            .iter()
602            .map(|effort| {
603                effort.parse::<ReasoningEffort>().ok().filter(|effort| effort.is_enabled()).ok_or_else(|| {
604                    CodegenError::UnsupportedReasoningEffort { model_id: model.id.clone(), effort: effort.to_string() }
605                })
606            })
607            .collect::<Result<_, _>>()?,
608    };
609    if disabled_support != ReasoningDisabledSupport::Unsupported {
610        levels.push(ReasoningEffort::Disabled);
611    }
612    Ok(ReasoningEffort::selectable_levels().iter().copied().filter(|level| levels.contains(level)).collect())
613}
614
615/// Returns true for "latest" alias IDs that just point to another model
616fn is_alias(id: &str) -> bool {
617    id.ends_with("-latest")
618}
619
620/// Convert a model ID like "claude-sonnet-4-5-20250929" into a `PascalCase` variant name.
621/// Treats `-`, `.`, `/`, and `:` as word separators.
622fn model_id_to_variant(id: &str) -> String {
623    let mut result = String::new();
624    let mut capitalize_next = true;
625
626    for ch in id.chars() {
627        if ch == '-' || ch == '.' || ch == '/' || ch == ':' {
628            capitalize_next = true;
629        } else if capitalize_next {
630            result.push(ch.to_ascii_uppercase());
631            capitalize_next = false;
632        } else {
633            result.push(ch);
634        }
635    }
636
637    if result.starts_with(|c: char| c.is_ascii_digit()) {
638        result.insert(0, '_');
639    }
640
641    result
642}
643
644fn emit_generated_source(ctx: &CodegenCtx) -> String {
645    let provider_enum = emit_provider_enum();
646    let catalog_enums = emit_catalog_enums(&ctx.provider_models);
647    let llm_model = emit_llm_model();
648
649    let file_tokens = quote! {
650        #provider_enum
651        #catalog_enums
652        #llm_model
653    };
654
655    let file: syn::File = syn::parse2(file_tokens).expect("generated tokens parse as Rust");
656    let formatted = prettyplease::unparse(&file);
657    format!(
658        "// Auto-generated from models.dev — do not edit manually\n// Regenerated automatically by build.rs\n\n{formatted}"
659    )
660}
661
662fn emit_provider_enum() -> TokenStream {
663    let variants: Vec<_> = PROVIDERS.iter().map(|cfg| format_ident!("{}", cfg.enum_name)).collect();
664    let info = PROVIDERS.iter().map(|cfg| {
665        let (parser_name, genai_provider_name, display_name, is_local) =
666            (cfg.parser_name, cfg.genai_provider_name, cfg.display_name, cfg.is_local());
667        let required_env_var = option_tokens(cfg.env_var);
668        let oauth_provider_id = option_tokens(cfg.oauth_provider_id);
669        let reasoning_off = variant_ident(cfg.reasoning_off);
670        quote! {
671            ProviderInfo {
672                parser_name: #parser_name,
673                genai_provider_name: #genai_provider_name,
674                display_name: #display_name,
675                required_env_var: #required_env_var,
676                oauth_provider_id: #oauth_provider_id,
677                is_local: #is_local,
678                reasoning_off: ReasoningOff::#reasoning_off,
679            }
680        }
681    });
682
683    quote! {
684        /// Typed provider identifier — covers both catalog providers
685        /// (`Anthropic`, `Codex`, …) and dynamic providers whose model name is
686        /// user-supplied (`Ollama`, `LlamaCpp`).
687        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
688        pub enum Provider {
689            #(#variants,)*
690        }
691
692        impl Provider {
693            /// All providers — catalog and dynamic — in declaration order.
694            pub const ALL: &[Provider] = &[#(Self::#variants),*];
695
696            const INFO: &[ProviderInfo] = &[#(#info,)*];
697        }
698    }
699}
700
701fn emit_catalog_enums(provider_models: &ProviderModels) -> TokenStream {
702    let enums = catalog_providers().map(|cfg| {
703        let inner = format_ident!("{}", cfg.inner_enum_name());
704        let models = &provider_models[cfg.dev_id];
705        let variants: Vec<_> = models.iter().map(|m| format_ident!("{}", m.variant_name)).collect();
706        let entries = models.iter().map(emit_catalog_entry);
707        quote! {
708            #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
709            pub enum #inner {
710                #(#variants,)*
711            }
712
713            impl #inner {
714                const ALL: &[Self] = &[#(Self::#variants),*];
715
716                #[allow(clippy::large_stack_arrays, clippy::unreadable_literal)]
717                const ENTRIES: &[CatalogEntry] = &[#(#entries,)*];
718
719                fn entry(self) -> &'static CatalogEntry {
720                    &Self::ENTRIES[self as usize]
721                }
722            }
723        }
724    });
725    quote! { #(#enums)* }
726}
727
728fn emit_catalog_entry(model: &ModelInfo) -> TokenStream {
729    let (id, display_name, supports_prompt_caching) =
730        (&model.model_id, &model.display_name, model.supports_prompt_caching);
731    let context_window = num_lit_with_underscores(model.context_window);
732    let reasoning_levels = model.reasoning.levels.iter().copied().map(variant_ident);
733    let disabled_support = variant_ident(model.reasoning.disabled_support);
734    let reasoning_control = variant_ident(model.reasoning.control);
735    let pricing = option_tokens(model.pricing.as_ref().map(|pricing| {
736        let (input, output) = (pricing.input, pricing.output);
737        let (cache_read, cache_write) = (option_tokens(pricing.cache_read), option_tokens(pricing.cache_write));
738        quote! {
739            ModelPricing {
740                input_per_million: #input,
741                output_per_million: #output,
742                cache_read_per_million: #cache_read,
743                cache_write_per_million: #cache_write,
744            }
745        }
746    }));
747    let supports_image = model.input_modalities.iter().any(|modality| modality == "image");
748    let supports_audio = model.input_modalities.iter().any(|modality| modality == "audio");
749    let transport = option_tokens(model.transport.as_ref().map(|transport| match transport {
750        TransportInfo::OpenAiResponses { base_url_template } => {
751            let base_url_template = base_url_template.as_ref();
752            quote! { ModelTransport::OpenAiResponses { base_url_template: #base_url_template } }
753        }
754        TransportInfo::AnthropicMessages => quote! { ModelTransport::AnthropicMessages },
755    }));
756    quote! {
757        CatalogEntry {
758            id: #id,
759            display_name: #display_name,
760            context_window: #context_window,
761            reasoning_levels: &[#(ReasoningEffort::#reasoning_levels),*],
762            disabled_support: ReasoningDisabledSupport::#disabled_support,
763            supports_prompt_caching: #supports_prompt_caching,
764            reasoning_control: ReasoningControl::#reasoning_control,
765            pricing: #pricing,
766            supports_image: #supports_image,
767            supports_audio: #supports_audio,
768            transport: #transport,
769        }
770    }
771}
772
773fn emit_llm_model() -> TokenStream {
774    let variants = PROVIDERS.iter().map(|cfg| {
775        let v = format_ident!("{}", cfg.enum_name);
776        let outer = format_ident!("{}", cfg.outer_enum_name());
777        match cfg.model_ids {
778            ModelIds::Catalog | ModelIds::Hybrid => quote! { #v(#outer) },
779            ModelIds::Runtime => quote! { #v(String) },
780        }
781    });
782    let from_impls = catalog_providers().map(|cfg| {
783        let v = format_ident!("{}", cfg.enum_name);
784        let outer = format_ident!("{}", cfg.outer_enum_name());
785        quote! {
786            impl From<#outer> for LlmModel {
787                fn from(m: #outer) -> Self {
788                    LlmModel::#v(m)
789                }
790            }
791        }
792    });
793    let pushes = PROVIDERS.iter().filter_map(|cfg| {
794        let inner = format_ident!("{}", cfg.inner_enum_name());
795        let outer = format_ident!("{}", cfg.outer_enum_name());
796        let v = format_ident!("{}", cfg.enum_name);
797        match cfg.model_ids {
798            ModelIds::Catalog => Some(quote! { v.extend(#inner::ALL.iter().copied().map(LlmModel::#v)); }),
799            ModelIds::Hybrid => {
800                Some(quote! { v.extend(#inner::ALL.iter().copied().map(#outer::Foundation).map(LlmModel::#v)); })
801            }
802            ModelIds::Runtime => None,
803        }
804    });
805    let provider_arms = PROVIDERS.iter().map(|cfg| {
806        let v = format_ident!("{}", cfg.enum_name);
807        quote! { Self::#v(_) => Provider::#v, }
808    });
809    let source_arms = PROVIDERS.iter().filter_map(|cfg| {
810        let v = format_ident!("{}", cfg.enum_name);
811        match cfg.model_ids {
812            ModelIds::Catalog => Some(quote! { Self::#v(m) => ModelSource::Catalog(m.entry()), }),
813            ModelIds::Hybrid => Some(quote! { Self::#v(m) => m.source(), }),
814            ModelIds::Runtime => None,
815        }
816    });
817    let runtime_pats = PROVIDERS.iter().filter(|cfg| cfg.is_local()).map(|cfg| {
818        let v = format_ident!("{}", cfg.enum_name);
819        quote! { Self::#v(id) }
820    });
821
822    quote! {
823        /// A model from a specific provider
824        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
825        pub enum LlmModel {
826            #(#variants,)*
827        }
828
829        #(#from_impls)*
830
831        impl LlmModel {
832            /// All catalog models (excludes dynamic providers)
833            pub fn all() -> &'static [LlmModel] {
834                static ALL: LazyLock<Vec<LlmModel>> = LazyLock::new(|| {
835                    let mut v = Vec::new();
836                    #(#pushes)*
837                    v
838                });
839                &ALL
840            }
841
842            /// Typed provider identifier.
843            pub fn provider_enum(&self) -> Provider {
844                match self { #(#provider_arms)* }
845            }
846
847            fn source(&self) -> ModelSource<'_> {
848                match self {
849                    #(#source_arms)*
850                    #(#runtime_pats)|* => ModelSource::Runtime(id),
851                }
852            }
853        }
854    }
855}
856
857/// Emit `Some(value)` or `None` (`quote` emits a bare value or nothing for an `Option`).
858fn option_tokens(value: Option<impl ToTokens>) -> TokenStream {
859    value.map_or_else(|| quote! { None }, |value| quote! { Some(#value) })
860}
861
862/// Emit the variant name of a fieldless enum whose `Debug` derive prints it.
863fn variant_ident(variant: impl std::fmt::Debug) -> Ident {
864    format_ident!("{}", format!("{variant:?}"))
865}
866
867/// Emit a `u32` literal with underscore separators (e.g. `200_000`).
868fn num_lit_with_underscores(n: u32) -> TokenStream {
869    format_number(n).parse().expect("formatted number parses as a token")
870}
871
872/// Format a number with underscore separators (e.g. `200000` → `200_000`).
873fn format_number(n: u32) -> String {
874    let s = n.to_string();
875    if s.len() <= 4 {
876        return s;
877    }
878    let mut result = String::with_capacity(s.len() + s.len() / 3);
879    for (i, ch) in s.chars().enumerate() {
880        if i > 0 && (s.len() - i).is_multiple_of(3) {
881            result.push('_');
882        }
883        result.push(ch);
884    }
885    result
886}
887
888fn emit_provider_docs(ctx: &CodegenCtx) -> BTreeMap<String, String> {
889    PROVIDERS
890        .iter()
891        .map(|cfg| {
892            let doc = if cfg.is_local() {
893                local_provider_doc(cfg)
894            } else {
895                catalog_provider_doc(cfg, &ctx.provider_models[cfg.dev_id])
896            };
897            (cfg.dev_id.to_string(), doc)
898        })
899        .collect()
900}
901
902fn catalog_provider_doc(cfg: &ProviderConfig, models: &[ModelInfo]) -> String {
903    let mut doc = String::new();
904
905    pushln(&mut doc, format!("`{}` LLM provider.", cfg.display_name));
906    blank(&mut doc);
907
908    pushln(&mut doc, "# Authentication");
909    blank(&mut doc);
910    match cfg.env_var {
911        Some(var) => pushln(&mut doc, format!("Set the `{var}` environment variable.")),
912        None if cfg.oauth_provider_id.is_some() => {
913            pushln(&mut doc, "This provider uses OAuth authentication.");
914        }
915        None => {
916            pushln(&mut doc, "Uses the default AWS credential chain (environment variables, config files, IAM roles).");
917            pushln(
918                &mut doc,
919                "Models served from a dedicated endpoint also accept a Bedrock API key in `AWS_BEARER_TOKEN_BEDROCK`.",
920            );
921        }
922    }
923    blank(&mut doc);
924
925    pushln(&mut doc, "# Supported models");
926    blank(&mut doc);
927    pushln(&mut doc, "| Model ID | Name | Context | Reasoning | Image | Audio |");
928    pushln(&mut doc, "|----------|------|---------|-----------|-------|-------|");
929    for model in models {
930        let ctx_str = format_context_window(model.context_window);
931        let reasoning = if model.reasoning.levels.iter().any(|level| level.is_enabled()) { "yes" } else { "" };
932        let image = if model.input_modalities.contains(&"image".to_string()) { "yes" } else { "" };
933        let audio = if model.input_modalities.contains(&"audio".to_string()) { "yes" } else { "" };
934        pushln(
935            &mut doc,
936            format!(
937                "| `{}` | `{}` | `{}` | {} | {} | {} |",
938                model.model_id, model.display_name, ctx_str, reasoning, image, audio
939            ),
940        );
941    }
942
943    for model in models.iter().filter(|model| model.reasoning.disabled_support != ReasoningDisabledSupport::Unsupported)
944    {
945        pushln(
946            &mut doc,
947            format!("Model `{}` advertises `disabled` reasoning (subject to adapter support).", model.model_id),
948        );
949    }
950    push_transport_section(&mut doc, models);
951    doc
952}
953
954fn local_provider_doc(cfg: &ProviderConfig) -> String {
955    let mut doc = String::new();
956    pushln(&mut doc, format!("`{}` LLM provider.", cfg.display_name));
957    blank(&mut doc);
958    pushln(&mut doc, format!("This provider accepts any model name at runtime (e.g. `{}:my-model`).", cfg.parser_name));
959    pushln(&mut doc, "No API key is required.");
960    doc
961}
962
963/// Document the models that do not use the provider's default transport.
964fn push_transport_section(doc: &mut String, models: &[ModelInfo]) {
965    let overridden: Vec<(&ModelInfo, &TransportInfo)> =
966        models.iter().filter_map(|model| Some((model, model.transport.as_ref()?))).collect();
967    if overridden.is_empty() {
968        return;
969    }
970
971    blank(doc);
972    pushln(doc, "# Models with a dedicated transport");
973    blank(doc);
974    pushln(doc, "These models are served by their own API and wire protocol rather than");
975    pushln(doc, "the provider's default. `${VAR}` placeholders are resolved at request time.");
976    blank(doc);
977    pushln(doc, "| Model ID | API | Wire shape |");
978    pushln(doc, "|----------|-----|------------|");
979    for (model, transport) in overridden {
980        let (api, shape) = match transport {
981            TransportInfo::OpenAiResponses { base_url_template } => (base_url_template.as_ref(), "responses"),
982            TransportInfo::AnthropicMessages => ("InvokeModelWithResponseStream", "messages"),
983        };
984        pushln(doc, format!("| `{}` | `{api}` | `{shape}` |", model.model_id));
985    }
986}
987
988/// Format a token count as human-readable (e.g. `1_000_000` → `1M`, `200_000` → `200k`).
989fn format_context_window(tokens: u32) -> String {
990    if tokens == 0 {
991        return "unknown".to_string();
992    }
993    if tokens >= 1_000_000 && tokens.is_multiple_of(1_000_000) {
994        format!("{}M", tokens / 1_000_000)
995    } else if tokens >= 1_000 && tokens.is_multiple_of(1_000) {
996        format!("{}k", tokens / 1_000)
997    } else {
998        format_number(tokens)
999    }
1000}
1001
1002fn pushln(out: &mut String, line: impl AsRef<str>) {
1003    writeln!(out, "{}", line.as_ref()).expect("writing to String should not fail");
1004}
1005
1006fn blank(out: &mut String) {
1007    pushln(out, "");
1008}