Skip to main content

strands/models/
streaming.rs

1//! Model stream events, token usage and metrics.
2//!
3//! Each event serializes with its `type` discriminator first, for example
4//! `{"type":"modelMessageStartEvent","role":"assistant"}`.
5
6use serde::{Deserialize, Serialize};
7
8use crate::types::json::present;
9use crate::types::media::base64_bytes;
10use crate::types::{
11    Citation, CitationGeneratedContent, JsonObject, JsonValue, ReasoningProviderData, Role, StopReason,
12};
13
14/// Token usage of a model response (`Usage`).
15#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "camelCase")]
17#[non_exhaustive]
18pub struct Usage {
19    /// Input tokens.
20    pub input_tokens: u64,
21    /// Output tokens.
22    pub output_tokens: u64,
23    /// Total tokens.
24    pub total_tokens: u64,
25    /// Input tokens read from the prompt cache.
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub cache_read_input_tokens: Option<u64>,
28    /// Input tokens written to the prompt cache.
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub cache_write_input_tokens: Option<u64>,
31}
32
33impl Usage {
34    /// Creates usage without cache counts.
35    pub fn new(input_tokens: u64, output_tokens: u64, total_tokens: u64) -> Self {
36        Self {
37            input_tokens,
38            output_tokens,
39            total_tokens,
40            cache_read_input_tokens: None,
41            cache_write_input_tokens: None,
42        }
43    }
44
45    /// Sets the cache read count.
46    #[must_use]
47    pub fn with_cache_read_input_tokens(mut self, tokens: u64) -> Self {
48        self.cache_read_input_tokens = Some(tokens);
49        self
50    }
51
52    /// Sets the cache write count.
53    #[must_use]
54    pub fn with_cache_write_input_tokens(mut self, tokens: u64) -> Self {
55        self.cache_write_input_tokens = Some(tokens);
56        self
57    }
58
59    /// Adds `other` into `self`, saturating at `u64::MAX`. Cache counts are added
60    /// only when `other` has them.
61    pub fn accumulate(&mut self, other: &Self) {
62        self.input_tokens = self.input_tokens.saturating_add(other.input_tokens);
63        self.output_tokens = self.output_tokens.saturating_add(other.output_tokens);
64        self.total_tokens = self.total_tokens.saturating_add(other.total_tokens);
65        if let Some(read) = other.cache_read_input_tokens {
66            self.cache_read_input_tokens = Some(self.cache_read_input_tokens.unwrap_or(0).saturating_add(read));
67        }
68        if let Some(write) = other.cache_write_input_tokens {
69            self.cache_write_input_tokens = Some(self.cache_write_input_tokens.unwrap_or(0).saturating_add(write));
70        }
71    }
72
73    /// The whole prompt size, cached or not.
74    ///
75    /// Providers either count cache tokens inside `input_tokens` (input plus output equals the
76    /// total) or separately, in which case they are added.
77    #[must_use]
78    pub fn total_prompt_tokens(&self) -> u64 {
79        if self.input_tokens.saturating_add(self.output_tokens) == self.total_tokens {
80            return self.input_tokens;
81        }
82        self.input_tokens
83            .saturating_add(self.cache_read_input_tokens.unwrap_or(0))
84            .saturating_add(self.cache_write_input_tokens.unwrap_or(0))
85    }
86}
87
88/// Performance metrics of a model response (`Metrics`).
89#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
90#[serde(rename_all = "camelCase")]
91#[non_exhaustive]
92pub struct Metrics {
93    /// End-to-end latency in milliseconds.
94    pub latency_ms: u64,
95    /// Time to the first byte in milliseconds.
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub time_to_first_byte_ms: Option<u64>,
98}
99
100impl Metrics {
101    /// Creates metrics with a latency.
102    pub fn new(latency_ms: u64) -> Self {
103        Self {
104            latency_ms,
105            time_to_first_byte_ms: None,
106        }
107    }
108
109    /// Sets the time to the first byte.
110    #[must_use]
111    pub fn with_time_to_first_byte_ms(mut self, time_to_first_byte_ms: u64) -> Self {
112        self.time_to_first_byte_ms = Some(time_to_first_byte_ms);
113        self
114    }
115}
116
117/// An event in a model's response stream (`ModelStreamEvent`).
118#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
119#[serde(tag = "type")]
120#[non_exhaustive]
121pub enum ModelStreamEvent {
122    /// The model started a message.
123    #[serde(rename = "modelMessageStartEvent")]
124    MessageStart(ModelMessageStartEvent),
125    /// A content block started.
126    #[serde(rename = "modelContentBlockStartEvent")]
127    ContentBlockStart(ModelContentBlockStartEvent),
128    /// A content block received a delta.
129    #[serde(rename = "modelContentBlockDeltaEvent")]
130    ContentBlockDelta(ModelContentBlockDeltaEvent),
131    /// A content block ended.
132    #[serde(rename = "modelContentBlockStopEvent")]
133    ContentBlockStop(ModelContentBlockStopEvent),
134    /// The message ended.
135    #[serde(rename = "modelMessageStopEvent")]
136    MessageStop(ModelMessageStopEvent),
137    /// Usage, metrics and trace data.
138    #[serde(rename = "modelMetadataEvent")]
139    Metadata(ModelMetadataEvent),
140    /// A guardrail redacted content.
141    #[serde(rename = "modelRedactionEvent")]
142    Redaction(ModelRedactionEvent),
143}
144
145macro_rules! stream_event_from {
146    ($($variant:ident($event:ty)),* $(,)?) => {
147        $(impl From<$event> for ModelStreamEvent {
148            fn from(event: $event) -> Self {
149                Self::$variant(event)
150            }
151        })*
152    };
153}
154
155stream_event_from!(
156    MessageStart(ModelMessageStartEvent),
157    ContentBlockStart(ModelContentBlockStartEvent),
158    ContentBlockDelta(ModelContentBlockDeltaEvent),
159    ContentBlockStop(ModelContentBlockStopEvent),
160    MessageStop(ModelMessageStopEvent),
161    Metadata(ModelMetadataEvent),
162    Redaction(ModelRedactionEvent),
163);
164
165/// The model started a message (`ModelMessageStartEvent`).
166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
167#[non_exhaustive]
168pub struct ModelMessageStartEvent {
169    /// The role of the message.
170    pub role: Role,
171}
172
173impl ModelMessageStartEvent {
174    /// Creates the event.
175    pub fn new(role: Role) -> Self {
176        Self { role }
177    }
178}
179
180/// A content block started (`ModelContentBlockStartEvent`). Text blocks carry no start data.
181#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
182#[non_exhaustive]
183pub struct ModelContentBlockStartEvent {
184    /// Start data for blocks that have it, such as tool use.
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub start: Option<ContentBlockStart>,
187}
188
189impl ModelContentBlockStartEvent {
190    /// Creates the event without start data.
191    pub fn new() -> Self {
192        Self::default()
193    }
194
195    /// Sets the start data.
196    #[must_use]
197    pub fn with_start(mut self, start: impl Into<ContentBlockStart>) -> Self {
198        self.start = Some(start.into());
199        self
200    }
201}
202
203/// Start data of a content block (`ContentBlockStart`).
204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
205#[serde(tag = "type")]
206#[non_exhaustive]
207pub enum ContentBlockStart {
208    /// A tool use block started.
209    #[serde(rename = "toolUseStart")]
210    ToolUse(ToolUseStart),
211}
212
213impl From<ToolUseStart> for ContentBlockStart {
214    fn from(start: ToolUseStart) -> Self {
215        Self::ToolUse(start)
216    }
217}
218
219/// A tool use block started (`ToolUseStart`).
220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
221#[serde(rename_all = "camelCase")]
222#[non_exhaustive]
223pub struct ToolUseStart {
224    /// The tool name.
225    pub name: String,
226    /// The tool use id.
227    pub tool_use_id: String,
228    /// Reasoning signature from thinking models.
229    #[serde(default, skip_serializing_if = "Option::is_none")]
230    pub reasoning_signature: Option<String>,
231}
232
233impl ToolUseStart {
234    /// Creates the start data.
235    pub fn new(name: impl Into<String>, tool_use_id: impl Into<String>) -> Self {
236        Self {
237            name: name.into(),
238            tool_use_id: tool_use_id.into(),
239            reasoning_signature: None,
240        }
241    }
242
243    /// Sets the reasoning signature.
244    #[must_use]
245    pub fn with_reasoning_signature(mut self, signature: impl Into<String>) -> Self {
246        self.reasoning_signature = Some(signature.into());
247        self
248    }
249}
250
251/// A content block received a delta (`ModelContentBlockDeltaEvent`).
252#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
253#[serde(rename_all = "camelCase")]
254#[non_exhaustive]
255pub struct ModelContentBlockDeltaEvent {
256    /// Index of the block within the message, when the provider reports it.
257    #[serde(default, skip_serializing_if = "Option::is_none")]
258    pub content_block_index: Option<u64>,
259    /// The delta.
260    pub delta: ContentBlockDelta,
261}
262
263impl ModelContentBlockDeltaEvent {
264    /// Creates the event.
265    pub fn new(delta: impl Into<ContentBlockDelta>) -> Self {
266        Self {
267            content_block_index: None,
268            delta: delta.into(),
269        }
270    }
271
272    /// Sets the index of the block within the message.
273    #[must_use]
274    pub fn with_content_block_index(mut self, content_block_index: u64) -> Self {
275        self.content_block_index = Some(content_block_index);
276        self
277    }
278}
279
280/// A delta within a content block (`ContentBlockDelta`).
281#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
282#[serde(tag = "type")]
283#[non_exhaustive]
284pub enum ContentBlockDelta {
285    /// Text.
286    #[serde(rename = "textDelta")]
287    Text(TextDelta),
288    /// A fragment of tool input JSON.
289    #[serde(rename = "toolUseInputDelta")]
290    ToolUseInput(ToolUseInputDelta),
291    /// Reasoning content.
292    #[serde(rename = "reasoningContentDelta")]
293    ReasoningContent(ReasoningContentDelta),
294    /// Citations.
295    #[serde(rename = "citationsDelta")]
296    Citations(CitationsDelta),
297}
298
299macro_rules! delta_from {
300    ($($variant:ident($delta:ty)),* $(,)?) => {
301        $(impl From<$delta> for ContentBlockDelta {
302            fn from(delta: $delta) -> Self {
303                Self::$variant(delta)
304            }
305        })*
306    };
307}
308
309delta_from!(
310    Text(TextDelta),
311    ToolUseInput(ToolUseInputDelta),
312    ReasoningContent(ReasoningContentDelta),
313    Citations(CitationsDelta),
314);
315
316/// A text delta (`TextDelta`).
317#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
318#[non_exhaustive]
319pub struct TextDelta {
320    /// The text fragment.
321    pub text: String,
322}
323
324impl TextDelta {
325    /// Creates the delta.
326    pub fn new(text: impl Into<String>) -> Self {
327        Self { text: text.into() }
328    }
329}
330
331/// A fragment of tool input JSON (`ToolUseInputDelta`).
332#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
333#[non_exhaustive]
334pub struct ToolUseInputDelta {
335    /// The JSON fragment.
336    pub input: String,
337}
338
339impl ToolUseInputDelta {
340    /// Creates the delta.
341    pub fn new(input: impl Into<String>) -> Self {
342        Self { input: input.into() }
343    }
344}
345
346/// A reasoning delta (`ReasoningContentDelta`). `redacted_content` is base64 on the wire.
347#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
348#[serde(rename_all = "camelCase")]
349#[non_exhaustive]
350pub struct ReasoningContentDelta {
351    /// A reasoning text fragment.
352    #[serde(default, skip_serializing_if = "Option::is_none")]
353    pub text: Option<String>,
354    /// A reasoning signature fragment.
355    #[serde(default, skip_serializing_if = "Option::is_none")]
356    pub signature: Option<String>,
357    /// Redacted reasoning bytes.
358    #[serde(default, skip_serializing_if = "Option::is_none", with = "base64_bytes::option")]
359    pub redacted_content: Option<Vec<u8>>,
360    /// Provider-native reasoning for the block, sent only to the provider and model that produced
361    /// it.
362    #[serde(default, skip_serializing_if = "Option::is_none")]
363    pub provider_data: Option<ReasoningProviderData>,
364}
365
366impl ReasoningContentDelta {
367    /// Creates an empty delta.
368    pub fn new() -> Self {
369        Self::default()
370    }
371
372    /// Sets the text fragment.
373    #[must_use]
374    pub fn with_text(mut self, text: impl Into<String>) -> Self {
375        self.text = Some(text.into());
376        self
377    }
378
379    /// Sets the signature fragment.
380    #[must_use]
381    pub fn with_signature(mut self, signature: impl Into<String>) -> Self {
382        self.signature = Some(signature.into());
383        self
384    }
385
386    /// Sets the redacted bytes.
387    #[must_use]
388    pub fn with_redacted_content(mut self, redacted_content: Vec<u8>) -> Self {
389        self.redacted_content = Some(redacted_content);
390        self
391    }
392
393    /// Sets the provider-native reasoning.
394    #[must_use]
395    pub fn with_provider_data(mut self, provider_data: ReasoningProviderData) -> Self {
396        self.provider_data = Some(provider_data);
397        self
398    }
399}
400
401/// The [`ReasoningProviderData::provider`] tag of Claude-signed reasoning.
402#[cfg_attr(
403    not(any(feature = "anthropic", feature = "bedrock")),
404    allow(dead_code, reason = "the Claude providers tag reasoning")
405)]
406pub(crate) const ANTHROPIC_REASONING_PROVIDER: &str = "anthropic";
407
408/// Tags a signed or redacted reasoning delta with `provider` and `model_id`, and empty data since
409/// the block's own fields hold everything. The signature is bound to the vendor, so any of its
410/// models takes it back. Other events pass through as they are.
411#[cfg_attr(
412    not(any(feature = "anthropic", feature = "bedrock")),
413    allow(dead_code, reason = "the Claude providers tag reasoning")
414)]
415pub(crate) fn tag_signed_reasoning(mut event: ModelStreamEvent, provider: &str, model_id: &str) -> ModelStreamEvent {
416    if let ModelStreamEvent::ContentBlockDelta(ModelContentBlockDeltaEvent {
417        delta: ContentBlockDelta::ReasoningContent(delta),
418        ..
419    }) = &mut event
420        && (delta
421            .signature
422            .as_deref()
423            .is_some_and(|signature| !signature.is_empty())
424            || delta.redacted_content.is_some())
425    {
426        delta.provider_data = Some(ReasoningProviderData::new(provider, model_id, JsonObject::new()));
427    }
428    event
429}
430
431/// A citations delta (`CitationsDelta`).
432#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
433#[non_exhaustive]
434pub struct CitationsDelta {
435    /// The citations.
436    pub citations: Vec<Citation>,
437    /// The generated content the citations belong to.
438    pub content: Vec<CitationGeneratedContent>,
439}
440
441impl CitationsDelta {
442    /// Creates the delta.
443    pub fn new(citations: Vec<Citation>, content: Vec<CitationGeneratedContent>) -> Self {
444        Self { citations, content }
445    }
446}
447
448/// A content block ended (`ModelContentBlockStopEvent`).
449#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
450#[non_exhaustive]
451pub struct ModelContentBlockStopEvent {}
452
453impl ModelContentBlockStopEvent {
454    /// Creates the event.
455    pub fn new() -> Self {
456        Self {}
457    }
458}
459
460/// The message ended (`ModelMessageStopEvent`).
461#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
462#[serde(rename_all = "camelCase")]
463#[non_exhaustive]
464pub struct ModelMessageStopEvent {
465    /// Why the model stopped.
466    pub stop_reason: StopReason,
467    /// Provider-specific response fields. A present `null` stays `Some(JsonValue::Null)`.
468    #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
469    pub additional_model_response_fields: Option<JsonValue>,
470}
471
472impl ModelMessageStopEvent {
473    /// Creates the event.
474    pub fn new(stop_reason: StopReason) -> Self {
475        Self {
476            stop_reason,
477            additional_model_response_fields: None,
478        }
479    }
480
481    /// Sets the provider-specific response fields.
482    #[must_use]
483    pub fn with_additional_model_response_fields(mut self, fields: JsonValue) -> Self {
484        self.additional_model_response_fields = Some(fields);
485        self
486    }
487}
488
489/// Usage, metrics and trace data (`ModelMetadataEvent`).
490#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
491#[non_exhaustive]
492pub struct ModelMetadataEvent {
493    /// Token usage.
494    #[serde(default, skip_serializing_if = "Option::is_none")]
495    pub usage: Option<Usage>,
496    /// Performance metrics.
497    #[serde(default, skip_serializing_if = "Option::is_none")]
498    pub metrics: Option<Metrics>,
499    /// Provider trace data, such as guardrail evaluations. A present `null` stays
500    /// `Some(JsonValue::Null)`.
501    #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
502    pub trace: Option<JsonValue>,
503}
504
505impl ModelMetadataEvent {
506    /// Creates an empty event.
507    pub fn new() -> Self {
508        Self::default()
509    }
510
511    /// Sets the usage.
512    #[must_use]
513    pub fn with_usage(mut self, usage: Usage) -> Self {
514        self.usage = Some(usage);
515        self
516    }
517
518    /// Sets the metrics.
519    #[must_use]
520    pub fn with_metrics(mut self, metrics: Metrics) -> Self {
521        self.metrics = Some(metrics);
522        self
523    }
524
525    /// Sets the trace data.
526    #[must_use]
527    pub fn with_trace(mut self, trace: JsonValue) -> Self {
528        self.trace = Some(trace);
529        self
530    }
531}
532
533/// Replacement for redacted input (`RedactInputContent`).
534#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
535#[serde(rename_all = "camelCase")]
536#[non_exhaustive]
537pub struct RedactInputContent {
538    /// The text that replaces the redacted input.
539    pub replace_content: String,
540}
541
542impl RedactInputContent {
543    /// Creates the redaction.
544    pub fn new(replace_content: impl Into<String>) -> Self {
545        Self {
546            replace_content: replace_content.into(),
547        }
548    }
549}
550
551/// Replacement for redacted output (`RedactOutputContent`).
552#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
553#[serde(rename_all = "camelCase")]
554#[non_exhaustive]
555pub struct RedactOutputContent {
556    /// The output that was redacted.
557    #[serde(default, skip_serializing_if = "Option::is_none")]
558    pub redacted_content: Option<String>,
559    /// The text that replaces it.
560    pub replace_content: String,
561}
562
563impl RedactOutputContent {
564    /// Creates the redaction.
565    pub fn new(replace_content: impl Into<String>) -> Self {
566        Self {
567            redacted_content: None,
568            replace_content: replace_content.into(),
569        }
570    }
571
572    /// Sets the redacted output.
573    #[must_use]
574    pub fn with_redacted_content(mut self, redacted_content: impl Into<String>) -> Self {
575        self.redacted_content = Some(redacted_content.into());
576        self
577    }
578}
579
580/// A guardrail redacted content (`ModelRedactionEvent`).
581#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
582#[serde(rename_all = "camelCase")]
583#[non_exhaustive]
584pub struct ModelRedactionEvent {
585    /// Input redaction.
586    #[serde(default, skip_serializing_if = "Option::is_none")]
587    pub input_redaction: Option<RedactInputContent>,
588    /// Output redaction.
589    #[serde(default, skip_serializing_if = "Option::is_none")]
590    pub output_redaction: Option<RedactOutputContent>,
591}
592
593impl ModelRedactionEvent {
594    /// Creates an empty event.
595    pub fn new() -> Self {
596        Self::default()
597    }
598
599    /// Sets the input redaction.
600    #[must_use]
601    pub fn with_input_redaction(mut self, redaction: RedactInputContent) -> Self {
602        self.input_redaction = Some(redaction);
603        self
604    }
605
606    /// Sets the output redaction.
607    #[must_use]
608    pub fn with_output_redaction(mut self, redaction: RedactOutputContent) -> Self {
609        self.output_redaction = Some(redaction);
610        self
611    }
612}
613
614#[cfg(test)]
615mod tests {
616    use serde_json::json;
617
618    use super::*;
619
620    fn parses(value: serde_json::Value) -> bool {
621        serde_json::from_value::<ModelStreamEvent>(value).is_ok()
622    }
623
624    #[test]
625    fn returns_true_for_model_message_start_event() {
626        assert!(parses(json!({"type": "modelMessageStartEvent", "role": "assistant"})));
627    }
628
629    #[test]
630    fn returns_true_for_model_content_block_start_event() {
631        assert!(parses(json!({"type": "modelContentBlockStartEvent"})));
632    }
633
634    #[test]
635    fn returns_true_for_model_content_block_delta_event() {
636        assert!(parses(
637            json!({"type": "modelContentBlockDeltaEvent", "delta": {"type": "textDelta", "text": "hello"}})
638        ));
639    }
640
641    #[test]
642    fn returns_true_for_model_content_block_stop_event() {
643        assert!(parses(json!({"type": "modelContentBlockStopEvent"})));
644    }
645
646    #[test]
647    fn returns_true_for_model_message_stop_event() {
648        assert!(parses(
649            json!({"type": "modelMessageStopEvent", "stopReason": "endTurn"})
650        ));
651    }
652
653    #[test]
654    fn returns_true_for_model_metadata_event() {
655        assert!(parses(json!({
656            "type": "modelMetadataEvent",
657            "usage": {"inputTokens": 10, "outputTokens": 5, "totalTokens": 15}
658        })));
659    }
660
661    #[test]
662    fn returns_true_for_model_redaction_event() {
663        assert!(parses(json!({
664            "type": "modelRedactionEvent",
665            "inputRedaction": {"replaceContent": "[User input redacted.]"}
666        })));
667    }
668
669    #[test]
670    fn returns_false_for_unknown_event_types() {
671        assert!(!parses(json!({"type": "unknownEvent"})));
672    }
673
674    #[test]
675    fn returns_false_for_content_block_types() {
676        assert!(!parses(json!({"type": "textBlock", "text": "hello"})));
677    }
678
679    #[test]
680    fn counts_cache_tokens_on_disjoint_providers_where_they_add_to_input_tokens() {
681        let usage = Usage::new(10, 4, 5862).with_cache_read_input_tokens(5848);
682        assert_eq!(usage.total_prompt_tokens(), 5858);
683    }
684
685    #[test]
686    fn does_not_double_count_cache_tokens_on_subset_providers_where_they_sit_inside_input_tokens() {
687        let usage = Usage::new(12936, 10, 12946).with_cache_read_input_tokens(6457);
688        assert_eq!(usage.total_prompt_tokens(), 12936);
689    }
690
691    #[test]
692    fn counts_the_cache_read_from_an_anthropic_direct_payload_whose_total_tokens_includes_the_cache() {
693        let usage = Usage::new(10, 4, 5862).with_cache_read_input_tokens(5848);
694        assert_eq!(usage.total_prompt_tokens(), 5858);
695    }
696
697    #[test]
698    fn adds_cache_reads_and_writes_on_disjoint_providers() {
699        let usage = Usage::new(10, 5, 100)
700            .with_cache_read_input_tokens(60)
701            .with_cache_write_input_tokens(25);
702        assert_eq!(usage.total_prompt_tokens(), 95);
703    }
704
705    #[test]
706    fn collapses_to_input_tokens_when_there_are_no_cache_tokens() {
707        assert_eq!(Usage::new(100, 50, 150).total_prompt_tokens(), 100);
708    }
709
710    #[test]
711    fn accumulate_adds_counts_and_only_present_cache_tokens() {
712        let mut total = Usage::default();
713        total.accumulate(&Usage::new(1, 2, 3));
714        assert_eq!(total.cache_read_input_tokens, None);
715        total.accumulate(&Usage::new(1, 1, 2).with_cache_read_input_tokens(4));
716        assert_eq!(total, Usage::new(2, 3, 5).with_cache_read_input_tokens(4));
717    }
718
719    #[test]
720    fn accumulate_saturates_instead_of_overflowing() {
721        let mut total = Usage::new(u64::MAX, 1, u64::MAX).with_cache_read_input_tokens(u64::MAX);
722        total.accumulate(&Usage::new(1, 1, 1).with_cache_read_input_tokens(1));
723        assert_eq!(total.input_tokens, u64::MAX);
724        assert_eq!(total.cache_read_input_tokens, Some(u64::MAX));
725        assert_eq!(total.total_prompt_tokens(), u64::MAX);
726    }
727
728    #[test]
729    fn present_null_fields_survive_a_round_trip() {
730        let stop =
731            json!({"type": "modelMessageStopEvent", "stopReason": "endTurn", "additionalModelResponseFields": null});
732        let metadata = json!({"type": "modelMetadataEvent", "trace": null});
733        for wire in [stop, metadata] {
734            let event: ModelStreamEvent = serde_json::from_value(wire.clone()).unwrap();
735            assert_eq!(serde_json::to_value(&event).unwrap(), wire);
736        }
737    }
738
739    #[test]
740    fn reasoning_delta_accepts_ts_index_keyed_redacted_content() {
741        let event: ModelStreamEvent = serde_json::from_value(json!({
742            "type": "modelContentBlockDeltaEvent",
743            "delta": {"type": "reasoningContentDelta", "redactedContent": {"1": 2, "0": 1, "2": 3}}
744        }))
745        .unwrap();
746        let ModelStreamEvent::ContentBlockDelta(delta) = event else {
747            panic!("expected a delta event");
748        };
749        let ContentBlockDelta::ReasoningContent(reasoning) = delta.delta else {
750            panic!("expected a reasoning delta");
751        };
752        assert_eq!(reasoning.redacted_content, Some(vec![1, 2, 3]));
753    }
754
755    #[test]
756    fn reasoning_delta_rejects_a_byte_object_with_gaps() {
757        let error =
758            serde_json::from_value::<ReasoningContentDelta>(json!({"redactedContent": {"0": 1, "2": 3}})).unwrap_err();
759        assert!(error.to_string().contains("byte object keys must be the indices 0..n"));
760    }
761
762    #[test]
763    fn delta_event_carries_an_optional_block_index() {
764        let event = ModelContentBlockDeltaEvent::new(TextDelta::new("a")).with_content_block_index(2);
765        assert_eq!(
766            serde_json::to_value(&event).unwrap(),
767            json!({"contentBlockIndex": 2, "delta": {"type": "textDelta", "text": "a"}})
768        );
769    }
770
771    #[test]
772    fn events_serialize_with_the_type_first() {
773        let event = ModelStreamEvent::from(ModelContentBlockDeltaEvent::new(TextDelta::new("Hel")));
774        assert_eq!(
775            serde_json::to_string(&event).unwrap(),
776            r#"{"type":"modelContentBlockDeltaEvent","delta":{"type":"textDelta","text":"Hel"}}"#
777        );
778    }
779
780    #[test]
781    fn reasoning_delta_encodes_redacted_content_as_base64() {
782        let event = ModelContentBlockDeltaEvent::new(ReasoningContentDelta::new().with_redacted_content(vec![1, 2, 3]));
783        assert_eq!(
784            serde_json::to_value(ModelStreamEvent::from(event)).unwrap(),
785            json!({"type": "modelContentBlockDeltaEvent", "delta": {"type": "reasoningContentDelta", "redactedContent": "AQID"}})
786        );
787    }
788}