pub fn prompt_prefills_think(prompt: &str) -> bool {
prompt.trim_end().ends_with("<think>")
}
#[derive(Clone, Debug)]
pub enum Delta {
Reasoning(String),
Content(String),
ToolCall {
name: String,
arguments: String,
},
Logprob(crate::TokenLogprob),
}
pub struct ChatStream {
raw: String,
sent_r: usize, sent_c: usize, lead: Option<(usize, usize)>,
sent_lead: usize,
shown_gap: Option<String>,
allow_tools: bool,
cur_think_open: Cursor,
cur_think_close: Cursor,
cur_tool: Cursor, cur_pipe: Cursor, cur_final: Cursor, bare: BareJson,
logprobs: Vec<TokenSpan>,
}
#[derive(Clone, Debug)]
struct TokenSpan {
start: usize,
end: usize,
lps: Vec<crate::TokenLogprob>,
}
#[derive(Default)]
struct BareJson {
cs: Option<usize>, scanned: usize,
head: BareHead,
depth: usize,
in_str: bool,
esc: bool,
}
#[derive(Default, Clone, Copy, PartialEq)]
enum BareHead {
#[default]
Pending,
Open(usize),
Call(usize),
No,
}
impl BareJson {
fn open(&mut self, raw: &str, cs: usize) -> Option<usize> {
if self.cs != Some(cs) {
*self = Self {
cs: Some(cs),
scanned: cs,
..Self::default()
};
}
let bytes = raw.as_bytes();
while self.scanned < bytes.len() {
let i = self.scanned;
let b = bytes[i];
self.scanned += 1;
match self.head {
BareHead::Pending => match b {
b' ' | b'\n' | b'\t' | b'\r' => {}
b'{' => {
self.head = BareHead::Open(i);
self.depth = 1;
}
_ => self.head = BareHead::No,
},
BareHead::Open(start) => {
if self.in_str {
match b {
_ if self.esc => self.esc = false,
b'\\' => self.esc = true,
b'"' => self.in_str = false,
_ => {}
}
} else {
match b {
b'"' => self.in_str = true,
b'{' => self.depth += 1,
b'}' => {
self.depth -= 1;
if self.depth == 0 {
let call = crate::tools::parse_bare_json_call(&raw[start..=i]);
self.head = if call.is_some() {
BareHead::Call(start)
} else {
BareHead::No
};
}
}
_ => {}
}
}
}
BareHead::Call(_) | BareHead::No => {
self.scanned = bytes.len();
}
}
}
match self.head {
BareHead::Open(i) | BareHead::Call(i) => Some(i),
BareHead::Pending | BareHead::No => None,
}
}
}
#[derive(Default)]
struct Cursor {
off: Option<usize>,
scanned: usize,
}
impl Cursor {
fn find(&mut self, raw: &str, needle: &str) -> Option<usize> {
self.find_from(raw, needle, 0)
}
fn find_from(&mut self, raw: &str, needle: &str, from: usize) -> Option<usize> {
match self.off {
Some(p) if p >= from => return Some(p),
Some(_) => {
self.off = None;
self.scanned = from;
}
None => {}
}
let mut start = self
.scanned
.saturating_sub(needle.len().saturating_sub(1))
.max(from);
while start > from && !raw.is_char_boundary(start) {
start -= 1;
}
if let Some(p) = raw[start..].find(needle) {
self.off = Some(start + p);
}
self.scanned = raw.len();
self.off
}
}
impl ChatStream {
pub fn new(allow_tools: bool) -> Self {
Self {
raw: String::new(),
sent_r: 0,
sent_c: 0,
lead: None,
sent_lead: 0,
shown_gap: None,
allow_tools,
cur_think_open: Cursor::default(),
cur_think_close: Cursor::default(),
cur_tool: Cursor::default(),
cur_pipe: Cursor::default(),
cur_final: Cursor::default(),
bare: BareJson::default(),
logprobs: Vec::new(),
}
}
pub fn push_with_logprobs(
&mut self,
piece: &str,
logprobs: Vec<crate::TokenLogprob>,
on_delta: &mut dyn FnMut(Delta),
) {
let start = self.raw.len();
self.raw.push_str(piece);
if !logprobs.is_empty() && !piece.is_empty() {
self.logprobs.push(TokenSpan {
start,
end: self.raw.len(),
lps: logprobs,
});
}
self.emit(false, on_delta);
}
#[cfg(test)]
fn queued_logprobs(&self) -> usize {
self.logprobs.len()
}
pub fn push(&mut self, piece: &str, on_delta: &mut dyn FnMut(Delta)) {
self.raw.push_str(piece);
self.emit(false, on_delta);
}
pub fn finish(&mut self, on_delta: &mut dyn FnMut(Delta)) {
self.emit(true, on_delta);
self.logprobs.clear();
}
fn tool_open_at(&mut self, cs: usize, final_flush: bool) -> Option<usize> {
if !self.allow_tools {
return None;
}
const TL: &str = "<tool_call>";
const PIPE: &str = "<|tool_call>";
let hermes = self.cur_tool.find_from(&self.raw, TL, cs);
let pipe = self.cur_pipe.find_from(&self.raw, PIPE, cs);
let bare = self.bare_json_open(cs, final_flush);
[hermes, pipe, bare].into_iter().flatten().min()
}
fn bare_json_open(&mut self, cs: usize, final_flush: bool) -> Option<usize> {
let i = self.bare.open(&self.raw, cs)?;
if final_flush && crate::tools::parse_bare_json_call(&self.raw[i..]).is_none() {
return None; }
Some(i)
}
fn emit(&mut self, final_flush: bool, on_delta: &mut dyn FnMut(Delta)) {
let mut logprobs = std::mem::take(&mut self.logprobs);
self.emit_with(final_flush, on_delta, &mut logprobs);
self.logprobs = logprobs;
}
fn emit_with(
&mut self,
final_flush: bool,
on_delta: &mut dyn FnMut(Delta),
logprobs: &mut Vec<TokenSpan>,
) {
const TO: &str = "<think>";
const TC: &str = "</think>";
const FINAL: &str = "<channel|>";
if let Some(hm) = channel_thought_head(&self.raw) {
let (r_end, hold, c_start) = match self.cur_final.find(&self.raw, FINAL) {
Some(f) => (f, false, Some(f + FINAL.len())),
None => (self.raw.len(), !final_flush, None),
};
emit_region(
&self.raw,
hm,
r_end,
hold,
&mut self.sent_r,
true,
on_delta,
logprobs,
);
if let Some(cs) = c_start {
self.emit_content(cs, final_flush, on_delta, logprobs);
}
return;
}
if !final_flush
&& CHANNEL_THOUGHT.iter().any(|m| {
m.as_bytes()
.starts_with(&self.raw.as_bytes()[..self.raw.len().min(m.len())])
})
&& self.raw.len() < CHANNEL_THOUGHT[0].len()
{
return; }
let think_open = self.cur_think_open.find(&self.raw, TO);
let think_close =
think_open.and_then(|to| self.cur_think_close.find_from(&self.raw, TC, to + TO.len()));
let lead = think_open.map(|to| match self.lead {
Some(lead) => lead,
None => {
self.sent_lead = std::mem::take(&mut self.sent_c);
let stop = match to {
0 => 0,
_ => self.tool_open_at(0, false).map_or(to, |t| t.min(to)),
};
self.lead = Some((stop, to));
(stop, to)
}
});
if let Some((stop, end)) = lead {
let unsent = self.sent_lead < end;
let from = self.sent_lead;
emit_region(
&self.raw,
0,
stop,
false,
&mut self.sent_lead,
false,
on_delta,
logprobs,
);
note_shown(&mut self.shown_gap, &self.raw[from..self.sent_lead]);
if unsent && stop < end {
settle_held(
&self.raw[stop..end],
&mut self.shown_gap,
false,
on_delta,
logprobs,
stop,
);
self.sent_lead = end;
}
}
if let Some(to) = think_open {
let rs = to + TO.len();
let (r_end, hold) = match think_close {
Some(tc) => (tc, false),
None => (self.raw.len(), !final_flush),
};
emit_region(
&self.raw,
rs,
r_end,
hold,
&mut self.sent_r,
true,
on_delta,
logprobs,
);
}
let c_start = match think_close {
Some(tc) => Some(tc + TC.len()),
None if think_open.is_none() => Some(0),
None => None,
};
if let Some(cs) = c_start {
self.emit_content(cs, final_flush, on_delta, logprobs);
}
}
fn emit_content(
&mut self,
cs: usize,
final_flush: bool,
on_delta: &mut dyn FnMut(Delta),
logprobs: &mut Vec<TokenSpan>,
) {
let tool_open = self.tool_open_at(cs, final_flush).filter(|&t| t >= cs);
let (c_end, hold) = match tool_open {
Some(t) => (t, false),
None => (self.raw.len(), !final_flush),
};
let from = cs + self.sent_c;
emit_region(
&self.raw,
cs,
c_end,
hold,
&mut self.sent_c,
false,
on_delta,
logprobs,
);
note_shown(&mut self.shown_gap, &self.raw[from..cs + self.sent_c]);
if let (true, Some(t)) = (final_flush, tool_open) {
settle_held(
&self.raw[t..],
&mut self.shown_gap,
true,
on_delta,
logprobs,
t,
);
}
}
}
fn settle_held(
held: &str,
shown_gap: &mut Option<String>,
at_end: bool,
on_delta: &mut dyn FnMut(Delta),
logprobs: &mut Vec<TokenSpan>,
base: usize,
) {
let mut fired = Vec::new();
let spans = reasoning_spans(held);
let last_text = spans.iter().rposition(|s| matches!(s, Span::Text(..)));
for (i, span) in spans.into_iter().enumerate() {
let (at, text) = match span {
Span::Reasoning(r) => {
if !r.is_empty() {
on_delta(Delta::Reasoning(r.to_owned()));
}
continue;
}
Span::Text(off, t) => (base + off, t),
};
let (clean, calls) = if logprobs.is_empty() {
let (clean, calls) = crate::tools::parse_any_tool_calls_traced::<()>(text);
(
crate::tools::Traced {
text: clean.text,
origin: crate::tools::Origins::new(),
},
calls,
)
} else {
crate::tools::parse_any_tool_calls_traced::<crate::tools::Origins>(text)
};
let content = if calls.is_empty() {
if !text.is_empty() {
emit_logprobs(
logprobs,
|s| s.start < at + text.len() && s.end > at,
on_delta,
);
}
text
} else {
let (opens_with_cut, closes_with_cut) = cut_edges(text, &clean.text);
let (mut lo, mut hi) = (0, clean.text.len());
if opens_with_cut {
let rest = clean.text.trim_start();
let gap = &clean.text[..clean.text.len() - rest.len()];
let keep = match shown_gap.as_deref() {
None => false,
Some("") => true,
Some(shown) => gap.contains('\n') && !shown.contains('\n'),
};
if !keep {
lo = gap.len();
}
}
if at_end && closes_with_cut && Some(i) == last_text {
hi = lo + clean.text[lo..].trim_end().len();
}
let kept: Vec<usize> = clean
.origin
.get(lo..hi)
.unwrap_or_default()
.iter()
.flatten()
.map(|&o| at + o)
.collect();
if !kept.is_empty() {
emit_logprobs(
logprobs,
|s| {
kept.get(kept.partition_point(|&o| o < s.start))
.is_some_and(|&o| o < s.end)
},
on_delta,
);
}
&clean.text[lo..hi]
};
if !content.is_empty() {
note_shown(shown_gap, content);
on_delta(Delta::Content(content.to_owned()));
}
fired.extend(calls);
}
let end = base + held.len();
logprobs.retain(|s| s.start < base || s.end > end);
for call in fired {
on_delta(Delta::ToolCall {
name: call.name,
arguments: serde_json::to_string(&call.arguments).unwrap_or_else(|_| "{}".to_string()),
});
}
}
fn cut_edges(text: &str, clean: &str) -> (bool, bool) {
let head = text
.char_indices()
.zip(clean.chars())
.find(|((_, a), b)| a != b)
.map_or(clean.len().min(text.len()), |((i, _), _)| i);
let tail = text
.char_indices()
.rev()
.zip(clean.chars().rev())
.find(|((_, a), b)| a != b)
.map_or(text.len() - clean.len().min(text.len()), |((i, a), _)| {
i + a.len_utf8()
});
(
text[..head].trim().is_empty(),
text[tail..].trim().is_empty(),
)
}
fn note_shown(gap: &mut Option<String>, text: &str) {
if text.is_empty() {
return;
}
let word = text.trim_end();
if word.is_empty() {
gap.get_or_insert_with(String::new).push_str(text);
} else {
*gap = Some(text[word.len()..].to_owned());
}
}
enum Span<'a> {
Text(usize, &'a str),
Reasoning(&'a str),
}
fn reasoning_spans(text: &str) -> Vec<Span<'_>> {
const TO: &str = "<think>";
const TC: &str = "</think>";
let mut out = Vec::new();
let mut at = 0;
while let Some(o) = text[at..].find(TO) {
out.push(Span::Text(at, &text[at..at + o]));
let inner = at + o + TO.len();
let Some(c) = text[inner..].find(TC) else {
out.push(Span::Reasoning(&text[inner..]));
return out;
};
out.push(Span::Reasoning(&text[inner..inner + c]));
at = inner + c + TC.len();
}
out.push(Span::Text(at, &text[at..]));
out
}
const CHANNEL_THOUGHT: [&str; 2] = ["<|channel|>thought", "<|channel>thought"];
fn channel_thought_head(raw: &str) -> Option<usize> {
CHANNEL_THOUGHT
.iter()
.find_map(|m| raw.starts_with(m).then_some(m.len()))
}
fn emit_logprobs(
logprobs: &mut Vec<TokenSpan>,
in_content: impl Fn(&TokenSpan) -> bool,
on_delta: &mut dyn FnMut(Delta),
) {
logprobs.retain_mut(|s| {
if in_content(s) {
for lp in s.lps.drain(..) {
on_delta(Delta::Logprob(lp));
}
false
} else {
true
}
});
}
#[allow(clippy::too_many_arguments)]
fn emit_region(
raw: &str,
region_start: usize,
region_end: usize,
hold: bool,
sent: &mut usize,
reasoning: bool,
on_delta: &mut dyn FnMut(Delta),
logprobs: &mut Vec<TokenSpan>,
) {
const HOLD: usize = 12; let abs = region_start + *sent;
if abs >= region_end {
return;
}
let mut end = if hold {
region_end.saturating_sub(HOLD).max(abs)
} else {
region_end
};
if !reasoning && !(!hold && end == region_end) {
if let Some(s) = logprobs.iter().find(|s| s.start < end && s.end > end) {
if s.start <= abs {
return;
}
end = s.start;
}
}
while end > abs && !raw.is_char_boundary(end) {
end -= 1;
}
if end <= abs {
return;
}
if reasoning {
logprobs.retain(|s| s.start < region_start || s.end > end);
} else {
emit_logprobs(logprobs, |s| s.start < end && s.end > abs, on_delta);
}
let text = &raw[abs..end];
if text.is_empty() {
return;
}
on_delta(if reasoning {
Delta::Reasoning(text.to_owned())
} else {
Delta::Content(text.to_owned())
});
*sent += text.len();
}
#[cfg(test)]
mod chat_stream_tests {
use super::*;
fn run(pieces: &[&str], allow_tools: bool) -> (String, String, Vec<(String, String)>) {
let mut out: Vec<Delta> = Vec::new();
let mut s = ChatStream::new(allow_tools);
{
let mut od = |d: Delta| out.push(d);
for p in pieces {
s.push(p, &mut od);
}
}
s.finish(&mut |d: Delta| out.push(d));
let (mut r, mut c, mut t) = (String::new(), String::new(), Vec::new());
for d in &out {
match d {
Delta::Reasoning(x) => r.push_str(x),
Delta::Content(x) => c.push_str(x),
Delta::ToolCall { name, arguments } => t.push((name.clone(), arguments.clone())),
Delta::Logprob(_) => {}
}
}
(r, c, t)
}
#[test]
fn logprobs_ride_the_token_aligned_content_chunks() {
fn lp(c: char) -> crate::TokenLogprob {
crate::TokenLogprob {
token: c as u32,
text: c.to_string(),
bytes: c.to_string().into_bytes(),
logprob: -0.5,
top: Vec::new(),
}
}
let mut out: Vec<Delta> = Vec::new();
let mut s = ChatStream::new(false);
for c in "abcdefghijklmnop".chars() {
s.push_with_logprobs(&c.to_string(), vec![lp(c)], &mut |d| out.push(d));
}
s.finish(&mut |d| out.push(d));
let mut queued: Vec<String> = Vec::new();
let mut content = String::new();
for d in out {
match d {
Delta::Logprob(lp) => queued.push(lp.text),
Delta::Content(text) => {
assert_eq!(
queued.len(),
text.chars().count(),
"chunk {text:?} has {queued:?}"
);
for (lp, c) in queued.drain(..).zip(text.chars()) {
assert_eq!(lp, c.to_string());
}
content.push_str(&text);
}
other => panic!("unexpected {other:?}"),
}
}
assert_eq!(content, "abcdefghijklmnop");
assert!(queued.is_empty());
}
fn content_chunks(pieces: &[(&str, u32)], allow_tools: bool) -> Vec<(String, Vec<u32>)> {
let mut out: Vec<Delta> = Vec::new();
let mut s = ChatStream::new(allow_tools);
for &(piece, id) in pieces {
let lp = crate::TokenLogprob {
token: id,
text: piece.to_owned(),
bytes: piece.as_bytes().to_vec(),
logprob: -1.0,
top: Vec::new(),
};
s.push_with_logprobs(piece, vec![lp], &mut |d| out.push(d));
}
s.finish(&mut |d| out.push(d));
let mut chunks = Vec::new();
let mut queued = Vec::new();
for d in out {
match d {
Delta::Logprob(lp) => queued.push(lp.token),
Delta::Content(text) => chunks.push((text, std::mem::take(&mut queued))),
other => assert!(queued.is_empty(), "{queued:?} rode {other:?}"),
}
}
assert!(queued.is_empty(), "{queued:?} were left with no content");
chunks
}
#[test]
fn logprobs_cover_the_answer_and_not_the_reasoning() {
let chunks = content_chunks(
&[
("<think>", 1),
("\nhmm", 2),
("</think>", 3),
("\n\nYes", 4),
(", it", 5),
(" is.", 6),
],
false,
);
let ids: Vec<u32> = chunks.iter().flat_map(|c| c.1.clone()).collect();
assert_eq!(ids, [4, 5, 6]);
let text: String = chunks.iter().map(|c| c.0.as_str()).collect();
assert_eq!(text, "\n\nYes, it is.");
for (text, ids) in &chunks {
assert!(!ids.is_empty(), "{text:?} has no entries");
}
}
#[test]
fn prose_around_parsed_calls_keeps_its_entries() {
const CALL: &str = "{\"name\": \"f\", \"arguments\": {}}";
let chunks = content_chunks(
&[
("A", 1),
("<tool_call>", 2),
(CALL, 3),
("</tool_call>", 4),
(" then", 5),
("<tool_call>", 6),
(CALL, 7),
("</tool_call>", 8),
(" done.", 9),
],
true,
);
assert_eq!(
chunks,
[
("A".to_owned(), vec![1]),
(" then done.".to_owned(), vec![5, 9])
]
);
let chunks = content_chunks(
&[
("<tool_call>", 1),
(CALL, 2),
("</tool_call>", 3),
("\n", 4),
("Done", 5),
(".", 6),
],
true,
);
assert_eq!(chunks, [("Done.".to_owned(), vec![5, 6])]);
}
#[test]
fn a_group_past_a_settled_stretch_keeps_its_entry() {
let chunks = content_chunks(
&[
("Hi ", 1),
("<tool_call>", 2),
("{\"name\": \"f\", \"arguments\": {}}", 3),
("</tool_call><think>r</think>Done", 4),
],
true,
);
assert_eq!(
chunks,
[("Hi ".to_owned(), vec![1]), ("Done".to_owned(), vec![4])]
);
}
#[test]
fn reasoning_entries_do_not_pile_up() {
let lp = |id: u32, text: &str| crate::TokenLogprob {
token: id,
text: text.to_owned(),
bytes: text.as_bytes().to_vec(),
logprob: -1.0,
top: Vec::new(),
};
let mut s = ChatStream::new(false);
let mut out = Vec::new();
s.push_with_logprobs("<think>", vec![lp(0, "<think>")], &mut |d| out.push(d));
let mut most = 0;
for i in 1..=2000 {
s.push_with_logprobs("word ", vec![lp(i, "word ")], &mut |d| out.push(d));
most = most.max(s.queued_logprobs());
}
assert!(most <= 5, "the queue reached {most}");
s.push_with_logprobs("</think>", vec![lp(9000, "</think>")], &mut |d| out.push(d));
s.push_with_logprobs("Answer", vec![lp(9001, "Answer")], &mut |d| out.push(d));
s.finish(&mut |d| out.push(d));
let ids: Vec<u32> = out
.iter()
.filter_map(|d| match d {
Delta::Logprob(lp) => Some(lp.token),
_ => None,
})
.collect();
assert_eq!(ids, [9001]);
}
#[test]
fn a_stray_closer_after_streamed_content_does_not_panic() {
let (r, c, _) = run(&["abcdefghijklmnopqrstuvwxyz", "</think>"], false);
assert_eq!(r, "");
assert_eq!(c, "abcdefghijklmnopqrstuvwxyz</think>");
}
#[test]
fn output_does_not_depend_on_chunking() {
let replies = [
"abcdefghijklmnopqrstuvwxyz</think>",
"abc</think>def",
"x</think>y<think>r</think>z",
"</think></think>a",
"<think>r</think>a</think>b",
"lead</think> <think>think</think>\n\nanswer",
"Hi <tool_call>{\"name\": \"f\", \"arguments\": {}}</tool_call></think>done",
"<think>why</think>\n\n{\"name\": \"f\", \"arguments\": {}}",
];
fn feed(pieces: &[&str], tools: bool, entries: bool) -> (String, String, String) {
let mut out = Vec::new();
let mut s = ChatStream::new(tools);
for (i, p) in pieces.iter().enumerate() {
let lps = if entries {
vec![crate::TokenLogprob {
token: i as u32,
text: p.to_string(),
bytes: p.as_bytes().to_vec(),
logprob: -1.0,
top: Vec::new(),
}]
} else {
Vec::new()
};
s.push_with_logprobs(p, lps, &mut |d| out.push(d));
}
s.finish(&mut |d| out.push(d));
let (mut r, mut c, mut t) = (String::new(), String::new(), String::new());
for d in out {
match d {
Delta::Reasoning(x) => r.push_str(&x),
Delta::Content(x) => c.push_str(&x),
Delta::ToolCall { name, arguments } => {
t.push_str(&format!("{name}{arguments};"))
}
Delta::Logprob(_) => {}
}
}
(r, c, t)
}
let mut state = 0x2545_F491_4F6C_DD1Du64;
for reply in replies {
let chars: Vec<(usize, char)> = reply.char_indices().collect();
let bytewise: Vec<&str> = chars
.iter()
.map(|&(i, ch)| &reply[i..i + ch.len_utf8()])
.collect();
let mut uneven = Vec::new();
let mut at = 0;
while at < reply.len() {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
let mut end = (at + 1 + (state % 7) as usize).min(reply.len());
while !reply.is_char_boundary(end) {
end += 1;
}
uneven.push(&reply[at..end]);
at = end;
}
for tools in [false, true] {
for entries in [false, true] {
let whole = feed(&[reply], tools, entries);
assert_eq!(
feed(&bytewise, tools, entries),
whole,
"{reply:?} char by char, tools {tools}, entries {entries}"
);
assert_eq!(
feed(&uneven, tools, entries),
whole,
"{reply:?} in {uneven:?}, tools {tools}, entries {entries}"
);
}
}
}
}
#[test]
fn logprobs_follow_settled_text_and_skip_parsed_calls() {
let chunks = content_chunks(&[("Hi ", 1), ("<tool_call>", 2), ("oops", 3)], true);
let ids: Vec<u32> = chunks.iter().flat_map(|c| c.1.clone()).collect();
assert_eq!(ids, [1, 2, 3]);
let text: String = chunks.iter().map(|c| c.0.as_str()).collect();
assert_eq!(text, "Hi <tool_call>oops");
let chunks = content_chunks(
&[
("Sure", 1),
("<tool_call>", 2),
("{\"name\": \"f\", \"arguments\": {}}", 3),
("</tool_call>", 4),
],
true,
);
assert_eq!(chunks, [("Sure".to_owned(), vec![1])]);
}
#[test]
fn streams_channel_thought_then_final() {
let (r, c, t) = run(
&[
"<|channel>th",
"ought\nreaso",
"ning<chan",
"nel|>the answer",
],
false,
);
assert_eq!(r.trim(), "reasoning");
assert_eq!(c.trim(), "the answer");
assert!(t.is_empty());
}
#[test]
fn prefilled_think_via_injected_opener() {
let (r, c, t) = run(&["<think>", "reasoning here", "</think>", "answer"], false);
assert_eq!(r.trim(), "reasoning here");
assert_eq!(c.trim(), "answer");
assert!(t.is_empty());
}
#[test]
fn streams_think_then_content() {
let (r, c, t) = run(
&["<think>", "reason", "ing", "</think>", "the ", "answer"],
true,
);
assert_eq!(r.trim(), "reasoning");
assert_eq!(c.trim(), "the answer");
assert!(t.is_empty());
}
#[test]
fn plain_content_no_think() {
let (r, c, _) = run(&["hello ", "world, this is a longer reply"], true);
assert!(r.trim().is_empty());
assert_eq!(c.trim(), "hello world, this is a longer reply");
}
#[test]
fn tool_call_buffered_and_parsed() {
let (r, _c, t) = run(
&[
"<think>plan</think>",
"<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>",
],
true,
);
assert_eq!(r.trim(), "plan");
assert_eq!(t.len(), 1);
assert_eq!(t[0].0, "run_bash");
assert!(t[0].1.contains("ls"));
}
#[test]
fn tool_choice_none_keeps_tool_text_as_content() {
let (_r, c, t) = run(&["<tool_call>{\"name\":\"x\"}</tool_call>"], false);
assert!(t.is_empty());
assert!(c.contains("tool_call"));
}
#[test]
fn pipe_form_tool_call_not_streamed_as_content() {
let (_r, c, t) = run(
&[
"<|tool_",
"call>call:get_weather{city:<|\"|>Par",
"is<|\"|>}",
"<tool_call|>",
],
true,
);
assert!(
!c.contains("tool_call") && !c.contains("get_weather"),
"pipe markup leaked as content: {c:?}"
);
assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
assert_eq!(t[0].0, "get_weather");
}
#[test]
fn bare_json_tool_call_not_streamed_as_content() {
let (_r, c, t) = run(
&[
"{\"name\": \"get_weather\", ",
"\"parameters\": {\"city\": \"Paris\"}}",
],
true,
);
assert!(c.trim().is_empty(), "bare json leaked as content: {c:?}");
assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
assert_eq!(t[0].0, "get_weather");
}
#[test]
fn content_with_stray_brace_not_swallowed() {
let (_r, c, t) = run(
&[
"The config is {",
"\"a\": 1} and that is the whole story here, nothing more.",
],
true,
);
assert!(t.is_empty(), "stray brace misparsed as tool call: {t:?}");
assert!(c.contains("The config is"), "content lost: {c:?}");
assert!(c.contains("whole story"), "content truncated: {c:?}");
}
#[test]
fn tool_marker_in_reasoning_does_not_hide_the_real_call() {
let call = "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>";
for pipe in [false, true] {
let (mention, real) = if pipe {
(
"I could emit <|tool_call> here",
"<|tool_call>call:run_bash{command:<|\"|>ls<|\"|>}<tool_call|>",
)
} else {
("I could emit <tool_call> here", call)
};
let pieces = ["<think>", mention, "</think>", "Sure. ", real];
let (_r, c, t) = run(&pieces, true);
assert!(
!c.contains("run_bash"),
"the call streamed as content: {c:?}"
);
assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
assert_eq!(t[0].0, "run_bash");
}
}
#[test]
fn tool_call_in_channel_reasoning_is_not_a_call() {
let (r, c, t) = run(
&[
"<|channel>thought\nmaybe <|tool_call>call:get_weather{city:<|\"|>Paris<|\"|>}",
"<tool_call|> but no<channel|>It is sunny.",
],
true,
);
assert!(r.contains("maybe"), "reasoning lost: {r:?}");
assert_eq!(c.trim(), "It is sunny.");
assert!(t.is_empty(), "a call quoted in the reasoning fired: {t:?}");
}
#[test]
fn a_quoted_channel_marker_does_not_switch_formats() {
let (_r, c, t) = run(
&[
"<think>plan</think>",
"The <|channel> marker is how E2B splits. ",
"<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>",
],
true,
);
assert!(c.contains("<|channel> marker"), "content lost: {c:?}");
assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
assert_eq!(t[0].0, "run_bash");
}
#[test]
fn a_leading_json_answer_streams_before_finish() {
let pieces = [
"{\"a\": [1, ",
"2], \"b\": \"x} \\\"q\\\" {\"}",
" and the prose after it keeps coming",
" for a while longer.",
];
let mut s = ChatStream::new(true);
let mut streamed = String::new();
for p in pieces {
s.push(p, &mut |d| {
if let Delta::Content(x) = d {
streamed.push_str(&x)
}
});
}
assert!(
streamed.starts_with("{\"a\": [1, 2], \"b\": \"x} \\\"q\\\" {\"}"),
"the object was not streamed before finish: {streamed:?}"
);
let (_r, c, t) = run(&pieces, true);
assert!(t.is_empty(), "a plain object fired as a call: {t:?}");
assert_eq!(c, pieces.concat());
}
#[test]
fn content_before_a_late_think_is_streamed() {
let pieces = [
"Sure, let me check. ",
"<think>",
"plan",
"</think>",
"It is 4.",
];
let mut out = Vec::new();
let mut s = ChatStream::new(false);
for p in pieces {
s.push(p, &mut |d| out.push(d));
}
s.finish(&mut |d| out.push(d));
let lead = out
.iter()
.position(|d| matches!(d, Delta::Content(x) if x.contains("check.")));
let think = out.iter().position(|d| matches!(d, Delta::Reasoning(_)));
assert!(
lead < think && lead.is_some(),
"lead missing or late: {out:?}"
);
let (r, c, _) = run(&pieces, false);
assert_eq!(r, "plan");
assert_eq!(c, "Sure, let me check. It is 4.");
}
#[test]
fn a_held_lead_in_that_is_no_call_is_emitted_in_order() {
for (pieces, want) in [
(
&[
"{not a call} so ",
"<think>",
"plan",
"</think>",
"an answer long enough to stream",
][..],
"{not a call} so an answer long enough to stream",
),
(
&[
"Hi <tool_call>oops ",
"<think>",
"plan",
"</think>",
"done, and more after that",
][..],
"Hi <tool_call>oops done, and more after that",
),
] {
let (r, c, t) = run(pieces, true);
assert_eq!(r, "plan");
assert!(t.is_empty(), "no call was made: {t:?}");
assert_eq!(c, want);
}
}
#[test]
fn a_call_after_reasoning_fires_despite_a_lead_in() {
let (_r, c, t) = run(
&[
"Sure. ",
"<think>",
"plan",
"</think>",
"{\"name\": \"get_weather\", \"parameters\": {\"city\": \"Paris\"}}",
],
true,
);
assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
assert_eq!(t[0].0, "get_weather");
assert_eq!(c, "Sure. ");
}
#[test]
fn a_marker_that_holds_no_call_is_emitted_as_content() {
let (_r, c, t) = run(&["Here: ", "<tool_call>not json</tool_call>"], true);
assert!(t.is_empty(), "{t:?}");
assert_eq!(c, "Here: <tool_call>not json</tool_call>");
}
#[test]
fn reasoning_after_a_held_call_is_not_content() {
let (r, c, t) = run(
&[
"<think>plan</think>",
"<tool_call>{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}</tool_call>",
"<think>second thoughts</think>",
"Done after the call.",
],
true,
);
assert_eq!(t.len(), 1, "{t:?}");
assert!(!c.contains("think") && !c.contains("second"), "{c:?}");
assert!(c.contains("Done after the call."), "{c:?}");
assert!(r.contains("second thoughts"), "{r:?}");
}
#[test]
fn an_unparseable_block_beside_a_call_is_shown() {
let (_r, c, t) = run(
&[
"Here: ",
"<tool_call>not json</tool_call> and ",
"<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
],
true,
);
assert_eq!(t.len(), 1, "{t:?}");
assert!(c.contains("<tool_call>not json</tool_call>"), "{c:?}");
}
#[test]
fn prose_around_a_removed_call_is_not_glued() {
let (_r, c, t) = run(
&[
"Sure.",
"<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
" More text after it.",
],
true,
);
assert_eq!(t.len(), 1, "{t:?}");
assert_eq!(c, "Sure. More text after it.");
}
fn deltas(pieces: &[&str]) -> Vec<Delta> {
let mut out = Vec::new();
let mut s = ChatStream::new(true);
for p in pieces {
s.push(p, &mut |d| out.push(d));
}
s.finish(&mut |d| out.push(d));
out
}
fn first_at(out: &[Delta], pred: impl Fn(&Delta) -> bool) -> usize {
out.iter()
.position(pred)
.unwrap_or_else(|| panic!("no such delta in {out:?}"))
}
#[test]
fn a_held_stretch_settles_in_textual_order() {
let out = deltas(&[
"<think>plan</think>",
"<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call> Before.",
"<think>second</think>",
" After.",
]);
let before = first_at(
&out,
|d| matches!(d, Delta::Content(x) if x.contains("Before")),
);
let mid = first_at(
&out,
|d| matches!(d, Delta::Reasoning(x) if x.contains("second")),
);
let after = first_at(
&out,
|d| matches!(d, Delta::Content(x) if x.contains("After")),
);
assert!(before < mid && mid < after, "{out:?}");
}
#[test]
fn a_held_lead_in_arrives_before_the_reasoning_after_it() {
let out = deltas(&["Hi <tool_call>oops ", "<think>", "plan", "</think>", "done"]);
let lead = first_at(
&out,
|d| matches!(d, Delta::Content(x) if x.contains("oops")),
);
let think = first_at(&out, |d| matches!(d, Delta::Reasoning(_)));
assert!(lead < think, "{out:?}");
}
#[test]
fn whitespace_left_by_a_removed_call_is_dropped() {
const CALL: &str = "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>";
for (pieces, want) in [
(vec![CALL, "\n\nI'll check."], "I'll check."),
(vec!["A ", CALL, " B"], "A B"),
(vec!["A ", CALL, " and ", CALL, " B"], "A and B"),
(vec!["I'll check.\n", CALL, "\n"], "I'll check.\n"),
] {
let (_r, c, t) = run(&pieces, true);
assert!(!t.is_empty(), "{pieces:?}: no call fired");
assert_eq!(c, want, "{pieces:?}");
}
}
const GOOD_CALL: &str = "<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>";
#[test]
fn a_cut_gap_is_judged_against_the_shown_text() {
let lead = format!("Hi {GOOD_CALL}");
let main = format!("{GOOD_CALL} Done.");
let (_r, c, t) = run(&[&lead, "<think>p</think>", &main], true);
assert_eq!(t.len(), 2, "{t:?}");
assert_eq!(c, "Hi Done.");
}
#[test]
fn a_span_after_reasoning_keeps_its_line_breaks() {
let first = format!("{GOOD_CALL}Before.\n");
let last = format!("\n\nAfter {GOOD_CALL}");
let (_r, c, _t) = run(
&["<think>p</think>", &first, "<think>t</think>", &last],
true,
);
assert_eq!(c, "Before.\n\n\nAfter");
}
#[test]
fn a_lead_in_keeps_the_space_before_later_content() {
let lead = format!("Hi {GOOD_CALL} now ");
let (_r, c, _t) = run(&[&lead, "<think>p</think>", "Done."], true);
assert_eq!(c, "Hi now Done.");
}
#[test]
fn only_the_last_span_of_a_stretch_loses_its_trailing_gap() {
let held = format!("{GOOD_CALL}X {GOOD_CALL}<think>r</think>Y");
let (r, c, t) = run(&["<think>p</think>", &held], true);
assert_eq!(t.len(), 2, "{t:?}");
assert_eq!(r, "pr");
assert_eq!(c, "X Y");
}
#[test]
fn a_reply_with_no_parsed_call_is_byte_identical() {
for pieces in [
&["Here: ", "<tool_call>not json</tool_call>", "\n\n "][..],
&["{not a call} \n", "<think>p</think>", " ok "][..],
&["Hi <tool_call>oops\n\n", "<think>p</think>", "\n done"][..],
] {
let want: String = pieces
.iter()
.map(|p| {
p.split("<think>").next().unwrap_or_default().to_owned()
+ p.split("</think>").nth(1).unwrap_or_default()
})
.collect();
let (_r, c, t) = run(pieces, true);
assert!(t.is_empty(), "{t:?}");
assert_eq!(c, want, "{pieces:?}");
}
}
#[test]
fn mixed_dialect_calls_all_fire() {
let (_r, c, t) = run(
&[
"<tool_call>{\"name\": \"run_bash\", \"arguments\": {}}</tool_call>",
"<|tool_call>call:get_weather{city:<|\"|>Paris<|\"|>}<tool_call|>",
],
true,
);
let names: Vec<&str> = t.iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(names, ["run_bash", "get_weather"]);
assert!(!c.contains("tool_call"), "{c:?}");
}
#[test]
fn leading_brace_non_call_survives_as_content() {
let (_r, c, t) = run(
&["{not json here, just prose that opens with a brace}"],
true,
);
assert!(t.is_empty(), "non-call misparsed: {t:?}");
assert!(c.contains("not json here"), "content dropped: {c:?}");
}
}