Skip to main content

llm_codegen/
lib.rs

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