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, lead: Option<(usize, usize)>,
39 sent_lead: usize,
40 shown_gap: Option<String>,
43 allow_tools: bool,
44 cur_think_open: Cursor,
48 cur_think_close: Cursor,
49 cur_tool: Cursor, cur_pipe: Cursor, cur_final: Cursor, bare: BareJson,
53}
54
55#[derive(Default)]
59struct BareJson {
60 cs: Option<usize>, scanned: usize,
62 head: BareHead,
63 depth: usize,
64 in_str: bool,
65 esc: bool,
66}
67
68#[derive(Default, Clone, Copy, PartialEq)]
69enum BareHead {
70 #[default]
72 Pending,
73 Open(usize),
75 Call(usize),
77 No,
79}
80
81impl BareJson {
82 fn open(&mut self, raw: &str, cs: usize) -> Option<usize> {
84 if self.cs != Some(cs) {
85 *self = Self {
86 cs: Some(cs),
87 scanned: cs,
88 ..Self::default()
89 };
90 }
91 let bytes = raw.as_bytes();
92 while self.scanned < bytes.len() {
93 let i = self.scanned;
94 let b = bytes[i];
95 self.scanned += 1;
96 match self.head {
97 BareHead::Pending => match b {
98 b' ' | b'\n' | b'\t' | b'\r' => {}
99 b'{' => {
100 self.head = BareHead::Open(i);
101 self.depth = 1;
102 }
103 _ => self.head = BareHead::No,
104 },
105 BareHead::Open(start) => {
106 if self.in_str {
107 match b {
108 _ if self.esc => self.esc = false,
109 b'\\' => self.esc = true,
110 b'"' => self.in_str = false,
111 _ => {}
112 }
113 } else {
114 match b {
115 b'"' => self.in_str = true,
116 b'{' => self.depth += 1,
117 b'}' => {
118 self.depth -= 1;
119 if self.depth == 0 {
120 let call = crate::tools::parse_bare_json_call(&raw[start..=i]);
123 self.head = if call.is_some() {
124 BareHead::Call(start)
125 } else {
126 BareHead::No
127 };
128 }
129 }
130 _ => {}
131 }
132 }
133 }
134 BareHead::Call(_) | BareHead::No => {
135 self.scanned = bytes.len();
136 }
137 }
138 }
139 match self.head {
140 BareHead::Open(i) | BareHead::Call(i) => Some(i),
141 BareHead::Pending | BareHead::No => None,
142 }
143 }
144}
145
146#[derive(Default)]
150struct Cursor {
151 off: Option<usize>,
152 scanned: usize,
153}
154
155impl Cursor {
156 fn find(&mut self, raw: &str, needle: &str) -> Option<usize> {
157 self.find_from(raw, needle, 0)
158 }
159
160 fn find_from(&mut self, raw: &str, needle: &str, from: usize) -> Option<usize> {
164 match self.off {
165 Some(p) if p >= from => return Some(p),
166 Some(_) => {
167 self.off = None;
168 self.scanned = from;
169 }
170 None => {}
171 }
172 let mut start = self
173 .scanned
174 .saturating_sub(needle.len().saturating_sub(1))
175 .max(from);
176 while start > from && !raw.is_char_boundary(start) {
177 start -= 1;
178 }
179 if let Some(p) = raw[start..].find(needle) {
180 self.off = Some(start + p);
181 }
182 self.scanned = raw.len();
183 self.off
184 }
185}
186
187impl ChatStream {
188 pub fn new(allow_tools: bool) -> Self {
189 Self {
190 raw: String::new(),
191 sent_r: 0,
192 sent_c: 0,
193 lead: None,
194 sent_lead: 0,
195 shown_gap: None,
196 allow_tools,
197 cur_think_open: Cursor::default(),
198 cur_think_close: Cursor::default(),
199 cur_tool: Cursor::default(),
200 cur_pipe: Cursor::default(),
201 cur_final: Cursor::default(),
202 bare: BareJson::default(),
203 }
204 }
205
206 pub fn push(&mut self, piece: &str, on_delta: &mut dyn FnMut(Delta)) {
207 self.raw.push_str(piece);
208 self.emit(false, on_delta);
209 }
210
211 pub fn finish(&mut self, on_delta: &mut dyn FnMut(Delta)) {
215 self.emit(true, on_delta);
216 }
217
218 fn tool_open_at(&mut self, cs: usize, final_flush: bool) -> Option<usize> {
224 if !self.allow_tools {
225 return None;
226 }
227 const TL: &str = "<tool_call>";
228 const PIPE: &str = "<|tool_call>";
229 let hermes = self.cur_tool.find_from(&self.raw, TL, cs);
230 let pipe = self.cur_pipe.find_from(&self.raw, PIPE, cs);
231 let bare = self.bare_json_open(cs, final_flush);
232 [hermes, pipe, bare].into_iter().flatten().min()
233 }
234
235 fn bare_json_open(&mut self, cs: usize, final_flush: bool) -> Option<usize> {
243 let i = self.bare.open(&self.raw, cs)?;
244 if final_flush && crate::tools::parse_bare_json_call(&self.raw[i..]).is_none() {
245 return None; }
247 Some(i)
248 }
249
250 fn emit(&mut self, final_flush: bool, on_delta: &mut dyn FnMut(Delta)) {
251 const TO: &str = "<think>";
252 const TC: &str = "</think>";
253 const FINAL: &str = "<channel|>";
257 if let Some(hm) = channel_thought_head(&self.raw) {
258 let (r_end, hold, c_start) = match self.cur_final.find(&self.raw, FINAL) {
259 Some(f) => (f, false, Some(f + FINAL.len())),
260 None => (self.raw.len(), !final_flush, None),
261 };
262 emit_region(&self.raw, hm, r_end, hold, &mut self.sent_r, true, on_delta);
263 if let Some(cs) = c_start {
264 self.emit_content(cs, final_flush, on_delta);
265 }
266 return;
267 }
268 if !final_flush
269 && CHANNEL_THOUGHT.iter().any(|m| {
270 m.as_bytes()
271 .starts_with(&self.raw.as_bytes()[..self.raw.len().min(m.len())])
272 })
273 && self.raw.len() < CHANNEL_THOUGHT[0].len()
274 {
275 return; }
277 let think_open = self.cur_think_open.find(&self.raw, TO);
278 let think_close = self.cur_think_close.find(&self.raw, TC);
279 let lead = think_open
283 .filter(|&to| think_close.is_none_or(|tc| tc > to))
284 .map(|to| match self.lead {
285 Some(lead) => lead,
286 None => {
287 self.sent_lead = std::mem::take(&mut self.sent_c);
288 let stop = match to {
291 0 => 0,
292 _ => self.tool_open_at(0, false).map_or(to, |t| t.min(to)),
293 };
294 self.lead = Some((stop, to));
295 (stop, to)
296 }
297 });
298 if let Some((stop, end)) = lead {
299 let unsent = self.sent_lead < end;
300 let from = self.sent_lead;
301 emit_region(
302 &self.raw,
303 0,
304 stop,
305 false,
306 &mut self.sent_lead,
307 false,
308 on_delta,
309 );
310 note_shown(&mut self.shown_gap, &self.raw[from..self.sent_lead]);
311 if unsent && stop < end {
315 settle_held(&self.raw[stop..end], &mut self.shown_gap, false, on_delta);
316 self.sent_lead = end;
317 }
318 }
319 if let Some(to) = think_open {
321 let rs = to + TO.len();
322 let (r_end, hold) = match think_close {
323 Some(tc) => (tc, false),
324 None => (self.raw.len(), !final_flush),
325 };
326 emit_region(&self.raw, rs, r_end, hold, &mut self.sent_r, true, on_delta);
327 }
328 let c_start = match think_close {
331 Some(tc) => Some(tc + TC.len()),
332 None if think_open.is_none() => Some(0),
333 None => None,
334 };
335 if let Some(cs) = c_start {
336 self.emit_content(cs, final_flush, on_delta);
337 }
338 }
339
340 fn emit_content(&mut self, cs: usize, final_flush: bool, on_delta: &mut dyn FnMut(Delta)) {
343 let tool_open = self.tool_open_at(cs, final_flush).filter(|&t| t >= cs);
344 let (c_end, hold) = match tool_open {
345 Some(t) => (t, false),
346 None => (self.raw.len(), !final_flush),
347 };
348 let from = cs + self.sent_c;
349 emit_region(
350 &self.raw,
351 cs,
352 c_end,
353 hold,
354 &mut self.sent_c,
355 false,
356 on_delta,
357 );
358 note_shown(&mut self.shown_gap, &self.raw[from..cs + self.sent_c]);
359 if let (true, Some(t)) = (final_flush, tool_open) {
360 settle_held(&self.raw[t..], &mut self.shown_gap, true, on_delta);
361 }
362 }
363}
364
365fn settle_held(
378 held: &str,
379 shown_gap: &mut Option<String>,
380 at_end: bool,
381 on_delta: &mut dyn FnMut(Delta),
382) {
383 let mut fired = Vec::new();
384 let spans = reasoning_spans(held);
385 let last_text = spans.iter().rposition(|s| matches!(s, Span::Text(_)));
387 for (i, span) in spans.into_iter().enumerate() {
388 let text = match span {
389 Span::Reasoning(r) => {
390 if !r.is_empty() {
391 on_delta(Delta::Reasoning(r.to_owned()));
392 }
393 continue;
394 }
395 Span::Text(t) => t,
396 };
397 let (clean, calls) = crate::parse_any_tool_calls(text);
400 let content = if calls.is_empty() {
401 text
402 } else {
403 let (opens_with_cut, closes_with_cut) = cut_edges(text, &clean);
404 let mut c = clean.as_str();
405 if opens_with_cut {
406 let rest = c.trim_start();
407 let gap = &c[..c.len() - rest.len()];
408 let keep = match shown_gap.as_deref() {
409 None => false,
410 Some("") => true,
411 Some(shown) => gap.contains('\n') && !shown.contains('\n'),
412 };
413 if !keep {
414 c = rest;
415 }
416 }
417 if at_end && closes_with_cut && Some(i) == last_text {
418 c = c.trim_end();
419 }
420 c
421 };
422 if !content.is_empty() {
423 note_shown(shown_gap, content);
424 on_delta(Delta::Content(content.to_owned()));
425 }
426 fired.extend(calls);
427 }
428 for call in fired {
429 on_delta(Delta::ToolCall {
430 name: call.name,
431 arguments: serde_json::to_string(&call.arguments).unwrap_or_else(|_| "{}".to_string()),
432 });
433 }
434}
435
436fn cut_edges(text: &str, clean: &str) -> (bool, bool) {
439 let head = text
440 .char_indices()
441 .zip(clean.chars())
442 .find(|((_, a), b)| a != b)
443 .map_or(clean.len().min(text.len()), |((i, _), _)| i);
444 let tail = text
445 .char_indices()
446 .rev()
447 .zip(clean.chars().rev())
448 .find(|((_, a), b)| a != b)
449 .map_or(text.len() - clean.len().min(text.len()), |((i, a), _)| {
450 i + a.len_utf8()
451 });
452 (
453 text[..head].trim().is_empty(),
454 text[tail..].trim().is_empty(),
455 )
456}
457
458fn note_shown(gap: &mut Option<String>, text: &str) {
460 if text.is_empty() {
461 return;
462 }
463 let word = text.trim_end();
464 if word.is_empty() {
465 gap.get_or_insert_with(String::new).push_str(text);
466 } else {
467 *gap = Some(text[word.len()..].to_owned());
468 }
469}
470
471enum Span<'a> {
473 Text(&'a str),
474 Reasoning(&'a str),
475}
476
477fn reasoning_spans(text: &str) -> Vec<Span<'_>> {
479 const TO: &str = "<think>";
480 const TC: &str = "</think>";
481 let mut out = Vec::new();
482 let mut rest = text;
483 while let Some(o) = rest.find(TO) {
484 out.push(Span::Text(&rest[..o]));
485 let inner = &rest[o + TO.len()..];
486 let Some(c) = inner.find(TC) else {
487 out.push(Span::Reasoning(inner));
488 return out;
489 };
490 out.push(Span::Reasoning(&inner[..c]));
491 rest = &inner[c + TC.len()..];
492 }
493 out.push(Span::Text(rest));
494 out
495}
496
497const CHANNEL_THOUGHT: [&str; 2] = ["<|channel|>thought", "<|channel>thought"];
500
501fn channel_thought_head(raw: &str) -> Option<usize> {
505 CHANNEL_THOUGHT
506 .iter()
507 .find_map(|m| raw.starts_with(m).then_some(m.len()))
508}
509
510fn emit_region(
514 raw: &str,
515 region_start: usize,
516 region_end: usize,
517 hold: bool,
518 sent: &mut usize,
519 reasoning: bool,
520 on_delta: &mut dyn FnMut(Delta),
521) {
522 const HOLD: usize = 12; let abs = region_start + *sent;
524 if abs >= region_end {
525 return;
526 }
527 let mut end = if hold {
528 region_end.saturating_sub(HOLD).max(abs)
529 } else {
530 region_end
531 };
532 while end > abs && !raw.is_char_boundary(end) {
533 end -= 1;
534 }
535 if end <= abs {
536 return;
537 }
538 let text = &raw[abs..end];
539 if text.is_empty() {
540 return;
541 }
542 on_delta(if reasoning {
543 Delta::Reasoning(text.to_owned())
544 } else {
545 Delta::Content(text.to_owned())
546 });
547 *sent += text.len();
548}
549
550#[cfg(test)]
551mod chat_stream_tests {
552 use super::*;
553
554 fn run(pieces: &[&str], allow_tools: bool) -> (String, String, Vec<(String, String)>) {
556 let mut out: Vec<Delta> = Vec::new();
557 let mut s = ChatStream::new(allow_tools);
558 {
559 let mut od = |d: Delta| out.push(d);
560 for p in pieces {
561 s.push(p, &mut od);
562 }
563 }
564 s.finish(&mut |d: Delta| out.push(d));
565 let (mut r, mut c, mut t) = (String::new(), String::new(), Vec::new());
566 for d in &out {
567 match d {
568 Delta::Reasoning(x) => r.push_str(x),
569 Delta::Content(x) => c.push_str(x),
570 Delta::ToolCall { name, arguments } => t.push((name.clone(), arguments.clone())),
571 }
572 }
573 (r, c, t)
574 }
575
576 #[test]
577 fn streams_channel_thought_then_final() {
578 let (r, c, t) = run(
581 &[
582 "<|channel>th",
583 "ought\nreaso",
584 "ning<chan",
585 "nel|>the answer",
586 ],
587 false,
588 );
589 assert_eq!(r.trim(), "reasoning");
590 assert_eq!(c.trim(), "the answer");
591 assert!(t.is_empty());
592 }
593
594 #[test]
595 fn prefilled_think_via_injected_opener() {
596 let (r, c, t) = run(&["<think>", "reasoning here", "</think>", "answer"], false);
599 assert_eq!(r.trim(), "reasoning here");
600 assert_eq!(c.trim(), "answer");
601 assert!(t.is_empty());
602 }
603
604 #[test]
605 fn streams_think_then_content() {
606 let (r, c, t) = run(
607 &["<think>", "reason", "ing", "</think>", "the ", "answer"],
608 true,
609 );
610 assert_eq!(r.trim(), "reasoning");
611 assert_eq!(c.trim(), "the answer");
612 assert!(t.is_empty());
613 }
614
615 #[test]
616 fn plain_content_no_think() {
617 let (r, c, _) = run(&["hello ", "world, this is a longer reply"], true);
618 assert!(r.trim().is_empty());
619 assert_eq!(c.trim(), "hello world, this is a longer reply");
620 }
621
622 #[test]
623 fn tool_call_buffered_and_parsed() {
624 let (r, _c, t) = run(
625 &[
626 "<think>plan</think>",
627 "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>",
628 ],
629 true,
630 );
631 assert_eq!(r.trim(), "plan");
632 assert_eq!(t.len(), 1);
633 assert_eq!(t[0].0, "run_bash");
634 assert!(t[0].1.contains("ls"));
635 }
636
637 #[test]
638 fn tool_choice_none_keeps_tool_text_as_content() {
639 let (_r, c, t) = run(&["<tool_call>{\"name\":\"x\"}</tool_call>"], false);
641 assert!(t.is_empty());
642 assert!(c.contains("tool_call"));
643 }
644
645 #[test]
646 fn pipe_form_tool_call_not_streamed_as_content() {
647 let (_r, c, t) = run(
650 &[
651 "<|tool_",
652 "call>call:get_weather{city:<|\"|>Par",
653 "is<|\"|>}",
654 "<tool_call|>",
655 ],
656 true,
657 );
658 assert!(
659 !c.contains("tool_call") && !c.contains("get_weather"),
660 "pipe markup leaked as content: {c:?}"
661 );
662 assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
663 assert_eq!(t[0].0, "get_weather");
664 }
665
666 #[test]
667 fn bare_json_tool_call_not_streamed_as_content() {
668 let (_r, c, t) = run(
670 &[
671 "{\"name\": \"get_weather\", ",
672 "\"parameters\": {\"city\": \"Paris\"}}",
673 ],
674 true,
675 );
676 assert!(c.trim().is_empty(), "bare json leaked as content: {c:?}");
677 assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
678 assert_eq!(t[0].0, "get_weather");
679 }
680
681 #[test]
682 fn content_with_stray_brace_not_swallowed() {
683 let (_r, c, t) = run(
685 &[
686 "The config is {",
687 "\"a\": 1} and that is the whole story here, nothing more.",
688 ],
689 true,
690 );
691 assert!(t.is_empty(), "stray brace misparsed as tool call: {t:?}");
692 assert!(c.contains("The config is"), "content lost: {c:?}");
693 assert!(c.contains("whole story"), "content truncated: {c:?}");
694 }
695
696 #[test]
699 fn tool_marker_in_reasoning_does_not_hide_the_real_call() {
700 let call = "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>";
701 for pipe in [false, true] {
702 let (mention, real) = if pipe {
703 (
704 "I could emit <|tool_call> here",
705 "<|tool_call>call:run_bash{command:<|\"|>ls<|\"|>}<tool_call|>",
706 )
707 } else {
708 ("I could emit <tool_call> here", call)
709 };
710 let pieces = ["<think>", mention, "</think>", "Sure. ", real];
711 let (_r, c, t) = run(&pieces, true);
712 assert!(
713 !c.contains("run_bash"),
714 "the call streamed as content: {c:?}"
715 );
716 assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
717 assert_eq!(t[0].0, "run_bash");
718 }
719 }
720
721 #[test]
724 fn tool_call_in_channel_reasoning_is_not_a_call() {
725 let (r, c, t) = run(
726 &[
727 "<|channel>thought\nmaybe <|tool_call>call:get_weather{city:<|\"|>Paris<|\"|>}",
728 "<tool_call|> but no<channel|>It is sunny.",
729 ],
730 true,
731 );
732 assert!(r.contains("maybe"), "reasoning lost: {r:?}");
733 assert_eq!(c.trim(), "It is sunny.");
734 assert!(t.is_empty(), "a call quoted in the reasoning fired: {t:?}");
735 }
736
737 #[test]
741 fn a_quoted_channel_marker_does_not_switch_formats() {
742 let (_r, c, t) = run(
743 &[
744 "<think>plan</think>",
745 "The <|channel> marker is how E2B splits. ",
746 "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>",
747 ],
748 true,
749 );
750 assert!(c.contains("<|channel> marker"), "content lost: {c:?}");
751 assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
752 assert_eq!(t[0].0, "run_bash");
753 }
754
755 #[test]
759 fn a_leading_json_answer_streams_before_finish() {
760 let pieces = [
761 "{\"a\": [1, ",
762 "2], \"b\": \"x} \\\"q\\\" {\"}",
763 " and the prose after it keeps coming",
764 " for a while longer.",
765 ];
766 let mut s = ChatStream::new(true);
767 let mut streamed = String::new();
768 for p in pieces {
769 s.push(p, &mut |d| {
770 if let Delta::Content(x) = d {
771 streamed.push_str(&x)
772 }
773 });
774 }
775 assert!(
776 streamed.starts_with("{\"a\": [1, 2], \"b\": \"x} \\\"q\\\" {\"}"),
777 "the object was not streamed before finish: {streamed:?}"
778 );
779 let (_r, c, t) = run(&pieces, true);
780 assert!(t.is_empty(), "a plain object fired as a call: {t:?}");
781 assert_eq!(c, pieces.concat());
782 }
783
784 #[test]
787 fn content_before_a_late_think_is_streamed() {
788 let pieces = [
789 "Sure, let me check. ",
790 "<think>",
791 "plan",
792 "</think>",
793 "It is 4.",
794 ];
795 let mut out = Vec::new();
796 let mut s = ChatStream::new(false);
797 for p in pieces {
798 s.push(p, &mut |d| out.push(d));
799 }
800 s.finish(&mut |d| out.push(d));
801 let lead = out
802 .iter()
803 .position(|d| matches!(d, Delta::Content(x) if x.contains("check.")));
804 let think = out.iter().position(|d| matches!(d, Delta::Reasoning(_)));
805 assert!(
806 lead < think && lead.is_some(),
807 "lead missing or late: {out:?}"
808 );
809 let (r, c, _) = run(&pieces, false);
810 assert_eq!(r, "plan");
811 assert_eq!(c, "Sure, let me check. It is 4.");
812 }
813
814 #[test]
818 fn a_held_lead_in_that_is_no_call_is_emitted_in_order() {
819 for (pieces, want) in [
820 (
821 &[
822 "{not a call} so ",
823 "<think>",
824 "plan",
825 "</think>",
826 "an answer long enough to stream",
827 ][..],
828 "{not a call} so an answer long enough to stream",
829 ),
830 (
831 &[
832 "Hi <tool_call>oops ",
833 "<think>",
834 "plan",
835 "</think>",
836 "done, and more after that",
837 ][..],
838 "Hi <tool_call>oops done, and more after that",
839 ),
840 ] {
841 let (r, c, t) = run(pieces, true);
842 assert_eq!(r, "plan");
843 assert!(t.is_empty(), "no call was made: {t:?}");
844 assert_eq!(c, want);
845 }
846 }
847
848 #[test]
851 fn a_call_after_reasoning_fires_despite_a_lead_in() {
852 let (_r, c, t) = run(
853 &[
854 "Sure. ",
855 "<think>",
856 "plan",
857 "</think>",
858 "{\"name\": \"get_weather\", \"parameters\": {\"city\": \"Paris\"}}",
859 ],
860 true,
861 );
862 assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
863 assert_eq!(t[0].0, "get_weather");
864 assert_eq!(c, "Sure. ");
865 }
866
867 #[test]
869 fn a_marker_that_holds_no_call_is_emitted_as_content() {
870 let (_r, c, t) = run(&["Here: ", "<tool_call>not json</tool_call>"], true);
871 assert!(t.is_empty(), "{t:?}");
872 assert_eq!(c, "Here: <tool_call>not json</tool_call>");
873 }
874
875 #[test]
878 fn reasoning_after_a_held_call_is_not_content() {
879 let (r, c, t) = run(
880 &[
881 "<think>plan</think>",
882 "<tool_call>{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}</tool_call>",
883 "<think>second thoughts</think>",
884 "Done after the call.",
885 ],
886 true,
887 );
888 assert_eq!(t.len(), 1, "{t:?}");
889 assert!(!c.contains("think") && !c.contains("second"), "{c:?}");
890 assert!(c.contains("Done after the call."), "{c:?}");
891 assert!(r.contains("second thoughts"), "{r:?}");
892 }
893
894 #[test]
897 fn an_unparseable_block_beside_a_call_is_shown() {
898 let (_r, c, t) = run(
899 &[
900 "Here: ",
901 "<tool_call>not json</tool_call> and ",
902 "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
903 ],
904 true,
905 );
906 assert_eq!(t.len(), 1, "{t:?}");
907 assert!(c.contains("<tool_call>not json</tool_call>"), "{c:?}");
908 }
909
910 #[test]
912 fn prose_around_a_removed_call_is_not_glued() {
913 let (_r, c, t) = run(
914 &[
915 "Sure.",
916 "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
917 " More text after it.",
918 ],
919 true,
920 );
921 assert_eq!(t.len(), 1, "{t:?}");
922 assert_eq!(c, "Sure. More text after it.");
923 }
924
925 fn deltas(pieces: &[&str]) -> Vec<Delta> {
927 let mut out = Vec::new();
928 let mut s = ChatStream::new(true);
929 for p in pieces {
930 s.push(p, &mut |d| out.push(d));
931 }
932 s.finish(&mut |d| out.push(d));
933 out
934 }
935
936 fn first_at(out: &[Delta], pred: impl Fn(&Delta) -> bool) -> usize {
937 out.iter()
938 .position(pred)
939 .unwrap_or_else(|| panic!("no such delta in {out:?}"))
940 }
941
942 #[test]
945 fn a_held_stretch_settles_in_textual_order() {
946 let out = deltas(&[
947 "<think>plan</think>",
948 "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call> Before.",
949 "<think>second</think>",
950 " After.",
951 ]);
952 let before = first_at(
953 &out,
954 |d| matches!(d, Delta::Content(x) if x.contains("Before")),
955 );
956 let mid = first_at(
957 &out,
958 |d| matches!(d, Delta::Reasoning(x) if x.contains("second")),
959 );
960 let after = first_at(
961 &out,
962 |d| matches!(d, Delta::Content(x) if x.contains("After")),
963 );
964 assert!(before < mid && mid < after, "{out:?}");
965 }
966
967 #[test]
970 fn a_held_lead_in_arrives_before_the_reasoning_after_it() {
971 let out = deltas(&["Hi <tool_call>oops ", "<think>", "plan", "</think>", "done"]);
972 let lead = first_at(
973 &out,
974 |d| matches!(d, Delta::Content(x) if x.contains("oops")),
975 );
976 let think = first_at(&out, |d| matches!(d, Delta::Reasoning(_)));
977 assert!(lead < think, "{out:?}");
978 }
979
980 #[test]
983 fn whitespace_left_by_a_removed_call_is_dropped() {
984 const CALL: &str = "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>";
985 for (pieces, want) in [
986 (vec![CALL, "\n\nI'll check."], "I'll check."),
987 (vec!["A ", CALL, " B"], "A B"),
988 (vec!["A ", CALL, " and ", CALL, " B"], "A and B"),
989 (vec!["I'll check.\n", CALL, "\n"], "I'll check.\n"),
990 ] {
991 let (_r, c, t) = run(&pieces, true);
992 assert!(!t.is_empty(), "{pieces:?}: no call fired");
993 assert_eq!(c, want, "{pieces:?}");
994 }
995 }
996
997 const GOOD_CALL: &str = "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>";
998
999 #[test]
1002 fn a_cut_gap_is_judged_against_the_shown_text() {
1003 let lead = format!("Hi {GOOD_CALL}");
1004 let main = format!("{GOOD_CALL} Done.");
1005 let (_r, c, t) = run(&[&lead, "<think>p</think>", &main], true);
1006 assert_eq!(t.len(), 2, "{t:?}");
1007 assert_eq!(c, "Hi Done.");
1008 }
1009
1010 #[test]
1013 fn a_span_after_reasoning_keeps_its_line_breaks() {
1014 let first = format!("{GOOD_CALL}Before.\n");
1015 let last = format!("\n\nAfter {GOOD_CALL}");
1016 let (_r, c, _t) = run(
1017 &["<think>p</think>", &first, "<think>t</think>", &last],
1018 true,
1019 );
1020 assert_eq!(c, "Before.\n\n\nAfter");
1021 }
1022
1023 #[test]
1026 fn a_lead_in_keeps_the_space_before_later_content() {
1027 let lead = format!("Hi {GOOD_CALL} now ");
1028 let (_r, c, _t) = run(&[&lead, "<think>p</think>", "Done."], true);
1029 assert_eq!(c, "Hi now Done.");
1030 }
1031
1032 #[test]
1035 fn only_the_last_span_of_a_stretch_loses_its_trailing_gap() {
1036 let held = format!("{GOOD_CALL}X {GOOD_CALL}<think>r</think>Y");
1037 let (r, c, t) = run(&["<think>p</think>", &held], true);
1038 assert_eq!(t.len(), 2, "{t:?}");
1039 assert_eq!(r, "pr");
1040 assert_eq!(c, "X Y");
1041 }
1042
1043 #[test]
1046 fn a_reply_with_no_parsed_call_is_byte_identical() {
1047 for pieces in [
1048 &["Here: ", "<tool_call>not json</tool_call>", "\n\n "][..],
1049 &["{not a call} \n", "<think>p</think>", " ok "][..],
1050 &["Hi <tool_call>oops\n\n", "<think>p</think>", "\n done"][..],
1051 ] {
1052 let want: String = pieces
1053 .iter()
1054 .map(|p| {
1055 p.split("<think>").next().unwrap_or_default().to_owned()
1056 + p.split("</think>").nth(1).unwrap_or_default()
1057 })
1058 .collect();
1059 let (_r, c, t) = run(pieces, true);
1060 assert!(t.is_empty(), "{t:?}");
1061 assert_eq!(c, want, "{pieces:?}");
1062 }
1063 }
1064
1065 #[test]
1067 fn mixed_dialect_calls_all_fire() {
1068 let (_r, c, t) = run(
1069 &[
1070 "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
1071 "<|tool_call>call:get_weather{city:<|\"|>Paris<|\"|>}<tool_call|>",
1072 ],
1073 true,
1074 );
1075 let names: Vec<&str> = t.iter().map(|(n, _)| n.as_str()).collect();
1076 assert_eq!(names, ["run_bash", "get_weather"]);
1077 assert!(!c.contains("tool_call"), "{c:?}");
1078 }
1079
1080 #[test]
1081 fn leading_brace_non_call_survives_as_content() {
1082 let (_r, c, t) = run(
1084 &["{not json here, just prose that opens with a brace}"],
1085 true,
1086 );
1087 assert!(t.is_empty(), "non-call misparsed: {t:?}");
1088 assert!(c.contains("not json here"), "content dropped: {c:?}");
1089 }
1090}