1pub fn prompt_prefills_think(prompt: &str) -> bool {
13 prompt.trim_end().ends_with("<think>")
14}
15
16#[derive(Clone, Debug)]
18pub enum Delta {
19 Reasoning(String),
20 Content(String),
21 ToolCall { name: String, arguments: String },
22}
23
24pub struct ChatStream {
32 raw: String,
33 sent_r: usize, sent_c: usize, allow_tools: bool,
36 cur_think_open: Cursor,
40 cur_think_close: Cursor,
41 cur_tool: Cursor, cur_pipe: Cursor, cur_final: Cursor, }
45
46#[derive(Default)]
50struct Cursor {
51 off: Option<usize>,
52 scanned: usize,
53}
54
55impl Cursor {
56 fn find(&mut self, raw: &str, needle: &str) -> Option<usize> {
57 if self.off.is_some() {
58 return self.off;
59 }
60 let mut start = self.scanned.saturating_sub(needle.len().saturating_sub(1));
61 while start > 0 && !raw.is_char_boundary(start) {
62 start -= 1;
63 }
64 if let Some(p) = raw[start..].find(needle) {
65 self.off = Some(start + p);
66 }
67 self.scanned = raw.len();
68 self.off
69 }
70}
71
72impl ChatStream {
73 pub fn new(allow_tools: bool) -> Self {
74 Self {
75 raw: String::new(),
76 sent_r: 0,
77 sent_c: 0,
78 allow_tools,
79 cur_think_open: Cursor::default(),
80 cur_think_close: Cursor::default(),
81 cur_tool: Cursor::default(),
82 cur_pipe: Cursor::default(),
83 cur_final: Cursor::default(),
84 }
85 }
86
87 pub fn push(&mut self, piece: &str, on_delta: &mut dyn FnMut(Delta)) {
88 self.raw.push_str(piece);
89 self.emit(false, on_delta);
90 }
91
92 pub fn finish(&mut self, on_delta: &mut dyn FnMut(Delta)) {
93 self.emit(true, on_delta); if self.allow_tools {
95 let (_r, body) = crate::split_think(&self.raw);
96 let (_content, calls) = crate::parse_any_tool_calls(&body);
99 for call in calls {
100 on_delta(Delta::ToolCall {
101 name: call.name,
102 arguments: serde_json::to_string(&call.arguments)
103 .unwrap_or_else(|_| "{}".to_string()),
104 });
105 }
106 }
107 }
108
109 fn tool_open_at(&mut self, cs: usize, final_flush: bool) -> Option<usize> {
115 if !self.allow_tools {
116 return None;
117 }
118 const TL: &str = "<tool_call>";
119 const PIPE: &str = "<|tool_call>";
120 let hermes = self.cur_tool.find(&self.raw, TL).filter(|&p| p >= cs);
121 let pipe = self.cur_pipe.find(&self.raw, PIPE).filter(|&p| p >= cs);
122 let bare = self.bare_json_open(cs, final_flush);
123 [hermes, pipe, bare].into_iter().flatten().min()
124 }
125
126 fn bare_json_open(&self, cs: usize, final_flush: bool) -> Option<usize> {
133 let bytes = self.raw.as_bytes();
134 let mut i = cs;
135 while i < bytes.len() && matches!(bytes[i], b' ' | b'\n' | b'\t' | b'\r') {
136 i += 1;
137 }
138 if i >= bytes.len() || bytes[i] != b'{' {
139 return None;
140 }
141 if final_flush && crate::tools::parse_bare_json_call(&self.raw[i..]).is_none() {
142 return None; }
144 Some(i)
145 }
146
147 fn emit(&mut self, final_flush: bool, on_delta: &mut dyn FnMut(Delta)) {
148 const TO: &str = "<think>";
149 const TC: &str = "</think>";
150 const CT: [&str; 2] = ["<|channel|>thought", "<|channel>thought"];
154 const FINAL: &str = "<channel|>";
155 if let Some(hm) = CT
156 .iter()
157 .find_map(|m| self.raw.starts_with(m).then_some(m.len()))
158 {
159 let (r_end, hold, c_start) = match self.cur_final.find(&self.raw, FINAL) {
160 Some(f) => (f, false, Some(f + FINAL.len())),
161 None => (self.raw.len(), !final_flush, None),
162 };
163 emit_region(&self.raw, hm, r_end, hold, &mut self.sent_r, true, on_delta);
164 if let Some(cs) = c_start {
165 let tool_open = self.tool_open_at(cs, final_flush);
166 let (c_end, hold) = match tool_open {
167 Some(t) if t >= cs => (t, false),
168 _ => (self.raw.len(), !final_flush),
169 };
170 emit_region(
171 &self.raw,
172 cs,
173 c_end,
174 hold,
175 &mut self.sent_c,
176 false,
177 on_delta,
178 );
179 }
180 return;
181 }
182 if !final_flush
183 && CT.iter().any(|m| {
184 m.as_bytes()
185 .starts_with(&self.raw.as_bytes()[..self.raw.len().min(m.len())])
186 })
187 && self.raw.len() < CT[0].len()
188 {
189 return; }
191 let think_open = self.cur_think_open.find(&self.raw, TO);
192 let think_close = self.cur_think_close.find(&self.raw, TC);
193 if let Some(to) = think_open {
195 let rs = to + TO.len();
196 let (r_end, hold) = match think_close {
197 Some(tc) => (tc, false),
198 None => (self.raw.len(), !final_flush),
199 };
200 emit_region(&self.raw, rs, r_end, hold, &mut self.sent_r, true, on_delta);
201 }
202 let c_start = match think_close {
205 Some(tc) => Some(tc + TC.len()),
206 None if think_open.is_none() => Some(0),
207 None => None,
208 };
209 if let Some(cs) = c_start {
210 let tool_open = self.tool_open_at(cs, final_flush);
211 let (c_end, hold) = match tool_open {
212 Some(t) if t >= cs => (t, false),
213 _ => (self.raw.len(), !final_flush),
214 };
215 emit_region(
216 &self.raw,
217 cs,
218 c_end,
219 hold,
220 &mut self.sent_c,
221 false,
222 on_delta,
223 );
224 }
225 }
226}
227
228fn emit_region(
232 raw: &str,
233 region_start: usize,
234 region_end: usize,
235 hold: bool,
236 sent: &mut usize,
237 reasoning: bool,
238 on_delta: &mut dyn FnMut(Delta),
239) {
240 const HOLD: usize = 12; let abs = region_start + *sent;
242 if abs >= region_end {
243 return;
244 }
245 let mut end = if hold {
246 region_end.saturating_sub(HOLD).max(abs)
247 } else {
248 region_end
249 };
250 while end > abs && !raw.is_char_boundary(end) {
251 end -= 1;
252 }
253 if end <= abs {
254 return;
255 }
256 let text = &raw[abs..end];
257 if text.is_empty() {
258 return;
259 }
260 on_delta(if reasoning {
261 Delta::Reasoning(text.to_owned())
262 } else {
263 Delta::Content(text.to_owned())
264 });
265 *sent += text.len();
266}
267
268#[cfg(test)]
269mod chat_stream_tests {
270 use super::*;
271
272 fn run(pieces: &[&str], allow_tools: bool) -> (String, String, Vec<(String, String)>) {
274 let mut out: Vec<Delta> = Vec::new();
275 let mut s = ChatStream::new(allow_tools);
276 {
277 let mut od = |d: Delta| out.push(d);
278 for p in pieces {
279 s.push(p, &mut od);
280 }
281 }
282 s.finish(&mut |d: Delta| out.push(d));
283 let (mut r, mut c, mut t) = (String::new(), String::new(), Vec::new());
284 for d in &out {
285 match d {
286 Delta::Reasoning(x) => r.push_str(x),
287 Delta::Content(x) => c.push_str(x),
288 Delta::ToolCall { name, arguments } => t.push((name.clone(), arguments.clone())),
289 }
290 }
291 (r, c, t)
292 }
293
294 #[test]
295 fn streams_channel_thought_then_final() {
296 let (r, c, t) = run(
299 &[
300 "<|channel>th",
301 "ought\nreaso",
302 "ning<chan",
303 "nel|>the answer",
304 ],
305 false,
306 );
307 assert_eq!(r.trim(), "reasoning");
308 assert_eq!(c.trim(), "the answer");
309 assert!(t.is_empty());
310 }
311
312 #[test]
313 fn prefilled_think_via_injected_opener() {
314 let (r, c, t) = run(&["<think>", "reasoning here", "</think>", "answer"], false);
317 assert_eq!(r.trim(), "reasoning here");
318 assert_eq!(c.trim(), "answer");
319 assert!(t.is_empty());
320 }
321
322 #[test]
323 fn streams_think_then_content() {
324 let (r, c, t) = run(
325 &["<think>", "reason", "ing", "</think>", "the ", "answer"],
326 true,
327 );
328 assert_eq!(r.trim(), "reasoning");
329 assert_eq!(c.trim(), "the answer");
330 assert!(t.is_empty());
331 }
332
333 #[test]
334 fn plain_content_no_think() {
335 let (r, c, _) = run(&["hello ", "world, this is a longer reply"], true);
336 assert!(r.trim().is_empty());
337 assert_eq!(c.trim(), "hello world, this is a longer reply");
338 }
339
340 #[test]
341 fn tool_call_buffered_and_parsed() {
342 let (r, _c, t) = run(
343 &[
344 "<think>plan</think>",
345 "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>",
346 ],
347 true,
348 );
349 assert_eq!(r.trim(), "plan");
350 assert_eq!(t.len(), 1);
351 assert_eq!(t[0].0, "run_bash");
352 assert!(t[0].1.contains("ls"));
353 }
354
355 #[test]
356 fn tool_choice_none_keeps_tool_text_as_content() {
357 let (_r, c, t) = run(&["<tool_call>{\"name\":\"x\"}</tool_call>"], false);
359 assert!(t.is_empty());
360 assert!(c.contains("tool_call"));
361 }
362
363 #[test]
364 fn pipe_form_tool_call_not_streamed_as_content() {
365 let (_r, c, t) = run(
368 &[
369 "<|tool_",
370 "call>call:get_weather{city:<|\"|>Par",
371 "is<|\"|>}",
372 "<tool_call|>",
373 ],
374 true,
375 );
376 assert!(
377 !c.contains("tool_call") && !c.contains("get_weather"),
378 "pipe markup leaked as content: {c:?}"
379 );
380 assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
381 assert_eq!(t[0].0, "get_weather");
382 }
383
384 #[test]
385 fn bare_json_tool_call_not_streamed_as_content() {
386 let (_r, c, t) = run(
388 &[
389 "{\"name\": \"get_weather\", ",
390 "\"parameters\": {\"city\": \"Paris\"}}",
391 ],
392 true,
393 );
394 assert!(c.trim().is_empty(), "bare json leaked as content: {c:?}");
395 assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
396 assert_eq!(t[0].0, "get_weather");
397 }
398
399 #[test]
400 fn content_with_stray_brace_not_swallowed() {
401 let (_r, c, t) = run(
403 &[
404 "The config is {",
405 "\"a\": 1} and that is the whole story here, nothing more.",
406 ],
407 true,
408 );
409 assert!(t.is_empty(), "stray brace misparsed as tool call: {t:?}");
410 assert!(c.contains("The config is"), "content lost: {c:?}");
411 assert!(c.contains("whole story"), "content truncated: {c:?}");
412 }
413
414 #[test]
415 fn leading_brace_non_call_survives_as_content() {
416 let (_r, c, t) = run(
418 &["{not json here, just prose that opens with a brace}"],
419 true,
420 );
421 assert!(t.is_empty(), "non-call misparsed: {t:?}");
422 assert!(c.contains("not json here"), "content dropped: {c:?}");
423 }
424}