anthropic-async 0.5.2

Anthropic API client for Rust with prompt caching support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
//! Server-Sent Events (SSE) streaming support.
//!
//! This module provides streaming response handling for the Messages API.

#[cfg(feature = "streaming")]
/// Streaming API implementation
pub mod streaming {
    use futures::Stream;
    use serde::Deserialize;
    use serde::Serialize;
    use std::pin::Pin;

    use crate::error::AnthropicError;
    use crate::types::content::ContentBlock;
    use crate::types::content::MessageRole;
    use crate::types::messages::MessagesCreateResponse;

    /// Type alias for the event stream returned by streaming APIs
    pub type EventStream =
        Pin<Box<dyn Stream<Item = Result<Event, AnthropicError>> + Send + 'static>>;

    // =========================================================================
    // SSE Frame and Decoder
    // =========================================================================

    /// Raw SSE frame with optional event type and data payload
    #[derive(Debug, Clone, Default)]
    pub struct SseFrame {
        /// Event type (from `event:` line)
        pub event: Option<String>,
        /// Data payload (from `data:` lines, may be multiline)
        pub data: String,
    }

    /// SSE decoder that parses raw bytes into frames
    ///
    /// Handles:
    /// - Multi-line data (multiple `data:` lines)
    /// - Chunk boundaries splitting lines
    /// - Empty `data:` lines
    /// - Unknown fields (ignored per SSE spec)
    #[derive(Debug, Default)]
    pub struct SSEDecoder {
        buffer: String,
        current_frame: SseFrame,
    }

    impl SSEDecoder {
        /// Create a new decoder
        #[must_use]
        pub fn new() -> Self {
            Self::default()
        }

        /// Push a chunk of bytes and return any complete frames
        pub fn push(&mut self, chunk: &[u8]) -> Vec<SseFrame> {
            let text = String::from_utf8_lossy(chunk);
            self.buffer.push_str(&text);

            let mut frames = Vec::new();

            // Process complete lines
            while let Some(newline_pos) = self.buffer.find('\n') {
                let line = self.buffer[..newline_pos]
                    .trim_end_matches('\r')
                    .to_string();
                self.buffer = self.buffer[newline_pos + 1..].to_string();

                if line.is_empty() {
                    // Blank line = end of frame
                    if self.current_frame.event.is_some() || !self.current_frame.data.is_empty() {
                        frames.push(std::mem::take(&mut self.current_frame));
                    }
                } else if let Some(value) = line.strip_prefix("event:") {
                    self.current_frame.event = Some(value.trim().to_string());
                } else if let Some(value) = line.strip_prefix("data:") {
                    let data_value = value.strip_prefix(' ').unwrap_or(value);
                    if !self.current_frame.data.is_empty() {
                        self.current_frame.data.push('\n');
                    }
                    self.current_frame.data.push_str(data_value);
                }
                // Ignore other fields (id:, retry:, comments starting with :)
            }

            frames
        }

        /// Flush any remaining data as a final frame
        ///
        /// This processes any incomplete line still in the buffer before returning
        /// the current frame.
        pub fn flush(&mut self) -> Option<SseFrame> {
            // Process any remaining incomplete line in the buffer
            if !self.buffer.is_empty() {
                let line = std::mem::take(&mut self.buffer);
                let line = line.trim_end_matches('\r');
                if let Some(value) = line.strip_prefix("event:") {
                    self.current_frame.event = Some(value.trim().to_string());
                } else if let Some(value) = line.strip_prefix("data:") {
                    let data_value = value.strip_prefix(' ').unwrap_or(value);
                    if !self.current_frame.data.is_empty() {
                        self.current_frame.data.push('\n');
                    }
                    self.current_frame.data.push_str(data_value);
                }
            }

            if self.current_frame.event.is_some() || !self.current_frame.data.is_empty() {
                Some(std::mem::take(&mut self.current_frame))
            } else {
                None
            }
        }
    }

    // =========================================================================
    // Typed Event Structures
    // =========================================================================

    /// Streaming event types from Anthropic Messages API
    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
    #[serde(tag = "type", rename_all = "snake_case")]
    #[allow(clippy::derive_partial_eq_without_eq)] // ContentBlock doesn't impl Eq
    #[non_exhaustive]
    pub enum Event {
        /// Message creation started
        MessageStart {
            /// The message object being built
            message: MessageStartPayload,
        },
        /// Content block started
        ContentBlockStart {
            /// Index of the content block
            index: usize,
            /// Initial content block data
            content_block: ContentBlockStartData,
        },
        /// Delta update for a content block
        ContentBlockDelta {
            /// Index of the content block being updated
            index: usize,
            /// The delta data
            delta: ContentBlockDeltaData,
        },
        /// Content block completed
        ContentBlockStop {
            /// Index of the completed content block
            index: usize,
        },
        /// Message metadata delta (usage, `stop_reason`)
        MessageDelta {
            /// Delta containing `stop_reason` and usage
            delta: MessageDeltaPayload,
            /// Updated usage information
            #[serde(skip_serializing_if = "Option::is_none")]
            usage: Option<MessageDeltaUsage>,
        },
        /// Message streaming completed
        MessageStop,
        /// Ping event (keep-alive)
        Ping,
        /// Error event
        Error {
            /// Error details
            error: EventError,
        },
        /// Forward-compatible catch-all for unknown event types
        #[serde(skip)]
        Unknown {
            /// Raw event type string received
            event_type: String,
            /// Raw data payload
            data: String,
        },
    }

    /// Payload for `message_start` event
    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
    pub struct MessageStartPayload {
        /// Message ID
        pub id: String,
        /// Type (always "message")
        #[serde(rename = "type")]
        pub kind: String,
        /// Role (always "assistant")
        pub role: MessageRole,
        /// Model used
        pub model: String,
        /// Initial content (usually empty)
        #[serde(default)]
        pub content: Vec<ContentBlock>,
        /// Stop reason (None initially)
        #[serde(skip_serializing_if = "Option::is_none")]
        pub stop_reason: Option<String>,
        /// Stop sequence (None initially)
        #[serde(skip_serializing_if = "Option::is_none")]
        pub stop_sequence: Option<String>,
        /// Initial usage
        #[serde(skip_serializing_if = "Option::is_none")]
        pub usage: Option<MessageStartUsage>,
    }

    /// Usage information in `message_start`
    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
    pub struct MessageStartUsage {
        /// Input tokens
        pub input_tokens: u64,
        /// Output tokens (initially 0)
        pub output_tokens: u64,
        /// Cache creation input tokens
        #[serde(skip_serializing_if = "Option::is_none")]
        pub cache_creation_input_tokens: Option<u64>,
        /// Cache read input tokens
        #[serde(skip_serializing_if = "Option::is_none")]
        pub cache_read_input_tokens: Option<u64>,
    }

    /// Content block type at start
    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
    #[serde(tag = "type", rename_all = "snake_case")]
    pub enum ContentBlockStartData {
        /// Text block
        Text {
            /// Initial text (usually empty string)
            text: String,
        },
        /// Tool use block
        ToolUse {
            /// Tool use ID
            id: String,
            /// Tool name
            name: String,
            /// Initial input (usually empty object)
            input: serde_json::Value,
        },
        /// Thinking block (extended thinking feature)
        Thinking {
            /// Initial thinking text (usually empty)
            #[serde(default)]
            thinking: String,
            /// Initial signature (usually empty)
            #[serde(default)]
            signature: String,
        },
        /// Unknown block type (forward compatibility)
        #[serde(other)]
        Unknown,
    }

    /// Content block delta data
    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
    #[serde(tag = "type", rename_all = "snake_case")]
    pub enum ContentBlockDeltaData {
        /// Text delta
        TextDelta {
            /// Text to append
            text: String,
        },
        /// JSON delta for tool input
        InputJsonDelta {
            /// Partial JSON to append
            partial_json: String,
        },
        /// Thinking delta (forward-compatible, extended thinking feature)
        ThinkingDelta {
            /// Thinking text to append
            thinking: String,
        },
        /// Citations delta (forward-compatible, web search feature)
        CitationsDelta {
            /// Partial citations JSON to append
            citation: String,
        },
        /// Signature delta (forward-compatible)
        SignatureDelta {
            /// Signature to append
            signature: String,
        },
        /// Catch-all for unknown/future delta types
        #[serde(other)]
        Unknown,
    }

    /// Message delta payload
    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
    pub struct MessageDeltaPayload {
        /// Stop reason
        #[serde(skip_serializing_if = "Option::is_none")]
        pub stop_reason: Option<String>,
        /// Stop sequence that triggered stop
        #[serde(skip_serializing_if = "Option::is_none")]
        pub stop_sequence: Option<String>,
    }

    /// Usage information in `message_delta`
    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
    pub struct MessageDeltaUsage {
        /// Output tokens generated so far
        pub output_tokens: u64,
    }

    /// Error details in error event
    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
    pub struct EventError {
        /// Error type
        #[serde(rename = "type")]
        pub kind: String,
        /// Error message
        pub message: String,
    }

    // =========================================================================
    // Event Parsing
    // =========================================================================

    impl Event {
        /// Parse an SSE frame into a typed Event
        ///
        /// Unknown event types return `Ok(Event::Unknown { .. })` for forward compatibility.
        ///
        /// # Errors
        ///
        /// Returns an error if event data cannot be parsed for a known event type.
        pub fn from_frame(frame: &SseFrame) -> Result<Self, AnthropicError> {
            let event_type = frame.event.as_deref().unwrap_or("message");

            match event_type {
                "message_start" => {
                    let payload: MessageStartEvent = serde_json::from_str(&frame.data)
                        .map_err(|e| AnthropicError::Serde(format!("message_start: {e}")))?;
                    Ok(Self::MessageStart {
                        message: payload.message,
                    })
                }
                "content_block_start" => {
                    let payload: ContentBlockStartEvent = serde_json::from_str(&frame.data)
                        .map_err(|e| AnthropicError::Serde(format!("content_block_start: {e}")))?;
                    Ok(Self::ContentBlockStart {
                        index: payload.index,
                        content_block: payload.content_block,
                    })
                }
                "content_block_delta" => {
                    let payload: ContentBlockDeltaEvent = serde_json::from_str(&frame.data)
                        .map_err(|e| AnthropicError::Serde(format!("content_block_delta: {e}")))?;
                    Ok(Self::ContentBlockDelta {
                        index: payload.index,
                        delta: payload.delta,
                    })
                }
                "content_block_stop" => {
                    let payload: ContentBlockStopEvent = serde_json::from_str(&frame.data)
                        .map_err(|e| AnthropicError::Serde(format!("content_block_stop: {e}")))?;
                    Ok(Self::ContentBlockStop {
                        index: payload.index,
                    })
                }
                "message_delta" => {
                    let payload: MessageDeltaEvent = serde_json::from_str(&frame.data)
                        .map_err(|e| AnthropicError::Serde(format!("message_delta: {e}")))?;
                    Ok(Self::MessageDelta {
                        delta: payload.delta,
                        usage: payload.usage,
                    })
                }
                "message_stop" => Ok(Self::MessageStop),
                "ping" => Ok(Self::Ping),
                "error" => {
                    let payload: ErrorEvent = serde_json::from_str(&frame.data)
                        .map_err(|e| AnthropicError::Serde(format!("error event: {e}")))?;
                    Ok(Self::Error {
                        error: payload.error,
                    })
                }
                _ => {
                    // Forward-compatible: return Unknown event instead of error
                    Ok(Self::Unknown {
                        event_type: event_type.to_string(),
                        data: frame.data.clone(),
                    })
                }
            }
        }
    }

    // Wire format structures for deserialization
    #[derive(Deserialize)]
    struct MessageStartEvent {
        message: MessageStartPayload,
    }

    #[derive(Deserialize)]
    struct ContentBlockStartEvent {
        index: usize,
        content_block: ContentBlockStartData,
    }

    #[derive(Deserialize)]
    struct ContentBlockDeltaEvent {
        index: usize,
        delta: ContentBlockDeltaData,
    }

    #[derive(Deserialize)]
    struct ContentBlockStopEvent {
        index: usize,
    }

    #[derive(Deserialize)]
    struct MessageDeltaEvent {
        delta: MessageDeltaPayload,
        usage: Option<MessageDeltaUsage>,
    }

    #[derive(Deserialize)]
    struct ErrorEvent {
        error: EventError,
    }

    // =========================================================================
    // Accumulator
    // =========================================================================

    /// Accumulates streaming events into a complete response
    ///
    /// # Example
    ///
    /// ```ignore
    /// let mut acc = Accumulator::new();
    /// while let Some(event) = stream.next().await {
    ///     if let Some(response) = acc.apply(&event?)? {
    ///         // Response is complete
    ///         return Ok(response);
    ///     }
    /// }
    /// ```
    #[derive(Debug, Default)]
    pub struct Accumulator {
        id: Option<String>,
        model: Option<String>,
        role: Option<MessageRole>,
        content_blocks: Vec<AccumulatorBlock>,
        stop_reason: Option<String>,
        input_tokens: Option<u64>,
        output_tokens: Option<u64>,
        cache_creation_input_tokens: Option<u64>,
        cache_read_input_tokens: Option<u64>,
        complete: bool,
    }

    #[derive(Debug, Clone)]
    enum AccumulatorBlock {
        Text(String),
        ToolUse {
            id: String,
            name: String,
            input_json: String,
        },
        Thinking {
            thinking: String,
            signature: String,
        },
        Unknown,
    }

    impl Accumulator {
        /// Create a new accumulator
        #[must_use]
        pub fn new() -> Self {
            Self::default()
        }

        /// Apply an event to the accumulator
        ///
        /// Returns `Some(response)` when the message is complete (after `message_stop`).
        ///
        /// # Errors
        ///
        /// Returns an error if:
        /// - An error event is received
        /// - JSON parsing fails for tool inputs
        /// - Events arrive out of order
        pub fn apply(
            &mut self,
            event: &Event,
        ) -> Result<Option<MessagesCreateResponse>, AnthropicError> {
            match event {
                Event::MessageStart { message } => {
                    self.id = Some(message.id.clone());
                    self.model = Some(message.model.clone());
                    self.role = Some(message.role.clone());
                    if let Some(usage) = &message.usage {
                        self.input_tokens = Some(usage.input_tokens);
                        self.output_tokens = Some(usage.output_tokens);
                        self.cache_creation_input_tokens = usage.cache_creation_input_tokens;
                        self.cache_read_input_tokens = usage.cache_read_input_tokens;
                    }
                }
                Event::ContentBlockStart {
                    index,
                    content_block,
                } => {
                    // Ensure we have enough slots
                    while self.content_blocks.len() <= *index {
                        self.content_blocks
                            .push(AccumulatorBlock::Text(String::new()));
                    }
                    self.content_blocks[*index] = match content_block {
                        ContentBlockStartData::Text { text } => {
                            AccumulatorBlock::Text(text.clone())
                        }
                        ContentBlockStartData::ToolUse { id, name, .. } => {
                            AccumulatorBlock::ToolUse {
                                id: id.clone(),
                                name: name.clone(),
                                input_json: String::new(),
                            }
                        }
                        ContentBlockStartData::Thinking {
                            thinking,
                            signature,
                        } => AccumulatorBlock::Thinking {
                            thinking: thinking.clone(),
                            signature: signature.clone(),
                        },
                        ContentBlockStartData::Unknown => AccumulatorBlock::Unknown,
                    };
                }
                Event::ContentBlockDelta { index, delta } => {
                    if *index >= self.content_blocks.len() {
                        return Err(AnthropicError::Serde(format!(
                            "Delta for unknown block index {index}"
                        )));
                    }
                    match (&mut self.content_blocks[*index], delta) {
                        (
                            AccumulatorBlock::Text(text),
                            ContentBlockDeltaData::TextDelta { text: t },
                        ) => {
                            text.push_str(t);
                        }
                        (
                            AccumulatorBlock::ToolUse { input_json, .. },
                            ContentBlockDeltaData::InputJsonDelta { partial_json },
                        ) => {
                            input_json.push_str(partial_json);
                        }
                        (
                            AccumulatorBlock::Thinking { thinking, .. },
                            ContentBlockDeltaData::ThinkingDelta { thinking: t },
                        ) => {
                            thinking.push_str(t);
                        }
                        (
                            AccumulatorBlock::Thinking { signature, .. },
                            ContentBlockDeltaData::SignatureDelta { signature: s },
                        ) => {
                            signature.push_str(s);
                        }
                        // Forward-compatible: ignore mismatched or unknown delta types
                        _ => {}
                    }
                }
                Event::ContentBlockStop { .. } | Event::Ping | Event::Unknown { .. } => {
                    // Block complete, keep-alive, or unknown event - nothing to do
                }
                Event::MessageDelta { delta, usage } => {
                    if let Some(reason) = &delta.stop_reason {
                        self.stop_reason = Some(reason.clone());
                    }
                    if let Some(u) = usage {
                        self.output_tokens = Some(u.output_tokens);
                    }
                }
                Event::MessageStop => {
                    self.complete = true;
                }
                Event::Error { error } => {
                    return Err(AnthropicError::Api(crate::error::ApiErrorObject {
                        r#type: Some(error.kind.clone()),
                        message: error.message.clone(),
                        request_id: None,
                        code: None,
                    }));
                }
            }

            if self.complete {
                Ok(Some(self.build_response()?))
            } else {
                Ok(None)
            }
        }

        /// Build the final response from accumulated data
        fn build_response(&self) -> Result<MessagesCreateResponse, AnthropicError> {
            let content = self
                .content_blocks
                .iter()
                .map(|block| match block {
                    AccumulatorBlock::Text(text) => Ok(ContentBlock::Text {
                        text: text.clone(),
                        citations: None,
                    }),
                    AccumulatorBlock::ToolUse {
                        id,
                        name,
                        input_json,
                    } => {
                        let input: serde_json::Value = if input_json.is_empty() {
                            serde_json::Value::Object(serde_json::Map::new())
                        } else {
                            serde_json::from_str(input_json).map_err(|e| {
                                AnthropicError::Serde(format!("tool input JSON: {e}"))
                            })?
                        };
                        Ok(ContentBlock::ToolUse {
                            id: id.clone(),
                            name: name.clone(),
                            input,
                        })
                    }
                    AccumulatorBlock::Thinking {
                        thinking,
                        signature,
                    } => Ok(ContentBlock::Thinking {
                        thinking: thinking.clone(),
                        signature: signature.clone(),
                    }),
                    AccumulatorBlock::Unknown => Ok(ContentBlock::Unknown),
                })
                .collect::<Result<Vec<_>, AnthropicError>>()?;

            let usage = if self.input_tokens.is_some() || self.output_tokens.is_some() {
                Some(crate::types::common::Usage {
                    input_tokens: self.input_tokens,
                    output_tokens: self.output_tokens,
                    cache_creation_input_tokens: self.cache_creation_input_tokens,
                    cache_read_input_tokens: self.cache_read_input_tokens,
                })
            } else {
                None
            };

            Ok(MessagesCreateResponse {
                id: self.id.clone().unwrap_or_default(),
                kind: "message".to_string(),
                role: self.role.clone().unwrap_or(MessageRole::Assistant),
                content,
                model: self.model.clone().unwrap_or_default(),
                stop_reason: self.stop_reason.clone(),
                usage,
            })
        }

        /// Get current accumulated text (convenience method)
        ///
        /// Returns concatenated text from all text blocks.
        #[must_use]
        pub fn current_text(&self) -> String {
            self.content_blocks
                .iter()
                .filter_map(|block| match block {
                    AccumulatorBlock::Text(text) => Some(text.as_str()),
                    AccumulatorBlock::ToolUse { .. }
                    | AccumulatorBlock::Thinking { .. }
                    | AccumulatorBlock::Unknown => None,
                })
                .collect::<Vec<_>>()
                .join("")
        }
    }

    // =========================================================================
    // Stream Creation
    // =========================================================================

    /// Create an event stream from a reqwest Response
    ///
    /// This function converts the response body into a stream of parsed events.
    /// The stream owns the response and will close the connection when dropped.
    ///
    /// Unknown event types are yielded as `Event::Unknown` for forward compatibility.
    #[must_use]
    pub fn event_stream_from_response(response: reqwest::Response) -> EventStream {
        use futures::StreamExt;

        let byte_stream = response.bytes_stream();

        Box::pin(futures::stream::unfold(
            (byte_stream, SSEDecoder::new(), Vec::<SseFrame>::new()),
            |(mut stream, mut decoder, mut pending_frames)| async move {
                // Drain pending frames first
                if let Some(frame) = pending_frames.pop() {
                    let parsed = Event::from_frame(&frame);
                    return Some((parsed, (stream, decoder, pending_frames)));
                }

                loop {
                    match stream.next().await {
                        Some(Ok(chunk)) => {
                            let mut frames = decoder.push(&chunk);
                            frames.reverse();
                            pending_frames = frames;

                            if let Some(frame) = pending_frames.pop() {
                                let parsed = Event::from_frame(&frame);
                                return Some((parsed, (stream, decoder, pending_frames)));
                            }
                            // Else loop to get more data
                        }
                        Some(Err(e)) => {
                            return Some((
                                Err(AnthropicError::Reqwest(e)),
                                (stream, decoder, pending_frames),
                            ));
                        }
                        None => {
                            if let Some(frame) = decoder.flush() {
                                let parsed = Event::from_frame(&frame);
                                return Some((parsed, (stream, decoder, pending_frames)));
                            }
                            return None;
                        }
                    }
                }
            },
        ))
    }
}

#[cfg(all(test, feature = "streaming"))]
mod tests {
    use super::streaming::*;
    use crate::types::content::ContentBlock;

    #[test]
    fn test_sse_decoder_single_event() {
        let mut decoder = SSEDecoder::new();
        let chunk = b"event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude\",\"content\":[],\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":0}}}\n\n";
        let frames = decoder.push(chunk);
        assert_eq!(frames.len(), 1);
        assert_eq!(frames[0].event, Some("message_start".to_string()));
        assert!(frames[0].data.contains("message_start"));
    }

    #[test]
    fn test_sse_decoder_multiline_data() {
        let mut decoder = SSEDecoder::new();
        let chunk = b"event: test\ndata: line1\ndata: line2\n\n";
        let frames = decoder.push(chunk);
        assert_eq!(frames.len(), 1);
        assert_eq!(frames[0].data, "line1\nline2");
    }

    #[test]
    fn test_sse_decoder_split_chunks() {
        let mut decoder = SSEDecoder::new();
        let frames1 = decoder.push(b"event: test\nda");
        assert!(frames1.is_empty());
        let frames2 = decoder.push(b"ta: hello\n\n");
        assert_eq!(frames2.len(), 1);
        assert_eq!(frames2[0].event, Some("test".to_string()));
        assert_eq!(frames2[0].data, "hello");
    }

    #[test]
    fn test_event_mapping_message_start() {
        let frame = SseFrame {
            event: Some("message_start".to_string()),
            data: r#"{"type":"message_start","message":{"id":"msg_123","type":"message","role":"assistant","model":"claude-3-5-sonnet","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":0}}}"#.to_string(),
        };
        let event = Event::from_frame(&frame).unwrap();
        match event {
            Event::MessageStart { message } => {
                assert_eq!(message.id, "msg_123");
                assert_eq!(message.model, "claude-3-5-sonnet");
            }
            _ => panic!("Expected MessageStart"),
        }
    }

    #[test]
    fn test_event_mapping_content_block_delta() {
        let frame = SseFrame {
            event: Some("content_block_delta".to_string()),
            data: r#"{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}"#.to_string(),
        };
        let event = Event::from_frame(&frame).unwrap();
        match event {
            Event::ContentBlockDelta { index, delta } => {
                assert_eq!(index, 0);
                match delta {
                    ContentBlockDeltaData::TextDelta { text } => {
                        assert_eq!(text, "Hello");
                    }
                    _ => panic!("Expected TextDelta"),
                }
            }
            _ => panic!("Expected ContentBlockDelta"),
        }
    }

    #[test]
    fn test_accumulator_text_blocks() {
        let mut acc = Accumulator::new();

        // message_start
        let event1 = Event::MessageStart {
            message: MessageStartPayload {
                id: "msg_test".to_string(),
                kind: "message".to_string(),
                role: crate::types::content::MessageRole::Assistant,
                model: "claude".to_string(),
                content: vec![],
                stop_reason: None,
                stop_sequence: None,
                usage: Some(MessageStartUsage {
                    input_tokens: 10,
                    output_tokens: 0,
                    cache_creation_input_tokens: None,
                    cache_read_input_tokens: None,
                }),
            },
        };
        assert!(acc.apply(&event1).unwrap().is_none());

        // content_block_start
        let event2 = Event::ContentBlockStart {
            index: 0,
            content_block: ContentBlockStartData::Text {
                text: String::new(),
            },
        };
        assert!(acc.apply(&event2).unwrap().is_none());

        // content_block_delta
        let event3 = Event::ContentBlockDelta {
            index: 0,
            delta: ContentBlockDeltaData::TextDelta {
                text: "Hello, ".to_string(),
            },
        };
        assert!(acc.apply(&event3).unwrap().is_none());

        let event4 = Event::ContentBlockDelta {
            index: 0,
            delta: ContentBlockDeltaData::TextDelta {
                text: "world!".to_string(),
            },
        };
        assert!(acc.apply(&event4).unwrap().is_none());
        assert_eq!(acc.current_text(), "Hello, world!");

        // content_block_stop
        let event5 = Event::ContentBlockStop { index: 0 };
        assert!(acc.apply(&event5).unwrap().is_none());

        // message_delta
        let event6 = Event::MessageDelta {
            delta: MessageDeltaPayload {
                stop_reason: Some("end_turn".to_string()),
                stop_sequence: None,
            },
            usage: Some(MessageDeltaUsage { output_tokens: 3 }),
        };
        assert!(acc.apply(&event6).unwrap().is_none());

        // message_stop
        let event7 = Event::MessageStop;
        let response = acc.apply(&event7).unwrap().unwrap();

        assert_eq!(response.id, "msg_test");
        assert_eq!(response.content.len(), 1);
        match &response.content[0] {
            ContentBlock::Text { text, .. } => assert_eq!(text, "Hello, world!"),
            _ => panic!("Expected Text block"),
        }
        assert_eq!(response.stop_reason, Some("end_turn".to_string()));
    }

    #[test]
    fn test_accumulator_tool_use() {
        let mut acc = Accumulator::new();

        // message_start
        acc.apply(&Event::MessageStart {
            message: MessageStartPayload {
                id: "msg_tool".to_string(),
                kind: "message".to_string(),
                role: crate::types::content::MessageRole::Assistant,
                model: "claude".to_string(),
                content: vec![],
                stop_reason: None,
                stop_sequence: None,
                usage: None,
            },
        })
        .unwrap();

        // content_block_start (tool_use)
        acc.apply(&Event::ContentBlockStart {
            index: 0,
            content_block: ContentBlockStartData::ToolUse {
                id: "tool_123".to_string(),
                name: "get_weather".to_string(),
                input: serde_json::json!({}),
            },
        })
        .unwrap();

        // input_json_delta
        acc.apply(&Event::ContentBlockDelta {
            index: 0,
            delta: ContentBlockDeltaData::InputJsonDelta {
                partial_json: r#"{"city":"#.to_string(),
            },
        })
        .unwrap();

        acc.apply(&Event::ContentBlockDelta {
            index: 0,
            delta: ContentBlockDeltaData::InputJsonDelta {
                partial_json: r#""Paris"}"#.to_string(),
            },
        })
        .unwrap();

        // content_block_stop
        acc.apply(&Event::ContentBlockStop { index: 0 }).unwrap();

        // message_delta
        acc.apply(&Event::MessageDelta {
            delta: MessageDeltaPayload {
                stop_reason: Some("tool_use".to_string()),
                stop_sequence: None,
            },
            usage: None,
        })
        .unwrap();

        // message_stop
        let response = acc.apply(&Event::MessageStop).unwrap().unwrap();

        assert_eq!(response.content.len(), 1);
        match &response.content[0] {
            ContentBlock::ToolUse { id, name, input } => {
                assert_eq!(id, "tool_123");
                assert_eq!(name, "get_weather");
                assert_eq!(input["city"], "Paris");
            }
            _ => panic!("Expected ToolUse block"),
        }
    }

    #[test]
    fn test_accumulator_thinking_block() {
        let mut acc = Accumulator::new();

        // message_start
        acc.apply(&Event::MessageStart {
            message: MessageStartPayload {
                id: "msg_think".to_string(),
                kind: "message".to_string(),
                role: crate::types::content::MessageRole::Assistant,
                model: "claude".to_string(),
                content: vec![],
                stop_reason: None,
                stop_sequence: None,
                usage: None,
            },
        })
        .unwrap();

        // content_block_start (thinking)
        acc.apply(&Event::ContentBlockStart {
            index: 0,
            content_block: ContentBlockStartData::Thinking {
                thinking: String::new(),
                signature: String::new(),
            },
        })
        .unwrap();

        // thinking_delta
        acc.apply(&Event::ContentBlockDelta {
            index: 0,
            delta: ContentBlockDeltaData::ThinkingDelta {
                thinking: "Let me think ".to_string(),
            },
        })
        .unwrap();

        acc.apply(&Event::ContentBlockDelta {
            index: 0,
            delta: ContentBlockDeltaData::ThinkingDelta {
                thinking: "about this...".to_string(),
            },
        })
        .unwrap();

        // signature_delta
        acc.apply(&Event::ContentBlockDelta {
            index: 0,
            delta: ContentBlockDeltaData::SignatureDelta {
                signature: "sig_abc123".to_string(),
            },
        })
        .unwrap();

        // content_block_stop
        acc.apply(&Event::ContentBlockStop { index: 0 }).unwrap();

        // message_delta
        acc.apply(&Event::MessageDelta {
            delta: MessageDeltaPayload {
                stop_reason: Some("end_turn".to_string()),
                stop_sequence: None,
            },
            usage: None,
        })
        .unwrap();

        // message_stop
        let response = acc.apply(&Event::MessageStop).unwrap().unwrap();

        assert_eq!(response.content.len(), 1);
        match &response.content[0] {
            ContentBlock::Thinking {
                thinking,
                signature,
            } => {
                assert_eq!(thinking, "Let me think about this...");
                assert_eq!(signature, "sig_abc123");
            }
            _ => panic!("Expected Thinking block"),
        }
    }

    #[test]
    fn test_accumulator_zero_token_thinking() {
        let mut acc = Accumulator::new();

        // message_start
        acc.apply(&Event::MessageStart {
            message: MessageStartPayload {
                id: "msg_zero".to_string(),
                kind: "message".to_string(),
                role: crate::types::content::MessageRole::Assistant,
                model: "claude".to_string(),
                content: vec![],
                stop_reason: None,
                stop_sequence: None,
                usage: None,
            },
        })
        .unwrap();

        // content_block_start (thinking) - no deltas, immediate stop
        acc.apply(&Event::ContentBlockStart {
            index: 0,
            content_block: ContentBlockStartData::Thinking {
                thinking: String::new(),
                signature: String::new(),
            },
        })
        .unwrap();

        // content_block_stop (no deltas)
        acc.apply(&Event::ContentBlockStop { index: 0 }).unwrap();

        // message_delta
        acc.apply(&Event::MessageDelta {
            delta: MessageDeltaPayload {
                stop_reason: Some("end_turn".to_string()),
                stop_sequence: None,
            },
            usage: None,
        })
        .unwrap();

        // message_stop
        let response = acc.apply(&Event::MessageStop).unwrap().unwrap();

        assert_eq!(response.content.len(), 1);
        match &response.content[0] {
            ContentBlock::Thinking {
                thinking,
                signature,
            } => {
                assert_eq!(thinking, "");
                assert_eq!(signature, "");
            }
            _ => panic!("Expected Thinking block"),
        }
    }

    #[test]
    fn test_accumulator_unknown_block() {
        let mut acc = Accumulator::new();

        // message_start
        acc.apply(&Event::MessageStart {
            message: MessageStartPayload {
                id: "msg_unk".to_string(),
                kind: "message".to_string(),
                role: crate::types::content::MessageRole::Assistant,
                model: "claude".to_string(),
                content: vec![],
                stop_reason: None,
                stop_sequence: None,
                usage: None,
            },
        })
        .unwrap();

        // content_block_start (unknown)
        acc.apply(&Event::ContentBlockStart {
            index: 0,
            content_block: ContentBlockStartData::Unknown,
        })
        .unwrap();

        // content_block_stop
        acc.apply(&Event::ContentBlockStop { index: 0 }).unwrap();

        // message_delta
        acc.apply(&Event::MessageDelta {
            delta: MessageDeltaPayload {
                stop_reason: Some("end_turn".to_string()),
                stop_sequence: None,
            },
            usage: None,
        })
        .unwrap();

        // message_stop
        let response = acc.apply(&Event::MessageStop).unwrap().unwrap();

        assert_eq!(response.content.len(), 1);
        assert!(matches!(response.content[0], ContentBlock::Unknown));
    }
}