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
//! Streaming utilities for handling LLM response streams.
use std::pin::Pin;
use std::task::{Context, Poll};
use futures::Stream;
use pin_project_lite::pin_project;
use crate::error::Result;
use crate::types::{
CompletionResponse, ContentBlock, ContentDelta, StopReason, StreamChunk, StreamEventType, Usage,
};
pin_project! {
/// A stream wrapper that collects chunks into a final response.
pub struct CollectingStream<S> {
#[pin]
inner: S,
response_id: Option<String>,
model: Option<String>,
content_blocks: Vec<ContentBlockBuilder>,
current_block_index: Option<usize>,
stop_reason: Option<StopReason>,
usage: Usage,
}
}
/// Builder for accumulating content block data from stream deltas.
#[derive(Debug, Clone)]
enum ContentBlockBuilder {
Text(String),
ToolUse {
id: String,
name: String,
input_json: String,
},
Thinking(String),
}
impl ContentBlockBuilder {
fn into_content_block(self) -> Result<ContentBlock> {
match self {
ContentBlockBuilder::Text(text) => Ok(ContentBlock::Text { text }),
ContentBlockBuilder::ToolUse {
id,
name,
input_json,
} => {
let input = serde_json::from_str(&input_json)
.unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new()));
Ok(ContentBlock::ToolUse { id, name, input })
}
ContentBlockBuilder::Thinking(thinking) => Ok(ContentBlock::Thinking { thinking }),
}
}
}
impl<S> CollectingStream<S>
where
S: Stream<Item = Result<StreamChunk>>,
{
/// Create a new collecting stream.
pub fn new(inner: S) -> Self {
Self {
inner,
response_id: None,
model: None,
content_blocks: Vec::new(),
current_block_index: None,
stop_reason: None,
usage: Usage::default(),
}
}
/// Convert accumulated state into a final response.
pub fn into_response(self) -> Result<CompletionResponse> {
let content: Vec<ContentBlock> = self
.content_blocks
.into_iter()
.filter_map(|b| b.into_content_block().ok())
.collect();
Ok(CompletionResponse {
id: self
.response_id
.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
model: self.model.unwrap_or_default(),
content,
stop_reason: self.stop_reason.unwrap_or(StopReason::EndTurn),
usage: self.usage,
})
}
}
impl<S> Stream for CollectingStream<S>
where
S: Stream<Item = Result<StreamChunk>>,
{
type Item = Result<StreamChunk>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project();
match this.inner.poll_next(cx) {
Poll::Ready(Some(Ok(chunk))) => {
// Process the chunk to accumulate state
match chunk.event_type {
StreamEventType::ContentBlockStart => {
if let Some(index) = chunk.index {
*this.current_block_index = Some(index);
// Ensure we have enough space
while this.content_blocks.len() <= index {
this.content_blocks
.push(ContentBlockBuilder::Text(String::new()));
}
// Initialize based on delta type if provided
if let Some(delta) = &chunk.delta {
match delta {
ContentDelta::Text { .. } => {
this.content_blocks[index] =
ContentBlockBuilder::Text(String::new());
}
ContentDelta::ToolUse { id, name, .. } => {
this.content_blocks[index] = ContentBlockBuilder::ToolUse {
id: id.clone().unwrap_or_default(),
name: name.clone().unwrap_or_default(),
input_json: String::new(),
};
}
ContentDelta::Thinking { .. } => {
this.content_blocks[index] =
ContentBlockBuilder::Thinking(String::new());
}
}
}
}
}
StreamEventType::ContentBlockDelta => {
if let (Some(index), Some(delta)) =
(chunk.index.or(*this.current_block_index), &chunk.delta)
{
if index < this.content_blocks.len() {
match delta {
ContentDelta::Text { text } => {
if let ContentBlockBuilder::Text(ref mut s) =
this.content_blocks[index]
{
s.push_str(text);
}
}
ContentDelta::ToolUse {
id,
name,
input_json_delta,
} => {
if let ContentBlockBuilder::ToolUse {
id: ref mut block_id,
name: ref mut block_name,
input_json: ref mut json,
} = this.content_blocks[index]
{
if let Some(new_id) = id {
*block_id = new_id.clone();
}
if let Some(new_name) = name {
*block_name = new_name.clone();
}
if let Some(delta_json) = input_json_delta {
json.push_str(delta_json);
}
}
}
ContentDelta::Thinking { thinking } => {
if let ContentBlockBuilder::Thinking(ref mut s) =
this.content_blocks[index]
{
s.push_str(thinking);
}
}
}
}
}
}
StreamEventType::ContentBlockStop => {
*this.current_block_index = None;
}
StreamEventType::MessageDelta | StreamEventType::MessageStop => {
if let Some(stop) = chunk.stop_reason {
*this.stop_reason = Some(stop);
}
}
_ => {}
}
if let Some(usage) = chunk.usage {
*this.usage = usage;
}
Poll::Ready(Some(Ok(chunk)))
}
Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(e))),
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
}
}
/// Collect a stream into a final response.
pub async fn collect_stream<S>(stream: S) -> Result<CompletionResponse>
where
S: Stream<Item = Result<StreamChunk>> + Unpin,
{
use futures::StreamExt;
let mut collecting = CollectingStream::new(stream);
// Consume all chunks
while let Some(result) = collecting.next().await {
result?; // Propagate errors
}
collecting.into_response()
}
/// Helper to create a simple text stream chunk.
pub fn text_chunk(text: impl Into<String>, index: usize) -> StreamChunk {
StreamChunk {
event_type: StreamEventType::ContentBlockDelta,
index: Some(index),
delta: Some(ContentDelta::Text { text: text.into() }),
stop_reason: None,
usage: None,
}
}
/// Helper to create a message stop chunk.
pub fn stop_chunk(stop_reason: StopReason, usage: Usage) -> StreamChunk {
StreamChunk {
event_type: StreamEventType::MessageStop,
index: None,
delta: None,
stop_reason: Some(stop_reason),
usage: Some(usage),
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::stream;
#[tokio::test]
async fn test_collect_text_stream() {
let chunks = vec![
Ok(StreamChunk {
event_type: StreamEventType::ContentBlockStart,
index: Some(0),
delta: Some(ContentDelta::Text {
text: String::new(),
}),
stop_reason: None,
usage: None,
}),
Ok(text_chunk("Hello", 0)),
Ok(text_chunk(" world", 0)),
Ok(stop_chunk(
StopReason::EndTurn,
Usage {
input_tokens: 10,
output_tokens: 5,
..Default::default()
},
)),
];
let stream = stream::iter(chunks);
let response = collect_stream(stream).await.unwrap();
assert_eq!(response.text_content(), "Hello world");
assert_eq!(response.stop_reason, StopReason::EndTurn);
assert_eq!(response.usage.input_tokens, 10);
assert_eq!(response.usage.output_tokens, 5);
}
}