Skip to main content

strands/models/
model.rs

1//! The [`Model`] trait, its request and result types, and stream aggregation.
2
3use std::collections::HashSet;
4use std::pin::Pin;
5
6use async_trait::async_trait;
7use futures::{Stream, StreamExt};
8use serde::{Deserialize, Serialize};
9
10use super::model_info::lookup_model_info;
11use super::model_info::{DeferredToolLoading, ModelCapabilities, ModelInfo, ModelLimits, default_context_window_limit};
12use super::streaming::{
13    ContentBlockDelta, ContentBlockStart, ModelContentBlockStartEvent, ModelMetadataEvent, ModelRedactionEvent,
14    ModelStreamEvent, ReasoningContentDelta,
15};
16use super::summarize::{SummarizeResult, summarize_client_side};
17use crate::cancel::CancelSignal;
18use crate::error::{Error, MaxTokensError, ModelError, Result};
19use crate::logging::warn_once;
20use crate::state_store::StateStore;
21use crate::types::{
22    AgentMetadata, Citation, CitationGeneratedContent, CitationsBlock, ContentBlock, JsonValue, Message,
23    MessageMetadata, ReasoningBlock, Role, StopReason, SystemContentBlock, SystemPrompt, TextBlock, ToolChoice,
24    ToolResultContent, ToolSpec, ToolUseBlock,
25};
26
27/// A pinned, boxed, `Send` stream, as returned by [`Model::stream`].
28pub type BoxStream<'a, T> = Pin<Box<dyn Stream<Item = T> + Send + 'a>>;
29
30/// Configuration every model provider supports (`BaseModelConfig`).
31///
32/// Providers have their own typed configuration as well; this is the common view returned by
33/// [`Model::get_config`].
34#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
35pub struct BaseModelConfig {
36    /// The model identifier in the provider's catalog.
37    #[builder(into)]
38    pub model_id: Option<String>,
39    /// Maximum number of tokens to generate in the response.
40    pub max_tokens: Option<u64>,
41    /// Controls randomness in generation.
42    pub temperature: Option<f64>,
43    /// Controls diversity via nucleus sampling.
44    pub top_p: Option<f64>,
45    /// Context window size in tokens. The same fact as `model_info.limits.context_window`: it wins
46    /// over the shared model info, and `model_info` wins over it. Vended providers fill it from the
47    /// shared model info when unset; [`Model::model_info`] is the resolved view to read.
48    pub context_window_limit: Option<u64>,
49    /// Overrides for what the SDK knows about the model. Fields set here win over the shared model
50    /// info and the provider. An update that sets it replaces the previous override entirely.
51    pub model_info: Option<ModelInfo>,
52}
53
54impl BaseModelConfig {
55    /// Shallow-merges `update` into `self`: every field `update` sets replaces the current value.
56    /// Providers implement [`Model::update_config`] with it.
57    pub fn merge(&mut self, update: Self) {
58        let Self {
59            model_id,
60            max_tokens,
61            temperature,
62            top_p,
63            context_window_limit,
64            model_info,
65        } = update;
66        self.model_id = model_id.or(self.model_id.take());
67        self.max_tokens = max_tokens.or(self.max_tokens);
68        self.temperature = temperature.or(self.temperature);
69        self.top_p = top_p.or(self.top_p);
70        self.context_window_limit = context_window_limit.or(self.context_window_limit);
71        self.model_info = model_info.or(self.model_info.take());
72    }
73}
74
75/// One request to a model: the conversation and its options.
76///
77/// The request is owned, so a provider can move it into a spawned task.
78#[derive(Debug, Clone, Default, bon::Builder)]
79pub struct ModelRequest {
80    /// The conversation to send.
81    #[builder(default)]
82    pub messages: Vec<Message>,
83    /// System prompt guiding the model's behavior.
84    #[builder(into)]
85    pub system_prompt: Option<SystemPrompt>,
86    /// Tools the model may call.
87    #[builder(default)]
88    pub tool_specs: Vec<ToolSpec>,
89    /// How the model selects tools.
90    pub tool_choice: Option<ToolChoice>,
91    /// State for providers that keep conversation state server-side, such as a response id for
92    /// chaining. The agent passes a copy and keeps the provider's changes only when the call
93    /// succeeds.
94    #[builder(default)]
95    pub model_state: StateStore,
96    /// How many trailing blocks of the last user message are rebuilt on every call.
97    pub dynamic_trailing_blocks: Option<usize>,
98    /// Metadata of the invoking agent.
99    pub agent_metadata: Option<AgentMetadata>,
100    /// JSON schema this call must produce, set by the agent on its structured output retry. The
101    /// response must then call the tool named in `tool_choice`, or be a final text response that is
102    /// exactly one JSON object valid against this schema.
103    pub structured_output_schema: Option<JsonValue>,
104    /// Signal a provider can forward to abort the in-flight request. Support is provider-dependent.
105    pub cancel_signal: Option<CancelSignal>,
106    /// Names of the tools in `tool_specs` this call defers; empty when it defers none. A provider
107    /// whose model defers tools natively (`ModelCapabilities::deferred_tool_loading` is
108    /// [`DeferredToolLoading::Native`](super::DeferredToolLoading::Native)) keeps their input
109    /// schemas out of the model's context until the model loads them; every other provider
110    /// ignores it.
111    #[builder(default)]
112    pub deferred_tools: HashSet<String>,
113}
114
115/// Options for [`Model::count_tokens`] (`CountTokensOptions`).
116#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
117pub struct CountTokensOptions {
118    /// System prompt to include in the count.
119    #[builder(into)]
120    pub system_prompt: Option<SystemPrompt>,
121    /// Tool specifications to include in the count.
122    #[builder(default)]
123    pub tool_specs: Vec<ToolSpec>,
124}
125
126/// Options for [`Model::summarize`] (`SummarizeOptions`).
127#[derive(Debug, Clone, Default, bon::Builder)]
128pub struct SummarizeOptions {
129    /// The request's system prompt.
130    #[builder(into)]
131    pub system_prompt: Option<SystemPrompt>,
132    /// The request's tool specifications.
133    #[builder(default)]
134    pub tool_specs: Vec<ToolSpec>,
135    /// Instructions replacing the default ones; `None` or an empty string keeps them. The base
136    /// implementation's instruction not to act on the request or call tools is always sent.
137    #[builder(into)]
138    pub instructions: Option<String>,
139    /// Signal that aborts the call.
140    pub cancel_signal: Option<CancelSignal>,
141    /// Metadata of the invoking agent, as passed to [`Model::stream`]. A provider may derive a
142    /// prompt-cache routing key from it, so a replay can share the agent's cache.
143    pub agent_metadata: Option<AgentMetadata>,
144    /// Names of the tools in `tool_specs` the request defers, as in
145    /// [`ModelRequest::deferred_tools`].
146    #[builder(default)]
147    pub deferred_tools: HashSet<String>,
148}
149
150/// Redaction of the user's input when a guardrail blocked it (`Redaction`).
151#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
152#[serde(rename_all = "camelCase")]
153#[non_exhaustive]
154pub struct Redaction {
155    /// The text to replace the last user message with.
156    pub user_message: String,
157}
158
159impl Redaction {
160    /// Creates the redaction.
161    pub fn new(user_message: impl Into<String>) -> Self {
162        Self {
163            user_message: user_message.into(),
164        }
165    }
166}
167
168/// The final value of [`Model::stream_aggregated`] (`StreamAggregatedResult`).
169#[derive(Debug, Clone, PartialEq)]
170#[non_exhaustive]
171pub struct StreamAggregatedResult {
172    /// The complete message from the model.
173    pub message: Message,
174    /// Why the model stopped generating.
175    pub stop_reason: StopReason,
176    /// The last metadata event, with usage and metrics, if the provider sent one.
177    pub metadata: Option<ModelMetadataEvent>,
178    /// Input redaction when a guardrail blocked the input. Output redaction replaces the message.
179    pub redaction: Option<Redaction>,
180}
181
182impl StreamAggregatedResult {
183    /// Creates a result without metadata or redaction.
184    pub fn new(message: Message, stop_reason: StopReason) -> Self {
185        Self {
186            message,
187            stop_reason,
188            metadata: None,
189            redaction: None,
190        }
191    }
192
193    /// Sets the metadata event.
194    #[must_use]
195    pub fn with_metadata(mut self, metadata: ModelMetadataEvent) -> Self {
196        self.metadata = Some(metadata);
197        self
198    }
199
200    /// Sets the input redaction.
201    #[must_use]
202    pub fn with_redaction(mut self, redaction: Redaction) -> Self {
203        self.redaction = Some(redaction);
204        self
205    }
206}
207
208/// An item of [`Model::stream_aggregated`]: a raw event, a completed block, or the final result.
209#[derive(Debug, Clone, PartialEq)]
210#[non_exhaustive]
211#[allow(clippy::large_enum_variant, reason = "`Done` is the single last item of each stream")]
212pub enum AggregatedEvent {
213    /// A provider event, passed through unchanged.
214    ModelStreamEvent(ModelStreamEvent),
215    /// A content block, emitted when the block completes.
216    ContentBlock(ContentBlock),
217    /// The final message, always the last item of a successful stream.
218    Done(StreamAggregatedResult),
219}
220
221/// A model provider (`Model`).
222///
223/// Implement [`stream`](Model::stream), [`get_config`](Model::get_config) and
224/// [`update_config`](Model::update_config); everything else has a default. Agents hold models as
225/// `Arc<dyn Model>`, so a provider keeps its configuration behind interior locking. A provider that
226/// overrides a default and still needs it calls the free function behind it:
227/// [`base_model_info`] with [`ModelInfo::merge`](crate::models::ModelInfo::merge) for
228/// [`model_info`](Model::model_info), [`estimate_tokens`] for [`count_tokens`](Model::count_tokens)
229/// and [`summarize_client_side`](crate::models::summarize_client_side) for
230/// [`summarize`](Model::summarize). Use [`macro@crate::async_trait`] on the impl when overriding
231/// the async methods.
232///
233/// ```
234/// use std::sync::RwLock;
235///
236/// use futures::StreamExt;
237/// use strands::models::streaming::{
238///     ModelContentBlockDeltaEvent, ModelContentBlockStartEvent, ModelContentBlockStopEvent,
239///     ModelMessageStartEvent, ModelMessageStopEvent, ModelStreamEvent, TextDelta,
240/// };
241/// use strands::models::{AggregatedEvent, BaseModelConfig, BoxStream, Model, ModelRequest};
242/// use strands::{Message, Role, StopReason};
243///
244/// /// Replies with the text of the last message.
245/// #[derive(Default)]
246/// struct EchoModel {
247///     config: RwLock<BaseModelConfig>,
248/// }
249///
250/// #[strands::async_trait]
251/// impl Model for EchoModel {
252///     fn stream(&self, request: ModelRequest) -> BoxStream<'static, strands::Result<ModelStreamEvent>> {
253///         let text = request.messages.last().map(Message::text).unwrap_or_default();
254///         let events: Vec<ModelStreamEvent> = vec![
255///             ModelMessageStartEvent::new(Role::Assistant).into(),
256///             ModelContentBlockStartEvent::new().into(),
257///             ModelContentBlockDeltaEvent::new(TextDelta::new(text)).into(),
258///             ModelContentBlockStopEvent::new().into(),
259///             ModelMessageStopEvent::new(StopReason::EndTurn).into(),
260///         ];
261///         Box::pin(futures::stream::iter(events.into_iter().map(Ok)))
262///     }
263///
264///     fn get_config(&self) -> BaseModelConfig {
265///         self.config.read().unwrap().clone()
266///     }
267///
268///     fn update_config(&self, config: BaseModelConfig) -> strands::Result<()> {
269///         self.config.write().unwrap().merge(config);
270///         Ok(())
271///     }
272/// }
273///
274/// let model = EchoModel::default();
275/// let request = ModelRequest::builder().messages(vec![Message::user("ping")]).build();
276/// futures::executor::block_on(async {
277///     let mut stream = model.stream_aggregated(request);
278///     while let Some(item) = stream.next().await {
279///         if let AggregatedEvent::Done(result) = item.unwrap() {
280///             assert_eq!(result.message.text(), "ping");
281///         }
282///     }
283/// });
284/// ```
285#[async_trait]
286pub trait Model: Send + Sync + 'static {
287    /// Streams the model's response to `request` as raw events.
288    ///
289    /// The stream is `'static` so the call can be spawned: clone what the stream needs (a config
290    /// snapshot, a client handle) out of `&self`.
291    ///
292    /// # Errors
293    ///
294    /// Report failures as stream items, translating provider errors to the SDK's model errors so
295    /// the agent can react: [`ModelThrottledError`](crate::ModelThrottledError) and
296    /// [`ModelNetworkError`](crate::ModelNetworkError) are retried by the default retry strategy,
297    /// and [`ContextWindowOverflowError`](crate::ContextWindowOverflowError) makes the
298    /// conversation manager reduce the context. Keep the provider's error as the source.
299    fn stream(&self, request: ModelRequest) -> BoxStream<'static, Result<ModelStreamEvent>>;
300
301    /// Streams the response with content blocks and the final message assembled.
302    ///
303    /// Yields every raw event, then each completed [`ContentBlock`], and ends with
304    /// [`AggregatedEvent::Done`]. Errors that are not model errors are wrapped in [`ModelError`];
305    /// model errors such as [`ContextWindowOverflowError`](crate::ContextWindowOverflowError),
306    /// [`ModelThrottledError`](crate::ModelThrottledError) and [`MaxTokensError`] (which carries the
307    /// partial message) pass through.
308    fn stream_aggregated(&self, request: ModelRequest) -> BoxStream<'static, Result<AggregatedEvent>> {
309        aggregate(self.stream(request))
310    }
311
312    /// The current configuration.
313    fn get_config(&self) -> BaseModelConfig;
314
315    /// Merges `config` into the configuration: every field it sets replaces the current value
316    /// ([`BaseModelConfig::merge`]).
317    ///
318    /// # Errors
319    ///
320    /// The provider rejects the update (for example a model id its client cannot be rebuilt
321    /// for); the configuration is left unchanged.
322    fn update_config(&self, config: BaseModelConfig) -> Result<()>;
323
324    /// The configured model id.
325    fn model_id(&self) -> Option<String> {
326        self.get_config().model_id
327    }
328
329    /// Everything the SDK knows about the configured model, resolved on each call.
330    ///
331    /// Layers, later ones winning: the shared model info for the model id, `temporary_messages`
332    /// off (a provider that supports them turns them back on), `deferred_tool_loading` as `Stubs`
333    /// unless the shared info says `Unsupported` (a provider that defers natively says `Native`),
334    /// the `context_window_limit` config value, and the `model_info` config override
335    /// ([`base_model_info`]). A provider that knows
336    /// better overrides this method, layering its facts over [`base_model_info`] and the user's
337    /// override on top with [`ModelInfo::merge`](crate::models::ModelInfo::merge); it must not call
338    /// [`stateful`](Model::stateful), which reads this method.
339    fn model_info(&self) -> ModelInfo {
340        base_model_info(&self.get_config())
341    }
342
343    /// Whether the model keeps conversation state server-side (`stateful`), from
344    /// `model_info().capabilities.stateful`; `false` when unknown.
345    ///
346    /// When `true`, the agent sends only the latest message and clears its local history after each
347    /// invocation.
348    fn stateful(&self) -> bool {
349        self.model_info().capabilities.stateful.unwrap_or(false)
350    }
351
352    /// Estimates the input tokens of a request before sending it.
353    ///
354    /// The default is [`estimate_tokens`], a character heuristic (text length / 4, JSON length / 2)
355    /// that counts only the latest user message's injected blocks, the ones a model reads.
356    /// Providers with a native counting API override it and fall back to [`estimate_tokens`] on
357    /// failure.
358    async fn count_tokens(&self, messages: &[Message], options: CountTokensOptions) -> Result<u64> {
359        Ok(estimate_tokens(messages, &options))
360    }
361
362    /// Summarizes `messages`, a request as the caller would send it to [`stream`](Model::stream)
363    /// (`summarize`).
364    ///
365    /// The default sends that request closed by an instruction not to act on it or call tools,
366    /// followed by `instructions` (or the default ones), so a caller replaying its own conversation
367    /// can share its prompt cache. The summary is the reply's text, including a reply cut off at the
368    /// output limit or a stop sequence; a reply that ends for another reason (a tool call, a
369    /// cancellation, a guardrail) or holds no text gives an empty result. Every summary is a
370    /// `SummaryBlock`; the default leaves its `provider` unset. A provider whose model info reports
371    /// `server_side_summary` overrides this to summarize server-side and sets `provider`, falling
372    /// back to [`summarize_client_side`](crate::models::summarize_client_side).
373    async fn summarize(&self, messages: Vec<Message>, options: SummarizeOptions) -> Result<SummarizeResult> {
374        summarize_client_side(self, messages, options).await
375    }
376
377    /// The fraction of the context window that `input_tokens` fills; above 1.0 means overflow.
378    ///
379    /// Uses `model_info().limits.context_window`, or the default limit with a one-time warning when
380    /// it is unknown.
381    fn estimate_utilization(&self, input_tokens: u64) -> f64 {
382        let limit = self
383            .model_info()
384            .limits
385            .context_window
386            .filter(|limit| *limit > 0)
387            .unwrap_or_else(|| {
388                let default = default_context_window_limit();
389                warn_once(&default_context_window_warning(default));
390                default
391            });
392        input_tokens as f64 / limit as f64
393    }
394}
395
396fn default_context_window_warning(default: u64) -> String {
397    format!(
398        "contextWindowLimit is not set on the model, using default of {default} for utilization estimate | set contextWindowLimit in your model config for accurate results"
399    )
400}
401
402/// The default [`Model::model_info`] for a configuration, before any provider facts: the shared model
403/// info for the model id, `temporary_messages` off, `deferred_tool_loading` as `Stubs` unless the
404/// shared info says `Unsupported`, the `context_window_limit` and the `model_info` override. A provider that overrides [`Model::model_info`] starts from it (see
405/// [`ModelInfo::merge`](crate::models::ModelInfo::merge)).
406#[must_use]
407pub fn base_model_info(config: &BaseModelConfig) -> ModelInfo {
408    let shared = lookup_model_info(config.model_id.as_deref().unwrap_or_default());
409    let deferred_tool_loading = match shared.capabilities.deferred_tool_loading {
410        Some(DeferredToolLoading::Unsupported) => DeferredToolLoading::Unsupported,
411        _ => DeferredToolLoading::Stubs,
412    };
413    let defaults = ModelInfo {
414        capabilities: ModelCapabilities {
415            temporary_messages: Some(false),
416            deferred_tool_loading: Some(deferred_tool_loading),
417            ..ModelCapabilities::default()
418        },
419        limits: ModelLimits {
420            context_window: config.context_window_limit,
421            ..ModelLimits::default()
422        },
423    };
424    ModelInfo::merge([Some(&shared), Some(&defaults), config.model_info.as_ref()])
425}
426
427/// Fills `context_window_limit` from the model info when it is unset.
428#[allow(dead_code, reason = "providers fill the context window of `get_config` with it")]
429pub(crate) fn resolve_config_metadata(mut config: BaseModelConfig, model_id: &str) -> BaseModelConfig {
430    if config.context_window_limit.is_some() {
431        return config;
432    }
433    let info = ModelInfo::merge([Some(&lookup_model_info(model_id)), config.model_info.as_ref()]);
434    config.context_window_limit = info.limits.context_window;
435    config
436}
437
438/// The `max_tokens` to send: the configured value, else the model's output ceiling from the
439/// shared model info with the override applied.
440#[allow(dead_code, reason = "providers that need a max_tokens resolve it with this")]
441pub(crate) fn resolve_max_tokens(config: &BaseModelConfig, model_id: &str) -> Option<u64> {
442    config.max_tokens.or_else(|| {
443        ModelInfo::merge([Some(&lookup_model_info(model_id)), config.model_info.as_ref()])
444            .limits
445            .max_output_tokens
446    })
447}
448
449/// Index of the latest user message, `None` when there is none.
450pub(crate) fn latest_user_index(messages: &[Message]) -> Option<usize> {
451    messages.iter().rposition(|message| message.role == Role::User)
452}
453
454/// Whether caching skips models that are not known to support it (`CacheConfig.strategy`).
455#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
456#[non_exhaustive]
457pub enum CacheStrategy {
458    /// Cache only when the model is known to support it.
459    #[default]
460    Auto,
461    /// Cache without that check, for model identifiers the SDK cannot inspect (an application
462    /// inference profile, for example).
463    Anthropic,
464}
465
466/// TTL of a cache entry (`CacheTTL`), such as `"5m"` or `"1h"`. Providers validate it server-side.
467pub type CacheTtl = String;
468
469/// Whether a cache section is cached, and for how long.
470#[derive(Debug, Clone, PartialEq, Eq)]
471#[non_exhaustive]
472pub enum CacheSectionSetting {
473    /// `true` caches the section with the shared TTL; `false` disables it.
474    Enabled(bool),
475    /// Caches the section with this TTL.
476    Ttl(CacheTtl),
477}
478
479impl From<bool> for CacheSectionSetting {
480    fn from(enabled: bool) -> Self {
481        Self::Enabled(enabled)
482    }
483}
484
485impl From<&str> for CacheSectionSetting {
486    fn from(ttl: &str) -> Self {
487        Self::Ttl(ttl.to_owned())
488    }
489}
490
491impl From<String> for CacheSectionSetting {
492    fn from(ttl: String) -> Self {
493        Self::Ttl(ttl)
494    }
495}
496
497/// The prompt-cache routing key for providers that route by key.
498#[derive(Debug, Clone, PartialEq, Eq)]
499#[non_exhaustive]
500pub enum CacheKey {
501    /// Use this key.
502    Key(String),
503    /// Opt out of routing.
504    Disabled,
505}
506
507impl From<&str> for CacheKey {
508    fn from(key: &str) -> Self {
509        Self::Key(key.to_owned())
510    }
511}
512
513impl From<String> for CacheKey {
514    fn from(key: String) -> Self {
515        Self::Key(key)
516    }
517}
518
519/// Prompt caching configuration (`CacheConfig`). Providers consume only the fields they support.
520#[derive(Debug, Clone, Default, PartialEq, Eq, bon::Builder)]
521pub struct CacheConfig {
522    /// Whether to skip caching for models that do not support it. Default [`CacheStrategy::Auto`].
523    pub strategy: Option<CacheStrategy>,
524    /// TTL for every cache point, overridden by a per-section TTL; the provider default when unset.
525    ///
526    /// Bedrock requires checkpoint TTLs to be non-increasing across tools, system and messages, so
527    /// this TTL also fills in for a cache point placed by hand in the system prompt that carries
528    /// none. A TTL written on such a point is left as written.
529    #[builder(into)]
530    pub ttl: Option<CacheTtl>,
531    /// Cache the tool definitions. A TTL sets this section's duration; `false` disables it.
532    /// Default `true`.
533    #[builder(into)]
534    pub tools_ttl: Option<CacheSectionSetting>,
535    /// Cache the system prompt, adding a cache point at its end. A TTL sets this section's
536    /// duration; `true` uses `ttl`; `false` disables it. Default `true`.
537    #[builder(into)]
538    pub system_prompt_ttl: Option<CacheSectionSetting>,
539    /// Cache the conversation prefix, on the last user message. A TTL sets this section's
540    /// duration; `false` disables it. Default `true`.
541    #[builder(into)]
542    pub messages_ttl: Option<CacheSectionSetting>,
543    /// Stable identity a prompt-cache-routing provider (OpenAI) uses as its cache key. Unset, it
544    /// is derived per request as `strands-<sessionId>` when the agent has a session manager. The
545    /// resolved key is sent to the provider.
546    #[builder(into)]
547    pub cache_key: Option<CacheKey>,
548}
549
550/// A cache section resolved to the values a provider emits (`ResolvedCacheSection`).
551#[derive(Debug, Clone, PartialEq, Eq)]
552pub(crate) struct ResolvedCacheSection {
553    /// Whether this section carries a cache point.
554    pub(crate) enabled: bool,
555    /// The TTL to emit, absent when no TTL applies.
556    pub(crate) ttl: Option<CacheTtl>,
557}
558
559/// Resolves whether a cache section is enabled and which TTL it carries.
560///
561/// `ttl_fallbacks` are tried in order after the section's own TTL; an empty TTL counts as unset.
562#[allow(dead_code, reason = "providers place cache points with it")]
563pub(crate) fn resolve_cache_section(
564    section: Option<&CacheSectionSetting>,
565    ttl_fallbacks: &[Option<&str>],
566) -> ResolvedCacheSection {
567    let enabled = !matches!(section, Some(CacheSectionSetting::Enabled(false)));
568    let section_ttl = match section {
569        Some(CacheSectionSetting::Ttl(ttl)) => Some(ttl.as_str()),
570        _ => None,
571    };
572    let ttl = std::iter::once(section_ttl)
573        .chain(ttl_fallbacks.iter().copied())
574        .flatten()
575        .find(|ttl| !ttl.is_empty())
576        .map(str::to_owned);
577    ResolvedCacheSection { enabled, ttl }
578}
579
580/// Wraps an error that is not a model error in a [`ModelError`] carrying it as the source.
581fn into_model_error(error: Error) -> Error {
582    if error.is_model_error() {
583        return error;
584    }
585    ModelError::new(error.to_string()).with_source(error).into()
586}
587
588/// Turns a raw event stream into the [`Model::stream_aggregated`] stream.
589pub(crate) fn aggregate(
590    mut events: BoxStream<'static, Result<ModelStreamEvent>>,
591) -> BoxStream<'static, Result<AggregatedEvent>> {
592    Box::pin(async_stream::stream! {
593        let mut aggregator = Aggregator::default();
594        while let Some(event) = events.next().await {
595            let event = match event {
596                Ok(event) => event,
597                Err(error) => {
598                    yield Err(into_model_error(error));
599                    return;
600                }
601            };
602            let block = aggregator.apply(&event);
603            yield Ok(AggregatedEvent::ModelStreamEvent(event));
604            if let Some(block) = block {
605                yield Ok(AggregatedEvent::ContentBlock(block));
606            }
607        }
608        yield aggregator.finish().map(AggregatedEvent::Done);
609    })
610}
611
612/// Whitespace for trimming: Unicode `White_Space` without U+0085 (next line), plus the byte order mark.
613pub(crate) fn is_js_whitespace(c: char) -> bool {
614    (c.is_whitespace() && c != '\u{85}') || c == '\u{feff}'
615}
616
617#[derive(Default)]
618struct Aggregator {
619    role: Option<Role>,
620    blocks: Vec<ContentBlock>,
621    text: String,
622    tool_input: String,
623    tool_name: String,
624    tool_use_id: String,
625    tool_signature: String,
626    reasoning: ReasoningBlock,
627    citations: Vec<Citation>,
628    citation_content: Vec<CitationGeneratedContent>,
629    stopped: Option<Message>,
630    stop_reason: Option<StopReason>,
631    metadata: Option<ModelMetadataEvent>,
632    redaction: Option<String>,
633    parse_error: Option<serde_json::Error>,
634}
635
636impl Aggregator {
637    fn apply(&mut self, event: &ModelStreamEvent) -> Option<ContentBlock> {
638        match event {
639            ModelStreamEvent::MessageStart(start) => {
640                self.role = Some(start.role);
641                self.blocks.clear();
642            }
643            ModelStreamEvent::ContentBlockStart(start) => self.start_block(start),
644            ModelStreamEvent::ContentBlockDelta(delta) => self.add_delta(&delta.delta),
645            ModelStreamEvent::ContentBlockStop(_) => return self.finish_block(),
646            ModelStreamEvent::MessageStop(stop) => {
647                let content = self
648                    .blocks
649                    .iter()
650                    .filter(|block| !matches!(block, ContentBlock::Text(text) if text.text.trim_matches(is_js_whitespace).is_empty()))
651                    .cloned()
652                    .collect();
653                self.stopped = Some(Message::new(self.role.unwrap_or(Role::Assistant), content));
654                self.stop_reason = Some(stop.stop_reason.clone());
655            }
656            ModelStreamEvent::Metadata(metadata) => self.metadata = Some(metadata.clone()),
657            ModelStreamEvent::Redaction(redaction) => self.redact(redaction),
658        }
659        None
660    }
661
662    fn start_block(&mut self, start: &ModelContentBlockStartEvent) {
663        if let Some(ContentBlockStart::ToolUse(tool_use)) = &start.start {
664            self.tool_name.clone_from(&tool_use.name);
665            self.tool_use_id.clone_from(&tool_use.tool_use_id);
666            self.tool_signature = tool_use.reasoning_signature.clone().unwrap_or_default();
667        }
668        self.tool_input.clear();
669        self.text.clear();
670        self.reasoning = ReasoningBlock::default();
671        self.reset_citations();
672    }
673
674    fn add_delta(&mut self, delta: &ContentBlockDelta) {
675        match delta {
676            ContentBlockDelta::Text(text) => self.text.push_str(&text.text),
677            ContentBlockDelta::ToolUseInput(input) => self.tool_input.push_str(&input.input),
678            ContentBlockDelta::ReasoningContent(reasoning) => self.add_reasoning(reasoning),
679            ContentBlockDelta::Citations(citations) => {
680                self.citations.extend(citations.citations.iter().cloned());
681                self.citation_content.extend(citations.content.iter().cloned());
682            }
683        }
684    }
685
686    fn add_reasoning(&mut self, delta: &ReasoningContentDelta) {
687        if let Some(text) = delta.text.as_deref().filter(|text| !text.is_empty()) {
688            self.reasoning.text.get_or_insert_with(String::new).push_str(text);
689        }
690        if let Some(signature) = delta.signature.as_deref().filter(|signature| !signature.is_empty()) {
691            self.reasoning.signature = Some(signature.to_owned());
692        }
693        if let Some(redacted) = &delta.redacted_content {
694            self.reasoning.redacted_content = Some(redacted.clone());
695        }
696        if let Some(provider_data) = &delta.provider_data {
697            self.reasoning.provider_data = Some(provider_data.clone());
698        }
699    }
700
701    fn has_reasoning(&self) -> bool {
702        self.reasoning.text.is_some()
703            || self.reasoning.signature.is_some()
704            || self.reasoning.redacted_content.is_some()
705            || self.reasoning.provider_data.is_some()
706    }
707
708    fn reset_citations(&mut self) {
709        self.citations.clear();
710        self.citation_content.clear();
711    }
712
713    /// Completes the current block; `None` when its tool input is not valid JSON.
714    fn finish_block(&mut self) -> Option<ContentBlock> {
715        let block = if !self.tool_use_id.is_empty() {
716            self.finish_tool_use()?
717        } else if self.has_reasoning() {
718            ContentBlock::Reasoning(std::mem::take(&mut self.reasoning))
719        } else if !self.citations.is_empty() {
720            self.finish_citations()
721        } else {
722            ContentBlock::Text(TextBlock::new(std::mem::take(&mut self.text)))
723        };
724        self.blocks.push(block.clone());
725        Some(block)
726    }
727
728    fn finish_tool_use(&mut self) -> Option<ContentBlock> {
729        let name = std::mem::take(&mut self.tool_name);
730        let tool_use_id = std::mem::take(&mut self.tool_use_id);
731        let signature = std::mem::take(&mut self.tool_signature);
732        let input = if self.tool_input.is_empty() {
733            Ok(JsonValue::Object(serde_json::Map::new()))
734        } else {
735            serde_json::from_str(&self.tool_input)
736        };
737        let input = match input {
738            Ok(input) => input,
739            Err(error) => {
740                tracing::error!("error=<{error}> | unable to parse tool input JSON");
741                self.parse_error = Some(error);
742                return None;
743            }
744        };
745        let mut block = ToolUseBlock::new(name, tool_use_id, input);
746        if !signature.is_empty() {
747            block = block.with_reasoning_signature(signature);
748        }
749        Some(ContentBlock::ToolUse(block))
750    }
751
752    fn finish_citations(&mut self) -> ContentBlock {
753        let text = std::mem::take(&mut self.text);
754        let mut content = std::mem::take(&mut self.citation_content);
755        if content.is_empty() && !text.is_empty() {
756            content.push(CitationGeneratedContent::new(text));
757        }
758        let citations = std::mem::take(&mut self.citations);
759        ContentBlock::Citations(CitationsBlock::new(citations, content))
760    }
761
762    fn redact(&mut self, redaction: &ModelRedactionEvent) {
763        if let Some(input) = &redaction.input_redaction {
764            self.redaction = Some(input.replace_content.clone());
765        }
766        if let Some(output) = &redaction.output_redaction {
767            self.stopped = Some(Message::assistant(output.replace_content.clone()));
768        }
769    }
770
771    fn finish(self) -> Result<StreamAggregatedResult> {
772        let (Some(mut message), Some(stop_reason)) = (self.stopped, self.stop_reason) else {
773            let mut error = ModelError::new("Stream ended without completing a message");
774            if let Some(parse_error) = self.parse_error {
775                error = error.with_source(parse_error);
776            }
777            return Err(error.into());
778        };
779        let usage = self.metadata.as_ref().and_then(|metadata| metadata.usage);
780        let metrics = self.metadata.as_ref().and_then(|metadata| metadata.metrics);
781        if usage.is_some() || metrics.is_some() {
782            message = message.with_metadata(MessageMetadata {
783                usage,
784                metrics,
785                ..MessageMetadata::default()
786            });
787        }
788        if stop_reason == StopReason::MaxTokens {
789            return Err(MaxTokensError::new(
790                "Model reached maximum token limit. This is an unrecoverable state that requires intervention.",
791                message,
792            )
793            .into());
794        }
795        if let Some(parse_error) = self.parse_error {
796            return Err(ModelError::new("unable to parse tool input JSON")
797                .with_source(parse_error)
798                .into());
799        }
800        Ok(StreamAggregatedResult {
801            message,
802            stop_reason,
803            metadata: self.metadata,
804            redaction: self.redaction.map(Redaction::new),
805        })
806    }
807}
808
809fn utf16_len(text: &str) -> u64 {
810    text.encode_utf16().count() as u64
811}
812
813fn heuristic_text(text: &str) -> u64 {
814    utf16_len(text).div_ceil(4)
815}
816
817/// Rewrites whole-number floats as integers, so `1.0` counts as `1`.
818fn normalize_js_numbers(value: &mut JsonValue) {
819    match value {
820        JsonValue::Number(number) => {
821            let Some(float) = number.as_f64().filter(|_| number.is_f64()) else {
822                return;
823            };
824            if float.fract() == 0.0 && float.abs() <= MAX_SAFE_INTEGER {
825                *value = JsonValue::from(float as i64);
826            }
827        }
828        JsonValue::Array(items) => items.iter_mut().for_each(normalize_js_numbers),
829        JsonValue::Object(map) => map.values_mut().for_each(normalize_js_numbers),
830        _ => {}
831    }
832}
833
834/// 2^53 - 1, the largest integer below which a 64-bit float holds every integer exactly.
835const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
836
837pub(crate) fn heuristic_json(value: &impl Serialize) -> u64 {
838    let Ok(mut json) = serde_json::to_value(value) else {
839        tracing::debug!("unable to serialize object for token estimation, skipping");
840        return 0;
841    };
842    normalize_js_numbers(&mut json);
843    utf16_len(&json.to_string()).div_ceil(2)
844}
845
846fn estimate_content_block_tokens(block: &ContentBlock) -> u64 {
847    match block {
848        ContentBlock::Text(text) => heuristic_text(&text.text),
849        ContentBlock::ToolUse(tool_use) => heuristic_text(&tool_use.name) + heuristic_json(&tool_use.input),
850        ContentBlock::ToolResult(result) => result
851            .content
852            .iter()
853            .map(|item| match item {
854                ToolResultContent::Text(text) => heuristic_text(&text.text),
855                ToolResultContent::Json(json) => heuristic_json(&json.json),
856                _ => 0,
857            })
858            .sum(),
859        ContentBlock::Reasoning(reasoning) => reasoning.text.as_deref().map_or(0, heuristic_text),
860        ContentBlock::GuardContent(guard) => guard.text().map_or(0, |text| heuristic_text(&text.text)),
861        ContentBlock::Citations(citations) => citations.content.iter().map(|item| heuristic_text(&item.text)).sum(),
862        ContentBlock::Injected(injected) => heuristic_text(&injected.text),
863        ContentBlock::Summary(summary) => heuristic_text(&summary.text),
864        _ => 0,
865    }
866}
867
868fn estimate_system_prompt_tokens(system_prompt: &SystemPrompt) -> u64 {
869    match system_prompt {
870        SystemPrompt::Text(text) => heuristic_text(text),
871        SystemPrompt::Blocks(blocks) => blocks
872            .iter()
873            .map(|block| match block {
874                SystemContentBlock::Text(text) => heuristic_text(&text.text),
875                SystemContentBlock::GuardContent(guard) => guard.text().map_or(0, |text| heuristic_text(&text.text)),
876                _ => 0,
877            })
878            .sum(),
879    }
880}
881
882/// Counts the messages, with only the latest user message's injected blocks, the ones a model reads.
883fn estimate_message_tokens(messages: &[Message]) -> u64 {
884    let latest_user = latest_user_index(messages);
885    messages
886        .iter()
887        .enumerate()
888        .flat_map(|(index, message)| {
889            let keep_injected = Some(index) == latest_user;
890            message
891                .content
892                .iter()
893                .filter(move |block| keep_injected || !matches!(block, ContentBlock::Injected(_)))
894        })
895        .map(estimate_content_block_tokens)
896        .sum()
897}
898
899/// The default [`Model::count_tokens`] estimate: text length / 4 and JSON length / 2, in UTF-16 code
900/// units, with only the latest user message's injected blocks.
901///
902/// Providers with a native counting API fall back to it on failure.
903#[must_use]
904pub fn estimate_tokens(messages: &[Message], options: &CountTokensOptions) -> u64 {
905    let system = options.system_prompt.as_ref().map_or(0, estimate_system_prompt_tokens);
906    let tools: u64 = options.tool_specs.iter().map(heuristic_json).sum();
907    system + estimate_message_tokens(messages) + tools
908}
909
910/// Tests the provider-independent model behaviour, including cache config portability.
911#[cfg(test)]
912mod tests;