Skip to main content

infr_chat/
stream.rs

1//! Streaming reasoning/content splitter — THE single place model output is separated into
2//! reasoning vs answer (vs tool calls) as it streams. `infr run` (display styling), `infr serve`
3//! (OpenAI deltas) and the history stripper all consume this module, so every thinking model is
4//! exposed the same way on every surface; a new reasoning format (e.g. channel markers) lands
5//! here once and everywhere at once.
6
7/// Does this rendered prompt end with a `<think>` PREFILL (the template opened the reasoning
8/// block itself — Qwen3.5 style — so the model's output starts MID-reasoning with only
9/// the close marker)? Callers inject a synthetic `"<think>"` piece at the head of the stream when
10/// this is true, so the streaming splitter, the display styler and the history stripper all see a
11/// well-formed block through the one shared grammar.
12pub fn prompt_prefills_think(prompt: &str) -> bool {
13    prompt.trim_end().ends_with("<think>")
14}
15
16/// A streamed piece of a response.
17#[derive(Clone, Debug)]
18pub enum Delta {
19    Reasoning(String),
20    Content(String),
21    ToolCall { name: String, arguments: String },
22}
23
24/// Incremental splitter for the streaming server path. Accumulates the raw decoded text and, on each
25/// piece, emits the newly-stable Reasoning (`<think>…</think>`) and Content deltas — holding back a
26/// marker-length tail so a partial `<think>`/`</think>`/`<tool_call>` marker is never emitted. Once a
27/// tool-call opener appears (and tool calls are allowed) it stops streaming content — matching every
28/// dialect `finish()` parses (Hermes `<tool_call>`, the pipe form `<|tool_call>`, and a Llama-3
29/// bare-JSON `{…}` body), so non-Hermes calls can't leak as content while also firing as a ToolCall.
30/// `finish()` flushes the held-back tails and parses the buffered tool call(s) into ToolCall deltas.
31pub struct ChatStream {
32    raw: String,
33    sent_r: usize, // reasoning bytes already emitted (offset within the reasoning region)
34    sent_c: usize, // content bytes already emitted (offset within the content region)
35    allow_tools: bool,
36    // Per-marker cursors so `emit` doesn't re-`find` from offset 0 over the whole buffer on every
37    // pushed piece (that was O(n²) across a response). Each caches the first hit once found and
38    // otherwise resumes scanning from the previously-scanned tail.
39    cur_think_open: Cursor,
40    cur_think_close: Cursor,
41    cur_tool: Cursor,  // Hermes/Qwen `<tool_call>`
42    cur_pipe: Cursor,  // gemma4/E2B/DG `<|tool_call>`
43    cur_final: Cursor, // channel-format `<channel|>`
44}
45
46/// A forward-only search for a fixed `needle` in an append-only buffer: once the needle is found its
47/// byte offset is cached; until then, each call resumes scanning from just before the previously
48/// scanned tail (so a needle straddling the append boundary is still caught).
49#[derive(Default)]
50struct Cursor {
51    off: Option<usize>,
52    scanned: usize,
53}
54
55impl Cursor {
56    fn find(&mut self, raw: &str, needle: &str) -> Option<usize> {
57        if self.off.is_some() {
58            return self.off;
59        }
60        let mut start = self.scanned.saturating_sub(needle.len().saturating_sub(1));
61        while start > 0 && !raw.is_char_boundary(start) {
62            start -= 1;
63        }
64        if let Some(p) = raw[start..].find(needle) {
65            self.off = Some(start + p);
66        }
67        self.scanned = raw.len();
68        self.off
69    }
70}
71
72impl ChatStream {
73    pub fn new(allow_tools: bool) -> Self {
74        Self {
75            raw: String::new(),
76            sent_r: 0,
77            sent_c: 0,
78            allow_tools,
79            cur_think_open: Cursor::default(),
80            cur_think_close: Cursor::default(),
81            cur_tool: Cursor::default(),
82            cur_pipe: Cursor::default(),
83            cur_final: Cursor::default(),
84        }
85    }
86
87    pub fn push(&mut self, piece: &str, on_delta: &mut dyn FnMut(Delta)) {
88        self.raw.push_str(piece);
89        self.emit(false, on_delta);
90    }
91
92    pub fn finish(&mut self, on_delta: &mut dyn FnMut(Delta)) {
93        self.emit(true, on_delta); // flush the held-back tails (no marker can still be forming)
94        if self.allow_tools {
95            let (_r, body) = crate::split_think(&self.raw);
96            // Dialect-aware: hermes JSON + qwen3.5/3.6 XML + gemma pipe-marker + llama3 bare JSON
97            // (hermes-only here silently dropped every non-qwen3 model's calls over serve).
98            let (_content, calls) = crate::parse_any_tool_calls(&body);
99            for call in calls {
100                on_delta(Delta::ToolCall {
101                    name: call.name,
102                    arguments: serde_json::to_string(&call.arguments)
103                        .unwrap_or_else(|_| "{}".to_string()),
104                });
105            }
106        }
107    }
108
109    /// The earliest tool-call opener at/after `cs`, across every dialect `finish()` parses — Hermes
110    /// `<tool_call>`, the pipe form `<|tool_call>`, and (when the content region begins with `{`) a
111    /// Llama-3 bare-JSON call. Returns `None` when tools aren't allowed or no opener is present, so
112    /// the content region runs to the buffer end. Matching `finish()`'s dialect set here is what
113    /// stops non-Hermes calls from leaking as `Delta::Content` while also firing as `Delta::ToolCall`.
114    fn tool_open_at(&mut self, cs: usize, final_flush: bool) -> Option<usize> {
115        if !self.allow_tools {
116            return None;
117        }
118        const TL: &str = "<tool_call>";
119        const PIPE: &str = "<|tool_call>";
120        let hermes = self.cur_tool.find(&self.raw, TL).filter(|&p| p >= cs);
121        let pipe = self.cur_pipe.find(&self.raw, PIPE).filter(|&p| p >= cs);
122        let bare = self.bare_json_open(cs, final_flush);
123        [hermes, pipe, bare].into_iter().flatten().min()
124    }
125
126    /// Position of a bare-JSON (`{…}`) tool-call opener in the content region starting at `cs`, or
127    /// `None`. Scoped to the leading `{` of the region (skipping only whitespace) so ordinary prose
128    /// that merely *contains* a brace is never suppressed. During streaming a leading `{` is held
129    /// back optimistically; on the final flush it's confirmed a real call via
130    /// [`crate::tools::parse_bare_json_call`] so a leading brace that isn't a call still streams as
131    /// content instead of being dropped.
132    fn bare_json_open(&self, cs: usize, final_flush: bool) -> Option<usize> {
133        let bytes = self.raw.as_bytes();
134        let mut i = cs;
135        while i < bytes.len() && matches!(bytes[i], b' ' | b'\n' | b'\t' | b'\r') {
136            i += 1;
137        }
138        if i >= bytes.len() || bytes[i] != b'{' {
139            return None;
140        }
141        if final_flush && crate::tools::parse_bare_json_call(&self.raw[i..]).is_none() {
142            return None; // leading `{` but not actually a call — let it stream as content
143        }
144        Some(i)
145    }
146
147    fn emit(&mut self, final_flush: bool, on_delta: &mut dyn FnMut(Delta)) {
148        const TO: &str = "<think>";
149        const TC: &str = "</think>";
150        // Channel-format head (E2B/gpt-oss: `<|channel>thought…<channel|>answer`): reasoning runs
151        // from after the thought marker to the final-answer marker, content after it. While the
152        // head could still be a forming marker, hold everything back.
153        const CT: [&str; 2] = ["<|channel|>thought", "<|channel>thought"];
154        const FINAL: &str = "<channel|>";
155        if let Some(hm) = CT
156            .iter()
157            .find_map(|m| self.raw.starts_with(m).then_some(m.len()))
158        {
159            let (r_end, hold, c_start) = match self.cur_final.find(&self.raw, FINAL) {
160                Some(f) => (f, false, Some(f + FINAL.len())),
161                None => (self.raw.len(), !final_flush, None),
162            };
163            emit_region(&self.raw, hm, r_end, hold, &mut self.sent_r, true, on_delta);
164            if let Some(cs) = c_start {
165                let tool_open = self.tool_open_at(cs, final_flush);
166                let (c_end, hold) = match tool_open {
167                    Some(t) if t >= cs => (t, false),
168                    _ => (self.raw.len(), !final_flush),
169                };
170                emit_region(
171                    &self.raw,
172                    cs,
173                    c_end,
174                    hold,
175                    &mut self.sent_c,
176                    false,
177                    on_delta,
178                );
179            }
180            return;
181        }
182        if !final_flush
183            && CT.iter().any(|m| {
184                m.as_bytes()
185                    .starts_with(&self.raw.as_bytes()[..self.raw.len().min(m.len())])
186            })
187            && self.raw.len() < CT[0].len()
188        {
189            return; // head could still become a channel marker — hold
190        }
191        let think_open = self.cur_think_open.find(&self.raw, TO);
192        let think_close = self.cur_think_close.find(&self.raw, TC);
193        // Reasoning region: between `<think>` and `</think>` (or end, while still thinking).
194        if let Some(to) = think_open {
195            let rs = to + TO.len();
196            let (r_end, hold) = match think_close {
197                Some(tc) => (tc, false),
198                None => (self.raw.len(), !final_flush),
199            };
200            emit_region(&self.raw, rs, r_end, hold, &mut self.sent_r, true, on_delta);
201        }
202        // Content region: after `</think>` (or from the start when there's no `<think>` at all), up to
203        // a tool-call opener (whose block is buffered, not streamed) or the end.
204        let c_start = match think_close {
205            Some(tc) => Some(tc + TC.len()),
206            None if think_open.is_none() => Some(0),
207            None => None,
208        };
209        if let Some(cs) = c_start {
210            let tool_open = self.tool_open_at(cs, final_flush);
211            let (c_end, hold) = match tool_open {
212                Some(t) if t >= cs => (t, false),
213                _ => (self.raw.len(), !final_flush),
214            };
215            emit_region(
216                &self.raw,
217                cs,
218                c_end,
219                hold,
220                &mut self.sent_c,
221                false,
222                on_delta,
223            );
224        }
225    }
226}
227
228/// Emit the not-yet-sent slice of `raw[region_start .. region_end]` (past `*sent` bytes), holding back
229/// a marker-length tail when `hold` (so a partial marker isn't emitted mid-stream), clamped to a UTF-8
230/// boundary. Advances `*sent`.
231fn emit_region(
232    raw: &str,
233    region_start: usize,
234    region_end: usize,
235    hold: bool,
236    sent: &mut usize,
237    reasoning: bool,
238    on_delta: &mut dyn FnMut(Delta),
239) {
240    const HOLD: usize = 12; // > the longest marker, so a partial one never streams
241    let abs = region_start + *sent;
242    if abs >= region_end {
243        return;
244    }
245    let mut end = if hold {
246        region_end.saturating_sub(HOLD).max(abs)
247    } else {
248        region_end
249    };
250    while end > abs && !raw.is_char_boundary(end) {
251        end -= 1;
252    }
253    if end <= abs {
254        return;
255    }
256    let text = &raw[abs..end];
257    if text.is_empty() {
258        return;
259    }
260    on_delta(if reasoning {
261        Delta::Reasoning(text.to_owned())
262    } else {
263        Delta::Content(text.to_owned())
264    });
265    *sent += text.len();
266}
267
268#[cfg(test)]
269mod chat_stream_tests {
270    use super::*;
271
272    /// Feed `pieces` through a `ChatStream` and collect every emitted delta (streaming + finish).
273    fn run(pieces: &[&str], allow_tools: bool) -> (String, String, Vec<(String, String)>) {
274        let mut out: Vec<Delta> = Vec::new();
275        let mut s = ChatStream::new(allow_tools);
276        {
277            let mut od = |d: Delta| out.push(d);
278            for p in pieces {
279                s.push(p, &mut od);
280            }
281        }
282        s.finish(&mut |d: Delta| out.push(d));
283        let (mut r, mut c, mut t) = (String::new(), String::new(), Vec::new());
284        for d in &out {
285            match d {
286                Delta::Reasoning(x) => r.push_str(x),
287                Delta::Content(x) => c.push_str(x),
288                Delta::ToolCall { name, arguments } => t.push((name.clone(), arguments.clone())),
289            }
290        }
291        (r, c, t)
292    }
293
294    #[test]
295    fn streams_channel_thought_then_final() {
296        // E2B/gpt-oss channel format: reasoning after the thought marker, content after the
297        // final-answer marker — streamed as Reasoning/Content like the <think> form.
298        let (r, c, t) = run(
299            &[
300                "<|channel>th",
301                "ought\nreaso",
302                "ning<chan",
303                "nel|>the answer",
304            ],
305            false,
306        );
307        assert_eq!(r.trim(), "reasoning");
308        assert_eq!(c.trim(), "the answer");
309        assert!(t.is_empty());
310    }
311
312    #[test]
313    fn prefilled_think_via_injected_opener() {
314        // Template-prefilled thinking (Qwen3.5): the caller injects "<think>" before the model's
315        // mid-reasoning output; the splitter then treats the head as Reasoning.
316        let (r, c, t) = run(&["<think>", "reasoning here", "</think>", "answer"], false);
317        assert_eq!(r.trim(), "reasoning here");
318        assert_eq!(c.trim(), "answer");
319        assert!(t.is_empty());
320    }
321
322    #[test]
323    fn streams_think_then_content() {
324        let (r, c, t) = run(
325            &["<think>", "reason", "ing", "</think>", "the ", "answer"],
326            true,
327        );
328        assert_eq!(r.trim(), "reasoning");
329        assert_eq!(c.trim(), "the answer");
330        assert!(t.is_empty());
331    }
332
333    #[test]
334    fn plain_content_no_think() {
335        let (r, c, _) = run(&["hello ", "world, this is a longer reply"], true);
336        assert!(r.trim().is_empty());
337        assert_eq!(c.trim(), "hello world, this is a longer reply");
338    }
339
340    #[test]
341    fn tool_call_buffered_and_parsed() {
342        let (r, _c, t) = run(
343            &[
344                "<think>plan</think>",
345                "<tool_call>\n{\"name\": \"run_bash\", \"arguments\": {\"command\": \"ls\"}}\n</tool_call>",
346            ],
347            true,
348        );
349        assert_eq!(r.trim(), "plan");
350        assert_eq!(t.len(), 1);
351        assert_eq!(t[0].0, "run_bash");
352        assert!(t[0].1.contains("ls"));
353    }
354
355    #[test]
356    fn tool_choice_none_keeps_tool_text_as_content() {
357        // allow_tools=false → a <tool_call> block is NOT extracted; it stays content.
358        let (_r, c, t) = run(&["<tool_call>{\"name\":\"x\"}</tool_call>"], false);
359        assert!(t.is_empty());
360        assert!(c.contains("tool_call"));
361    }
362
363    #[test]
364    fn pipe_form_tool_call_not_streamed_as_content() {
365        // gemma4/E2B/DG pipe form has no `<tool_call>` substring — it must still gate content
366        // and fire exactly once as a ToolCall (not leak as Content AND duplicate).
367        let (_r, c, t) = run(
368            &[
369                "<|tool_",
370                "call>call:get_weather{city:<|\"|>Par",
371                "is<|\"|>}",
372                "<tool_call|>",
373            ],
374            true,
375        );
376        assert!(
377            !c.contains("tool_call") && !c.contains("get_weather"),
378            "pipe markup leaked as content: {c:?}"
379        );
380        assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
381        assert_eq!(t[0].0, "get_weather");
382    }
383
384    #[test]
385    fn bare_json_tool_call_not_streamed_as_content() {
386        // Llama-3 bare-JSON form: the whole body is one JSON object — no markers at all.
387        let (_r, c, t) = run(
388            &[
389                "{\"name\": \"get_weather\", ",
390                "\"parameters\": {\"city\": \"Paris\"}}",
391            ],
392            true,
393        );
394        assert!(c.trim().is_empty(), "bare json leaked as content: {c:?}");
395        assert_eq!(t.len(), 1, "expected exactly one tool call, got {t:?}");
396        assert_eq!(t[0].0, "get_weather");
397    }
398
399    #[test]
400    fn content_with_stray_brace_not_swallowed() {
401        // Ordinary prose that merely contains a brace mid-text must NOT be treated as a call.
402        let (_r, c, t) = run(
403            &[
404                "The config is {",
405                "\"a\": 1} and that is the whole story here, nothing more.",
406            ],
407            true,
408        );
409        assert!(t.is_empty(), "stray brace misparsed as tool call: {t:?}");
410        assert!(c.contains("The config is"), "content lost: {c:?}");
411        assert!(c.contains("whole story"), "content truncated: {c:?}");
412    }
413
414    #[test]
415    fn leading_brace_non_call_survives_as_content() {
416        // A leading `{` that is NOT a valid bare-JSON call must be flushed as content, not dropped.
417        let (_r, c, t) = run(
418            &["{not json here, just prose that opens with a brace}"],
419            true,
420        );
421        assert!(t.is_empty(), "non-call misparsed: {t:?}");
422        assert!(c.contains("not json here"), "content dropped: {c:?}");
423    }
424}