Skip to main content

strands/models/
model_info.rs

1//! What the SDK knows about models: [`ModelInfo`] and the shared model info data.
2//!
3//! Every field is optional, and `None` means unknown. The same shape is used for the shared data
4//! file, the `model_info` config override and the resolved [`Model::model_info`]. A known
5//! `Unsupported` disables a feature; unknown leaves the SDK's existing default in place.
6//!
7//! The data is `shared/model-info.json` at the repository root, the source of truth for every
8//! Strands SDK, embedded by the build script.
9//!
10//! [`Model::model_info`]: crate::models::Model::model_info
11
12use std::collections::HashMap;
13use std::sync::LazyLock;
14
15use serde::{Deserialize, Serialize};
16
17/// How a model supports prompt caching (`PromptCaching`).
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
19#[serde(rename_all = "camelCase")]
20#[non_exhaustive]
21pub enum PromptCaching {
22    /// The model does not cache prompts.
23    Unsupported,
24    /// The provider caches automatically.
25    Auto,
26    /// The request places explicit cache points.
27    CachePoints,
28}
29
30/// How a model keeps deferred tool schemas out of its context until it loads them
31/// (`DeferredToolLoading`).
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
33#[serde(rename_all = "camelCase")]
34#[non_exhaustive]
35pub enum DeferredToolLoading {
36    /// Every tool goes with its full input schema.
37    Unsupported,
38    /// Deferred tools go with the API's own deferral flag.
39    Native,
40    /// Each deferred tool goes as its name and description with an open schema.
41    Stubs,
42}
43
44/// What the model can do (`ModelCapabilities`). `None` is unknown.
45///
46/// Fields are added as the SDK learns to read more facts, so build values with the builder or
47/// `ModelCapabilities { stateful: Some(true), ..Default::default() }` rather than listing every
48/// field. The same holds for [`ModelLimits`] and [`ModelInfo`].
49#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, bon::Builder)]
50#[serde(rename_all = "camelCase")]
51pub struct ModelCapabilities {
52    /// Whether the model keeps conversation state server-side; [`Model::stateful`] reads it.
53    ///
54    /// [`Model::stateful`]: crate::models::Model::stateful
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub stateful: Option<bool>,
57    /// Whether and how the model caches prompts.
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub prompt_caching: Option<PromptCaching>,
60    /// Whether the Bedrock and Anthropic providers force the structured output tool (`Any` or a
61    /// named tool) on the structured output retry. False when the model rejects forcing, or when a
62    /// forced call degrades the response (for example, it skips thinking).
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub forced_tool_choice: Option<bool>,
65    /// Whether the provider can make the model's text output conform to a JSON schema.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub native_structured_output: Option<bool>,
68    /// Whether the model summarizes history server-side through [`Model::summarize`]; set
69    /// `Some(false)` in `model_info` to summarize client-side.
70    ///
71    /// [`Model::summarize`]: crate::models::Model::summarize
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub server_side_summary: Option<bool>,
74    /// Whether the model and provider take temporary messages: injected text the model reads only
75    /// until the next user message. When `true`, the provider receives each `InjectedBlock` as
76    /// stored; otherwise it receives only the latest user message's injected text, as text. The
77    /// default [`Model::model_info`] reports `false` unless the provider can send them.
78    ///
79    /// [`Model::model_info`]: crate::models::Model::model_info
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub temporary_messages: Option<bool>,
82    /// How the model and provider defer tool schemas. In the shared data, `Native` is the path on
83    /// the model vendor's own API and `Unsupported` marks a model that cannot fill in a stub's
84    /// parameters, such as one that constrains its tool calls to the stub's open schema. The
85    /// default [`Model::model_info`] reports `Stubs` for every other model; `Native` comes only
86    /// from a provider that sends the deferral flag (`AnthropicModel`), and `Unsupported` from one
87    /// that needs each tool's full input schema (`BedrockModel` with `strict_tools`). A
88    /// `model_info` override that sets `Unsupported` sends every full spec to a model that handles
89    /// stubs badly. On a provider without the flag, an override that sets `Native` sends every full
90    /// spec and only changes the `load_tools` result: `BedrockModel` names each loaded tool and
91    /// other providers leave it out.
92    ///
93    /// [`Model::model_info`]: crate::models::Model::model_info
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub deferred_tool_loading: Option<DeferredToolLoading>,
96    /// MIME types the model and provider take in the media blocks of a user message; an empty list
97    /// when they take only text, `None` for every type. An entry matches a type exactly
98    /// (`image/png`) or by its `type/*`; case and `; parameters` are ignored. A wildcard can also
99    /// mean the kind isn't verified. Tool results can take fewer.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub accepted_mime_types: Option<Vec<String>>,
102    /// The [`ReasoningProviderData::provider`] tag of the reasoning the model takes back from
103    /// history, such as `openai_responses`. Reasoning tagged otherwise does not reach the model.
104    ///
105    /// [`ReasoningProviderData::provider`]: crate::types::ReasoningProviderData::provider
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub reasoning_provider: Option<String>,
108}
109
110impl ModelCapabilities {
111    /// Whether nothing is known.
112    #[must_use]
113    pub fn is_empty(&self) -> bool {
114        *self == Self::default()
115    }
116
117    fn overlay(&mut self, other: &Self) {
118        self.stateful = other.stateful.or(self.stateful);
119        self.prompt_caching = other.prompt_caching.or(self.prompt_caching);
120        self.forced_tool_choice = other.forced_tool_choice.or(self.forced_tool_choice);
121        self.native_structured_output = other.native_structured_output.or(self.native_structured_output);
122        self.server_side_summary = other.server_side_summary.or(self.server_side_summary);
123        self.temporary_messages = other.temporary_messages.or(self.temporary_messages);
124        self.deferred_tool_loading = other.deferred_tool_loading.or(self.deferred_tool_loading);
125        if other.accepted_mime_types.is_some() {
126            self.accepted_mime_types.clone_from(&other.accepted_mime_types);
127        }
128        if other.reasoning_provider.is_some() {
129            self.reasoning_provider.clone_from(&other.reasoning_provider);
130        }
131    }
132}
133
134/// Size limits of the model (`ModelLimits`). `None` is unknown.
135#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, bon::Builder)]
136#[serde(rename_all = "camelCase")]
137pub struct ModelLimits {
138    /// Context window size in tokens.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub context_window: Option<u64>,
141    /// Largest `max_tokens` the model accepts. Providers that need a default `max_tokens` use it.
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub max_output_tokens: Option<u64>,
144}
145
146impl ModelLimits {
147    /// Whether nothing is known.
148    #[must_use]
149    pub fn is_empty(&self) -> bool {
150        *self == Self::default()
151    }
152
153    fn overlay(&mut self, other: &Self) {
154        self.context_window = other.context_window.or(self.context_window);
155        self.max_output_tokens = other.max_output_tokens.or(self.max_output_tokens);
156    }
157}
158
159/// Everything the SDK knows about a model (`ModelInfo`). Read it from [`Model::model_info`].
160///
161/// [`Model::model_info`]: crate::models::Model::model_info
162#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, bon::Builder)]
163pub struct ModelInfo {
164    /// What the model can do.
165    #[serde(default, skip_serializing_if = "ModelCapabilities::is_empty")]
166    #[builder(default)]
167    pub capabilities: ModelCapabilities,
168    /// Size limits of the model.
169    #[serde(default, skip_serializing_if = "ModelLimits::is_empty")]
170    #[builder(default)]
171    pub limits: ModelLimits,
172}
173
174impl ModelInfo {
175    /// Merges partial records, later known fields winning; unknown fields inherit, and `None`
176    /// parts are skipped.
177    ///
178    /// A provider that overrides [`Model::model_info`] layers its facts over
179    /// [`base_model_info`](crate::models::base_model_info) and puts the user's `model_info`
180    /// override on top:
181    ///
182    /// ```
183    /// use strands::models::{BaseModelConfig, ModelCapabilities, ModelInfo, PromptCaching, base_model_info};
184    ///
185    /// let config = BaseModelConfig::builder().model_id("claude-sonnet-4-6").build();
186    /// let facts = ModelInfo {
187    ///     capabilities: ModelCapabilities { prompt_caching: Some(PromptCaching::Auto), ..Default::default() },
188    ///     ..Default::default()
189    /// };
190    /// let info = ModelInfo::merge([Some(&base_model_info(&config)), Some(&facts), config.model_info.as_ref()]);
191    /// assert_eq!(info.capabilities.prompt_caching, Some(PromptCaching::Auto));
192    /// ```
193    ///
194    /// [`Model::model_info`]: crate::models::Model::model_info
195    #[must_use]
196    pub fn merge<'a>(parts: impl IntoIterator<Item = Option<&'a ModelInfo>>) -> ModelInfo {
197        let mut merged = ModelInfo::default();
198        for part in parts.into_iter().flatten() {
199            merged.overlay(part);
200        }
201        merged
202    }
203
204    fn overlay(&mut self, other: &Self) {
205        self.capabilities.overlay(&other.capabilities);
206        self.limits.overlay(&other.limits);
207    }
208}
209
210/// Turns `server_side_summary` off, for providers that serve a model the shared data lists it for
211/// but have no server-side summary of their own (`SERVER_SIDE_SUMMARY_OFF`).
212#[allow(
213    dead_code,
214    reason = "providers without a server-side summary layer it over the shared data"
215)]
216pub(crate) fn server_side_summary_off() -> ModelInfo {
217    ModelInfo {
218        capabilities: ModelCapabilities {
219            server_side_summary: Some(false),
220            ..ModelCapabilities::default()
221        },
222        limits: ModelLimits::default(),
223    }
224}
225
226#[derive(Deserialize)]
227struct DefaultLimits {
228    #[serde(rename = "contextWindow")]
229    context_window: u64,
230}
231
232#[derive(Deserialize)]
233struct Defaults {
234    limits: DefaultLimits,
235}
236
237#[derive(Deserialize)]
238struct ModelInfoData {
239    defaults: Defaults,
240    models: HashMap<String, ModelInfo>,
241}
242
243const MODEL_INFO_JSON: &str = include_str!(concat!(env!("OUT_DIR"), "/model-info.json"));
244
245const FALLBACK_CONTEXT_WINDOW_LIMIT: u64 = 200_000;
246
247static DATA: LazyLock<ModelInfoData> = LazyLock::new(|| {
248    serde_json::from_str(MODEL_INFO_JSON).unwrap_or_else(|error| {
249        tracing::error!("error=<{error}> | embedded model info data is invalid | using no model info");
250        ModelInfoData {
251            defaults: Defaults {
252                limits: DefaultLimits {
253                    context_window: FALLBACK_CONTEXT_WINDOW_LIMIT,
254                },
255            },
256            models: HashMap::new(),
257        }
258    })
259});
260
261/// Context window limit in tokens assumed for a model whose window is unknown
262/// (`DEFAULT_CONTEXT_WINDOW_LIMIT`).
263pub(crate) fn default_context_window_limit() -> u64 {
264    DATA.defaults.limits.context_window
265}
266
267fn all_digits(text: &str) -> bool {
268    !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit())
269}
270
271/// Strips a trailing Bedrock version suffix (`-v1:0`, `-v2`, `-1:0`).
272fn strip_version_suffix(model_id: &str) -> &str {
273    let Some((head, tail)) = model_id.rsplit_once('-') else {
274        return model_id;
275    };
276    let is_version = match tail.strip_prefix('v') {
277        Some(version) => match version.split_once(':') {
278            Some((major, minor)) => all_digits(major) && all_digits(minor),
279            None => all_digits(version),
280        },
281        None => tail
282            .split_once(':')
283            .is_some_and(|(major, minor)| all_digits(major) && all_digits(minor)),
284    };
285    if is_version { head } else { model_id }
286}
287
288/// Strips a trailing snapshot date (`-20260401`, `@20251001`).
289fn strip_date_suffix(model_id: &str) -> &str {
290    let bytes = model_id.as_bytes();
291    let Some(start) = bytes.len().checked_sub(9) else {
292        return model_id;
293    };
294    let dated = matches!(bytes[start], b'-' | b'@') && bytes[start + 1..].iter().all(u8::is_ascii_digit);
295    if dated { &model_id[..start] } else { model_id }
296}
297
298/// Finds the entry for a model id.
299///
300/// Tries the id as given, then without a trailing Bedrock version suffix, then without a trailing
301/// date, then with each leading dot-separated segment removed in turn
302/// (`us.anthropic.claude-x`, `anthropic.claude-x`, `claude-x`), the rule the Python SDK applies.
303pub(crate) fn lookup_model(model_id: &str) -> Option<&'static ModelInfo> {
304    lookup_key(model_id).and_then(|key| DATA.models.get(key))
305}
306
307/// Finds the key of the entry for a model id, by the rule [`lookup_model`] documents.
308fn lookup_key(model_id: &str) -> Option<&'static str> {
309    let models = &DATA.models;
310    let mut candidate = model_id;
311    loop {
312        let unversioned = strip_version_suffix(candidate);
313        let keys = [candidate, unversioned, strip_date_suffix(unversioned)];
314        if let Some((key, _)) = keys.iter().find_map(|key| models.get_key_value(*key)) {
315            return Some(key.as_str());
316        }
317        let (_, rest) = candidate.split_once('.')?;
318        candidate = rest;
319    }
320}
321
322/// The values of `capabilities.chatCompletionsTools` in the data (`ChatCompletionsTools`).
323#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
324#[serde(rename_all = "camelCase")]
325pub(crate) enum ChatCompletionsTools {
326    /// The model accepts tools only with `reasoning_effort: "none"`.
327    ReasoningOff,
328    /// The model accepts no tools.
329    Unsupported,
330}
331
332/// The values of `capabilities.systemPromptPlacement` in the data (`SystemPromptPlacement`).
333#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
334#[serde(rename_all = "camelCase")]
335pub(crate) enum SystemPromptPlacement {
336    /// The system prompt goes at the start of the messages.
337    Message,
338}
339
340/// The `capabilities` fields of the shared data that [`ModelCapabilities`] does not carry, which
341/// a single provider reads.
342#[derive(Debug, Default, Deserialize)]
343#[serde(rename_all = "camelCase")]
344struct ProviderCapabilities {
345    chat_completions_tools: Option<ChatCompletionsTools>,
346    system_prompt_placement: Option<SystemPromptPlacement>,
347}
348
349#[derive(Deserialize)]
350struct ProviderEntry {
351    #[serde(default)]
352    capabilities: ProviderCapabilities,
353}
354
355#[derive(Deserialize)]
356struct ProviderData {
357    models: HashMap<String, ProviderEntry>,
358}
359
360/// [`ProviderCapabilities`] by model key.
361static PROVIDER_CAPABILITIES: LazyLock<HashMap<String, ProviderCapabilities>> = LazyLock::new(|| {
362    let data: ProviderData = serde_json::from_str(MODEL_INFO_JSON).unwrap_or_else(|error| {
363        tracing::error!("error=<{error}> | embedded model info data is invalid | using no provider capabilities");
364        ProviderData { models: HashMap::new() }
365    });
366    data.models
367        .into_iter()
368        .map(|(key, entry)| (key, entry.capabilities))
369        .collect()
370});
371
372fn provider_capabilities(model_id: &str) -> Option<&'static ProviderCapabilities> {
373    lookup_key(model_id).and_then(|key| PROVIDER_CAPABILITIES.get(key))
374}
375
376/// Whether OpenAI's Chat Completions API accepts tools for a model: `ReasoningOff` when only with
377/// reasoning off, `Unsupported` when not at all, `None` when the data does not say.
378#[allow(dead_code, reason = "the OpenAI Chat Completions provider reads it")]
379pub(crate) fn lookup_chat_completions_tools(model_id: &str) -> Option<ChatCompletionsTools> {
380    provider_capabilities(model_id)?.chat_completions_tools
381}
382
383/// Where a model's system prompt goes when not in the provider's system prompt field: `Message`
384/// at the start of the messages, `None` when the data does not say.
385#[allow(dead_code, reason = "the OpenAI Responses provider reads it")]
386pub(crate) fn lookup_system_prompt_placement(model_id: &str) -> Option<SystemPromptPlacement> {
387    provider_capabilities(model_id)?.system_prompt_placement
388}
389
390/// Whether a model takes a MIME type in a user message, by its `accepted_mime_types`: true when
391/// the list names the type or its `type/*`, or when the model has no list. Parameters
392/// (`; charset=utf-8`) are ignored.
393pub(crate) fn accepts_mime_type(info: &ModelInfo, mime_type: &str) -> bool {
394    let Some(accepted) = &info.capabilities.accepted_mime_types else {
395        return true;
396    };
397    let essence = mime_type
398        .split(';')
399        .next()
400        .unwrap_or_default()
401        .trim()
402        .to_ascii_lowercase();
403    let wildcard = format!("{}/*", essence.split('/').next().unwrap_or_default());
404    accepted.iter().any(|entry| {
405        let entry = entry.to_ascii_lowercase();
406        entry == essence || entry == wildcard
407    })
408}
409
410/// What the shared model info data knows about a model; empty when it knows nothing.
411pub(crate) fn lookup_model_info(model_id: &str) -> ModelInfo {
412    ModelInfo::merge([lookup_model(model_id)])
413}
414
415/// The context window limit the shared data lists for a model id.
416#[allow(dead_code, reason = "providers fill `context_window_limit` from it")]
417pub(crate) fn get_context_window_limit(model_id: &str) -> Option<u64> {
418    lookup_model_info(model_id).limits.context_window
419}
420
421/// Tests model info, its lookup and the provider defaults.
422#[cfg(test)]
423mod tests {
424    use serde_json::json;
425
426    use super::*;
427    use crate::types::JsonValue;
428
429    const CLAUDE_MIME_TYPES: [&str; 13] = [
430        "image/png",
431        "image/jpeg",
432        "image/gif",
433        "image/webp",
434        "application/pdf",
435        "text/csv",
436        "application/msword",
437        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
438        "application/vnd.ms-excel",
439        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
440        "text/html",
441        "text/plain",
442        "text/markdown",
443    ];
444    const NOVA_VIDEO_MIME_TYPES: [&str; 8] = [
445        "video/x-flv",
446        "video/x-matroska",
447        "video/quicktime",
448        "video/mpeg",
449        "video/mp4",
450        "video/3gpp",
451        "video/webm",
452        "video/x-ms-wmv",
453    ];
454
455    fn base() -> ModelInfo {
456        ModelInfo {
457            capabilities: ModelCapabilities {
458                stateful: Some(false),
459                prompt_caching: Some(PromptCaching::CachePoints),
460                ..Default::default()
461            },
462            limits: ModelLimits {
463                context_window: Some(200_000),
464                ..Default::default()
465            },
466        }
467    }
468
469    fn limits(context_window: u64) -> ModelInfo {
470        ModelInfo::builder()
471            .limits(ModelLimits::builder().context_window(context_window).build())
472            .build()
473    }
474
475    fn window(model_id: &str) -> Option<u64> {
476        get_context_window_limit(model_id)
477    }
478
479    #[test]
480    fn returns_the_base_when_nothing_else_is_given() {
481        assert_eq!(ModelInfo::merge([Some(&base())]), base());
482    }
483
484    #[test]
485    fn inherits_fields_a_later_record_leaves_out_or_sets_to_undefined() {
486        let merged = ModelInfo::merge([
487            Some(&base()),
488            Some(&limits(1_000_000)),
489            Some(&ModelInfo::builder().capabilities(ModelCapabilities::default()).build()),
490        ]);
491        assert_eq!(merged.capabilities, base().capabilities);
492        assert_eq!(merged.limits.context_window, Some(1_000_000));
493    }
494
495    #[test]
496    fn lets_a_later_record_win_over_an_earlier_one() {
497        let later = ModelInfo {
498            capabilities: ModelCapabilities::builder()
499                .prompt_caching(PromptCaching::Unsupported)
500                .build(),
501            limits: ModelLimits::builder().context_window(2).build(),
502        };
503        let merged = ModelInfo::merge([Some(&base()), Some(&limits(1)), None, Some(&later)]);
504        assert_eq!(
505            serde_json::to_value(&merged.capabilities).unwrap(),
506            json!({"stateful": false, "promptCaching": "unsupported"})
507        );
508        assert_eq!(merged.limits.context_window, Some(2));
509    }
510
511    #[test]
512    fn keeps_an_empty_accepted_list_as_known() {
513        let first = ModelInfo::builder()
514            .capabilities(
515                ModelCapabilities::builder()
516                    .accepted_mime_types(vec!["image/png".to_owned()])
517                    .build(),
518            )
519            .build();
520        let second = ModelInfo::builder()
521            .capabilities(ModelCapabilities::builder().accepted_mime_types(Vec::new()).build())
522            .build();
523        let merged = ModelInfo::merge([Some(&first), Some(&second)]);
524        assert_eq!(merged.capabilities.accepted_mime_types, Some(Vec::new()));
525    }
526
527    #[test]
528    fn accepts_mime_types_by_the_accepted_list() {
529        let cases: [(Option<&[&str]>, &str, bool); 9] = [
530            (None, "application/x-anything", true),
531            (Some(&[]), "image/png", false),
532            (Some(&["image/png"]), "image/png", true),
533            (Some(&["image/png"]), "IMAGE/PNG", true),
534            (Some(&["Image/PNG"]), "image/png", true),
535            (Some(&["text/plain"]), "text/plain; charset=utf-8", true),
536            (Some(&["image/png"]), "image/jpeg", false),
537            (Some(&["video/*"]), "video/mp4", true),
538            (Some(&["video/*"]), "audio/mp4", false),
539        ];
540        for (accepted, mime_type, expected) in cases {
541            let info = ModelInfo {
542                capabilities: ModelCapabilities {
543                    accepted_mime_types: accepted.map(|types| types.iter().map(|&t| t.to_owned()).collect()),
544                    ..Default::default()
545                },
546                ..Default::default()
547            };
548            assert_eq!(
549                accepts_mime_type(&info, mime_type),
550                expected,
551                "{accepted:?} {mime_type}"
552            );
553        }
554    }
555
556    fn assert_mime_type_list(value: &JsonValue, label: &str) {
557        let types: Vec<&str> = value.as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect();
558        let unique: std::collections::HashSet<&str> = types.iter().copied().collect();
559        assert_eq!(unique.len(), types.len(), "{label}");
560        for mime_type in types {
561            let (kind, subtype) = mime_type.split_once('/').unwrap_or_default();
562            assert!(
563                ["image", "video", "audio", "application", "text"].contains(&kind),
564                "{label}: {mime_type}"
565            );
566            let subtype_ok = subtype == "*"
567                || (!subtype.is_empty()
568                    && subtype
569                        .chars()
570                        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || ".+-".contains(c)));
571            assert!(subtype_ok, "{label}: {mime_type}");
572        }
573    }
574
575    #[test]
576    fn leaves_out_sections_with_nothing_known() {
577        let merged = ModelInfo::merge([Some(&ModelInfo::default()), None, Some(&ModelInfo::default())]);
578        assert_eq!(serde_json::to_value(merged).unwrap(), json!({}));
579    }
580
581    #[test]
582    fn resolves_every_spelling_of_a_model_to_its_one_entry() {
583        let entry = lookup_model("claude-opus-5-5").unwrap();
584        assert_eq!(entry.limits.context_window, Some(1_000_000));
585        for id in [
586            "anthropic.claude-opus-5-5",
587            "us.anthropic.claude-opus-5-5",
588            "arn:aws:bedrock:us-west-2:123:inference-profile/global.anthropic.claude-opus-5-5",
589        ] {
590            assert!(std::ptr::eq(lookup_model(id).unwrap(), entry), "{id}");
591        }
592    }
593
594    #[test]
595    fn resolves_a_dated_snapshot_to_the_undated_model() {
596        assert_eq!(
597            lookup_model("anthropic.claude-opus-5-5-20260401-v1:0"),
598            lookup_model("claude-opus-5-5")
599        );
600        assert_eq!(
601            lookup_model("claude-haiku-4-5@20251001"),
602            lookup_model("claude-haiku-4-5")
603        );
604        assert!(lookup_model("claude-haiku-4-5").is_some());
605        assert_eq!(
606            lookup_model("claude-3-5-haiku-20241022").unwrap().limits.context_window,
607            Some(200_000)
608        );
609    }
610
611    #[test]
612    fn reads_the_chat_completions_tools_fact_from_the_entry_the_id_resolves_to() {
613        let cases = [
614            ("gpt-6-sol", Some(ChatCompletionsTools::ReasoningOff)),
615            ("us.openai.gpt-6-luna", Some(ChatCompletionsTools::ReasoningOff)),
616            ("gpt-6-astra", Some(ChatCompletionsTools::Unsupported)),
617            ("openai.gpt-6.1-sol", Some(ChatCompletionsTools::Unsupported)),
618            ("openai.gpt-6.2-sol", Some(ChatCompletionsTools::Unsupported)),
619            ("gpt-5.4", None),
620            ("unknown-model", None),
621        ];
622        for (model_id, support) in cases {
623            assert_eq!(lookup_chat_completions_tools(model_id), support, "{model_id}");
624        }
625    }
626
627    #[test]
628    fn reads_the_system_prompt_placement_fact_from_the_entry_the_id_resolves_to() {
629        let cases = [
630            ("gpt-6.2-sol", Some(SystemPromptPlacement::Message)),
631            ("openai.gpt-6.2-astra", Some(SystemPromptPlacement::Message)),
632            ("gpt-6.1-sol", None),
633            ("unknown-model", None),
634        ];
635        for (model_id, placement) in cases {
636            assert_eq!(lookup_system_prompt_placement(model_id), placement, "{model_id}");
637        }
638    }
639
640    #[test]
641    fn does_not_read_inherited_object_keys() {
642        assert_eq!(lookup_model("toString"), None);
643        assert_eq!(lookup_model("x.constructor"), None);
644    }
645
646    #[test]
647    fn ignores_a_trailing_bedrock_version_suffix() {
648        assert_eq!(
649            lookup_model("anthropic.claude-3-5-haiku-20241022-v1:0"),
650            lookup_model("claude-3-5-haiku-20241022")
651        );
652        assert_eq!(
653            lookup_model("us.anthropic.claude-3-5-sonnet-20241022-v2:0")
654                .unwrap()
655                .limits
656                .context_window,
657            Some(200_000)
658        );
659    }
660
661    #[test]
662    fn returns_undefined_for_unknown_ids() {
663        assert_eq!(lookup_model("unknown-model"), None);
664        assert_eq!(lookup_model(""), None);
665    }
666
667    #[test]
668    fn keeps_the_typed_fields_and_skips_the_rest() {
669        // The data entry also carries defaultEffort, which the SDK does not type.
670        assert_eq!(
671            serde_json::to_value(lookup_model_info("claude-opus-5-5")).unwrap(),
672            json!({
673                "capabilities": {
674                    "promptCaching": "cachePoints",
675                    "forcedToolChoice": false,
676                    "nativeStructuredOutput": true,
677                    "serverSideSummary": true,
678                    "temporaryMessages": true,
679                    "deferredToolLoading": "native",
680                    "acceptedMimeTypes": CLAUDE_MIME_TYPES,
681                },
682                "limits": {"contextWindow": 1_000_000, "maxOutputTokens": 128_000},
683            })
684        );
685    }
686
687    #[test]
688    fn returns_the_entry_facts_and_nothing_for_unknown_ids() {
689        assert_eq!(
690            serde_json::to_value(lookup_model_info("eu.anthropic.claude-sonnet-4-6")).unwrap(),
691            json!({
692                "capabilities": {
693                    "promptCaching": "cachePoints",
694                    "deferredToolLoading": "native",
695                    "acceptedMimeTypes": CLAUDE_MIME_TYPES,
696                },
697                "limits": {"contextWindow": 1_000_000, "maxOutputTokens": 128_000},
698            })
699        );
700        for model_id in [
701            "anthropic.claude-opus-5-5",
702            "global.anthropic.claude-fable-5-2",
703            "claude-mythos-5-2",
704        ] {
705            assert_eq!(
706                serde_json::to_value(lookup_model_info(model_id)).unwrap(),
707                json!({
708                    "capabilities": {
709                        "promptCaching": "cachePoints",
710                        "forcedToolChoice": false,
711                        "nativeStructuredOutput": true,
712                        "serverSideSummary": true,
713                        "temporaryMessages": true,
714                        "deferredToolLoading": "native",
715                        "acceptedMimeTypes": CLAUDE_MIME_TYPES,
716                    },
717                    "limits": {"contextWindow": 1_000_000, "maxOutputTokens": 128_000},
718                }),
719                "{model_id}"
720            );
721        }
722        assert_eq!(
723            serde_json::to_value(lookup_model_info("amazon.nova-pro-v1:0")).unwrap(),
724            json!({
725                "capabilities": {
726                    "forcedToolChoice": true,
727                    "nativeStructuredOutput": false,
728                    "deferredToolLoading": "unsupported",
729                    "acceptedMimeTypes": ([CLAUDE_MIME_TYPES.as_slice(), NOVA_VIDEO_MIME_TYPES.as_slice()].concat()),
730                },
731                "limits": {"contextWindow": 300_000},
732            })
733        );
734        assert_eq!(lookup_model_info("claude-future-9"), ModelInfo::default());
735        assert_eq!(lookup_model_info(""), ModelInfo::default());
736    }
737
738    #[test]
739    fn keeps_get_context_window_limit_working_for_ids_the_python_table_already_knew() {
740        assert_eq!(window("mistral-large-latest"), Some(1_048_576));
741        assert_eq!(window("o3"), Some(200_000));
742    }
743
744    #[test]
745    fn exposes_the_context_window_default_from_the_data() {
746        assert_eq!(default_context_window_limit(), 200_000);
747    }
748
749    #[test]
750    fn has_only_the_fields_model_info_defines_with_the_right_types_in_every_entry() {
751        let data: JsonValue = serde_json::from_str(MODEL_INFO_JSON).unwrap();
752        let mut keys: Vec<_> = data.as_object().unwrap().keys().cloned().collect();
753        keys.sort();
754        assert_eq!(keys, ["$comment", "defaults", "models"]);
755        assert!(data["defaults"]["limits"]["contextWindow"].is_u64());
756        assert_eq!(data["defaults"].as_object().unwrap().len(), 1);
757        assert_eq!(data["defaults"]["limits"].as_object().unwrap().len(), 1);
758        for (id, entry) in data["models"].as_object().unwrap() {
759            let mut chars = id.chars();
760            assert!(
761                chars
762                    .next()
763                    .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
764                    && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || ".:@-".contains(c)),
765                "{id}"
766            );
767            let entry = entry.as_object().unwrap();
768            assert!(entry.keys().all(|key| key == "limits" || key == "capabilities"), "{id}");
769            for (key, value) in entry.get("limits").and_then(JsonValue::as_object).into_iter().flatten() {
770                assert!(
771                    ["contextWindow", "maxOutputTokens"].contains(&key.as_str()),
772                    "{id}.limits.{key}"
773                );
774                assert!(value.as_u64().is_some_and(|n| n > 0), "{id}.limits.{key}");
775            }
776            for (key, value) in entry
777                .get("capabilities")
778                .and_then(JsonValue::as_object)
779                .into_iter()
780                .flatten()
781            {
782                match key.as_str() {
783                    "promptCaching" => assert!(
784                        ["unsupported", "auto", "cachePoints"].contains(&value.as_str().unwrap()),
785                        "{id}.{key}"
786                    ),
787                    "forcedToolChoice" | "nativeStructuredOutput" | "serverSideSummary" | "temporaryMessages" => {
788                        assert!(value.is_boolean(), "{id}.{key}");
789                    }
790                    "deferredToolLoading" => assert!(
791                        ["unsupported", "native"].contains(&value.as_str().unwrap()),
792                        "{id}.{key}"
793                    ),
794                    "acceptedMimeTypes" => assert_mime_type_list(value, &format!("{id}.{key}")),
795                    // Fields the shared file carries for other readers, which `ModelInfo` skips.
796                    "defaultEffort" => assert!(
797                        ["minimal", "low", "medium", "high", "xhigh", "max"].contains(&value.as_str().unwrap()),
798                        "{id}.{key}"
799                    ),
800                    "chatCompletionsTools" => assert!(
801                        ["reasoningOff", "unsupported"].contains(&value.as_str().unwrap()),
802                        "{id}.{key}"
803                    ),
804                    "systemPromptPlacement" => assert_eq!(value, "message", "{id}.{key}"),
805                    "toolUse" => assert!(value.is_boolean(), "{id}.{key}"),
806                    other => panic!("{id}.capabilities.{other} is not a ModelCapabilities field"),
807                }
808            }
809        }
810        assert_eq!(DATA.models.len(), data["models"].as_object().unwrap().len());
811    }
812
813    #[test]
814    fn returns_the_context_window_limit_for_known_model_ids_across_all_providers() {
815        let cases = [
816            ("claude-sonnet-4-6", 1_000_000),
817            ("claude-opus-4-6", 1_000_000),
818            ("claude-opus-4-5", 200_000),
819            ("claude-haiku-4-5", 200_000),
820            ("anthropic.claude-sonnet-4-6", 1_000_000),
821            ("amazon.nova-pro-v1:0", 300_000),
822            ("amazon.nova-micro-v1:0", 128_000),
823            ("zai.glm-4.7", 203_000),
824            ("zai.glm-4.7-flash", 203_000),
825            ("zai.glm-5", 200_000),
826            ("zai.glm-5.3", 1_000_000),
827            ("us.zai.glm-5.3", 1_000_000),
828            ("global.zai.glm-5.3", 1_000_000),
829            ("mistral.mistral-large-3-675b-instruct", 256_000),
830            ("mistral.ministral-3-14b-instruct", 128_000),
831            ("mistral.ministral-3-8b-instruct", 128_000),
832            ("mistral.ministral-3-3b-instruct", 128_000),
833            ("mistral.magistral-small-2509", 128_000),
834            ("mistral.pixtral-large-2502-v1:0", 128_000),
835            ("mistral.mistral-small-2402-v1:0", 32_000),
836            ("mistral.mistral-large-2402-v1:0", 32_000),
837            ("us.mistral.mistral-large-3-675b-instruct", 256_000),
838            ("global.mistral.mistral-large-3-675b-instruct", 256_000),
839            ("google.gemma-4-31b", 256_000),
840            ("google.gemma-4-26b-a4b", 256_000),
841            ("google.gemma-4-e2b", 128_000),
842            ("us.google.gemma-4-31b", 256_000),
843            ("xai.grok-4.7", 524_288),
844            ("xai.grok-4.6", 500_000),
845            ("xai.grok-4.3", 1_000_000),
846            ("us.xai.grok-4.7", 524_288),
847            ("global.xai.grok-4.7", 524_288),
848            ("chat-latest", 272_000),
849            ("gpt-6.2-astra", 1_050_000),
850            ("gpt-6.2-sol", 1_050_000),
851            ("gpt-6-astra", 1_050_000),
852            ("gpt-6.1-sol", 1_050_000),
853            ("gpt-6.1-terra", 1_050_000),
854            ("gpt-6-sol", 1_050_000),
855            ("gpt-6-luna", 1_050_000),
856            ("gpt-6-cyber", 1_050_000),
857            ("gpt-5.4", 1_050_000),
858            ("gpt-4o", 128_000),
859            ("o3", 200_000),
860            ("o4-mini", 200_000),
861            ("gpt-oss-120b", 131_072),
862            ("gpt-oss-20b", 131_072),
863            ("gemini-4-argon", 1_048_576),
864            ("gemini-4-neon", 1_048_576),
865            ("gemini-4-hydrogen", 1_048_576),
866            ("gemini-3.8-flash", 1_048_576),
867            ("gemini-3.7-flash", 1_048_576),
868            ("gemini-2.5-flash", 1_048_576),
869            ("gemini-2.5-pro", 1_048_576),
870        ];
871        for (model_id, expected) in cases {
872            assert_eq!(window(model_id), Some(expected), "{model_id}");
873        }
874    }
875
876    #[test]
877    fn returns_1m_for_the_current_generation_anthropic_models() {
878        for model_id in [
879            "claude-sonnet-5-5",
880            "claude-opus-5-5",
881            "claude-fable-5-1",
882            "anthropic.claude-sonnet-5-5",
883            "anthropic.claude-opus-5-5",
884            "anthropic.claude-fable-5-1",
885            "global.anthropic.claude-opus-5-5",
886            "us.anthropic.claude-fable-5-1",
887            "claude-haiku-5-5",
888            "anthropic.claude-haiku-5-5",
889            "eu.anthropic.claude-haiku-5-5",
890            "global.anthropic.claude-haiku-5-5",
891            "claude-fable-5-2",
892            "global.anthropic.claude-fable-5-2",
893            "claude-mythos-5-2",
894            "us.anthropic.claude-mythos-5-2",
895        ] {
896            assert_eq!(window(model_id), Some(1_000_000), "{model_id}");
897        }
898    }
899
900    #[test]
901    fn returns_the_bedrock_window_for_gpt_oss_not_the_openai_hosted_one() {
902        for model_id in [
903            "openai.gpt-oss-120b",
904            "openai.gpt-oss-120b-1:0",
905            "openai.gpt-oss-20b",
906            "openai.gpt-oss-20b-1:0",
907            "openai.gpt-oss-safeguard-120b",
908            "openai.gpt-oss-safeguard-20b",
909            "us.openai.gpt-oss-120b-1:0",
910            "global.openai.gpt-oss-120b",
911        ] {
912            assert_eq!(window(model_id), Some(128_000), "{model_id}");
913        }
914    }
915
916    #[test]
917    fn resolves_bedrock_gpt_ids_which_are_not_derivable_from_the_openai_hosted_rows() {
918        let cases = [
919            ("openai.gpt-6-astra", 1_050_000),
920            ("openai.gpt-6.1-sol", 1_000_000),
921            ("openai.gpt-6.1-terra", 1_050_000),
922            ("openai.gpt-6-sol", 1_050_000),
923            ("openai.gpt-6-luna", 1_050_000),
924            ("openai.gpt-5.6-sol", 1_050_000),
925            ("openai.gpt-5.6-terra", 1_050_000),
926            ("openai.gpt-5.6-luna", 1_050_000),
927            ("openai.gpt-5.6-cyber", 1_050_000),
928            ("openai.gpt-daybreak-blue-5.6-sol", 1_050_000),
929            ("openai.gpt-5.5", 1_050_000),
930            ("openai.gpt-5.4", 1_050_000),
931            ("us.openai.gpt-5.5", 1_050_000),
932            ("global.openai.gpt-6.1-sol", 1_000_000),
933            ("us.openai.gpt-6.1-terra", 1_050_000),
934            ("us.openai.gpt-6.2-astra", 1_050_000),
935            ("global.openai.gpt-6.2-sol", 1_050_000),
936            ("in.openai.gpt-5.6-luna", 1_050_000),
937        ];
938        for (model_id, expected) in cases {
939            assert_eq!(window(model_id), Some(expected), "{model_id}");
940        }
941    }
942
943    #[test]
944    fn strips_bedrock_cross_region_prefix_before_lookup() {
945        assert_eq!(window("us.anthropic.claude-sonnet-4-6"), Some(1_000_000));
946        assert_eq!(window("global.anthropic.claude-sonnet-4-6"), Some(1_000_000));
947    }
948
949    #[test]
950    fn strips_leading_segments_one_at_a_time_like_the_python_sdk_so_unknown_prefixes_and_arns_resolve() {
951        assert_eq!(window("custom.gpt-5.4"), window("gpt-5.4"));
952        assert_eq!(
953            window("arn:aws:bedrock:us-west-2:123:inference-profile/us.anthropic.claude-sonnet-4-6"),
954            Some(1_000_000)
955        );
956    }
957
958    #[test]
959    fn returns_undefined_for_unknown_model_ids() {
960        assert_eq!(window("unknown-model-xyz"), None);
961        assert_eq!(window("us.unknown.model-v1:0"), None);
962    }
963
964    #[test]
965    fn version_and_date_suffixes_strip_only_their_exact_forms() {
966        assert_eq!(strip_version_suffix("model-v1:0"), "model");
967        assert_eq!(strip_version_suffix("model-v2"), "model");
968        assert_eq!(strip_version_suffix("model-1:0"), "model");
969        assert_eq!(strip_version_suffix("model-1"), "model-1");
970        assert_eq!(strip_version_suffix("model-v"), "model-v");
971        assert_eq!(strip_version_suffix("model-v1:"), "model-v1:");
972        assert_eq!(strip_date_suffix("model-20260401"), "model");
973        assert_eq!(strip_date_suffix("model@20251001"), "model");
974        assert_eq!(strip_date_suffix("model-2026040"), "model-2026040");
975        assert_eq!(strip_date_suffix("model_20260401"), "model_20260401");
976        assert_eq!(strip_date_suffix("é20260401"), "é20260401");
977    }
978}