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
use async_stream::try_stream;
use futures::{StreamExt, stream::BoxStream};
use crate::{
chat::{Chat, state::Unstructured},
error::ChatFailure,
traits::StreamProvider,
types::{
messages::Messages,
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;
while let Some(event_result) = provider_stream.next().await {
match event_result {
Ok(StreamEvent::Done(response)) => {
final_response = Some(response);
}
Ok(event) => {
yield event;
}
Err(err) => {
Err(ChatFailure { err, metadata: last_metadata.clone() })?;
}
}
}
if let Some(response) = final_response {
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))
}
}