Skip to main content

weirdnet_backends/
sse.rs

1//! OpenAI-style server-sent events from an engine, decoded into [`Chunk`]s.
2
3use serde_json::Value;
4use weirdnet_agent::ToolCall;
5use weirdnet_agent::remote::RemoteError;
6use weirdnet_agent::remote::infer::v2::Usage;
7
8use crate::error::engine_error;
9
10/// Splits a byte stream into SSE `data:` payloads.
11#[derive(Debug, Default)]
12pub struct SseParser {
13    buf: Vec<u8>,
14    data: String,
15}
16
17impl SseParser {
18    /// Feeds bytes; returns the payloads of every event completed by them.
19    pub fn feed(&mut self, bytes: &[u8]) -> Vec<String> {
20        self.buf.extend_from_slice(bytes);
21        let mut out = Vec::new();
22        while let Some(nl) = self.buf.iter().position(|&b| b == b'\n') {
23            let line: Vec<u8> = self.buf.drain(..=nl).collect();
24            let line = String::from_utf8_lossy(&line);
25            let line = line.trim_end_matches(['\n', '\r']);
26            if line.is_empty() {
27                if !self.data.is_empty() {
28                    out.push(std::mem::take(&mut self.data));
29                }
30            } else if let Some(rest) = line.strip_prefix("data:") {
31                if !self.data.is_empty() {
32                    self.data.push('\n');
33                }
34                self.data.push_str(rest.strip_prefix(' ').unwrap_or(rest));
35            }
36        }
37        out
38    }
39
40    /// Whatever is left when the stream ends without a blank line.
41    pub fn finish(&mut self) -> Option<String> {
42        let rest = self.feed(b"\n\n");
43        rest.into_iter().next()
44    }
45}
46
47/// One decoded piece of an engine's stream.
48#[derive(Debug, Clone, PartialEq)]
49#[non_exhaustive]
50pub enum Chunk {
51    Text(String),
52    Reasoning(String),
53    /// A fragment of a streamed tool call: the first fragment for an `index` has the id and name,
54    /// later ones add to the arguments. [`ToolCalls`] puts them together.
55    ToolCall {
56        index: u32,
57        id: Option<String>,
58        name: Option<String>,
59        arguments: String,
60    },
61    Done {
62        finish_reason: Option<String>,
63        usage: Option<Usage>,
64    },
65}
66
67/// Turns OpenAI `chat.completion.chunk` (and `text_completion`) JSON into [`Chunk`]s.
68#[derive(Debug, Default)]
69pub struct ChunkDecoder {
70    finish_reason: Option<String>,
71    usage: Option<Usage>,
72    done: bool,
73}
74
75impl ChunkDecoder {
76    /// Decodes one payload. `[DONE]` yields the final `Done`.
77    pub fn decode(&mut self, payload: &str) -> Result<Vec<Chunk>, RemoteError> {
78        if payload.trim() == "[DONE]" {
79            return Ok(self.finish().into_iter().collect());
80        }
81        let v: Value = serde_json::from_str(payload).map_err(|e| engine_error(format!("bad chunk: {e}")))?;
82        if let Some(err) = v.get("error") {
83            let msg = err.get("message").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| err.to_string());
84            return Err(engine_error(msg));
85        }
86        if let Some(u) = v.get("usage").filter(|u| u.is_object()) {
87            let mut usage = Usage::new(
88                u.get("prompt_tokens").and_then(Value::as_u64).unwrap_or(0),
89                u.get("completion_tokens").and_then(Value::as_u64).unwrap_or(0),
90            );
91            usage.cached_tokens = u.pointer("/prompt_tokens_details/cached_tokens").and_then(Value::as_u64).unwrap_or(0);
92            usage.reasoning_tokens = u.pointer("/completion_tokens_details/reasoning_tokens").and_then(Value::as_u64).unwrap_or(0);
93            self.usage = Some(usage);
94        }
95        let mut out = Vec::new();
96        let Some(choice) = v.get("choices").and_then(Value::as_array).and_then(|c| c.first()) else { return Ok(out) };
97        if let Some(reason) = choice.get("finish_reason").and_then(Value::as_str) {
98            self.finish_reason = Some(reason.to_string());
99        }
100        // `/v1/completions` chunks carry `text` instead of a delta.
101        if let Some(text) = choice.get("text").and_then(Value::as_str).filter(|t| !t.is_empty()) {
102            out.push(Chunk::Text(text.to_string()));
103        }
104        let Some(delta) = choice.get("delta") else { return Ok(out) };
105        for key in ["reasoning_content", "reasoning"] {
106            if let Some(text) = delta.get(key).and_then(Value::as_str).filter(|t| !t.is_empty()) {
107                out.push(Chunk::Reasoning(text.to_string()));
108                break;
109            }
110        }
111        if let Some(text) = delta.get("content").and_then(Value::as_str).filter(|t| !t.is_empty()) {
112            out.push(Chunk::Text(text.to_string()));
113        }
114        for (i, call) in delta.get("tool_calls").and_then(Value::as_array).into_iter().flatten().enumerate() {
115            let f = call.get("function");
116            out.push(Chunk::ToolCall {
117                index: call.get("index").and_then(Value::as_u64).unwrap_or(i as u64) as u32,
118                id: call.get("id").and_then(Value::as_str).map(str::to_string),
119                name: f.and_then(|f| f.get("name")).and_then(Value::as_str).map(str::to_string),
120                arguments: f.and_then(|f| f.get("arguments")).and_then(Value::as_str).unwrap_or("").to_string(),
121            });
122        }
123        Ok(out)
124    }
125
126    /// The `Done`, once.
127    pub fn finish(&mut self) -> Option<Chunk> {
128        if self.done {
129            return None;
130        }
131        self.done = true;
132        Some(Chunk::Done { finish_reason: self.finish_reason.take(), usage: self.usage })
133    }
134
135    /// The engine sent a finish reason or `[DONE]`.
136    pub fn complete(&self) -> bool {
137        self.done || self.finish_reason.is_some()
138    }
139}
140
141/// Puts streamed tool-call fragments together into whole calls, in index order.
142#[derive(Debug, Default)]
143pub struct ToolCalls {
144    calls: Vec<(u32, Option<String>, Option<String>, String)>,
145}
146
147impl ToolCalls {
148    pub fn push(&mut self, index: u32, id: Option<String>, name: Option<String>, arguments: &str) {
149        match self.calls.iter_mut().find(|c| c.0 == index) {
150            Some(c) => {
151                if c.1.is_none() {
152                    c.1 = id;
153                }
154                if c.2.is_none() {
155                    c.2 = name;
156                }
157                c.3.push_str(arguments);
158            }
159            None => self.calls.push((index, id, name, arguments.to_string())),
160        }
161    }
162
163    pub fn is_empty(&self) -> bool {
164        self.calls.is_empty()
165    }
166
167    /// The whole calls. Arguments that are not JSON are kept as a string; a call without an id
168    /// gets `call_<index>`.
169    pub fn finish(mut self) -> Vec<ToolCall> {
170        self.calls.sort_by_key(|c| c.0);
171        self.calls
172            .into_iter()
173            .map(|(index, id, name, args)| ToolCall {
174                id: id.unwrap_or_else(|| format!("call_{index}")),
175                name: name.unwrap_or_default(),
176                arguments: if args.trim().is_empty() {
177                    Value::Object(Default::default())
178                } else {
179                    serde_json::from_str(&args).unwrap_or(Value::String(args))
180                },
181            })
182            .collect()
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    #[test]
191    fn parses_split_events() {
192        let mut p = SseParser::default();
193        assert!(p.feed(b"data: {\"a\":").is_empty());
194        assert_eq!(p.feed(b"1}\r\n\r\ndata: [DONE]\n\n"), vec!["{\"a\":1}".to_string(), "[DONE]".to_string()]);
195    }
196
197    #[test]
198    fn decodes_llama_chunks() {
199        let mut d = ChunkDecoder::default();
200        assert!(d.decode(r#"{"choices":[{"index":0,"delta":{"role":"assistant","content":null}}]}"#).unwrap().is_empty());
201        assert_eq!(d.decode(r#"{"choices":[{"index":0,"delta":{"content":"Hello"}}]}"#).unwrap(), vec![Chunk::Text("Hello".into())]);
202        assert_eq!(d.decode(r#"{"choices":[{"index":0,"delta":{"reasoning_content":"hm"}}]}"#).unwrap(), vec![Chunk::Reasoning("hm".into())]);
203        d.decode(r#"{"choices":[{"index":0,"finish_reason":"stop","delta":{}}]}"#).unwrap();
204        d.decode(r#"{"choices":[],"usage":{"prompt_tokens":3,"completion_tokens":2,"prompt_tokens_details":{"cached_tokens":1}}}"#).unwrap();
205        let mut usage = Usage::new(3, 2);
206        usage.cached_tokens = 1;
207        assert_eq!(d.decode("[DONE]").unwrap(), vec![Chunk::Done { finish_reason: Some("stop".into()), usage: Some(usage) }]);
208        assert!(d.finish().is_none());
209    }
210
211    #[test]
212    fn completion_chunks() {
213        let mut d = ChunkDecoder::default();
214        assert_eq!(d.decode(r#"{"choices":[{"index":0,"text":"Once"}]}"#).unwrap(), vec![Chunk::Text("Once".into())]);
215    }
216
217    #[test]
218    fn tool_calls_and_errors() {
219        let mut d = ChunkDecoder::default();
220        let mut calls = ToolCalls::default();
221        for payload in [
222            r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","function":{"name":"f","arguments":"{\"x\""}}]}}]}"#,
223            r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":":1}"}}]}}]}"#,
224            r#"{"choices":[{"delta":{"tool_calls":[{"index":1,"function":{"name":"g","arguments":"not json"}}]}}]}"#,
225        ] {
226            for c in d.decode(payload).unwrap() {
227                if let Chunk::ToolCall { index, id, name, arguments } = c {
228                    calls.push(index, id, name, &arguments);
229                }
230            }
231        }
232        let calls = calls.finish();
233        assert_eq!((calls[0].id.as_str(), calls[0].name.as_str()), ("c1", "f"));
234        assert_eq!(calls[0].arguments, serde_json::json!({"x": 1}));
235        assert_eq!((calls[1].id.as_str(), calls[1].arguments.clone()), ("call_1", Value::String("not json".into())));
236        assert!(d.decode(r#"{"error":{"message":"boom"}}"#).is_err());
237    }
238}