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 {
22 name: String,
23 arguments: String,
24 },
25 Logprob(crate::TokenLogprob),
30}
31
32pub struct ChatStream {
40 raw: String,
41 sent_r: usize, sent_c: usize, lead: Option<(usize, usize)>,
47 sent_lead: usize,
48 shown_gap: Option<String>,
51 allow_tools: bool,
52 cur_think_open: Cursor,
56 cur_think_close: Cursor,
57 cur_tool: Cursor, cur_pipe: Cursor, cur_final: Cursor, bare: BareJson,
61 logprobs: Vec<TokenSpan>,
63}
64
65#[derive(Clone, Debug)]
68struct TokenSpan {
69 start: usize,
70 end: usize,
71 lps: Vec<crate::TokenLogprob>,
72}
73
74#[derive(Default)]
78struct BareJson {
79 cs: Option<usize>, scanned: usize,
81 head: BareHead,
82 depth: usize,
83 in_str: bool,
84 esc: bool,
85}
86
87#[derive(Default, Clone, Copy, PartialEq)]
88enum BareHead {
89 #[default]
91 Pending,
92 Open(usize),
94 Call(usize),
96 No,
98}
99
100impl BareJson {
101 fn open(&mut self, raw: &str, cs: usize) -> Option<usize> {
103 if self.cs != Some(cs) {
104 *self = Self {
105 cs: Some(cs),
106 scanned: cs,
107 ..Self::default()
108 };
109 }
110 let bytes = raw.as_bytes();
111 while self.scanned < bytes.len() {
112 let i = self.scanned;
113 let b = bytes[i];
114 self.scanned += 1;
115 match self.head {
116 BareHead::Pending => match b {
117 b' ' | b'\n' | b'\t' | b'\r' => {}
118 b'{' => {
119 self.head = BareHead::Open(i);
120 self.depth = 1;
121 }
122 _ => self.head = BareHead::No,
123 },
124 BareHead::Open(start) => {
125 if self.in_str {
126 match b {
127 _ if self.esc => self.esc = false,
128 b'\\' => self.esc = true,
129 b'"' => self.in_str = false,
130 _ => {}
131 }
132 } else {
133 match b {
134 b'"' => self.in_str = true,
135 b'{' => self.depth += 1,
136 b'}' => {
137 self.depth -= 1;
138 if self.depth == 0 {
139 let call = crate::tools::parse_bare_json_call(&raw[start..=i]);
142 self.head = if call.is_some() {
143 BareHead::Call(start)
144 } else {
145 BareHead::No
146 };
147 }
148 }
149 _ => {}
150 }
151 }
152 }
153 BareHead::Call(_) | BareHead::No => {
154 self.scanned = bytes.len();
155 }
156 }
157 }
158 match self.head {
159 BareHead::Open(i) | BareHead::Call(i) => Some(i),
160 BareHead::Pending | BareHead::No => None,
161 }
162 }
163}
164
165#[derive(Default)]
169struct Cursor {
170 off: Option<usize>,
171 scanned: usize,
172}
173
174impl Cursor {
175 fn find(&mut self, raw: &str, needle: &str) -> Option<usize> {
176 self.find_from(raw, needle, 0)
177 }
178
179 fn find_from(&mut self, raw: &str, needle: &str, from: usize) -> Option<usize> {
183 match self.off {
184 Some(p) if p >= from => return Some(p),
185 Some(_) => {
186 self.off = None;
187 self.scanned = from;
188 }
189 None => {}
190 }
191 let mut start = self
192 .scanned
193 .saturating_sub(needle.len().saturating_sub(1))
194 .max(from);
195 while start > from && !raw.is_char_boundary(start) {
196 start -= 1;
197 }
198 if let Some(p) = raw[start..].find(needle) {
199 self.off = Some(start + p);
200 }
201 self.scanned = raw.len();
202 self.off
203 }
204}
205
206impl ChatStream {
207 pub fn new(allow_tools: bool) -> Self {
208 Self {
209 raw: String::new(),
210 sent_r: 0,
211 sent_c: 0,
212 lead: None,
213 sent_lead: 0,
214 shown_gap: None,
215 allow_tools,
216 cur_think_open: Cursor::default(),
217 cur_think_close: Cursor::default(),
218 cur_tool: Cursor::default(),
219 cur_pipe: Cursor::default(),
220 cur_final: Cursor::default(),
221 bare: BareJson::default(),
222 logprobs: Vec::new(),
223 }
224 }
225
226 pub fn push_with_logprobs(
234 &mut self,
235 piece: &str,
236 logprobs: Vec<crate::TokenLogprob>,
237 on_delta: &mut dyn FnMut(Delta),
238 ) {
239 let start = self.raw.len();
240 self.raw.push_str(piece);
241 if !logprobs.is_empty() && !piece.is_empty() {
242 self.logprobs.push(TokenSpan {
243 start,
244 end: self.raw.len(),
245 lps: logprobs,
246 });
247 }
248 self.emit(false, on_delta);
249 }
250
251 #[cfg(test)]
253 fn queued_logprobs(&self) -> usize {
254 self.logprobs.len()
255 }
256
257 pub fn push(&mut self, piece: &str, on_delta: &mut dyn FnMut(Delta)) {
258 self.raw.push_str(piece);
259 self.emit(false, on_delta);
260 }
261
262 pub fn finish(&mut self, on_delta: &mut dyn FnMut(Delta)) {
266 self.emit(true, on_delta);
267 self.logprobs.clear();
269 }
270
271 fn tool_open_at(&mut self, cs: usize, final_flush: bool) -> Option<usize> {
277 if !self.allow_tools {
278 return None;
279 }
280 const TL: &str = "<tool_call>";
281 const PIPE: &str = "<|tool_call>";
282 let hermes = self.cur_tool.find_from(&self.raw, TL, cs);
283 let pipe = self.cur_pipe.find_from(&self.raw, PIPE, cs);
284 let bare = self.bare_json_open(cs, final_flush);
285 [hermes, pipe, bare].into_iter().flatten().min()
286 }
287
288 fn bare_json_open(&mut self, cs: usize, final_flush: bool) -> Option<usize> {
296 let i = self.bare.open(&self.raw, cs)?;
297 if final_flush && crate::tools::parse_bare_json_call(&self.raw[i..]).is_none() {
298 return None; }
300 Some(i)
301 }
302
303 fn emit(&mut self, final_flush: bool, on_delta: &mut dyn FnMut(Delta)) {
304 let mut logprobs = std::mem::take(&mut self.logprobs);
305 self.emit_with(final_flush, on_delta, &mut logprobs);
306 self.logprobs = logprobs;
307 }
308
309 fn emit_with(
310 &mut self,
311 final_flush: bool,
312 on_delta: &mut dyn FnMut(Delta),
313 logprobs: &mut Vec<TokenSpan>,
314 ) {
315 const TO: &str = "<think>";
316 const TC: &str = "</think>";
317 const FINAL: &str = "<channel|>";
321 if let Some(hm) = channel_thought_head(&self.raw) {
322 let (r_end, hold, c_start) = match self.cur_final.find(&self.raw, FINAL) {
323 Some(f) => (f, false, Some(f + FINAL.len())),
324 None => (self.raw.len(), !final_flush, None),
325 };
326 emit_region(
327 &self.raw,
328 hm,
329 r_end,
330 hold,
331 &mut self.sent_r,
332 true,
333 on_delta,
334 logprobs,
335 );
336 if let Some(cs) = c_start {
337 self.emit_content(cs, final_flush, on_delta, logprobs);
338 }
339 return;
340 }
341 if !final_flush
342 && CHANNEL_THOUGHT.iter().any(|m| {
343 m.as_bytes()
344 .starts_with(&self.raw.as_bytes()[..self.raw.len().min(m.len())])
345 })
346 && self.raw.len() < CHANNEL_THOUGHT[0].len()
347 {
348 return; }
350 let think_open = self.cur_think_open.find(&self.raw, TO);
351 let think_close =
355 think_open.and_then(|to| self.cur_think_close.find_from(&self.raw, TC, to + TO.len()));
356 let lead = think_open.map(|to| match self.lead {
360 Some(lead) => lead,
361 None => {
362 self.sent_lead = std::mem::take(&mut self.sent_c);
363 let stop = match to {
366 0 => 0,
367 _ => self.tool_open_at(0, false).map_or(to, |t| t.min(to)),
368 };
369 self.lead = Some((stop, to));
370 (stop, to)
371 }
372 });
373 if let Some((stop, end)) = lead {
374 let unsent = self.sent_lead < end;
375 let from = self.sent_lead;
376 emit_region(
377 &self.raw,
378 0,
379 stop,
380 false,
381 &mut self.sent_lead,
382 false,
383 on_delta,
384 logprobs,
385 );
386 note_shown(&mut self.shown_gap, &self.raw[from..self.sent_lead]);
387 if unsent && stop < end {
391 settle_held(
392 &self.raw[stop..end],
393 &mut self.shown_gap,
394 false,
395 on_delta,
396 logprobs,
397 stop,
398 );
399 self.sent_lead = end;
400 }
401 }
402 if let Some(to) = think_open {
404 let rs = to + TO.len();
405 let (r_end, hold) = match think_close {
406 Some(tc) => (tc, false),
407 None => (self.raw.len(), !final_flush),
408 };
409 emit_region(
410 &self.raw,
411 rs,
412 r_end,
413 hold,
414 &mut self.sent_r,
415 true,
416 on_delta,
417 logprobs,
418 );
419 }
420 let c_start = match think_close {
423 Some(tc) => Some(tc + TC.len()),
424 None if think_open.is_none() => Some(0),
425 None => None,
426 };
427 if let Some(cs) = c_start {
428 self.emit_content(cs, final_flush, on_delta, logprobs);
429 }
430 }
431
432 fn emit_content(
435 &mut self,
436 cs: usize,
437 final_flush: bool,
438 on_delta: &mut dyn FnMut(Delta),
439 logprobs: &mut Vec<TokenSpan>,
440 ) {
441 let tool_open = self.tool_open_at(cs, final_flush).filter(|&t| t >= cs);
442 let (c_end, hold) = match tool_open {
443 Some(t) => (t, false),
444 None => (self.raw.len(), !final_flush),
445 };
446 let from = cs + self.sent_c;
447 emit_region(
448 &self.raw,
449 cs,
450 c_end,
451 hold,
452 &mut self.sent_c,
453 false,
454 on_delta,
455 logprobs,
456 );
457 note_shown(&mut self.shown_gap, &self.raw[from..cs + self.sent_c]);
458 if let (true, Some(t)) = (final_flush, tool_open) {
459 settle_held(
460 &self.raw[t..],
461 &mut self.shown_gap,
462 true,
463 on_delta,
464 logprobs,
465 t,
466 );
467 }
468 }
469}
470
471fn settle_held(
484 held: &str,
485 shown_gap: &mut Option<String>,
486 at_end: bool,
487 on_delta: &mut dyn FnMut(Delta),
488 logprobs: &mut Vec<TokenSpan>,
489 base: usize,
490) {
491 let mut fired = Vec::new();
492 let spans = reasoning_spans(held);
493 let last_text = spans.iter().rposition(|s| matches!(s, Span::Text(..)));
495 for (i, span) in spans.into_iter().enumerate() {
496 let (at, text) = match span {
497 Span::Reasoning(r) => {
498 if !r.is_empty() {
499 on_delta(Delta::Reasoning(r.to_owned()));
500 }
501 continue;
502 }
503 Span::Text(off, t) => (base + off, t),
504 };
505 let (clean, calls) = if logprobs.is_empty() {
509 let (clean, calls) = crate::tools::parse_any_tool_calls_traced::<()>(text);
510 (
511 crate::tools::Traced {
512 text: clean.text,
513 origin: crate::tools::Origins::new(),
514 },
515 calls,
516 )
517 } else {
518 crate::tools::parse_any_tool_calls_traced::<crate::tools::Origins>(text)
519 };
520 let content = if calls.is_empty() {
521 if !text.is_empty() {
523 emit_logprobs(
524 logprobs,
525 |s| s.start < at + text.len() && s.end > at,
526 on_delta,
527 );
528 }
529 text
530 } else {
531 let (opens_with_cut, closes_with_cut) = cut_edges(text, &clean.text);
532 let (mut lo, mut hi) = (0, clean.text.len());
533 if opens_with_cut {
534 let rest = clean.text.trim_start();
535 let gap = &clean.text[..clean.text.len() - rest.len()];
536 let keep = match shown_gap.as_deref() {
537 None => false,
538 Some("") => true,
539 Some(shown) => gap.contains('\n') && !shown.contains('\n'),
540 };
541 if !keep {
542 lo = gap.len();
543 }
544 }
545 if at_end && closes_with_cut && Some(i) == last_text {
546 hi = lo + clean.text[lo..].trim_end().len();
547 }
548 let kept: Vec<usize> = clean
552 .origin
553 .get(lo..hi)
554 .unwrap_or_default()
555 .iter()
556 .flatten()
557 .map(|&o| at + o)
558 .collect();
559 if !kept.is_empty() {
560 emit_logprobs(
561 logprobs,
562 |s| {
564 kept.get(kept.partition_point(|&o| o < s.start))
565 .is_some_and(|&o| o < s.end)
566 },
567 on_delta,
568 );
569 }
570 &clean.text[lo..hi]
571 };
572 if !content.is_empty() {
573 note_shown(shown_gap, content);
574 on_delta(Delta::Content(content.to_owned()));
575 }
576 fired.extend(calls);
577 }
578 let end = base + held.len();
581 logprobs.retain(|s| s.start < base || s.end > end);
582 for call in fired {
583 on_delta(Delta::ToolCall {
584 name: call.name,
585 arguments: serde_json::to_string(&call.arguments).unwrap_or_else(|_| "{}".to_string()),
586 });
587 }
588}
589
590fn cut_edges(text: &str, clean: &str) -> (bool, bool) {
593 let head = text
594 .char_indices()
595 .zip(clean.chars())
596 .find(|((_, a), b)| a != b)
597 .map_or(clean.len().min(text.len()), |((i, _), _)| i);
598 let tail = text
599 .char_indices()
600 .rev()
601 .zip(clean.chars().rev())
602 .find(|((_, a), b)| a != b)
603 .map_or(text.len() - clean.len().min(text.len()), |((i, a), _)| {
604 i + a.len_utf8()
605 });
606 (
607 text[..head].trim().is_empty(),
608 text[tail..].trim().is_empty(),
609 )
610}
611
612fn note_shown(gap: &mut Option<String>, text: &str) {
614 if text.is_empty() {
615 return;
616 }
617 let word = text.trim_end();
618 if word.is_empty() {
619 gap.get_or_insert_with(String::new).push_str(text);
620 } else {
621 *gap = Some(text[word.len()..].to_owned());
622 }
623}
624
625enum Span<'a> {
628 Text(usize, &'a str),
629 Reasoning(&'a str),
630}
631
632fn reasoning_spans(text: &str) -> Vec<Span<'_>> {
634 const TO: &str = "<think>";
635 const TC: &str = "</think>";
636 let mut out = Vec::new();
637 let mut at = 0;
638 while let Some(o) = text[at..].find(TO) {
639 out.push(Span::Text(at, &text[at..at + o]));
640 let inner = at + o + TO.len();
641 let Some(c) = text[inner..].find(TC) else {
642 out.push(Span::Reasoning(&text[inner..]));
643 return out;
644 };
645 out.push(Span::Reasoning(&text[inner..inner + c]));
646 at = inner + c + TC.len();
647 }
648 out.push(Span::Text(at, &text[at..]));
649 out
650}
651
652const CHANNEL_THOUGHT: [&str; 2] = ["<|channel|>thought", "<|channel>thought"];
655
656fn channel_thought_head(raw: &str) -> Option<usize> {
660 CHANNEL_THOUGHT
661 .iter()
662 .find_map(|m| raw.starts_with(m).then_some(m.len()))
663}
664
665fn emit_logprobs(
668 logprobs: &mut Vec<TokenSpan>,
669 in_content: impl Fn(&TokenSpan) -> bool,
670 on_delta: &mut dyn FnMut(Delta),
671) {
672 logprobs.retain_mut(|s| {
673 if in_content(s) {
674 for lp in s.lps.drain(..) {
675 on_delta(Delta::Logprob(lp));
676 }
677 false
678 } else {
679 true
680 }
681 });
682}
683
684#[allow(clippy::too_many_arguments)]
688fn emit_region(
689 raw: &str,
690 region_start: usize,
691 region_end: usize,
692 hold: bool,
693 sent: &mut usize,
694 reasoning: bool,
695 on_delta: &mut dyn FnMut(Delta),
696 logprobs: &mut Vec<TokenSpan>,
697) {
698 const HOLD: usize = 12; let abs = region_start + *sent;
700 if abs >= region_end {
701 return;
702 }
703 let mut end = if hold {
704 region_end.saturating_sub(HOLD).max(abs)
705 } else {
706 region_end
707 };
708 if !reasoning && !(!hold && end == region_end) {
713 if let Some(s) = logprobs.iter().find(|s| s.start < end && s.end > end) {
714 if s.start <= abs {
715 return;
716 }
717 end = s.start;
718 }
719 }
720 while end > abs && !raw.is_char_boundary(end) {
721 end -= 1;
722 }
723 if end <= abs {
724 return;
725 }
726 if reasoning {
727 logprobs.retain(|s| s.start < region_start || s.end > end);
730 } else {
731 emit_logprobs(logprobs, |s| s.start < end && s.end > abs, on_delta);
732 }
733 let text = &raw[abs..end];
734 if text.is_empty() {
735 return;
736 }
737 on_delta(if reasoning {
738 Delta::Reasoning(text.to_owned())
739 } else {
740 Delta::Content(text.to_owned())
741 });
742 *sent += text.len();
743}
744
745#[cfg(test)]
746mod chat_stream_tests {
747 use super::*;
748
749 fn run(pieces: &[&str], allow_tools: bool) -> (String, String, Vec<(String, String)>) {
751 let mut out: Vec<Delta> = Vec::new();
752 let mut s = ChatStream::new(allow_tools);
753 {
754 let mut od = |d: Delta| out.push(d);
755 for p in pieces {
756 s.push(p, &mut od);
757 }
758 }
759 s.finish(&mut |d: Delta| out.push(d));
760 let (mut r, mut c, mut t) = (String::new(), String::new(), Vec::new());
761 for d in &out {
762 match d {
763 Delta::Reasoning(x) => r.push_str(x),
764 Delta::Content(x) => c.push_str(x),
765 Delta::ToolCall { name, arguments } => t.push((name.clone(), arguments.clone())),
766 Delta::Logprob(_) => {}
767 }
768 }
769 (r, c, t)
770 }
771
772 #[test]
773 fn logprobs_ride_the_token_aligned_content_chunks() {
774 fn lp(c: char) -> crate::TokenLogprob {
775 crate::TokenLogprob {
776 token: c as u32,
777 text: c.to_string(),
778 bytes: c.to_string().into_bytes(),
779 logprob: -0.5,
780 top: Vec::new(),
781 }
782 }
783 let mut out: Vec<Delta> = Vec::new();
784 let mut s = ChatStream::new(false);
785 for c in "abcdefghijklmnop".chars() {
786 s.push_with_logprobs(&c.to_string(), vec![lp(c)], &mut |d| out.push(d));
787 }
788 s.finish(&mut |d| out.push(d));
789
790 let mut queued: Vec<String> = Vec::new();
791 let mut content = String::new();
792 for d in out {
793 match d {
794 Delta::Logprob(lp) => queued.push(lp.text),
795 Delta::Content(text) => {
796 assert_eq!(
797 queued.len(),
798 text.chars().count(),
799 "chunk {text:?} has {queued:?}"
800 );
801 for (lp, c) in queued.drain(..).zip(text.chars()) {
802 assert_eq!(lp, c.to_string());
803 }
804 content.push_str(&text);
805 }
806 other => panic!("unexpected {other:?}"),
807 }
808 }
809 assert_eq!(content, "abcdefghijklmnop");
810 assert!(queued.is_empty());
811 }
812
813 fn content_chunks(pieces: &[(&str, u32)], allow_tools: bool) -> Vec<(String, Vec<u32>)> {
817 let mut out: Vec<Delta> = Vec::new();
818 let mut s = ChatStream::new(allow_tools);
819 for &(piece, id) in pieces {
820 let lp = crate::TokenLogprob {
821 token: id,
822 text: piece.to_owned(),
823 bytes: piece.as_bytes().to_vec(),
824 logprob: -1.0,
825 top: Vec::new(),
826 };
827 s.push_with_logprobs(piece, vec![lp], &mut |d| out.push(d));
828 }
829 s.finish(&mut |d| out.push(d));
830 let mut chunks = Vec::new();
831 let mut queued = Vec::new();
832 for d in out {
833 match d {
834 Delta::Logprob(lp) => queued.push(lp.token),
835 Delta::Content(text) => chunks.push((text, std::mem::take(&mut queued))),
836 other => assert!(queued.is_empty(), "{queued:?} rode {other:?}"),
837 }
838 }
839 assert!(queued.is_empty(), "{queued:?} were left with no content");
840 chunks
841 }
842
843 #[test]
847 fn logprobs_cover_the_answer_and_not_the_reasoning() {
848 let chunks = content_chunks(
849 &[
850 ("<think>", 1),
851 ("\nhmm", 2),
852 ("</think>", 3),
853 ("\n\nYes", 4),
854 (", it", 5),
855 (" is.", 6),
856 ],
857 false,
858 );
859 let ids: Vec<u32> = chunks.iter().flat_map(|c| c.1.clone()).collect();
860 assert_eq!(ids, [4, 5, 6]);
861 let text: String = chunks.iter().map(|c| c.0.as_str()).collect();
862 assert_eq!(text, "\n\nYes, it is.");
863 for (text, ids) in &chunks {
864 assert!(!ids.is_empty(), "{text:?} has no entries");
865 }
866 }
867
868 #[test]
872 fn prose_around_parsed_calls_keeps_its_entries() {
873 const CALL: &str = "{\"name\": \"f\", \"arguments\": {}}";
874 let chunks = content_chunks(
875 &[
876 ("A", 1),
877 ("<tool_call>", 2),
878 (CALL, 3),
879 ("</tool_call>", 4),
880 (" then", 5),
881 ("<tool_call>", 6),
882 (CALL, 7),
883 ("</tool_call>", 8),
884 (" done.", 9),
885 ],
886 true,
887 );
888 assert_eq!(
889 chunks,
890 [
891 ("A".to_owned(), vec![1]),
892 (" then done.".to_owned(), vec![5, 9])
893 ]
894 );
895
896 let chunks = content_chunks(
899 &[
900 ("<tool_call>", 1),
901 (CALL, 2),
902 ("</tool_call>", 3),
903 ("\n", 4),
904 ("Done", 5),
905 (".", 6),
906 ],
907 true,
908 );
909 assert_eq!(chunks, [("Done.".to_owned(), vec![5, 6])]);
910 }
911
912 #[test]
915 fn a_group_past_a_settled_stretch_keeps_its_entry() {
916 let chunks = content_chunks(
917 &[
918 ("Hi ", 1),
919 ("<tool_call>", 2),
920 ("{\"name\": \"f\", \"arguments\": {}}", 3),
921 ("</tool_call><think>r</think>Done", 4),
922 ],
923 true,
924 );
925 assert_eq!(
926 chunks,
927 [("Hi ".to_owned(), vec![1]), ("Done".to_owned(), vec![4])]
928 );
929 }
930
931 #[test]
934 fn reasoning_entries_do_not_pile_up() {
935 let lp = |id: u32, text: &str| crate::TokenLogprob {
936 token: id,
937 text: text.to_owned(),
938 bytes: text.as_bytes().to_vec(),
939 logprob: -1.0,
940 top: Vec::new(),
941 };
942 let mut s = ChatStream::new(false);
943 let mut out = Vec::new();
944 s.push_with_logprobs("<think>", vec![lp(0, "<think>")], &mut |d| out.push(d));
945 let mut most = 0;
946 for i in 1..=2000 {
947 s.push_with_logprobs("word ", vec![lp(i, "word ")], &mut |d| out.push(d));
948 most = most.max(s.queued_logprobs());
949 }
950 assert!(most <= 5, "the queue reached {most}");
952 s.push_with_logprobs("</think>", vec![lp(9000, "</think>")], &mut |d| out.push(d));
953 s.push_with_logprobs("Answer", vec![lp(9001, "Answer")], &mut |d| out.push(d));
954 s.finish(&mut |d| out.push(d));
955 let ids: Vec<u32> = out
956 .iter()
957 .filter_map(|d| match d {
958 Delta::Logprob(lp) => Some(lp.token),
959 _ => None,
960 })
961 .collect();
962 assert_eq!(ids, [9001]);
963 }
964
965 #[test]
968 fn a_stray_closer_after_streamed_content_does_not_panic() {
969 let (r, c, _) = run(&["abcdefghijklmnopqrstuvwxyz", "</think>"], false);
970 assert_eq!(r, "");
971 assert_eq!(c, "abcdefghijklmnopqrstuvwxyz</think>");
972 }
973
974 #[test]
977 fn output_does_not_depend_on_chunking() {
978 let replies = [
979 "abcdefghijklmnopqrstuvwxyz</think>",
980 "abc</think>def",
981 "x</think>y<think>r</think>z",
982 "</think></think>a",
983 "<think>r</think>a</think>b",
984 "lead</think> <think>think</think>\n\nanswer",
985 "Hi <tool_call>{\"name\": \"f\", \"arguments\": {}}</tool_call></think>done",
986 "<think>why</think>\n\n{\"name\": \"f\", \"arguments\": {}}",
987 ];
988 fn feed(pieces: &[&str], tools: bool, entries: bool) -> (String, String, String) {
989 let mut out = Vec::new();
990 let mut s = ChatStream::new(tools);
991 for (i, p) in pieces.iter().enumerate() {
992 let lps = if entries {
993 vec![crate::TokenLogprob {
994 token: i as u32,
995 text: p.to_string(),
996 bytes: p.as_bytes().to_vec(),
997 logprob: -1.0,
998 top: Vec::new(),
999 }]
1000 } else {
1001 Vec::new()
1002 };
1003 s.push_with_logprobs(p, lps, &mut |d| out.push(d));
1004 }
1005 s.finish(&mut |d| out.push(d));
1006 let (mut r, mut c, mut t) = (String::new(), String::new(), String::new());
1007 for d in out {
1008 match d {
1009 Delta::Reasoning(x) => r.push_str(&x),
1010 Delta::Content(x) => c.push_str(&x),
1011 Delta::ToolCall { name, arguments } => {
1012 t.push_str(&format!("{name}{arguments};"))
1013 }
1014 Delta::Logprob(_) => {}
1015 }
1016 }
1017 (r, c, t)
1018 }
1019 let mut state = 0x2545_F491_4F6C_DD1Du64;
1020 for reply in replies {
1021 let chars: Vec<(usize, char)> = reply.char_indices().collect();
1022 let bytewise: Vec<&str> = chars
1023 .iter()
1024 .map(|&(i, ch)| &reply[i..i + ch.len_utf8()])
1025 .collect();
1026 let mut uneven = Vec::new();
1027 let mut at = 0;
1028 while at < reply.len() {
1029 state ^= state << 13;
1030 state ^= state >> 7;
1031 state ^= state << 17;
1032 let mut end = (at + 1 + (state % 7) as usize).min(reply.len());
1033 while !reply.is_char_boundary(end) {
1034 end += 1;
1035 }
1036 uneven.push(&reply[at..end]);
1037 at = end;
1038 }
1039 for tools in [false, true] {
1040 for entries in [false, true] {
1041 let whole = feed(&[reply], tools, entries);
1042 assert_eq!(
1043 feed(&bytewise, tools, entries),
1044 whole,
1045 "{reply:?} char by char, tools {tools}, entries {entries}"
1046 );
1047 assert_eq!(
1048 feed(&uneven, tools, entries),
1049 whole,
1050 "{reply:?} in {uneven:?}, tools {tools}, entries {entries}"
1051 );
1052 }
1053 }
1054 }
1055 }
1056
1057 #[test]
1060 fn logprobs_follow_settled_text_and_skip_parsed_calls() {
1061 let chunks = content_chunks(&[("Hi ", 1), ("<tool_call>", 2), ("oops", 3)], true);
1062 let ids: Vec<u32> = chunks.iter().flat_map(|c| c.1.clone()).collect();
1063 assert_eq!(ids, [1, 2, 3]);
1064 let text: String = chunks.iter().map(|c| c.0.as_str()).collect();
1065 assert_eq!(text, "Hi <tool_call>oops");
1066
1067 let chunks = content_chunks(
1068 &[
1069 ("Sure", 1),
1070 ("<tool_call>", 2),
1071 ("{\"name\": \"f\", \"arguments\": {}}", 3),
1072 ("</tool_call>", 4),
1073 ],
1074 true,
1075 );
1076 assert_eq!(chunks, [("Sure".to_owned(), vec![1])]);
1077 }
1078
1079 #[test]
1080 fn streams_channel_thought_then_final() {
1081 let (r, c, t) = run(
1084 &[
1085 "<|channel>th",
1086 "ought\nreaso",
1087 "ning<chan",
1088 "nel|>the answer",
1089 ],
1090 false,
1091 );
1092 assert_eq!(r.trim(), "reasoning");
1093 assert_eq!(c.trim(), "the answer");
1094 assert!(t.is_empty());
1095 }
1096
1097 #[test]
1098 fn prefilled_think_via_injected_opener() {
1099 let (r, c, t) = run(&["<think>", "reasoning here", "</think>", "answer"], false);
1102 assert_eq!(r.trim(), "reasoning here");
1103 assert_eq!(c.trim(), "answer");
1104 assert!(t.is_empty());
1105 }
1106
1107 #[test]
1108 fn streams_think_then_content() {
1109 let (r, c, t) = run(
1110 &["<think>", "reason", "ing", "</think>", "the ", "answer"],
1111 true,
1112 );
1113 assert_eq!(r.trim(), "reasoning");
1114 assert_eq!(c.trim(), "the answer");
1115 assert!(t.is_empty());
1116 }
1117
1118 #[test]
1119 fn plain_content_no_think() {
1120 let (r, c, _) = run(&["hello ", "world, this is a longer reply"], true);
1121 assert!(r.trim().is_empty());
1122 assert_eq!(c.trim(), "hello world, this is a longer reply");
1123 }
1124
1125 #[test]
1126 fn tool_call_buffered_and_parsed() {
1127 let (r, _c, t) = run(
1128 &[
1129 "<think>plan</think>",
1130 "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>",
1131 ],
1132 true,
1133 );
1134 assert_eq!(r.trim(), "plan");
1135 assert_eq!(t.len(), 1);
1136 assert_eq!(t[0].0, "run_bash");
1137 assert!(t[0].1.contains("ls"));
1138 }
1139
1140 #[test]
1141 fn tool_choice_none_keeps_tool_text_as_content() {
1142 let (_r, c, t) = run(&["<tool_call>{\"name\":\"x\"}</tool_call>"], false);
1144 assert!(t.is_empty());
1145 assert!(c.contains("tool_call"));
1146 }
1147
1148 #[test]
1149 fn pipe_form_tool_call_not_streamed_as_content() {
1150 let (_r, c, t) = run(
1153 &[
1154 "<|tool_",
1155 "call>call:get_weather{city:<|\"|>Par",
1156 "is<|\"|>}",
1157 "<tool_call|>",
1158 ],
1159 true,
1160 );
1161 assert!(
1162 !c.contains("tool_call") && !c.contains("get_weather"),
1163 "pipe markup leaked as content: {c:?}"
1164 );
1165 assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
1166 assert_eq!(t[0].0, "get_weather");
1167 }
1168
1169 #[test]
1170 fn bare_json_tool_call_not_streamed_as_content() {
1171 let (_r, c, t) = run(
1173 &[
1174 "{\"name\": \"get_weather\", ",
1175 "\"parameters\": {\"city\": \"Paris\"}}",
1176 ],
1177 true,
1178 );
1179 assert!(c.trim().is_empty(), "bare json leaked as content: {c:?}");
1180 assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
1181 assert_eq!(t[0].0, "get_weather");
1182 }
1183
1184 #[test]
1185 fn content_with_stray_brace_not_swallowed() {
1186 let (_r, c, t) = run(
1188 &[
1189 "The config is {",
1190 "\"a\": 1} and that is the whole story here, nothing more.",
1191 ],
1192 true,
1193 );
1194 assert!(t.is_empty(), "stray brace misparsed as tool call: {t:?}");
1195 assert!(c.contains("The config is"), "content lost: {c:?}");
1196 assert!(c.contains("whole story"), "content truncated: {c:?}");
1197 }
1198
1199 #[test]
1202 fn tool_marker_in_reasoning_does_not_hide_the_real_call() {
1203 let call = "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>";
1204 for pipe in [false, true] {
1205 let (mention, real) = if pipe {
1206 (
1207 "I could emit <|tool_call> here",
1208 "<|tool_call>call:run_bash{command:<|\"|>ls<|\"|>}<tool_call|>",
1209 )
1210 } else {
1211 ("I could emit <tool_call> here", call)
1212 };
1213 let pieces = ["<think>", mention, "</think>", "Sure. ", real];
1214 let (_r, c, t) = run(&pieces, true);
1215 assert!(
1216 !c.contains("run_bash"),
1217 "the call streamed as content: {c:?}"
1218 );
1219 assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
1220 assert_eq!(t[0].0, "run_bash");
1221 }
1222 }
1223
1224 #[test]
1227 fn tool_call_in_channel_reasoning_is_not_a_call() {
1228 let (r, c, t) = run(
1229 &[
1230 "<|channel>thought\nmaybe <|tool_call>call:get_weather{city:<|\"|>Paris<|\"|>}",
1231 "<tool_call|> but no<channel|>It is sunny.",
1232 ],
1233 true,
1234 );
1235 assert!(r.contains("maybe"), "reasoning lost: {r:?}");
1236 assert_eq!(c.trim(), "It is sunny.");
1237 assert!(t.is_empty(), "a call quoted in the reasoning fired: {t:?}");
1238 }
1239
1240 #[test]
1244 fn a_quoted_channel_marker_does_not_switch_formats() {
1245 let (_r, c, t) = run(
1246 &[
1247 "<think>plan</think>",
1248 "The <|channel> marker is how E2B splits. ",
1249 "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>",
1250 ],
1251 true,
1252 );
1253 assert!(c.contains("<|channel> marker"), "content lost: {c:?}");
1254 assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
1255 assert_eq!(t[0].0, "run_bash");
1256 }
1257
1258 #[test]
1262 fn a_leading_json_answer_streams_before_finish() {
1263 let pieces = [
1264 "{\"a\": [1, ",
1265 "2], \"b\": \"x} \\\"q\\\" {\"}",
1266 " and the prose after it keeps coming",
1267 " for a while longer.",
1268 ];
1269 let mut s = ChatStream::new(true);
1270 let mut streamed = String::new();
1271 for p in pieces {
1272 s.push(p, &mut |d| {
1273 if let Delta::Content(x) = d {
1274 streamed.push_str(&x)
1275 }
1276 });
1277 }
1278 assert!(
1279 streamed.starts_with("{\"a\": [1, 2], \"b\": \"x} \\\"q\\\" {\"}"),
1280 "the object was not streamed before finish: {streamed:?}"
1281 );
1282 let (_r, c, t) = run(&pieces, true);
1283 assert!(t.is_empty(), "a plain object fired as a call: {t:?}");
1284 assert_eq!(c, pieces.concat());
1285 }
1286
1287 #[test]
1290 fn content_before_a_late_think_is_streamed() {
1291 let pieces = [
1292 "Sure, let me check. ",
1293 "<think>",
1294 "plan",
1295 "</think>",
1296 "It is 4.",
1297 ];
1298 let mut out = Vec::new();
1299 let mut s = ChatStream::new(false);
1300 for p in pieces {
1301 s.push(p, &mut |d| out.push(d));
1302 }
1303 s.finish(&mut |d| out.push(d));
1304 let lead = out
1305 .iter()
1306 .position(|d| matches!(d, Delta::Content(x) if x.contains("check.")));
1307 let think = out.iter().position(|d| matches!(d, Delta::Reasoning(_)));
1308 assert!(
1309 lead < think && lead.is_some(),
1310 "lead missing or late: {out:?}"
1311 );
1312 let (r, c, _) = run(&pieces, false);
1313 assert_eq!(r, "plan");
1314 assert_eq!(c, "Sure, let me check. It is 4.");
1315 }
1316
1317 #[test]
1321 fn a_held_lead_in_that_is_no_call_is_emitted_in_order() {
1322 for (pieces, want) in [
1323 (
1324 &[
1325 "{not a call} so ",
1326 "<think>",
1327 "plan",
1328 "</think>",
1329 "an answer long enough to stream",
1330 ][..],
1331 "{not a call} so an answer long enough to stream",
1332 ),
1333 (
1334 &[
1335 "Hi <tool_call>oops ",
1336 "<think>",
1337 "plan",
1338 "</think>",
1339 "done, and more after that",
1340 ][..],
1341 "Hi <tool_call>oops done, and more after that",
1342 ),
1343 ] {
1344 let (r, c, t) = run(pieces, true);
1345 assert_eq!(r, "plan");
1346 assert!(t.is_empty(), "no call was made: {t:?}");
1347 assert_eq!(c, want);
1348 }
1349 }
1350
1351 #[test]
1354 fn a_call_after_reasoning_fires_despite_a_lead_in() {
1355 let (_r, c, t) = run(
1356 &[
1357 "Sure. ",
1358 "<think>",
1359 "plan",
1360 "</think>",
1361 "{\"name\": \"get_weather\", \"parameters\": {\"city\": \"Paris\"}}",
1362 ],
1363 true,
1364 );
1365 assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
1366 assert_eq!(t[0].0, "get_weather");
1367 assert_eq!(c, "Sure. ");
1368 }
1369
1370 #[test]
1372 fn a_marker_that_holds_no_call_is_emitted_as_content() {
1373 let (_r, c, t) = run(&["Here: ", "<tool_call>not json</tool_call>"], true);
1374 assert!(t.is_empty(), "{t:?}");
1375 assert_eq!(c, "Here: <tool_call>not json</tool_call>");
1376 }
1377
1378 #[test]
1381 fn reasoning_after_a_held_call_is_not_content() {
1382 let (r, c, t) = run(
1383 &[
1384 "<think>plan</think>",
1385 "<tool_call>{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}</tool_call>",
1386 "<think>second thoughts</think>",
1387 "Done after the call.",
1388 ],
1389 true,
1390 );
1391 assert_eq!(t.len(), 1, "{t:?}");
1392 assert!(!c.contains("think") && !c.contains("second"), "{c:?}");
1393 assert!(c.contains("Done after the call."), "{c:?}");
1394 assert!(r.contains("second thoughts"), "{r:?}");
1395 }
1396
1397 #[test]
1400 fn an_unparseable_block_beside_a_call_is_shown() {
1401 let (_r, c, t) = run(
1402 &[
1403 "Here: ",
1404 "<tool_call>not json</tool_call> and ",
1405 "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
1406 ],
1407 true,
1408 );
1409 assert_eq!(t.len(), 1, "{t:?}");
1410 assert!(c.contains("<tool_call>not json</tool_call>"), "{c:?}");
1411 }
1412
1413 #[test]
1415 fn prose_around_a_removed_call_is_not_glued() {
1416 let (_r, c, t) = run(
1417 &[
1418 "Sure.",
1419 "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
1420 " More text after it.",
1421 ],
1422 true,
1423 );
1424 assert_eq!(t.len(), 1, "{t:?}");
1425 assert_eq!(c, "Sure. More text after it.");
1426 }
1427
1428 fn deltas(pieces: &[&str]) -> Vec<Delta> {
1430 let mut out = Vec::new();
1431 let mut s = ChatStream::new(true);
1432 for p in pieces {
1433 s.push(p, &mut |d| out.push(d));
1434 }
1435 s.finish(&mut |d| out.push(d));
1436 out
1437 }
1438
1439 fn first_at(out: &[Delta], pred: impl Fn(&Delta) -> bool) -> usize {
1440 out.iter()
1441 .position(pred)
1442 .unwrap_or_else(|| panic!("no such delta in {out:?}"))
1443 }
1444
1445 #[test]
1448 fn a_held_stretch_settles_in_textual_order() {
1449 let out = deltas(&[
1450 "<think>plan</think>",
1451 "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call> Before.",
1452 "<think>second</think>",
1453 " After.",
1454 ]);
1455 let before = first_at(
1456 &out,
1457 |d| matches!(d, Delta::Content(x) if x.contains("Before")),
1458 );
1459 let mid = first_at(
1460 &out,
1461 |d| matches!(d, Delta::Reasoning(x) if x.contains("second")),
1462 );
1463 let after = first_at(
1464 &out,
1465 |d| matches!(d, Delta::Content(x) if x.contains("After")),
1466 );
1467 assert!(before < mid && mid < after, "{out:?}");
1468 }
1469
1470 #[test]
1473 fn a_held_lead_in_arrives_before_the_reasoning_after_it() {
1474 let out = deltas(&["Hi <tool_call>oops ", "<think>", "plan", "</think>", "done"]);
1475 let lead = first_at(
1476 &out,
1477 |d| matches!(d, Delta::Content(x) if x.contains("oops")),
1478 );
1479 let think = first_at(&out, |d| matches!(d, Delta::Reasoning(_)));
1480 assert!(lead < think, "{out:?}");
1481 }
1482
1483 #[test]
1486 fn whitespace_left_by_a_removed_call_is_dropped() {
1487 const CALL: &str = "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>";
1488 for (pieces, want) in [
1489 (vec![CALL, "\n\nI'll check."], "I'll check."),
1490 (vec!["A ", CALL, " B"], "A B"),
1491 (vec!["A ", CALL, " and ", CALL, " B"], "A and B"),
1492 (vec!["I'll check.\n", CALL, "\n"], "I'll check.\n"),
1493 ] {
1494 let (_r, c, t) = run(&pieces, true);
1495 assert!(!t.is_empty(), "{pieces:?}: no call fired");
1496 assert_eq!(c, want, "{pieces:?}");
1497 }
1498 }
1499
1500 const GOOD_CALL: &str = "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>";
1501
1502 #[test]
1505 fn a_cut_gap_is_judged_against_the_shown_text() {
1506 let lead = format!("Hi {GOOD_CALL}");
1507 let main = format!("{GOOD_CALL} Done.");
1508 let (_r, c, t) = run(&[&lead, "<think>p</think>", &main], true);
1509 assert_eq!(t.len(), 2, "{t:?}");
1510 assert_eq!(c, "Hi Done.");
1511 }
1512
1513 #[test]
1516 fn a_span_after_reasoning_keeps_its_line_breaks() {
1517 let first = format!("{GOOD_CALL}Before.\n");
1518 let last = format!("\n\nAfter {GOOD_CALL}");
1519 let (_r, c, _t) = run(
1520 &["<think>p</think>", &first, "<think>t</think>", &last],
1521 true,
1522 );
1523 assert_eq!(c, "Before.\n\n\nAfter");
1524 }
1525
1526 #[test]
1529 fn a_lead_in_keeps_the_space_before_later_content() {
1530 let lead = format!("Hi {GOOD_CALL} now ");
1531 let (_r, c, _t) = run(&[&lead, "<think>p</think>", "Done."], true);
1532 assert_eq!(c, "Hi now Done.");
1533 }
1534
1535 #[test]
1538 fn only_the_last_span_of_a_stretch_loses_its_trailing_gap() {
1539 let held = format!("{GOOD_CALL}X {GOOD_CALL}<think>r</think>Y");
1540 let (r, c, t) = run(&["<think>p</think>", &held], true);
1541 assert_eq!(t.len(), 2, "{t:?}");
1542 assert_eq!(r, "pr");
1543 assert_eq!(c, "X Y");
1544 }
1545
1546 #[test]
1549 fn a_reply_with_no_parsed_call_is_byte_identical() {
1550 for pieces in [
1551 &["Here: ", "<tool_call>not json</tool_call>", "\n\n "][..],
1552 &["{not a call} \n", "<think>p</think>", " ok "][..],
1553 &["Hi <tool_call>oops\n\n", "<think>p</think>", "\n done"][..],
1554 ] {
1555 let want: String = pieces
1556 .iter()
1557 .map(|p| {
1558 p.split("<think>").next().unwrap_or_default().to_owned()
1559 + p.split("</think>").nth(1).unwrap_or_default()
1560 })
1561 .collect();
1562 let (_r, c, t) = run(pieces, true);
1563 assert!(t.is_empty(), "{t:?}");
1564 assert_eq!(c, want, "{pieces:?}");
1565 }
1566 }
1567
1568 #[test]
1570 fn mixed_dialect_calls_all_fire() {
1571 let (_r, c, t) = run(
1572 &[
1573 "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
1574 "<|tool_call>call:get_weather{city:<|\"|>Paris<|\"|>}<tool_call|>",
1575 ],
1576 true,
1577 );
1578 let names: Vec<&str> = t.iter().map(|(n, _)| n.as_str()).collect();
1579 assert_eq!(names, ["run_bash", "get_weather"]);
1580 assert!(!c.contains("tool_call"), "{c:?}");
1581 }
1582
1583 #[test]
1584 fn leading_brace_non_call_survives_as_content() {
1585 let (_r, c, t) = run(
1587 &["{not json here, just prose that opens with a brace}"],
1588 true,
1589 );
1590 assert!(t.is_empty(), "non-call misparsed: {t:?}");
1591 assert!(c.contains("not json here"), "content dropped: {c:?}");
1592 }
1593}