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
use async_stream::try_stream;
use futures::{StreamExt, stream::BoxStream};
use crate::{
chat::{Chat, state::Unstructured},
error::ChatFailure,
traits::StreamProvider,
types::{
messages::{Messages, parts::PartEnum},
metadata::Metadata,
response::{ChatResponse, StreamEvent},
},
};
impl<CP: StreamProvider> Chat<CP, Unstructured> {
/// Streaming chat loop with HITL support.
///
/// Yields each token/chunk as `StreamEvent::TextChunk` / similar. When
/// a tool strategy pauses execution (for example, `RequireApproval`),
/// the stream yields `StreamEvent::Paused(PauseReason)` and then
/// terminates. The caller resolves pending tools on `messages` —
/// typically via `Messages::find_tool_mut` — and calls `stream()`
/// again to continue. On re-entry, a pre-step executes any
/// newly-approved tools, emits `ToolResult` events for them, and
/// then falls through into the next provider turn.
pub async fn stream<'a>(
&'a mut self,
messages: &'a mut Messages,
) -> Result<BoxStream<'a, Result<StreamEvent, ChatFailure>>, ChatFailure> {
if let Some(strategy) = self.before_strategy.as_mut() {
strategy(messages, None).await;
}
let stream = try_stream! {
let max_steps = self.max_steps.unwrap_or(1);
let mut last_metadata: Option<Metadata> = None;
for _ in 0..max_steps {
// Pre-step: execute any tools already resolved to
// Approved on the last Content (typically from a
// prior pause that the caller just resolved). Emit
// ToolResult events for completed tools. Yield Paused
// if the pre-step itself produced a pause (can happen
// if the caller left some tools still Pending).
if let Some(last) = messages.0.last_mut() {
let pass = self
.tool_call(last)
.await
.map_err(|err| ChatFailure {
err,
metadata: last_metadata.clone(),
})?;
if pass.executed
&& let Some(last) = messages.0.last()
{
for tool in last.parts.tools() {
if let Some(fr) = tool.response() {
yield StreamEvent::ToolResult(fr.clone());
}
}
}
if let Some(reason) = pass.pause {
yield StreamEvent::Paused(reason);
return;
}
}
let decls =
crate::chat::tool_declarations_from(&self.scoped_collections);
let decls_dyn = decls
.as_ref()
.map(|d| d as &dyn crate::types::tools::ToolDeclarations);
let mut provider_stream = self
.model
.stream(messages, decls_dyn, self.model_options.as_ref())
.await
.map_err(|err| ChatFailure { err, metadata: last_metadata.clone() })?;
let mut final_response: Option<ChatResponse> = None;
// Mid-stream Structured events are also accumulated into
// the final ChatResponse so non-streaming consumers see
// them in `content.parts`, preserving the equivalence
// between `complete()` and accumulated `stream()`.
let mut structured_buffer: Vec<serde_json::Value> = Vec::new();
while let Some(event_result) = provider_stream.next().await {
match event_result {
Ok(StreamEvent::Done(response)) => {
final_response = Some(response);
}
Ok(event) => {
if let StreamEvent::Structured(ref v) = event {
structured_buffer.push(v.clone());
}
yield event;
}
Err(err) => {
Err(ChatFailure { err, metadata: last_metadata.clone() })?;
}
}
}
if let Some(mut response) = final_response {
for v in structured_buffer.drain(..) {
response.content.parts.push(PartEnum::Structured(v));
}
self.model.on_stream_done(&response);
if let Some(metadata) = response.metadata.clone() {
match &mut last_metadata {
Some(existing) => { existing.extend(&metadata); },
None => { last_metadata = Some(metadata); },
}
}
messages.push(response.content.clone());
// Post-step: apply strategy to any tools the model
// emitted this turn. Execute those that say Execute;
// pause on anything that needs approval/deferral.
let pass = match messages.0.last_mut() {
Some(last) => self.tool_call(last).await
.map_err(|err| ChatFailure { err, metadata: last_metadata.clone() })?,
None => crate::chat::ToolCallPass::default(),
};
if pass.executed
&& let Some(last) = messages.0.last()
{
for tool in last.parts.tools() {
if let Some(fr) = tool.response() {
yield StreamEvent::ToolResult(fr.clone());
}
}
}
if let Some(reason) = pass.pause {
yield StreamEvent::Paused(reason);
return;
}
if pass.executed {
// Tools ran; need another provider turn so the
// model can react to the results.
continue;
}
if let Some(strategy) = self.after_strategy.as_mut() {
strategy(messages, last_metadata.as_ref()).await;
}
yield StreamEvent::Done(response);
break;
}
}
};
Ok(Box::pin(stream))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
error::ChatError,
types::{
messages::{
Messages,
content::{Content, RoleEnum},
parts::{PartEnum, Parts},
},
options::ChatOptions,
response::ChatResponse,
tools::ToolDeclarations,
},
};
use async_trait::async_trait;
use serde_json::json;
use std::collections::HashMap;
use std::marker::PhantomData;
/// Minimal `StreamProvider` that yields a pre-loaded event sequence,
/// then ends. Used to exercise the engine's accumulator without
/// touching a real network or wire protocol.
struct MockStreamProvider {
events: Vec<Result<StreamEvent, ChatError>>,
}
#[async_trait]
impl StreamProvider for MockStreamProvider {
async fn stream(
&mut self,
_messages: &mut Messages,
_tool_declarations: Option<&dyn ToolDeclarations>,
_options: Option<&ChatOptions>,
) -> Result<
futures::stream::BoxStream<'static, Result<StreamEvent, ChatError>>,
ChatError,
> {
let events = std::mem::take(&mut self.events);
Ok(Box::pin(futures::stream::iter(events)))
}
}
fn chat_with(
events: Vec<Result<StreamEvent, ChatError>>,
) -> Chat<MockStreamProvider, Unstructured> {
Chat {
model: MockStreamProvider { events },
output_shape: None,
model_options: None,
max_steps: Some(1),
max_retries: None,
retry_strategy: None,
before_strategy: None,
after_strategy: None,
scoped_collections: Vec::new(),
routing: HashMap::new(),
_output: PhantomData,
}
}
/// Helper: builds an empty `Done` response — the provider's "I'm done"
/// signal. The contract we're testing is that mid-stream `Structured`
/// events get folded into `content.parts` by the engine, not the
/// provider, so the provider's `Done` has no parts of its own.
fn done_event() -> StreamEvent {
StreamEvent::Done(ChatResponse {
content: Content {
role: RoleEnum::Model,
parts: Parts::default(),
complete_reason: Default::default(),
},
metadata: None,
})
}
async fn collect_stream(
chat: &mut Chat<MockStreamProvider, Unstructured>,
messages: &mut Messages,
) -> Vec<StreamEvent> {
let mut s = chat.stream(messages).await.expect("stream open");
let mut out = Vec::new();
while let Some(ev) = s.next().await {
out.push(ev.expect("event ok"));
}
out
}
#[tokio::test]
async fn structured_events_flow_to_consumer_and_into_final_response() {
let mut chat = chat_with(vec![
Ok(StreamEvent::Structured(json!({"step": 1}))),
Ok(StreamEvent::Structured(json!({"step": 2}))),
Ok(done_event()),
]);
let mut messages = Messages::default();
let events = collect_stream(&mut chat, &mut messages).await;
// Consumer sees: 2 Structured events + the final Done.
assert_eq!(events.len(), 3);
assert!(matches!(events[0], StreamEvent::Structured(_)));
assert!(matches!(events[1], StreamEvent::Structured(_)));
// Final Done carries a ChatResponse whose parts include both
// Structured values, in order.
let StreamEvent::Done(response) = &events[2] else {
panic!("expected Done event");
};
let structured: Vec<&serde_json::Value> = response
.content
.parts
.0
.iter()
.filter_map(|p| match p {
PartEnum::Structured(v) => Some(v),
_ => None,
})
.collect();
assert_eq!(structured.len(), 2);
assert_eq!(structured[0], &json!({"step": 1}));
assert_eq!(structured[1], &json!({"step": 2}));
}
#[tokio::test]
async fn structured_interleaved_with_text_preserves_event_order() {
let mut chat = chat_with(vec![
Ok(StreamEvent::TextChunk("hello ".into())),
Ok(StreamEvent::Structured(json!({"step": 1}))),
Ok(StreamEvent::TextChunk("world".into())),
Ok(StreamEvent::Structured(json!({"step": 2}))),
Ok(done_event()),
]);
let mut messages = Messages::default();
let events = collect_stream(&mut chat, &mut messages).await;
// Event order on the consumer side is exactly what the provider
// emitted, untouched by the accumulator.
assert_eq!(events.len(), 5);
assert!(matches!(events[0], StreamEvent::TextChunk(ref t) if t == "hello "));
assert!(matches!(events[1], StreamEvent::Structured(_)));
assert!(matches!(events[2], StreamEvent::TextChunk(ref t) if t == "world"));
assert!(matches!(events[3], StreamEvent::Structured(_)));
// Final response.parts contains only the Structured entries
// (no text — provider's Done was empty), in order.
let StreamEvent::Done(response) = &events[4] else {
panic!("expected Done event");
};
let parts: Vec<&PartEnum> = response.content.parts.0.iter().collect();
assert_eq!(parts.len(), 2);
assert!(matches!(parts[0], PartEnum::Structured(v) if v == &json!({"step": 1})));
assert!(matches!(parts[1], PartEnum::Structured(v) if v == &json!({"step": 2})));
}
#[tokio::test]
async fn no_structured_events_leaves_final_response_untouched() {
// Regression guard: the buffer-and-drain path must not corrupt
// the response when no Structured events appear.
let mut chat = chat_with(vec![
Ok(StreamEvent::TextChunk("just text".into())),
Ok(done_event()),
]);
let mut messages = Messages::default();
let events = collect_stream(&mut chat, &mut messages).await;
assert_eq!(events.len(), 2);
let StreamEvent::Done(response) = &events[1] else {
panic!("expected Done event");
};
assert!(response.content.parts.0.is_empty());
}
}