Skip to main content

eclipse_core/
stream.rs

1//! Server-sent-events parsing and assembly of streamed chat-completion chunks.
2//!
3//! Pure and synchronous: bytes go in, events and a final [`Message`] come out, so the
4//! parsing is testable without any network.
5
6use crate::error::{Error, ProviderFailure, Result};
7use crate::message::{FunctionCall, Message, ToolCall};
8use serde_json::Value;
9use std::collections::BTreeMap;
10
11/// One piece of a reply as it arrives.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum Delta {
14    /// Assistant text.
15    Text(String),
16    /// Reasoning/thinking text emitted by a backend that streams it.
17    Reasoning(String),
18    /// A fragment of a tool call's JSON arguments, tagged with its call index.
19    ToolCallArgs { index: u64, json: String },
20}
21
22/// Receives each piece of the reply as it arrives.
23pub type DeltaFn<'a> = &'a (dyn Fn(Delta) + Send + Sync);
24
25/// Incremental SSE decoder. Feed it raw bytes in arbitrary chunks (a chunk may end in
26/// the middle of a line or of a UTF-8 character); it returns each completed event's
27/// `data` payload.
28#[derive(Default)]
29pub struct SseParser {
30    buf: Vec<u8>,
31    data: Vec<String>,
32}
33
34impl SseParser {
35    pub fn push(&mut self, bytes: &[u8]) -> Vec<String> {
36        self.buf.extend_from_slice(bytes);
37        let mut events = Vec::new();
38        while let Some(nl) = self.buf.iter().position(|b| *b == b'\n') {
39            let line: Vec<u8> = self.buf.drain(..=nl).collect();
40            self.line(&line[..line.len() - 1], &mut events);
41        }
42        events
43    }
44
45    /// Flush at end of stream: a final line or event that lacks its terminating newline
46    /// is still delivered (an incomplete JSON payload is rejected later by the caller).
47    pub fn finish(&mut self) -> Vec<String> {
48        let mut events = Vec::new();
49        if !self.buf.is_empty() {
50            let rest = std::mem::take(&mut self.buf);
51            self.line(&rest, &mut events);
52        }
53        self.line(b"", &mut events);
54        events
55    }
56
57    fn line(&mut self, raw: &[u8], events: &mut Vec<String>) {
58        let line = raw.strip_suffix(b"\r").unwrap_or(raw);
59        if line.is_empty() {
60            if !self.data.is_empty() {
61                events.push(self.data.join("\n"));
62                self.data.clear();
63            }
64            return;
65        }
66        if line[0] == b':' {
67            return;
68        }
69        let (field, value) = match line.iter().position(|b| *b == b':') {
70            Some(i) => (&line[..i], &line[i + 1..]),
71            None => (line, &b""[..]),
72        };
73        if field == b"data" {
74            let value = value.strip_prefix(b" ").unwrap_or(value);
75            self.data.push(String::from_utf8_lossy(value).into_owned());
76        }
77    }
78}
79
80#[derive(Default)]
81struct PartialCall {
82    id: String,
83    name: String,
84    arguments: String,
85}
86
87/// Folds `chat.completion.chunk` payloads into one assistant message.
88#[derive(Default)]
89pub struct StreamAccumulator {
90    content: String,
91    reasoning: String,
92    finish_reason: Option<String>,
93    calls: BTreeMap<u64, PartialCall>,
94    finished: bool,
95    /// Whatever the stream said about cost: a trailing `usage` chunk (OpenAI) and/or
96    /// `timings` (llama.cpp). Kept as a body so [`crate::usage::TurnUsage`] parses it the
97    /// same way it parses a non-streaming reply.
98    usage: Value,
99}
100
101impl StreamAccumulator {
102    /// Handle one SSE `data` payload, reporting any text through `on_delta`.
103    pub fn push_event(&mut self, data: &str, on_delta: DeltaFn<'_>) -> Result<()> {
104        let data = data.trim();
105        if data.is_empty() {
106            return Ok(());
107        }
108        if data == "[DONE]" {
109            self.finished = true;
110            return Ok(());
111        }
112        let chunk: Value = serde_json::from_str(data).map_err(|e| {
113            Error::Provider(ProviderFailure::Response {
114                message: format!("malformed stream chunk: {e}"),
115                body: Some(data.chars().take(300).collect()),
116            })
117        })?;
118        if let Some(err) = chunk.get("error").filter(|e| !e.is_null()) {
119            // A server that reports trouble inside the stream instead of with a status.
120            return Err(Error::Provider(ProviderFailure::Response {
121                message: format!("the server reported an error mid-stream: {err}"),
122                body: Some(data.chars().take(300).collect()),
123            }));
124        }
125        // Cost lands on chunks that carry no text at all — usually the last one.
126        for key in ["usage", "timings"] {
127            if let Some(v) = chunk.get(key).filter(|v| !v.is_null()) {
128                self.usage[key] = v.clone();
129            }
130        }
131        let Some(choice) = chunk.pointer("/choices/0") else {
132            return Ok(()); // e.g. a trailing usage-only chunk
133        };
134        if let Some(text) = choice
135            .pointer("/delta/content")
136            .and_then(Value::as_str)
137            .filter(|t| !t.is_empty())
138        {
139            self.content.push_str(text);
140            on_delta(Delta::Text(text.to_string()));
141        }
142        if let Some(reasoning) = choice
143            .pointer("/delta/reasoning_content")
144            .and_then(Value::as_str)
145            .filter(|t| !t.is_empty())
146        {
147            self.reasoning.push_str(reasoning);
148            on_delta(Delta::Reasoning(reasoning.to_string()));
149        }
150        if let Some(calls) = choice
151            .pointer("/delta/tool_calls")
152            .and_then(Value::as_array)
153        {
154            for call in calls {
155                self.push_tool_call(call, on_delta);
156            }
157        }
158        if let Some(f) = choice
159            .get("finish_reason")
160            .and_then(Value::as_str)
161            .filter(|f| !f.is_empty())
162        {
163            self.finish_reason = Some(f.to_string());
164            self.finished = true;
165        }
166        Ok(())
167    }
168
169    fn push_tool_call(&mut self, call: &Value, on_delta: DeltaFn<'_>) {
170        let id = call.get("id").and_then(Value::as_str).unwrap_or("");
171        // Some servers omit `index`; a fresh id then starts a new call and anything
172        // else continues the latest one.
173        let index = match call.get("index").and_then(Value::as_u64) {
174            Some(i) => i,
175            None => match self.calls.keys().next_back() {
176                Some(last) if id.is_empty() => *last,
177                Some(last) => last + 1,
178                None => 0,
179            },
180        };
181        let entry = self.calls.entry(index).or_default();
182        if entry.id.is_empty() {
183            entry.id = id.to_string();
184        }
185        if let Some(name) = call.pointer("/function/name").and_then(Value::as_str) {
186            if entry.name.is_empty() {
187                entry.name = name.to_string();
188            }
189        }
190        if let Some(args) = call.pointer("/function/arguments").and_then(Value::as_str) {
191            if !args.is_empty() {
192                on_delta(Delta::ToolCallArgs {
193                    index,
194                    json: args.to_string(),
195                });
196            }
197            entry.arguments.push_str(args);
198        }
199    }
200
201    /// The assembled message. Fails if the stream ended before the model signalled
202    /// completion, so a cut connection is never mistaken for a finished reply.
203    /// What the server said this call cost, in the same shape as a non-streaming reply.
204    pub fn usage_body(&self) -> Value {
205        self.usage.clone()
206    }
207
208    pub fn finish(self) -> Result<Message> {
209        if !self.finished {
210            return Err(Error::Provider(ProviderFailure::Truncated {
211                message: "the stream ended before the model finished its reply".into(),
212                streamed_chars: self.content.chars().count(),
213            }));
214        }
215        let content = (!self.content.is_empty()).then_some(self.content);
216        let reasoning = (!self.reasoning.is_empty()).then_some(self.reasoning);
217        if self.calls.is_empty() {
218            let mut m = Message::assistant(content.unwrap_or_default());
219            m.reasoning = reasoning;
220            m.finish_reason = self.finish_reason.clone();
221            return Ok(m);
222        }
223        let calls = self
224            .calls
225            .into_values()
226            .enumerate()
227            .map(|(i, c)| ToolCall {
228                id: if c.id.is_empty() {
229                    format!("call_{i}")
230                } else {
231                    c.id
232                },
233                kind: "function".into(),
234                function: FunctionCall {
235                    name: c.name,
236                    arguments: c.arguments,
237                },
238            })
239            .collect();
240        let mut m = Message::assistant_tool_calls(content, calls);
241        m.reasoning = reasoning;
242        m.finish_reason = self.finish_reason.clone();
243        Ok(m)
244    }
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250    use std::sync::Mutex;
251
252    #[test]
253    fn parser_handles_split_lines_crlf_comments_and_multiline_data() {
254        let mut p = SseParser::default();
255        assert!(p.push(b": keep-alive\n\ndata: one\n").is_empty());
256        assert_eq!(
257            p.push(b"\r\ndata:two\r\ndata: three\r\n\r\nda"),
258            ["one", "two\nthree"]
259        );
260        let ev = p.push(b"ta: x\n\n");
261        assert_eq!(ev, ["x"]);
262        // Event with an `event:` field and no space after the colon.
263        assert_eq!(p.push(b"event: ping\ndata:{}\n\n"), ["{}"]);
264    }
265
266    #[test]
267    fn parser_survives_a_multibyte_char_split_across_chunks() {
268        let bytes = "data: héllo\n\n".as_bytes();
269        let cut = bytes.iter().position(|b| *b == 0xC3).unwrap() + 1;
270        let mut p = SseParser::default();
271        assert!(p.push(&bytes[..cut]).is_empty());
272        assert_eq!(p.push(&bytes[cut..]), ["héllo"]);
273    }
274
275    #[test]
276    fn parser_finish_flushes_unterminated_tail() {
277        let mut p = SseParser::default();
278        assert!(p.push(b"data: [DONE]").is_empty());
279        assert_eq!(p.finish(), ["[DONE]"]);
280    }
281
282    fn feed(events: &[&str]) -> (Result<Message>, Vec<Delta>) {
283        let deltas = Mutex::new(Vec::new());
284        let sink = |d: Delta| deltas.lock().unwrap().push(d);
285        let mut acc = StreamAccumulator::default();
286        for e in events {
287            if let Err(e) = acc.push_event(e, &sink) {
288                return (Err(e), deltas.into_inner().unwrap());
289            }
290        }
291        (acc.finish(), deltas.into_inner().unwrap())
292    }
293
294    fn text_deltas(d: &[Delta]) -> Vec<String> {
295        d.iter()
296            .filter_map(|x| match x {
297                Delta::Text(t) => Some(t.clone()),
298                _ => None,
299            })
300            .collect()
301    }
302
303    #[test]
304    fn text_deltas_are_forwarded_and_joined() {
305        let (msg, deltas) = feed(&[
306            r#"{"choices":[{"delta":{"role":"assistant","content":""}}]}"#,
307            r#"{"choices":[{"delta":{"content":"Hel"}}]}"#,
308            r#"{"choices":[{"delta":{"content":"lo"},"finish_reason":null}]}"#,
309            r#"{"choices":[{"delta":{},"finish_reason":"stop"}]}"#,
310            r#"{"choices":[],"usage":{"total_tokens":3}}"#,
311            "[DONE]",
312        ]);
313        assert_eq!(text_deltas(&deltas), ["Hel", "lo"]);
314        let msg = msg.unwrap();
315        assert_eq!(msg.content.as_deref(), Some("Hello"));
316        assert_eq!(msg.finish_reason.as_deref(), Some("stop"));
317    }
318
319    #[test]
320    fn tool_call_fragments_are_assembled_by_index() {
321        let (msg, deltas) = feed(&[
322            r#"{"choices":[{"delta":{"content":"checking"}}]}"#,
323            r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","type":"function","function":{"name":"read_file","arguments":""}}]}}]}"#,
324            r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"path\":"}}]}}]}"#,
325            r#"{"choices":[{"delta":{"tool_calls":[{"index":1,"id":"","function":{"name":"shell","arguments":"{}"}}]}}]}"#,
326            r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"a\"}"}}]}}]}"#,
327            r#"{"choices":[{"delta":{},"finish_reason":"tool_calls"}]}"#,
328        ]);
329        assert_eq!(text_deltas(&deltas), ["checking"]);
330        let m = msg.unwrap();
331        assert_eq!(m.content.as_deref(), Some("checking"));
332        assert_eq!(m.tool_calls.len(), 2);
333        assert_eq!(m.tool_calls[0].id, "c1");
334        assert_eq!(m.tool_calls[0].function.name, "read_file");
335        assert_eq!(m.tool_calls[0].function.arguments, r#"{"path":"a"}"#);
336        assert_eq!(m.tool_calls[1].id, "call_1");
337        assert_eq!(m.tool_calls[1].function.name, "shell");
338    }
339
340    #[test]
341    fn tool_calls_without_index_are_still_separated() {
342        let (msg, _) = feed(&[
343            r#"{"choices":[{"delta":{"tool_calls":[{"id":"a","function":{"name":"x","arguments":"{"}}]}}]}"#,
344            r#"{"choices":[{"delta":{"tool_calls":[{"function":{"arguments":"}"}}]}}]}"#,
345            r#"{"choices":[{"delta":{"tool_calls":[{"id":"b","function":{"name":"y","arguments":"{}"}}]}}]}"#,
346            r#"{"choices":[{"finish_reason":"tool_calls"}]}"#,
347        ]);
348        let m = msg.unwrap();
349        assert_eq!(m.content, None);
350        let got: Vec<_> = m
351            .tool_calls
352            .iter()
353            .map(|c| (&*c.id, &*c.function.name, &*c.function.arguments))
354            .collect();
355        assert_eq!(got, [("a", "x", "{}"), ("b", "y", "{}")]);
356    }
357
358    #[test]
359    fn stream_without_completion_or_with_error_chunk_fails() {
360        let (msg, deltas) = feed(&[r#"{"choices":[{"delta":{"content":"partial"}}]}"#]);
361        assert_eq!(text_deltas(&deltas), ["partial"]);
362        let err = msg.unwrap_err();
363        assert!(err.to_string().contains("before it finished"), "{err}");
364        assert_eq!(
365            err.provider_failure().map(|f| f.kind()),
366            Some(crate::error::ProviderFailureKind::Truncated),
367            "a cut stream is classified, not just described"
368        );
369        let (msg, _) = feed(&[r#"{"error":{"message":"overloaded"}}"#]);
370        assert!(msg.unwrap_err().to_string().contains("overloaded"));
371        let (msg, _) = feed(&["{not json"]);
372        assert!(msg.unwrap_err().to_string().contains("malformed"));
373    }
374}
375
376#[cfg(test)]
377mod reasoning_tests {
378    use super::*;
379    use std::sync::Mutex;
380
381    #[test]
382    fn reasoning_deltas_are_forwarded_and_assembled() {
383        let deltas = Mutex::new(Vec::new());
384        let sink = |d: Delta| deltas.lock().unwrap().push(d);
385        let mut acc = StreamAccumulator::default();
386        acc.push_event(
387            r#"{"choices":[{"delta":{"reasoning_content":"thinking "}}]}"#,
388            &sink,
389        )
390        .unwrap();
391        acc.push_event(
392            r#"{"choices":[{"delta":{"reasoning_content":"hard"}}]}"#,
393            &sink,
394        )
395        .unwrap();
396        acc.push_event(
397            r#"{"choices":[{"delta":{"content":"answer"},"finish_reason":"stop"}]}"#,
398            &sink,
399        )
400        .unwrap();
401        let msg = acc.finish().unwrap();
402        let got = deltas.into_inner().unwrap();
403        assert!(got.contains(&Delta::Reasoning("thinking ".into())));
404        assert!(got.contains(&Delta::Reasoning("hard".into())));
405        assert_eq!(msg.reasoning.as_deref(), Some("thinking hard"));
406        assert_eq!(msg.content.as_deref(), Some("answer"));
407    }
408
409    #[test]
410    fn tool_call_arg_fragments_are_forwarded_with_their_index() {
411        let deltas = Mutex::new(Vec::new());
412        let sink = |d: Delta| deltas.lock().unwrap().push(d);
413        let mut acc = StreamAccumulator::default();
414        acc.push_event(
415            r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","function":{"name":"w","arguments":"{\"a\":"}}]}}]}"#,
416            &sink,
417        )
418        .unwrap();
419        acc.push_event(
420            r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"1}"}}]},"finish_reason":"tool_calls"}]}"#,
421            &sink,
422        )
423        .unwrap();
424        let got = deltas.into_inner().unwrap();
425        assert_eq!(
426            got,
427            [
428                Delta::ToolCallArgs {
429                    index: 0,
430                    json: "{\"a\":".into()
431                },
432                Delta::ToolCallArgs {
433                    index: 0,
434                    json: "1}".into()
435                },
436            ]
437        );
438        let msg = acc.finish().unwrap();
439        assert_eq!(msg.tool_calls[0].function.arguments, "{\"a\":1}");
440    }
441}