Skip to main content

graphrt_llm/
providers.rs

1//! Config-driven model providers.
2//!
3//! A providers file declares any number of OpenAI-compatible, Anthropic,
4//! Gemini or Bedrock endpoints without code:
5//!
6//! ```yaml
7//! providers:
8//!   - name: openrouter
9//!     kind: openai                       # openai | anthropic
10//!     base_url: https://openrouter.ai/api/v1
11//!     api_key_env: OPENROUTER_API_KEY    # read from the environment, never stored in the file
12//!     headers: { HTTP-Referer: "${SITE_URL}" }
13//!     aliases: [or]                      # extra provider names
14//!     models: { fast: meta-llama/llama-3.1-8b-instruct }   # model-name aliases
15//!     defaults: { temperature: 0.2, max_tokens: 1024 }     # applied when a node sets none
16//!   - name: azure
17//!     kind: openai
18//!     base_url: https://my.openai.azure.com/openai/deployments/gpt4o
19//!     api_key_env: AZURE_OPENAI_KEY
20//!     auth_header: api-key
21//!     query: { api-version: "2024-06-01" }
22//!   - name: gemini
23//!     kind: gemini
24//!     api_key_env: GEMINI_API_KEY
25//!   - name: vertex
26//!     kind: gemini
27//!     base_url: https://us-central1-aiplatform.googleapis.com/v1/projects/my-project/locations/us-central1/publishers/google
28//!     api_key_env: VERTEX_ACCESS_TOKEN
29//!     auth: bearer                       # gemini: api-key (default) | bearer
30//!   - name: bedrock
31//!     kind: bedrock
32//!     region: us-east-1
33//!     access_key_id_env: AWS_ACCESS_KEY_ID          # SigV4 ...
34//!     secret_access_key_env: AWS_SECRET_ACCESS_KEY
35//!     session_token_env: AWS_SESSION_TOKEN          # optional
36//!     # ... or a Bedrock API key: api_key_env: AWS_BEARER_TOKEN_BEDROCK
37//!   - name: openai                       # feature `replay`: recorded responses
38//!     kind: replay
39//!     cassettes: cassettes/              # relative to the providers file (CLI)
40//!     mode: replay                       # replay (default) | record | auto
41//!     upstream: { kind: openai, api_key_env: OPENAI_API_KEY }   # or the name of a provider above
42//! ```
43//!
44//! `${VAR}` in `base_url`, `headers` and `query` values is replaced with the
45//! environment variable `VAR`. Missing variables are errors that name the
46//! variable but never print values.
47
48#[cfg(feature = "http")]
49use std::sync::Arc;
50
51#[cfg(feature = "http")]
52use futures::future::BoxFuture;
53use indexmap::IndexMap;
54use serde::Deserialize;
55
56use crate::error::LlmError;
57use crate::registry::ModelRegistry;
58#[cfg(feature = "http")]
59use crate::types::{ChatModel, ChatRequest, ChatStream};
60
61/// Provider protocol.
62#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
63#[serde(rename_all = "lowercase")]
64#[non_exhaustive]
65pub enum ProviderKind {
66    /// OpenAI-compatible chat completions.
67    #[serde(alias = "openai-compatible", alias = "openai_compatible")]
68    Openai,
69    /// Anthropic Messages API.
70    Anthropic,
71    /// Google Gemini (Gemini API or Vertex AI).
72    Gemini,
73    /// AWS Bedrock Converse API.
74    Bedrock,
75}
76
77/// Default request parameters applied when the node does not set them.
78#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
79#[serde(deny_unknown_fields)]
80pub struct DefaultParams {
81    #[serde(default)]
82    pub temperature: Option<f64>,
83    #[serde(default)]
84    pub top_p: Option<f64>,
85    #[serde(default)]
86    pub max_tokens: Option<u32>,
87    #[serde(default)]
88    pub stop: Vec<String>,
89}
90
91/// One provider entry.
92#[derive(Clone, Debug, Deserialize)]
93#[serde(deny_unknown_fields)]
94pub struct ProviderConfig {
95    pub name: String,
96    pub kind: ProviderKind,
97    /// Endpoint base URL (provider default when omitted).
98    #[serde(default)]
99    pub base_url: Option<String>,
100    /// Environment variable holding the API key.
101    #[serde(default)]
102    pub api_key_env: Option<String>,
103    /// When true, a missing `api_key_env` variable is not an error (e.g. local servers).
104    #[serde(default)]
105    pub api_key_optional: bool,
106    /// OpenAI-compatible only: send the key in this header instead of `Authorization: Bearer`.
107    #[serde(default)]
108    pub auth_header: Option<String>,
109    #[serde(default)]
110    pub headers: IndexMap<String, String>,
111    /// OpenAI-compatible only: query parameters added to every request.
112    #[serde(default)]
113    pub query: IndexMap<String, String>,
114    /// Additional provider names resolving to this provider.
115    #[serde(default)]
116    pub aliases: Vec<String>,
117    /// Model-name aliases: `alias -> real model id`.
118    #[serde(default)]
119    pub models: IndexMap<String, String>,
120    #[serde(default)]
121    pub defaults: DefaultParams,
122    /// Price per model name, for the run's cost budget:
123    /// `{model: {input_per_million, output_per_million}}`.
124    #[serde(default)]
125    pub prices: IndexMap<String, crate::registry::Price>,
126    /// Gemini only: how the key is sent, `api-key` (default) or `bearer`.
127    #[serde(default)]
128    pub auth: Option<String>,
129    /// Bedrock only: AWS region (`${VAR}` allowed).
130    #[serde(default)]
131    pub region: Option<String>,
132    /// Bedrock only: environment variable holding the access key id (SigV4).
133    #[serde(default)]
134    pub access_key_id_env: Option<String>,
135    /// Bedrock only: environment variable holding the secret access key (SigV4).
136    #[serde(default)]
137    pub secret_access_key_env: Option<String>,
138    /// Bedrock only: environment variable holding a session token (optional).
139    #[serde(default)]
140    pub session_token_env: Option<String>,
141}
142
143/// A providers file: either `{providers: [...]}` or a bare list.
144#[derive(Clone, Debug, Default, Deserialize)]
145#[serde(from = "ProvidersRepr")]
146pub struct ProvidersConfig {
147    pub providers: Vec<ProviderConfig>,
148    /// `kind: replay` entries (feature `replay`), built after `providers` so they
149    /// can wrap one of them.
150    #[cfg(feature = "replay")]
151    pub replay: Vec<ReplayProviderConfig>,
152    /// Providers authenticated by a dynamic credential source (token broker, env var
153    /// read per request, or host-supplied), keyed by provider name. Entries replace
154    /// same-named providers. See `docs/credentials.md`.
155    pub credentials: IndexMap<String, crate::credential_config::ProviderCredentialConfig>,
156    /// Top level prices, also for providers this file does not configure, such
157    /// as the `openai` of `OPENAI_API_KEY`:
158    /// `{provider: {model: {input_per_million, output_per_million}}}`. They win
159    /// over the `prices` of an entry. A file may carry only prices (`providers`
160    /// empty), as a bundle's file does for a host that configures the endpoints.
161    pub prices: Prices,
162}
163
164/// Prices per provider and model name: `{provider: {model: price}}`.
165pub type Prices = IndexMap<String, IndexMap<String, crate::registry::Price>>;
166
167#[derive(Deserialize)]
168#[serde(untagged)]
169enum ProvidersRepr {
170    Wrapped {
171        #[serde(default)]
172        providers: Vec<ProviderConfig>,
173        #[serde(default)]
174        credentials: IndexMap<String, crate::credential_config::ProviderCredentialConfig>,
175        #[serde(default)]
176        prices: Prices,
177    },
178    List(Vec<ProviderConfig>),
179}
180
181impl From<ProvidersRepr> for ProvidersConfig {
182    fn from(repr: ProvidersRepr) -> Self {
183        match repr {
184            ProvidersRepr::Wrapped { providers, credentials, prices } => Self {
185                providers,
186                credentials,
187                prices,
188                #[cfg(feature = "replay")]
189                replay: Vec::new(),
190            },
191            ProvidersRepr::List(providers) => Self {
192                providers,
193                credentials: IndexMap::new(),
194                prices: Prices::new(),
195                #[cfg(feature = "replay")]
196                replay: Vec::new(),
197            },
198        }
199    }
200}
201
202impl ProvidersConfig {
203    /// Decode from a JSON value (hosts decode YAML into JSON first).
204    pub fn from_value(value: serde_json::Value) -> Result<Self, LlmError> {
205        // Decode through a strict wrapper first so typos produce a precise message
206        // instead of the generic "did not match any variant" of the untagged enum.
207        let mut credentials = IndexMap::new();
208        let mut prices = Prices::new();
209        let entries = match value {
210            serde_json::Value::Object(mut map) => {
211                let providers = map.remove("providers").unwrap_or(serde_json::Value::Array(Vec::new()));
212                if let Some(raw) = map.remove("credentials") {
213                    credentials = serde_json::from_value(raw)
214                        .map_err(|e| LlmError::Config(format!("providers config `credentials`: {e}")))?;
215                }
216                if let Some(raw) = map.remove("prices") {
217                    prices = serde_json::from_value(raw)
218                        .map_err(|e| LlmError::Config(format!("providers config `prices`: {e}")))?;
219                    flatten_prices(&prices)?;
220                }
221                if let Some(key) = map.keys().next() {
222                    return Err(LlmError::Config(format!("unknown key `{key}` in providers config")));
223                }
224                providers
225            }
226            other => other,
227        };
228        let serde_json::Value::Array(items) = entries else {
229            return Err(LlmError::Config("providers config must be a list of providers".into()));
230        };
231        let mut providers = Vec::with_capacity(items.len());
232        #[cfg(feature = "replay")]
233        let mut replay = Vec::new();
234        for (i, item) in items.into_iter().enumerate() {
235            let label = item.get("name").and_then(serde_json::Value::as_str).map(str::to_owned);
236            let context = |e: serde_json::Error| {
237                LlmError::Config(format!("provider #{} ({}): {e}", i + 1, label.as_deref().unwrap_or("unnamed")))
238            };
239            #[cfg(feature = "replay")]
240            if item.get("kind").and_then(serde_json::Value::as_str) == Some("replay") {
241                replay.push(serde_json::from_value(item).map_err(context)?);
242                continue;
243            }
244            let cfg: ProviderConfig = serde_json::from_value(item).map_err(context)?;
245            providers.push(cfg);
246        }
247        Ok(Self {
248            providers,
249            credentials,
250            prices,
251            #[cfg(feature = "replay")]
252            replay,
253        })
254    }
255
256    /// Decode from JSON text.
257    pub fn from_json(text: &str) -> Result<Self, LlmError> {
258        let value: serde_json::Value =
259            serde_json::from_str(text).map_err(|e| LlmError::Config(format!("invalid providers JSON: {e}")))?;
260        Self::from_value(value)
261    }
262}
263
264impl ModelRegistry {
265    /// Build a registry from a providers config, reading secrets and `${VAR}`
266    /// references from the process environment.
267    #[cfg(feature = "http")]
268    pub fn from_config(config: &ProvidersConfig) -> Result<Self, LlmError> {
269        let vars: Vec<(String, String)> = std::env::vars().collect();
270        Self::from_config_with_vars(config, &vars)
271    }
272
273    /// Like [`ModelRegistry::from_config`] with explicit variables.
274    ///
275    /// Top level `prices` for a provider the file does not configure are not
276    /// kept: use [`ProvidersConfig::load`], whose `unplaced_prices` the host
277    /// places on its own providers.
278    ///
279    /// A `typesafe` entry in the `credentials` section is not a chat model; use
280    /// [`ProvidersConfig::load`] to get its System One client as well.
281    #[cfg(feature = "http")]
282    pub fn from_config_with_vars(config: &ProvidersConfig, vars: &[(String, String)]) -> Result<Self, LlmError> {
283        config.load(vars).map(|loaded| loaded.models)
284    }
285}
286
287/// Everything a providers file configures.
288#[derive(Debug, Default)]
289#[non_exhaustive]
290pub struct LoadedProviders {
291    pub models: ModelRegistry,
292    /// Top level `prices` for providers this file does not configure:
293    /// `(provider, model, price)`, for the host to place on its own providers
294    /// with [`ModelRegistry::place_prices`].
295    pub unplaced_prices: Vec<(String, String, crate::registry::Price)>,
296    /// The TypeSafe System One client from a `typesafe` credentials entry.
297    #[cfg(feature = "typesafe")]
298    pub system_one: Option<crate::typesafe::SystemOneClient>,
299}
300
301impl ProvidersConfig {
302    /// Build the chat models (and the System One client of a `typesafe`
303    /// credentials entry), reading secrets and `${VAR}` references from `vars`.
304    ///
305    /// Providers files have no host app, so `credentials` entries cannot use
306    /// `source: external` or `app_auth: external`, and a credentials entry may not
307    /// share its name with a `providers` entry (it would silently replace its
308    /// aliases, model map and defaults).
309    #[cfg(feature = "http")]
310    pub fn load(&self, vars: &[(String, String)]) -> Result<LoadedProviders, LlmError> {
311        let config = self;
312        for (name, entry) in &config.credentials {
313            if entry.needs_host() {
314                return Err(LlmError::Config(format!(
315                    "credentials for `{name}`: `source: external` / `app_auth: external` need a host app that \
316                     registers credentials at run time (e.g. graphrt-ffi); in a providers file use `env` or \
317                     `token_broker`"
318                )));
319            }
320            if config.providers.iter().any(|p| &p.name == name || p.aliases.iter().any(|a| a == name)) {
321                return Err(LlmError::Config(format!(
322                    "credentials entry `{name}` has the same name as a `providers` entry; rename one of them"
323                )));
324            }
325        }
326        // An alias must not shadow a provider of the same file, and must name exactly
327        // one provider: either mistake would silently route requests elsewhere.
328        let names: std::collections::HashSet<&str> = config.providers.iter().map(|p| p.name.as_str()).collect();
329        let mut aliases: std::collections::HashMap<&str, &str> = std::collections::HashMap::new();
330        for provider in &config.providers {
331            for alias in &provider.aliases {
332                if names.contains(alias.as_str()) {
333                    return Err(LlmError::Config(format!(
334                        "provider `{}`: alias `{alias}` is also the name of a provider",
335                        provider.name
336                    )));
337                }
338                if let Some(other) = aliases.insert(alias.as_str(), provider.name.as_str()) {
339                    return Err(LlmError::Config(format!(
340                        "alias `{alias}` is declared by both `{other}` and `{}`",
341                        provider.name
342                    )));
343                }
344            }
345        }
346        let mut registry = ModelRegistry::new();
347        for provider in &config.providers {
348            let model = build_provider(provider, vars)?;
349            registry.try_add(provider.name.clone(), Arc::clone(&model))?;
350            for (name, price) in &provider.prices {
351                check_price(&provider.name, name, price)?;
352                registry.set_price(provider.name.clone(), name.clone(), *price);
353                // A workflow may name the model by an alias of `models`.
354                for (alias, target) in &provider.models {
355                    if target == name && !provider.prices.contains_key(alias) {
356                        registry.set_price(provider.name.clone(), alias.clone(), *price);
357                    }
358                }
359            }
360            for alias in &provider.aliases {
361                registry.alias(alias.clone(), provider.name.clone());
362            }
363        }
364        #[cfg(feature = "replay")]
365        for replay in &config.replay {
366            if names.contains(replay.name.as_str()) || aliases.contains_key(replay.name.as_str()) {
367                return Err(LlmError::Config(format!(
368                    "replay provider `{}` has the same name as another provider; rename one of them",
369                    replay.name
370                )));
371            }
372            let model = build_replay(replay, &registry, vars)?;
373            registry.try_add(replay.name.clone(), model)?;
374            for alias in &replay.aliases {
375                registry.alias(alias.clone(), replay.name.clone());
376            }
377        }
378        let host = crate::credential_config::HostCredentials::new();
379        #[allow(unused_variables)]
380        let applied = crate::credential_config::apply(&mut registry, &config.credentials, &host)?;
381        let unplaced_prices = registry.place_prices(flatten_prices(&config.prices)?, true);
382        Ok(LoadedProviders {
383            models: registry,
384            unplaced_prices,
385            #[cfg(feature = "typesafe")]
386            system_one: applied.system_one,
387        })
388    }
389}
390
391/// A price is finite, not negative and not absurd.
392fn check_price(provider: &str, model: &str, price: &crate::registry::Price) -> Result<(), LlmError> {
393    if price.is_valid() {
394        return Ok(());
395    }
396    Err(LlmError::Config(format!(
397        "provider `{provider}`: the price of `{model}` must be between 0 and 1e9 per million tokens"
398    )))
399}
400
401/// Every price of `prices` as `(provider, model, price)`, each one checked.
402fn flatten_prices(prices: &Prices) -> Result<Vec<(String, String, crate::registry::Price)>, LlmError> {
403    let mut flat = Vec::new();
404    for (provider, models) in prices {
405        for (model, price) in models {
406            check_price(provider, model, price)?;
407            flat.push((provider.clone(), model.clone(), *price));
408        }
409    }
410    Ok(flat)
411}
412
413/// What [`ModelRegistry::place_guest_prices`] did, for the host to report.
414#[derive(Debug, Default)]
415#[non_exhaustive]
416pub struct GuestPrices {
417    /// Entries (`providers`, `credentials`) of the guest file, each name once. None is built: their endpoints, headers and
418    /// credentials are not used, only the prices of `providers` entries.
419    pub ignored: Vec<String>,
420    /// Prices for a provider the host does not have: `(provider, model)`.
421    pub unplaced: Vec<(String, String)>,
422    /// Prices too low to be prices, not used: `(provider, model)`. A guest must
423    /// not make the host's models free, or nearly, under the host's cost
424    /// budget (see [`implausible_price`]).
425    pub too_low: Vec<(String, String)>,
426}
427
428/// The least price per million tokens a guest may give when the host prices
429/// no model of the same provider (a hundredth of a cent's unit per million).
430pub const MIN_GUEST_PRICE_PER_MILLION: f64 = 0.001;
431
432/// How far below the cheapest price the host gives a model of the same
433/// provider a guest's price may be: a thousandth (models of one provider span
434/// about that much, from a small model to its largest).
435pub const GUEST_PRICE_RATIO: f64 = 1_000.0;
436
437/// Whether a guest's `price` is too low to be a price: 0 for both input and
438/// output, or a part below a thousandth of the cheapest price the host gives
439/// that part for a model of the same provider, or, when the host prices none of
440/// it, below [`MIN_GUEST_PRICE_PER_MILLION`]. A part of 0 counts only when the
441/// host prices that part for none of the provider's models (it would make it
442/// free under the host's cost budget).
443pub fn implausible_price(price: &crate::registry::Price, host: &[crate::registry::Price]) -> bool {
444    if price.input_per_million <= 0.0 && price.output_per_million <= 0.0 {
445        return true;
446    }
447    let cheapest = |of: fn(&crate::registry::Price) -> f64| {
448        host.iter().map(of).filter(|value| *value > 0.0).fold(f64::INFINITY, f64::min)
449    };
450    let too_low = |given: f64, cheapest: f64| {
451        if cheapest.is_finite() {
452            given < cheapest / GUEST_PRICE_RATIO
453        } else {
454            given > 0.0 && given < MIN_GUEST_PRICE_PER_MILLION
455        }
456    };
457    too_low(price.input_per_million, cheapest(|p| p.input_per_million))
458        || too_low(price.output_per_million, cheapest(|p| p.output_per_million))
459}
460
461impl ModelRegistry {
462    /// Place `(provider, model, price)` on the providers of this registry,
463    /// under the name a provider name or alias resolves to (so a workflow that
464    /// names the provider either way finds the price). With `overwrite` false,
465    /// a model this registry already prices keeps its price. Returns the prices
466    /// whose provider this registry does not have.
467    pub fn place_prices(
468        &mut self,
469        prices: impl IntoIterator<Item = (String, String, crate::registry::Price)>,
470        overwrite: bool,
471    ) -> Vec<(String, String, crate::registry::Price)> {
472        let mut unplaced = Vec::new();
473        for (provider, model, price) in prices {
474            let Some(name) = self.resolve(&provider).map(str::to_owned) else {
475                unplaced.push((provider, model, price));
476                continue;
477            };
478            if overwrite || self.price(&name, &model).is_none() {
479                self.set_price(name, model, price);
480            }
481        }
482        unplaced
483    }
484
485    /// Take only the prices of a providers file that is not the host's own (a
486    /// bundle's): the top level `prices` and the `prices` of its entries, for
487    /// the providers this registry has and the models it does not price yet.
488    /// Nothing of the file is built, so it never adds a provider, never
489    /// changes the endpoint, headers or credentials of one, and never reads
490    /// a variable of the host. A price too low to be one is not used
491    /// ([`implausible_price`]).
492    ///
493    /// The file is read for its prices only: of an entry, `name`, `prices` and
494    /// `models` (whose aliases a price follows, as in a host's file); every
495    /// other field, and fields this build does not know, are not looked at.
496    ///
497    /// @throws LlmError - `Config` for a file that is not an object or a list,
498    /// or a price that is not a price (negative, not finite, absurd, unknown fields).
499    pub fn place_guest_prices(&mut self, file: &serde_json::Value) -> Result<GuestPrices, LlmError> {
500        use serde_json::Value;
501        let (entries, top, credentials) = match file {
502            Value::Object(map) => (map.get("providers"), map.get("prices"), map.get("credentials")),
503            list @ Value::Array(_) => (Some(list), None, None),
504            _ => return Err(LlmError::Config("a providers file is an object or a list of providers".into())),
505        };
506        let mut report = GuestPrices::default();
507        let top: Prices = match top {
508            Some(raw) => serde_json::from_value(raw.clone())
509                .map_err(|e| LlmError::Config(format!("providers config `prices`: {e}")))?,
510            None => Prices::new(),
511        };
512        let mut prices = Vec::new();
513        for entry in entries.and_then(Value::as_array).into_iter().flatten() {
514            let Some(name) = entry.get("name").and_then(Value::as_str) else { continue };
515            once(&mut report.ignored, name);
516            let own: IndexMap<String, crate::registry::Price> = match entry.get("prices") {
517                Some(raw) => serde_json::from_value(raw.clone())
518                    .map_err(|e| LlmError::Config(format!("provider `{name}` `prices`: {e}")))?,
519                None => IndexMap::new(),
520            };
521            let models: IndexMap<String, String> =
522                entry.get("models").and_then(|raw| serde_json::from_value(raw.clone()).ok()).unwrap_or_default();
523            for (model, price) in &own {
524                check_price(name, model, price)?;
525                prices.push((name.to_owned(), model.clone(), *price));
526                // A workflow may name the model by an alias of `models`, as in `load`.
527                for (alias, target) in &models {
528                    if target == model && !own.contains_key(alias) {
529                        prices.push((name.to_owned(), alias.clone(), *price));
530                    }
531                }
532            }
533        }
534        for name in credentials.and_then(Value::as_object).into_iter().flat_map(serde_json::Map::keys) {
535            once(&mut report.ignored, name);
536        }
537        // The top level first: it wins over an entry's price, as in the host's own file.
538        let mut all = flatten_prices(&top)?;
539        let entry_only: Vec<_> = prices
540            .into_iter()
541            .filter(|(provider, model, _)| !all.iter().any(|(p, m, _)| p == provider && m == model))
542            .collect();
543        all.extend(entry_only);
544        // Compared with what the host itself prices, before any guest price lands.
545        let (too_low, priced): (Vec<_>, Vec<_>) = all.into_iter().partition(|(provider, _, price)| {
546            let name = self.resolve(provider).unwrap_or(provider.as_str());
547            let host: Vec<crate::registry::Price> =
548                self.prices.iter().filter(|(known, _, _)| known == name).map(|(_, _, price)| *price).collect();
549            implausible_price(price, &host)
550        });
551        report.too_low = too_low.into_iter().map(|(provider, model, _)| (provider, model)).collect();
552        report.unplaced =
553            self.place_prices(priced, false).into_iter().map(|(provider, model, _)| (provider, model)).collect();
554        Ok(report)
555    }
556}
557
558/// Add `name` to `names` once.
559fn once(names: &mut Vec<String>, name: &str) {
560    if !names.iter().any(|known| known == name) {
561        names.push(name.to_owned());
562    }
563}
564
565impl ModelRegistry {
566    /// Add every provider and alias of `other`. `other` wins every conflict: a
567    /// same-named provider is replaced, and an alias of `other` shadows a provider
568    /// of `self` with that name (so a providers file can redirect `openai` to a
569    /// local server). Used to layer a providers file over [`ModelRegistry::from_env`].
570    pub fn merge(&mut self, other: ModelRegistry) -> &mut Self {
571        for (provider, model, price) in &other.prices {
572            self.set_price(provider.clone(), model.clone(), *price);
573        }
574        let (providers, aliases) = other.into_parts();
575        for (name, model) in providers {
576            self.remove(&name);
577            self.add(name, model);
578        }
579        for (alias, target) in aliases {
580            self.remove(&alias);
581            self.alias(alias, target);
582        }
583        self
584    }
585}
586
587#[cfg(feature = "http")]
588fn build_provider(p: &ProviderConfig, vars: &[(String, String)]) -> Result<Arc<dyn ChatModel>, LlmError> {
589    let ctx = |what: &str| format!("provider `{}`: {what}", p.name);
590    if p.name.trim().is_empty() {
591        return Err(LlmError::Config("provider `name` must not be empty".into()));
592    }
593    let api_key = match &p.api_key_env {
594        Some(var) => match lookup(vars, var) {
595            Some(v) => Some(v),
596            None if p.api_key_optional => None,
597            None => return Err(LlmError::Config(ctx(&format!("environment variable `{var}` is not set")))),
598        },
599        None => None,
600    };
601    let base_url = p.base_url.as_deref().map(|u| interpolate(u, vars)).transpose().map_err(|v| missing(&ctx, &v))?;
602    let mut headers = Vec::with_capacity(p.headers.len());
603    for (k, v) in &p.headers {
604        headers.push((k.clone(), interpolate(v, vars).map_err(|var| missing(&ctx, &var))?));
605    }
606
607    let protocol_only_fields = [
608        (p.auth.is_some() && p.kind != ProviderKind::Gemini, "auth"),
609        (p.region.is_some() && p.kind != ProviderKind::Bedrock, "region"),
610        (p.access_key_id_env.is_some() && p.kind != ProviderKind::Bedrock, "access_key_id_env"),
611        (p.secret_access_key_env.is_some() && p.kind != ProviderKind::Bedrock, "secret_access_key_env"),
612        (p.session_token_env.is_some() && p.kind != ProviderKind::Bedrock, "session_token_env"),
613    ];
614    if let Some((_, field)) = protocol_only_fields.iter().find(|(bad, _)| *bad) {
615        return Err(LlmError::Config(ctx(&format!("`{field}` is not supported for this provider kind"))));
616    }
617    let inner: Arc<dyn ChatModel> = match p.kind {
618        ProviderKind::Openai => openai_provider(p, base_url, api_key, headers, vars)?,
619        ProviderKind::Anthropic => anthropic_provider(p, base_url, api_key, headers)?,
620        ProviderKind::Gemini => gemini_provider(p, base_url, api_key, headers)?,
621        ProviderKind::Bedrock => bedrock_provider(p, base_url, api_key, headers, vars)?,
622    };
623    if p.models.is_empty() && p.defaults == DefaultParams::default() {
624        return Ok(inner);
625    }
626    Ok(Arc::new(Configured { inner, models: p.models.clone(), defaults: p.defaults.clone() }))
627}
628
629#[cfg(all(feature = "http", feature = "openai"))]
630fn openai_provider(
631    p: &ProviderConfig,
632    base_url: Option<String>,
633    api_key: Option<String>,
634    headers: Vec<(String, String)>,
635    vars: &[(String, String)],
636) -> Result<Arc<dyn ChatModel>, LlmError> {
637    use crate::openai::{AuthStyle, OpenAiConfig, OpenAiModel};
638    let mut cfg = OpenAiConfig::new(base_url.unwrap_or_else(|| OpenAiConfig::default().base_url), api_key);
639    cfg.use_max_completion_tokens = cfg.base_url.contains("api.openai.com");
640    if let Some(header) = &p.auth_header {
641        cfg.auth = AuthStyle::Header(header.clone());
642    }
643    cfg.headers = headers;
644    for (k, v) in &p.query {
645        let value =
646            interpolate(v, vars).map_err(|var| missing(&|w: &str| format!("provider `{}`: {w}", p.name), &var))?;
647        cfg.query.push((k.clone(), value));
648    }
649    Ok(Arc::new(OpenAiModel::new(cfg)?))
650}
651
652#[cfg(all(feature = "http", not(feature = "openai")))]
653fn openai_provider(
654    p: &ProviderConfig,
655    _base_url: Option<String>,
656    _api_key: Option<String>,
657    _headers: Vec<(String, String)>,
658    _vars: &[(String, String)],
659) -> Result<Arc<dyn ChatModel>, LlmError> {
660    Err(LlmError::Config(format!("provider `{}`: the `openai` feature is disabled in this build", p.name)))
661}
662
663#[cfg(all(feature = "http", feature = "anthropic"))]
664fn anthropic_provider(
665    p: &ProviderConfig,
666    base_url: Option<String>,
667    api_key: Option<String>,
668    headers: Vec<(String, String)>,
669) -> Result<Arc<dyn ChatModel>, LlmError> {
670    use crate::anthropic::{AnthropicConfig, AnthropicModel};
671    if !p.query.is_empty() || p.auth_header.is_some() {
672        return Err(LlmError::Config(format!(
673            "provider `{}`: `query` and `auth_header` are only supported for kind `openai`",
674            p.name
675        )));
676    }
677    let mut cfg = AnthropicConfig { api_key, ..AnthropicConfig::default() };
678    if let Some(base) = base_url {
679        cfg.base_url = base;
680    }
681    cfg.headers = headers;
682    Ok(Arc::new(AnthropicModel::new(cfg)?))
683}
684
685#[cfg(all(feature = "http", not(feature = "anthropic")))]
686fn anthropic_provider(
687    p: &ProviderConfig,
688    _base_url: Option<String>,
689    _api_key: Option<String>,
690    _headers: Vec<(String, String)>,
691) -> Result<Arc<dyn ChatModel>, LlmError> {
692    Err(LlmError::Config(format!("provider `{}`: the `anthropic` feature is disabled in this build", p.name)))
693}
694
695#[cfg(all(feature = "http", feature = "gemini"))]
696fn gemini_provider(
697    p: &ProviderConfig,
698    base_url: Option<String>,
699    api_key: Option<String>,
700    headers: Vec<(String, String)>,
701) -> Result<Arc<dyn ChatModel>, LlmError> {
702    use crate::gemini::{GeminiAuth, GeminiConfig, GeminiModel};
703    if !p.query.is_empty() || p.auth_header.is_some() {
704        return Err(LlmError::Config(format!(
705            "provider `{}`: `query` and `auth_header` are only supported for kind `openai`",
706            p.name
707        )));
708    }
709    let auth = match p.auth.as_deref() {
710        None | Some("api-key") => GeminiAuth::ApiKey,
711        Some("bearer") => GeminiAuth::Bearer,
712        Some(other) => {
713            return Err(LlmError::Config(format!(
714                "provider `{}`: unknown auth `{other}` (expected `api-key` or `bearer`)",
715                p.name
716            )));
717        }
718    };
719    let mut cfg = GeminiConfig { api_key, auth, headers, provider_name: p.name.clone(), ..GeminiConfig::default() };
720    if let Some(base) = base_url {
721        cfg.base_url = base;
722    }
723    Ok(Arc::new(GeminiModel::new(cfg)?))
724}
725
726#[cfg(all(feature = "http", not(feature = "gemini")))]
727fn gemini_provider(
728    p: &ProviderConfig,
729    _base_url: Option<String>,
730    _api_key: Option<String>,
731    _headers: Vec<(String, String)>,
732) -> Result<Arc<dyn ChatModel>, LlmError> {
733    Err(LlmError::Config(format!("provider `{}`: the `gemini` feature is disabled in this build", p.name)))
734}
735
736#[cfg(all(feature = "http", feature = "bedrock"))]
737fn bedrock_provider(
738    p: &ProviderConfig,
739    base_url: Option<String>,
740    api_key: Option<String>,
741    headers: Vec<(String, String)>,
742    vars: &[(String, String)],
743) -> Result<Arc<dyn ChatModel>, LlmError> {
744    use crate::bedrock::{AwsCredentials, BedrockAuth, BedrockConfig, BedrockModel};
745    let ctx = |w: &str| format!("provider `{}`: {w}", p.name);
746    if !p.query.is_empty() || p.auth_header.is_some() {
747        return Err(LlmError::Config(ctx("`query` and `auth_header` are only supported for kind `openai`")));
748    }
749    let region = match &p.region {
750        Some(r) => interpolate(r, vars).map_err(|v| missing(&ctx, &v))?,
751        None => lookup(vars, "AWS_REGION")
752            .or_else(|| lookup(vars, "AWS_DEFAULT_REGION"))
753            .ok_or_else(|| LlmError::Config(ctx("`region` is required (or set AWS_REGION)")))?,
754    };
755    let required = |var: &Option<String>, field: &str| -> Result<Option<String>, LlmError> {
756        match var {
757            Some(name) => lookup(vars, name)
758                .map(Some)
759                .ok_or_else(|| LlmError::Config(ctx(&format!("environment variable `{name}` ({field}) is not set")))),
760            None => Ok(None),
761        }
762    };
763    let access = required(&p.access_key_id_env, "access_key_id_env")?;
764    let secret = required(&p.secret_access_key_env, "secret_access_key_env")?;
765    let session_token = required(&p.session_token_env, "session_token_env")?;
766    if api_key.is_some() && session_token.is_some() {
767        return Err(LlmError::Config(ctx("`session_token_env` only applies to AWS access keys, not `api_key_env`")));
768    }
769    let auth = match (api_key, access, secret) {
770        (Some(_), Some(_), _) | (Some(_), _, Some(_)) => {
771            return Err(LlmError::Config(ctx("use either `api_key_env` or AWS access keys, not both")));
772        }
773        (Some(key), None, None) => BedrockAuth::ApiKey(key),
774        (None, Some(access_key_id), Some(secret_access_key)) => {
775            BedrockAuth::SigV4(AwsCredentials { access_key_id, secret_access_key, session_token })
776        }
777        _ => {
778            return Err(LlmError::Config(ctx(
779                "needs `api_key_env` (Bedrock API key) or both `access_key_id_env` and `secret_access_key_env`",
780            )));
781        }
782    };
783    let mut cfg = BedrockConfig::new(region, auth);
784    cfg.endpoint = base_url;
785    cfg.headers = headers;
786    cfg.provider_name.clone_from(&p.name);
787    Ok(Arc::new(BedrockModel::new(cfg)?))
788}
789
790#[cfg(all(feature = "http", not(feature = "bedrock")))]
791fn bedrock_provider(
792    p: &ProviderConfig,
793    _base_url: Option<String>,
794    _api_key: Option<String>,
795    _headers: Vec<(String, String)>,
796    _vars: &[(String, String)],
797) -> Result<Arc<dyn ChatModel>, LlmError> {
798    Err(LlmError::Config(format!("provider `{}`: the `bedrock` feature is disabled in this build", p.name)))
799}
800
801#[cfg(feature = "http")]
802fn missing(ctx: &dyn Fn(&str) -> String, var: &str) -> LlmError {
803    if var.ends_with("(unterminated `${`)") {
804        return LlmError::Config(ctx(&format!("invalid `${{...}}` reference: {var}")));
805    }
806    LlmError::Config(ctx(&format!("environment variable `{var}` referenced as ${{{var}}} is not set")))
807}
808
809fn lookup(vars: &[(String, String)], name: &str) -> Option<String> {
810    crate::registry::env_value(vars, name)
811}
812
813/// Replace `${VAR}` references. Returns the name of the first missing variable on error.
814/// `$$` is a literal `$`.
815pub fn interpolate(text: &str, vars: &[(String, String)]) -> Result<String, String> {
816    let mut out = String::with_capacity(text.len());
817    let mut rest = text;
818    while let Some(pos) = rest.find('$') {
819        let (before, after) = rest.split_at(pos);
820        out.push_str(before);
821        let after = &after[1..];
822        if let Some(stripped) = after.strip_prefix('$') {
823            out.push('$');
824            rest = stripped;
825        } else if let Some(body) = after.strip_prefix('{') {
826            match body.find('}') {
827                Some(end) => {
828                    let name = &body[..end];
829                    let value = lookup(vars, name).ok_or_else(|| name.to_owned())?;
830                    out.push_str(&value);
831                    rest = &body[end + 1..];
832                }
833                None => {
834                    // An unterminated `${` would otherwise end up literally in a URL or header.
835                    return Err(format!("{} (unterminated `${{`)", body.chars().take(40).collect::<String>()));
836                }
837            }
838        } else {
839            out.push('$');
840            rest = after;
841        }
842    }
843    out.push_str(rest);
844    Ok(out)
845}
846
847/// A `kind: replay` providers-file entry (see [`crate::replay`]).
848#[cfg(feature = "replay")]
849#[derive(Clone, Debug, Deserialize)]
850#[serde(deny_unknown_fields)]
851pub struct ReplayProviderConfig {
852    pub name: String,
853    /// Always `replay`.
854    pub kind: String,
855    /// Cassette directory. Relative paths are resolved by the host (the CLI
856    /// resolves them against the providers file, see [`ProvidersConfig::resolve_paths`]).
857    pub cassettes: std::path::PathBuf,
858    /// `replay` (default), `record` or `auto`; `GRAPHRT_REPLAY_MODE` overrides it.
859    #[serde(default)]
860    pub mode: crate::replay::ReplayMode,
861    /// Provider to record from: the name of another provider of this file, or an
862    /// inline provider entry whose `name` may be omitted.
863    /// Only built when the mode records, so replaying needs no API key.
864    #[serde(default)]
865    pub upstream: Option<ReplayUpstream>,
866    /// Additional provider names resolving to this provider.
867    #[serde(default)]
868    pub aliases: Vec<String>,
869}
870
871/// Where a replay provider records from.
872#[cfg(feature = "replay")]
873#[derive(Clone, Debug, Deserialize)]
874#[serde(untagged)]
875pub enum ReplayUpstream {
876    /// A provider registered under this name.
877    Provider(String),
878    /// An inline provider entry (`kind`, `base_url`, `api_key_env`, ...).
879    Inline(Box<serde_json::Value>),
880}
881
882#[cfg(feature = "replay")]
883impl ProvidersConfig {
884    /// Resolve relative replay `cassettes` directories against `base` (usually
885    /// the directory of the providers file).
886    pub fn resolve_paths(&mut self, base: &std::path::Path) {
887        for replay in &mut self.replay {
888            if replay.cassettes.is_relative() {
889                replay.cassettes = base.join(&replay.cassettes);
890            }
891        }
892    }
893}
894
895#[cfg(all(feature = "http", feature = "replay"))]
896fn build_replay(
897    p: &ReplayProviderConfig,
898    registry: &ModelRegistry,
899    vars: &[(String, String)],
900) -> Result<Arc<dyn ChatModel>, LlmError> {
901    use crate::replay::{REPLAY_MODE_ENV, ReplayMode, ReplayModel};
902    let ctx = |w: &str| LlmError::Config(format!("provider `{}`: {w}", p.name));
903    let mode = match lookup(vars, REPLAY_MODE_ENV) {
904        Some(text) => ReplayMode::parse(&text).map_err(|e| ctx(&format!("{REPLAY_MODE_ENV}: {e}")))?,
905        None => p.mode,
906    };
907    let upstream = match (&p.upstream, mode.needs_upstream()) {
908        (None, _) | (_, false) => None,
909        (Some(ReplayUpstream::Provider(name)), true) => Some(registry.get(name).map_err(|e| ctx(&e.to_string()))?),
910        (Some(ReplayUpstream::Inline(raw)), true) => {
911            let mut raw = (**raw).clone();
912            if let serde_json::Value::Object(map) = &mut raw {
913                map.entry("name").or_insert_with(|| serde_json::Value::String(format!("{}-upstream", p.name)));
914            }
915            let cfg: ProviderConfig =
916                serde_json::from_value(raw).map_err(|e| ctx(&format!("invalid `upstream`: {e}")))?;
917            Some(build_provider(&cfg, vars)?)
918        }
919    };
920    let model = ReplayModel::new(&p.cassettes, mode, upstream).map_err(|e| ctx(&e.to_string()))?;
921    Ok(Arc::new(model))
922}
923
924/// Applies model-name aliases and default parameters before delegating.
925#[cfg(feature = "http")]
926#[derive(Debug)]
927struct Configured {
928    inner: Arc<dyn ChatModel>,
929    models: IndexMap<String, String>,
930    defaults: DefaultParams,
931}
932
933#[cfg(feature = "http")]
934impl ChatModel for Configured {
935    fn chat(&self, mut request: ChatRequest) -> BoxFuture<'_, Result<ChatStream, LlmError>> {
936        if let Some(real) = self.models.get(&request.model) {
937            request.model.clone_from(real);
938        }
939        if request.temperature.is_none() {
940            request.temperature = self.defaults.temperature;
941        }
942        if request.top_p.is_none() {
943            request.top_p = self.defaults.top_p;
944        }
945        if request.max_tokens.is_none() {
946            request.max_tokens = self.defaults.max_tokens;
947        }
948        if request.stop.is_empty() {
949            request.stop.clone_from(&self.defaults.stop);
950        }
951        self.inner.chat(request)
952    }
953
954    fn default_max_tokens(&self) -> Option<u32> {
955        self.defaults.max_tokens.or_else(|| self.inner.default_max_tokens())
956    }
957}
958
959#[cfg(all(test, feature = "openai"))]
960mod credentials_section_tests {
961    use super::*;
962
963    #[test]
964    fn credentials_section_registers_dynamic_providers() {
965        let config = ProvidersConfig::from_value(serde_json::json!({
966            "providers": [],
967            "credentials": {
968                "proxy": {"source": "env", "kind": "openai", "var": "PROXY_TOKEN", "base_url": "https://proxy.example.com/v1"}
969            }
970        }))
971        .unwrap();
972        assert_eq!(config.credentials.len(), 1);
973        let registry = ModelRegistry::from_config_with_vars(&config, &[]).unwrap();
974        assert!(registry.get("proxy").is_ok());
975
976        let typo = ProvidersConfig::from_value(serde_json::json!({"credentials": {"p": {"source": "env", "vr": "X"}}}));
977        assert!(typo.is_err());
978    }
979
980    #[test]
981    fn host_sources_and_name_clashes_are_rejected_in_files() {
982        let load = |v: serde_json::Value| ProvidersConfig::from_value(v).unwrap().load(&[]);
983        let external = load(serde_json::json!({"credentials": {"openai": {"source": "external"}}}));
984        assert!(external.unwrap_err().to_string().contains("host app"));
985        let clash = load(serde_json::json!({
986            "providers": [{"name": "router", "kind": "openai", "api_key_env": "K", "api_key_optional": true}],
987            "credentials": {"router": {"source": "env", "var": "X", "kind": "openai"}}
988        }));
989        assert!(clash.unwrap_err().to_string().contains("same name"));
990    }
991
992    #[cfg(feature = "typesafe")]
993    #[test]
994    fn typesafe_credentials_build_the_system_one_client() {
995        let config = ProvidersConfig::from_value(
996            serde_json::json!({"credentials": {"typesafe": {"source": "env", "var": "TYPESAFE_API_KEY"}}}),
997        )
998        .unwrap();
999        let loaded = config.load(&[]).unwrap();
1000        assert!(loaded.system_one.is_some());
1001        assert!(loaded.models.get("typesafe").is_err());
1002    }
1003
1004    #[test]
1005    fn unterminated_interpolation_is_an_error() {
1006        assert!(interpolate("https://x/${HOST", &[]).is_err());
1007        let config = ProvidersConfig::from_value(serde_json::json!({
1008            "providers": [{"name": "a", "kind": "openai", "base_url": "https://${HOST/v1", "api_key_optional": true}]
1009        }))
1010        .unwrap();
1011        let err = ModelRegistry::from_config_with_vars(&config, &[]).unwrap_err().to_string();
1012        assert!(err.contains("unterminated"), "{err}");
1013    }
1014}
1015
1016#[cfg(all(test, feature = "replay", feature = "openai"))]
1017mod replay_tests {
1018    #![allow(clippy::unwrap_used, clippy::indexing_slicing)]
1019
1020    use super::*;
1021
1022    fn config(json: serde_json::Value) -> ProvidersConfig {
1023        ProvidersConfig::from_value(json).unwrap()
1024    }
1025
1026    #[test]
1027    fn replay_entries_build_without_upstream_keys_in_replay_mode() {
1028        let mut cfg = config(serde_json::json!({"providers": [
1029            {"name": "openai", "kind": "replay", "cassettes": "tapes",
1030             "upstream": {"kind": "openai", "api_key_env": "MISSING_KEY"}, "aliases": ["oai"]}
1031        ]}));
1032        assert_eq!(cfg.replay.len(), 1);
1033        assert!(cfg.providers.is_empty());
1034        cfg.resolve_paths(std::path::Path::new("/base"));
1035        assert_eq!(cfg.replay[0].cassettes, std::path::PathBuf::from("/base/tapes"));
1036        // Replay mode never builds the upstream, so its missing key is not an error.
1037        let registry = cfg.load(&[]).unwrap().models;
1038        assert!(registry.get("openai").is_ok() && registry.get("oai").is_ok());
1039        // Recording builds it.
1040        let vars = vec![("GRAPHRT_REPLAY_MODE".to_owned(), "record".to_owned())];
1041        let err = cfg.load(&vars).unwrap_err().to_string();
1042        assert!(err.contains("MISSING_KEY"), "{err}");
1043    }
1044
1045    #[test]
1046    fn replay_entries_are_validated() {
1047        let bad = |json: serde_json::Value| match ProvidersConfig::from_value(json) {
1048            Err(e) => e.to_string(),
1049            Ok(cfg) => cfg.load(&[]).unwrap_err().to_string(),
1050        };
1051        assert!(bad(serde_json::json!([{"name": "r", "kind": "replay", "casettes": "x"}])).contains("casettes"));
1052        assert!(
1053            bad(serde_json::json!([{"name": "r", "kind": "replay", "cassettes": "x", "mode": "auto"}]))
1054                .contains("upstream")
1055        );
1056        assert!(
1057            bad(serde_json::json!([
1058                {"name": "real", "kind": "openai", "base_url": "http://x/v1"},
1059                {"name": "real", "kind": "replay", "cassettes": "x"}
1060            ]))
1061            .contains("same name")
1062        );
1063        let named = config(serde_json::json!([
1064            {"name": "real", "kind": "openai", "base_url": "http://x/v1"},
1065            {"name": "r", "kind": "replay", "cassettes": "x", "mode": "auto", "upstream": "real"}
1066        ]));
1067        assert!(named.load(&[]).unwrap().models.get("r").is_ok());
1068    }
1069}
1070
1071#[cfg(test)]
1072mod tests {
1073    use super::*;
1074    #[cfg(feature = "mock")]
1075    use crate::types::ChatModel;
1076    #[cfg(feature = "mock")]
1077    use std::sync::Arc;
1078
1079    fn vars() -> Vec<(String, String)> {
1080        vec![("OR_KEY".into(), "sk-or-secret".into()), ("SITE".into(), "https://example.com".into())]
1081    }
1082
1083    #[test]
1084    fn interpolation() {
1085        let v = vars();
1086        assert_eq!(interpolate("${SITE}/x", &v).unwrap(), "https://example.com/x");
1087        assert_eq!(interpolate("a$$b $x", &v).unwrap(), "a$b $x");
1088        assert!(interpolate("a ${", &v).is_err(), "an unterminated `${{` is an error, not literal text");
1089        assert_eq!(interpolate("${NOPE}", &v).unwrap_err(), "NOPE");
1090    }
1091
1092    #[test]
1093    fn parses_wrapped_and_list_forms() {
1094        let wrapped = ProvidersConfig::from_json(r#"{"providers":[{"name":"a","kind":"openai"}]}"#).unwrap();
1095        let list = ProvidersConfig::from_json(r#"[{"name":"a","kind":"openai-compatible"}]"#).unwrap();
1096        assert_eq!(wrapped.providers.len(), 1);
1097        assert_eq!(list.providers[0].kind, ProviderKind::Openai);
1098    }
1099
1100    #[test]
1101    fn typos_are_reported() {
1102        let err = ProvidersConfig::from_json(r#"[{"name":"a","kind":"openai","api_key_evn":"X"}]"#).unwrap_err();
1103        assert!(err.to_string().contains("api_key_evn"), "{err}");
1104        let err = ProvidersConfig::from_json(r#"{"provider":[]}"#).unwrap_err();
1105        assert!(err.to_string().contains("provider"), "{err}");
1106    }
1107
1108    #[cfg(all(feature = "openai", feature = "anthropic"))]
1109    #[test]
1110    fn builds_registry_with_aliases_and_no_secret_leaks() {
1111        let cfg = ProvidersConfig::from_json(
1112            r#"{"providers":[
1113                {"name":"openrouter","kind":"openai","base_url":"https://openrouter.ai/api/v1","api_key_env":"OR_KEY",
1114                 "headers":{"HTTP-Referer":"${SITE}"},"aliases":["or"],"models":{"fast":"x/y"},"defaults":{"temperature":0.2}},
1115                {"name":"claude","kind":"anthropic","api_key_env":"OR_KEY"},
1116                {"name":"local","kind":"openai","base_url":"http://localhost:11434/v1","api_key_env":"NONE","api_key_optional":true}
1117            ]}"#,
1118        )
1119        .unwrap();
1120        let registry = ModelRegistry::from_config_with_vars(&cfg, &vars()).unwrap();
1121        assert!(registry.get("openrouter").is_ok());
1122        assert!(registry.get("or").is_ok());
1123        assert!(registry.get("claude").is_ok());
1124        assert!(registry.get("local").is_ok());
1125        let debug = format!("{registry:?} {:?}", registry.get("openrouter").unwrap());
1126        assert!(!debug.contains("sk-or-secret"), "{debug}");
1127    }
1128
1129    #[cfg(feature = "openai")]
1130    #[test]
1131    fn prices_are_read_checked_and_follow_aliases() {
1132        let cfg = ProvidersConfig::from_json(
1133            r#"[{"name":"or","kind":"openai","base_url":"http://x/v1","api_key_env":"NONE","api_key_optional":true,
1134                 "aliases":["router"],"models":{"fast":"x/small"},
1135                 "prices":{"x/small":{"input_per_million":0.5,"output_per_million":1.5}}}]"#,
1136        )
1137        .unwrap();
1138        let registry = ModelRegistry::from_config_with_vars(&cfg, &vars()).unwrap();
1139        let price = registry.price("or", "x/small").unwrap();
1140        assert_eq!((price.input_per_million, price.output_per_million), (0.5, 1.5));
1141        assert!(registry.price("router", "x/small").is_some(), "a provider alias");
1142        assert!(registry.price("or", "fast").is_some(), "a model alias of `models`");
1143        assert!(registry.price("or", "other").is_none());
1144        let mut merged = ModelRegistry::new();
1145        merged.merge(registry);
1146        assert!(merged.price("or", "x/small").is_some(), "merge carries prices");
1147        let negative = ProvidersConfig::from_json(
1148            r#"[{"name":"or","kind":"openai","base_url":"http://x/v1","prices":{"m":{"input_per_million":-1,"output_per_million":1}}}]"#,
1149        )
1150        .unwrap();
1151        let error = ModelRegistry::from_config_with_vars(&negative, &vars()).unwrap_err().to_string();
1152        assert!(error.contains("`or`") && error.contains("`m`"), "{error}");
1153        let typo = ProvidersConfig::from_json(
1154            r#"[{"name":"or","kind":"openai","prices":{"m":{"input_per_milion":1,"output_per_million":1}}}]"#,
1155        );
1156        assert!(typo.is_err());
1157    }
1158
1159    #[cfg(feature = "openai")]
1160    #[test]
1161    fn conflicting_aliases_are_rejected() {
1162        let shadow = ProvidersConfig::from_json(
1163            r#"[{"name":"a","kind":"openai","base_url":"http://x/v1","aliases":["b"]},
1164                {"name":"b","kind":"openai","base_url":"http://y/v1"}]"#,
1165        )
1166        .unwrap();
1167        let err = ModelRegistry::from_config_with_vars(&shadow, &[]).unwrap_err().to_string();
1168        assert!(err.contains("alias `b`"), "{err}");
1169        let twice = ProvidersConfig::from_json(
1170            r#"[{"name":"a","kind":"openai","base_url":"http://x/v1","aliases":["fast"]},
1171                {"name":"c","kind":"openai","base_url":"http://y/v1","aliases":["fast"]}]"#,
1172        )
1173        .unwrap();
1174        let err = ModelRegistry::from_config_with_vars(&twice, &[]).unwrap_err().to_string();
1175        assert!(err.contains("`fast`") && err.contains("both"), "{err}");
1176    }
1177
1178    #[cfg(feature = "openai")]
1179    #[test]
1180    fn missing_key_variable_names_the_variable() {
1181        let cfg = ProvidersConfig::from_json(r#"[{"name":"a","kind":"openai","api_key_env":"MISSING_KEY"}]"#).unwrap();
1182        let err = ModelRegistry::from_config_with_vars(&cfg, &[]).unwrap_err().to_string();
1183        assert!(err.contains("MISSING_KEY") && err.contains("`a`"), "{err}");
1184        let cfg = ProvidersConfig::from_json(r#"[{"name":"a","kind":"openai","headers":{"X":"${GONE}"}}]"#).unwrap();
1185        let err = ModelRegistry::from_config_with_vars(&cfg, &[]).unwrap_err().to_string();
1186        assert!(err.contains("GONE"), "{err}");
1187    }
1188
1189    #[cfg(all(feature = "mock", feature = "http"))]
1190    #[test]
1191    fn model_aliases_and_defaults_are_applied() {
1192        use crate::mock::MockModel;
1193        use crate::types::Message;
1194
1195        let mock = Arc::new(MockModel::new(vec![MockModel::text("ok")]));
1196        let configured = Configured {
1197            inner: Arc::clone(&mock) as Arc<dyn ChatModel>,
1198            models: IndexMap::from([("fast".to_owned(), "real-model".to_owned())]),
1199            defaults: DefaultParams { temperature: Some(0.3), max_tokens: Some(50), ..DefaultParams::default() },
1200        };
1201        let request = ChatRequest::new("fast", vec![Message::user("hi")]).with_temperature(0.9);
1202        let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
1203        let _stream = rt.block_on(configured.chat(request)).unwrap();
1204        let seen = mock.requests();
1205        let req = seen.first().unwrap();
1206        assert_eq!(req.model, "real-model");
1207        assert_eq!(req.temperature, Some(0.9));
1208        assert_eq!(req.max_tokens, Some(50));
1209    }
1210
1211    #[cfg(all(feature = "mock", feature = "openai"))]
1212    #[test]
1213    fn provider_alias_redirects_a_model_to_another_provider() {
1214        use crate::mock::MockModel;
1215        // A providers file mapping `openai/gpt-4o-mini` to a local `ollama/qwen2.5:14b`.
1216        let cfg = ProvidersConfig::from_json(
1217            r#"[{"name":"ollama","kind":"openai","base_url":"http://localhost:11434/v1",
1218                 "aliases":["openai"],"models":{"gpt-4o-mini":"qwen2.5:14b"}}]"#,
1219        )
1220        .unwrap();
1221        let overlay = ModelRegistry::from_config_with_vars(&cfg, &[]).unwrap();
1222        let env_openai: Arc<dyn ChatModel> = Arc::new(MockModel::new(vec![MockModel::text("from env")]));
1223        let mut registry = ModelRegistry::new().with("openai", Arc::clone(&env_openai));
1224        registry.merge(overlay);
1225        let resolved = registry.get("openai").unwrap();
1226        assert!(!Arc::ptr_eq(&resolved, &env_openai), "the providers file alias must win");
1227        assert!(format!("{resolved:?}").contains("qwen2.5:14b"), "{resolved:?}");
1228    }
1229
1230    #[cfg(all(feature = "gemini", feature = "bedrock"))]
1231    #[test]
1232    fn gemini_and_bedrock_entries() {
1233        let vars: Vec<(String, String)> = [
1234            ("GKEY", "AIza-secret"),
1235            ("REGION", "ap-southeast-1"),
1236            ("AK", "AKID"),
1237            ("SK", "aws-secret"),
1238            ("BKEY", "bedrock-key"),
1239        ]
1240        .iter()
1241        .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
1242        .collect();
1243        let cfg = ProvidersConfig::from_json(
1244            r#"[{"name":"g","kind":"gemini","api_key_env":"GKEY"},
1245                {"name":"vertex","kind":"gemini","api_key_env":"GKEY","auth":"bearer","base_url":"https://x/v1/projects/p/locations/l/publishers/google"},
1246                {"name":"b","kind":"bedrock","region":"${REGION}","access_key_id_env":"AK","secret_access_key_env":"SK"},
1247                {"name":"bk","kind":"bedrock","region":"us-east-1","api_key_env":"BKEY"}]"#,
1248        )
1249        .unwrap();
1250        let reg = ModelRegistry::from_config_with_vars(&cfg, &vars).unwrap();
1251        let debug = format!("{:?} {:?} {:?}", reg.get("g").unwrap(), reg.get("vertex").unwrap(), reg.get("b").unwrap());
1252        assert!(debug.contains("ap-southeast-1") && debug.contains("Bearer"), "{debug}");
1253        assert!(!debug.contains("AIza-secret") && !debug.contains("aws-secret"), "{debug}");
1254        assert!(reg.get("bk").is_ok());
1255
1256        let bad = |json: &str| {
1257            let cfg = ProvidersConfig::from_json(json).unwrap();
1258            ModelRegistry::from_config_with_vars(&cfg, &vars).unwrap_err().to_string()
1259        };
1260        assert!(bad(r#"[{"name":"x","kind":"bedrock","region":"us-east-1"}]"#).contains("needs"));
1261        assert!(
1262            bad(
1263                r#"[{"name":"x","kind":"bedrock","region":"us-east-1","api_key_env":"BKEY","access_key_id_env":"AK"}]"#
1264            )
1265            .contains("either")
1266        );
1267        assert!(bad(r#"[{"name":"x","kind":"gemini","api_key_env":"GKEY","auth":"oauth"}]"#).contains("auth"));
1268        assert!(bad(r#"[{"name":"x","kind":"openai","base_url":"http://x","region":"us-east-1"}]"#).contains("region"));
1269        assert!(bad(r#"[{"name":"x","kind":"bedrock","region":"us-east-1","access_key_id_env":"NOPE","secret_access_key_env":"SK"}]"#)
1270            .contains("NOPE"));
1271    }
1272
1273    #[cfg(feature = "mock")]
1274    #[test]
1275    fn merge_replaces_same_named_providers() {
1276        use crate::mock::MockModel;
1277        let a: Arc<dyn ChatModel> = Arc::new(MockModel::new(vec![MockModel::text("a")]));
1278        let b: Arc<dyn ChatModel> = Arc::new(MockModel::new(vec![MockModel::text("b")]));
1279        let mut base = ModelRegistry::new().with("openai", Arc::clone(&a));
1280        let mut overlay = ModelRegistry::new().with("openai", Arc::clone(&b));
1281        overlay.alias("oai", "openai");
1282        base.merge(overlay);
1283        assert!(Arc::ptr_eq(&base.get("openai").unwrap(), &b));
1284        assert!(base.get("oai").is_ok());
1285    }
1286}
1287
1288#[cfg(all(test, feature = "openai"))]
1289mod guest_tests {
1290    #![allow(clippy::unwrap_used)]
1291
1292    use super::*;
1293    use crate::registry::Price;
1294
1295    /// The host of the tests: `openai` from `OPENAI_BASE_URL`, as a server's environment sets it.
1296    fn host() -> ModelRegistry {
1297        ModelRegistry::from_vars(&vars()).unwrap()
1298    }
1299
1300    fn vars() -> Vec<(String, String)> {
1301        vec![("OPENAI_API_KEY".into(), "sk-host".into()), ("OPENAI_BASE_URL".into(), "http://host.test/v1".into())]
1302    }
1303
1304    fn endpoint(registry: &ModelRegistry, name: &str) -> String {
1305        format!("{:?}", registry.get(name).unwrap())
1306    }
1307
1308    #[test]
1309    fn a_file_of_prices_only_prices_the_providers_of_the_environment() {
1310        let config = ProvidersConfig::from_json(
1311            r#"{"providers":[],"prices":{"openai":{"gpt-test":{"input_per_million":1,"output_per_million":2}},
1312                "nowhere":{"m":{"input_per_million":1,"output_per_million":1}}}}"#,
1313        )
1314        .unwrap();
1315        let loaded = config.load(&vars()).unwrap();
1316        assert!(loaded.models.is_empty());
1317        let mut models = host();
1318        let unplaced = models.place_prices(loaded.unplaced_prices, true);
1319        let price = models.price("openai", "gpt-test").unwrap();
1320        assert_eq!((price.input_per_million, price.output_per_million), (1.0, 2.0));
1321        assert_eq!(unplaced.len(), 1);
1322        assert_eq!(unplaced.first().map(|(provider, _, _)| provider.as_str()), Some("nowhere"));
1323        let bad = ProvidersConfig::from_json(
1324            r#"{"prices":{"openai":{"m":{"input_per_million":-1,"output_per_million":1}}}}"#,
1325        );
1326        assert!(bad.unwrap_err().to_string().contains("`m`"));
1327    }
1328
1329    #[test]
1330    fn a_guest_builds_nothing_and_brings_prices_only() {
1331        let guest: serde_json::Value = serde_json::from_str(
1332            r#"{"providers":[
1333                  {"name":"openai","kind":"openai","base_url":"http://guest.test/v1","api_key_env":"OPENAI_API_KEY",
1334                   "prices":{"gpt-test":{"input_per_million":1,"output_per_million":1}}},
1335                  {"name":"router","kind":"openai","base_url":"http://router.test/v1","api_key_env":"OPENAI_API_KEY",
1336                   "aliases":["openai"],"prices":{"m":{"input_per_million":1,"output_per_million":1}}}],
1337                "credentials":{"typesafe":{"source":"env","var":"OPENAI_API_KEY","base_url":"https://guest.test"}},
1338                "prices":{"openai":{"gpt-test":{"input_per_million":3,"output_per_million":3},
1339                                   "gpt-other":{"input_per_million":2,"output_per_million":2}}}}"#,
1340        )
1341        .unwrap();
1342        let mut models = host();
1343        let names: Vec<String> = models.names().map(str::to_owned).collect();
1344        let report = models.place_guest_prices(&guest).unwrap();
1345        assert_eq!(models.names().map(str::to_owned).collect::<Vec<_>>(), names, "no provider added or replaced");
1346        let openai = endpoint(&models, "openai");
1347        assert!(openai.contains("http://host.test/v1") && !openai.contains("guest.test"), "{openai}");
1348        assert_eq!(report.ignored, ["openai", "router", "typesafe"]);
1349        assert_eq!(models.price("openai", "gpt-test").map(|p| p.input_per_million), Some(3.0), "top level wins");
1350        assert!(models.price("openai", "gpt-other").is_some());
1351        assert_eq!(report.unplaced, [("router".to_owned(), "m".to_owned())]);
1352    }
1353
1354    #[test]
1355    fn a_guest_prices_only_what_the_host_leaves_unpriced_and_never_for_free() {
1356        let mut models = host();
1357        models.set_price("openai", "gpt-test", Price::new(5.0, 5.0).unwrap());
1358        let guest: serde_json::Value = serde_json::from_str(
1359            r#"{"prices":{"openai":{"gpt-test":{"input_per_million":1,"output_per_million":1},
1360                                    "gpt-new":{"input_per_million":2,"output_per_million":2},
1361                                    "gpt-free":{"input_per_million":0,"output_per_million":0}}}}"#,
1362        )
1363        .unwrap();
1364        let report = models.place_guest_prices(&guest).unwrap();
1365        assert_eq!(
1366            models.price("openai", "gpt-test").map(|p| p.input_per_million),
1367            Some(5.0),
1368            "the host's price stays"
1369        );
1370        assert_eq!(models.price("openai", "gpt-new").map(|p| p.input_per_million), Some(2.0));
1371        assert!(models.price("openai", "gpt-free").is_none());
1372        assert_eq!(report.too_low, [("openai".to_owned(), "gpt-free".to_owned())]);
1373    }
1374
1375    #[test]
1376    fn a_price_named_by_an_alias_or_a_plugin_name_lands_on_the_provider() {
1377        let mut models = host();
1378        models.alias("oai", "openai");
1379        let guest: serde_json::Value = serde_json::from_str(
1380            r#"{"prices":{"oai":{"a":{"input_per_million":1,"output_per_million":1}},
1381                "acme/openai/openai":{"b":{"input_per_million":1,"output_per_million":1}}}}"#,
1382        )
1383        .unwrap();
1384        let report = models.place_guest_prices(&guest).unwrap();
1385        assert!(report.unplaced.is_empty());
1386        assert!(models.price("openai", "a").is_some() && models.price("openai", "b").is_some());
1387    }
1388
1389    #[test]
1390    fn top_level_prices_are_checked_however_the_config_is_made() {
1391        let mut config = ProvidersConfig::default();
1392        let bad = Price { input_per_million: -1.0, output_per_million: 1.0 };
1393        config.prices.entry("openai".to_owned()).or_default().insert("m".to_owned(), bad);
1394        assert!(config.load(&vars()).unwrap_err().to_string().contains("`m`"));
1395        let negative =
1396            serde_json::json!({"prices": {"openai": {"m": {"input_per_million": -1, "output_per_million": 1}}}});
1397        assert!(host().place_guest_prices(&negative).unwrap_err().to_string().contains("`m`"));
1398        let typo = serde_json::json!({"providers": [{"name": "openai", "prices": {"m": {"input_per_milion": 1}}}]});
1399        assert!(host().place_guest_prices(&typo).is_err());
1400    }
1401
1402    #[test]
1403    fn a_guest_entry_is_read_for_its_prices_only_whatever_else_it_carries() {
1404        // A kind this build does not know, and fields of no provider: nothing but the prices is read.
1405        let guest = serde_json::json!({"providers": [
1406            {"name": "openai", "kind": "replay", "cassettes": "tapes", "upstream": {"kind": "openai"},
1407             "models": {"fast": "gpt-test"},
1408             "prices": {"gpt-test": {"input_per_million": 1, "output_per_million": 1}}},
1409            {"name": "other", "kind": "a-kind-of-the-future", "unknown": true}],
1410            "a-key-of-the-future": 1});
1411        let mut models = host();
1412        let report = models.place_guest_prices(&guest).unwrap();
1413        assert_eq!(report.ignored, ["openai", "other"]);
1414        assert!(models.price("openai", "gpt-test").is_some());
1415        assert!(models.price("openai", "fast").is_some(), "a model alias of the entry follows its price");
1416    }
1417}
1418
1419#[cfg(all(test, feature = "openai"))]
1420mod implausible_tests {
1421    #![allow(clippy::unwrap_used)]
1422
1423    use super::*;
1424    use crate::registry::Price;
1425
1426    fn price(input: f64, output: f64) -> Price {
1427        Price::new(input, output).unwrap()
1428    }
1429
1430    #[test]
1431    fn a_guest_price_far_below_the_hosts_own_or_the_floor_is_no_price() {
1432        let host = [price(0.15, 0.6), price(2.5, 10.0)];
1433        assert!(implausible_price(&price(0.0, 0.0), &host));
1434        assert!(implausible_price(&price(0.0001, 0.6), &host), "input below a thousandth of 0.15");
1435        assert!(implausible_price(&price(0.15, 0.0005), &host), "output below a thousandth of 0.6");
1436        assert!(!implausible_price(&price(0.00015, 0.0006), &host), "a thousandth exactly is a price");
1437        // A free output is no price where the host pays for output; a part the host never prices may be 0.
1438        assert!(implausible_price(&price(0.15, 0.0), &host));
1439        assert!(!implausible_price(&price(0.02, 0.0), &[price(0.1, 0.0)]));
1440        // A host of large models only still takes a small one's price.
1441        assert!(!implausible_price(&price(0.15, 0.6), &[price(150.0, 600.0)]));
1442        // Nothing to compare with: the floor, each part apart.
1443        assert!(implausible_price(&price(1e-9, 1e-9), &[]));
1444        assert!(implausible_price(&price(0.0, 1e-9), &[]));
1445        assert!(implausible_price(&price(0.0005, 0.002), &[]), "an input below the floor");
1446        assert!(!implausible_price(&price(0.002, 0.002), &[]));
1447    }
1448
1449    #[test]
1450    fn a_guest_price_too_low_is_left_out_and_said() {
1451        let vars = vec![("OPENAI_API_KEY".to_owned(), "sk".to_owned())];
1452        let mut models = ModelRegistry::from_vars(&vars).unwrap();
1453        models.set_price("openai", "gpt-big", price(2.5, 10.0));
1454        let guest = serde_json::json!({"prices": {"openai": {
1455            "gpt-mini": {"input_per_million": 0.15, "output_per_million": 0.6},
1456            "gpt-cheat": {"input_per_million": 0.000001, "output_per_million": 0.000001}}}});
1457        let report = models.place_guest_prices(&guest).unwrap();
1458        assert!(models.price("openai", "gpt-mini").is_some());
1459        assert!(models.price("openai", "gpt-cheat").is_none());
1460        assert_eq!(report.too_low, [("openai".to_owned(), "gpt-cheat".to_owned())]);
1461    }
1462}