Skip to main content

adk_model/openrouter/
stream.rs

1//! Shared SSE frame decoding for OpenRouter-native streaming APIs.
2#![allow(missing_docs)]
3
4use super::chat::OpenRouterChatResponse;
5use super::responses::{OpenRouterResponse, OpenRouterResponseOutputItem};
6use adk_core::{AdkError, ErrorCategory, ErrorComponent};
7use futures::Stream;
8use serde::{Deserialize, Serialize};
9use std::collections::BTreeMap;
10use std::pin::Pin;
11
12type JsonMap = BTreeMap<String, serde_json::Value>;
13
14/// One parsed SSE frame.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct OpenRouterSseFrame {
17    pub event: Option<String>,
18    pub data: String,
19    pub id: Option<String>,
20    pub retry: Option<u64>,
21}
22
23/// Stream type returned by `send_chat_stream`.
24pub type OpenRouterChatStream =
25    Pin<Box<dyn Stream<Item = Result<OpenRouterChatStreamItem, AdkError>> + Send>>;
26
27/// Stream type returned by `create_response_stream`.
28pub type OpenRouterResponsesStream =
29    Pin<Box<dyn Stream<Item = Result<OpenRouterResponsesStreamItem, AdkError>> + Send>>;
30
31/// One chat-stream item emitted by the OpenRouter streaming client.
32#[derive(Debug, Clone, PartialEq)]
33pub enum OpenRouterChatStreamItem {
34    Chunk(Box<OpenRouterChatResponse>),
35    Error(Box<OpenRouterStreamError>),
36    Done,
37}
38
39/// One Responses-stream item emitted by the OpenRouter streaming client.
40#[derive(Debug, Clone, PartialEq)]
41pub enum OpenRouterResponsesStreamItem {
42    Event(Box<OpenRouterResponsesStreamEvent>),
43    Error(Box<OpenRouterStreamError>),
44    Done,
45}
46
47/// Stream-level error payload emitted during SSE decoding.
48#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
49pub struct OpenRouterStreamError {
50    pub message: String,
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub code: Option<serde_json::Value>,
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub param: Option<String>,
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub error_type: Option<String>,
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub provider_name: Option<String>,
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub metadata: Option<serde_json::Value>,
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub sequence_number: Option<u64>,
63    #[serde(default, flatten)]
64    pub extra: JsonMap,
65}
66
67/// Generic typed Responses SSE event payload.
68#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
69pub struct OpenRouterResponsesStreamEvent {
70    #[serde(rename = "type")]
71    pub kind: String,
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub sequence_number: Option<u64>,
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub response: Option<OpenRouterResponse>,
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub output_index: Option<u32>,
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub item_id: Option<String>,
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub content_index: Option<u32>,
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub annotation_index: Option<u32>,
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub summary_index: Option<u32>,
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub delta: Option<String>,
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub text: Option<String>,
90    #[serde(default, skip_serializing_if = "Option::is_none")]
91    pub refusal: Option<String>,
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub name: Option<String>,
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub arguments: Option<String>,
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub logprobs: Option<Vec<serde_json::Value>>,
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub item: Option<OpenRouterResponseOutputItem>,
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub part: Option<serde_json::Value>,
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub annotation: Option<serde_json::Value>,
104    #[serde(default, flatten)]
105    pub extra: JsonMap,
106}
107
108/// Parse one complete SSE frame block into a typed frame.
109pub fn parse_sse_frame_block(block: &str) -> Option<OpenRouterSseFrame> {
110    let mut event = None;
111    let mut data_lines = Vec::new();
112    let mut id = None;
113    let mut retry = None;
114
115    for line in block.lines() {
116        if line.is_empty() || line.starts_with(':') {
117            continue;
118        }
119
120        let (field, raw_value) = line.split_once(':').unwrap_or((line, ""));
121        let value = raw_value.strip_prefix(' ').unwrap_or(raw_value);
122
123        match field {
124            "event" => event = Some(value.to_string()),
125            "data" => data_lines.push(value.to_string()),
126            "id" => id = Some(value.to_string()),
127            "retry" => retry = value.parse::<u64>().ok(),
128            _ => {}
129        }
130    }
131
132    if event.is_none() && data_lines.is_empty() && id.is_none() && retry.is_none() {
133        return None;
134    }
135
136    Some(OpenRouterSseFrame { event, data: data_lines.join("\n"), id, retry })
137}
138
139/// Parse a chat streaming frame into a typed stream item.
140pub fn parse_chat_stream_frame(
141    frame: &OpenRouterSseFrame,
142) -> Result<Option<OpenRouterChatStreamItem>, AdkError> {
143    if frame.data.trim().is_empty() {
144        return Ok(None);
145    }
146    if frame.data.trim() == "[DONE]" {
147        return Ok(Some(OpenRouterChatStreamItem::Done));
148    }
149
150    let value = parse_frame_json(
151        &frame.data,
152        "model.openrouter.chat_stream_invalid_json",
153        "OpenRouter chat stream emitted invalid JSON",
154    )?;
155
156    if value.get("error").is_some() {
157        return Ok(Some(OpenRouterChatStreamItem::Error(Box::new(parse_stream_error(&value)))));
158    }
159
160    let chunk = serde_json::from_value::<OpenRouterChatResponse>(value).map_err(|err| {
161        AdkError::new(
162            ErrorComponent::Model,
163            ErrorCategory::Internal,
164            "model.openrouter.chat_stream_invalid_chunk",
165            "OpenRouter chat stream emitted a chunk that could not be parsed",
166        )
167        .with_provider("openrouter")
168        .with_source(err)
169    })?;
170
171    Ok(Some(OpenRouterChatStreamItem::Chunk(Box::new(chunk))))
172}
173
174/// Parse a Responses streaming frame into a typed stream item.
175pub fn parse_responses_stream_frame(
176    frame: &OpenRouterSseFrame,
177) -> Result<Option<OpenRouterResponsesStreamItem>, AdkError> {
178    if frame.data.trim().is_empty() {
179        return Ok(None);
180    }
181    if frame.data.trim() == "[DONE]" {
182        return Ok(Some(OpenRouterResponsesStreamItem::Done));
183    }
184
185    let value = parse_frame_json(
186        &frame.data,
187        "model.openrouter.responses_stream_invalid_json",
188        "OpenRouter responses stream emitted invalid JSON",
189    )?;
190
191    if value.get("type").and_then(|item| item.as_str()) == Some("error") {
192        return Ok(Some(OpenRouterResponsesStreamItem::Error(Box::new(parse_stream_error(
193            &value,
194        )))));
195    }
196
197    let event = serde_json::from_value::<OpenRouterResponsesStreamEvent>(value).map_err(|err| {
198        AdkError::new(
199            ErrorComponent::Model,
200            ErrorCategory::Internal,
201            "model.openrouter.responses_stream_invalid_event",
202            "OpenRouter responses stream emitted an event that could not be parsed",
203        )
204        .with_provider("openrouter")
205        .with_source(err)
206    })?;
207
208    Ok(Some(OpenRouterResponsesStreamItem::Event(Box::new(event))))
209}
210
211/// Stateful SSE decoder that accepts arbitrarily chunked text input.
212#[derive(Debug, Default)]
213pub struct OpenRouterSseDecoder {
214    buffer: String,
215    /// Bytes of a UTF-8 character whose remaining bytes have not arrived yet.
216    partial_utf8: Vec<u8>,
217}
218
219impl OpenRouterSseDecoder {
220    /// Create a new decoder with an empty internal buffer.
221    pub fn new() -> Self {
222        Self::default()
223    }
224
225    /// Push a UTF-8 text chunk into the decoder and return any completed SSE frames.
226    pub fn push(&mut self, chunk: &str) -> Vec<OpenRouterSseFrame> {
227        self.buffer.push_str(chunk);
228        // Normalized over the whole buffer, so a `\r\n` split across two chunks still joins.
229        if self.buffer.contains("\r\n") {
230            self.buffer = self.buffer.replace("\r\n", "\n");
231        }
232
233        let mut frames = Vec::new();
234
235        while let Some(delimiter_index) = self.buffer.find("\n\n") {
236            let block = self.buffer[..delimiter_index].to_string();
237            self.buffer.drain(..delimiter_index + 2);
238
239            if let Some(frame) = parse_sse_frame_block(&block) {
240                frames.push(frame);
241            }
242        }
243
244        frames
245    }
246
247    /// Push raw network bytes and return any completed SSE frames.
248    ///
249    /// A chunk may end inside a multi-byte UTF-8 character; its leading bytes wait for the
250    /// next chunk instead of being decoded as replacement characters.
251    ///
252    /// # Example
253    ///
254    /// ```
255    /// use adk_model::openrouter::OpenRouterSseDecoder;
256    ///
257    /// let frame = "data: {\"delta\":\"πŸ™‚\"}\n\n".as_bytes();
258    /// let mut decoder = OpenRouterSseDecoder::new();
259    /// // Byte 18 falls inside the four-byte emoji.
260    /// assert!(decoder.push_bytes(&frame[..18])?.is_empty());
261    /// let frames = decoder.push_bytes(&frame[18..])?;
262    /// assert_eq!(frames[0].data, "{\"delta\":\"πŸ™‚\"}");
263    /// # Ok::<(), adk_core::AdkError>(())
264    /// ```
265    ///
266    /// # Errors
267    ///
268    /// Returns an error when the bytes are not valid UTF-8.
269    pub fn push_bytes(&mut self, chunk: &[u8]) -> Result<Vec<OpenRouterSseFrame>, AdkError> {
270        let invalid = || {
271            AdkError::new(
272                ErrorComponent::Model,
273                ErrorCategory::Internal,
274                "model.openrouter.stream_invalid_utf8",
275                "OpenRouter stream emitted bytes that are not valid UTF-8",
276            )
277            .with_provider("openrouter")
278        };
279        self.partial_utf8.extend_from_slice(chunk);
280        let complete = match std::str::from_utf8(&self.partial_utf8) {
281            Ok(_) => self.partial_utf8.len(),
282            // `error_len() == None` means the input ends inside a character.
283            Err(error) if error.error_len().is_none() => error.valid_up_to(),
284            Err(_) => return Err(invalid()),
285        };
286        let text =
287            std::str::from_utf8(&self.partial_utf8[..complete]).map_err(|_| invalid())?.to_owned();
288        self.partial_utf8.drain(..complete);
289        Ok(self.push(&text))
290    }
291
292    /// Drain any remaining complete frame buffered in the decoder.
293    pub fn finish(self) -> Vec<OpenRouterSseFrame> {
294        if self.buffer.trim().is_empty() {
295            return Vec::new();
296        }
297
298        parse_sse_frame_block(self.buffer.trim_end()).into_iter().collect()
299    }
300}
301
302fn parse_frame_json(
303    data: &str,
304    code: &'static str,
305    message: &'static str,
306) -> Result<serde_json::Value, AdkError> {
307    serde_json::from_str(data).map_err(|err| {
308        AdkError::new(ErrorComponent::Model, ErrorCategory::Internal, code, message)
309            .with_provider("openrouter")
310            .with_source(err)
311    })
312}
313
314pub(super) fn parse_stream_error(value: &serde_json::Value) -> OpenRouterStreamError {
315    let error = value.get("error").unwrap_or(value);
316    let mut stream_error = OpenRouterStreamError::default();
317
318    if let Some(message) = error.get("message").and_then(|item| item.as_str()) {
319        stream_error.message = message.to_string();
320    }
321    if let Some(code) = error.get("code") {
322        stream_error.code = Some(code.clone());
323    }
324    if let Some(param) = error.get("param").and_then(|item| item.as_str()) {
325        stream_error.param = Some(param.to_string());
326    }
327    if let Some(error_type) = error.get("type").and_then(|item| item.as_str()) {
328        stream_error.error_type = Some(error_type.to_string());
329    }
330    if let Some(provider_name) = error.get("provider_name").and_then(|item| item.as_str()) {
331        stream_error.provider_name = Some(provider_name.to_string());
332    }
333    if let Some(metadata) = error.get("metadata") {
334        stream_error.metadata = Some(metadata.clone());
335    }
336    if let Some(sequence_number) = value.get("sequence_number").and_then(|item| item.as_u64()) {
337        stream_error.sequence_number = Some(sequence_number);
338    }
339
340    if let Some(object) = value.as_object() {
341        stream_error.extra = object
342            .iter()
343            .filter(|(key, _)| {
344                !matches!(
345                    key.as_str(),
346                    "error"
347                        | "message"
348                        | "code"
349                        | "param"
350                        | "type"
351                        | "provider_name"
352                        | "metadata"
353                        | "sequence_number"
354                )
355            })
356            .map(|(key, item)| (key.clone(), item.clone()))
357            .collect();
358    }
359
360    stream_error
361}
362
363#[cfg(test)]
364mod tests {
365    use super::{
366        OpenRouterChatStreamItem, OpenRouterResponsesStreamItem, OpenRouterSseDecoder,
367        OpenRouterSseFrame, parse_chat_stream_frame, parse_responses_stream_frame,
368        parse_sse_frame_block,
369    };
370    use serde_json::json;
371
372    #[test]
373    fn sse_decoder_reassembles_chunked_frames() {
374        let mut decoder = OpenRouterSseDecoder::new();
375        let first = decoder.push("data: {\"type\":\"response.output_text.delta\"");
376        let second = decoder.push(",\"delta\":\"hel\"}\n\n");
377
378        assert!(first.is_empty());
379        assert_eq!(second.len(), 1);
380        assert_eq!(second[0].data, "{\"type\":\"response.output_text.delta\",\"delta\":\"hel\"}");
381    }
382
383    #[test]
384    fn sse_decoder_keeps_characters_split_across_byte_chunks() {
385        let body = "data: {\"delta\":\"Γ©δΈ­πŸ™‚\"}\r\n\r\n".as_bytes();
386        for split in 1..body.len() {
387            let mut decoder = OpenRouterSseDecoder::new();
388            let mut frames = decoder.push_bytes(&body[..split]).expect("valid prefix");
389            frames.extend(decoder.push_bytes(&body[split..]).expect("valid suffix"));
390            assert_eq!(frames.len(), 1, "split at {split}");
391            assert_eq!(frames[0].data, "{\"delta\":\"Γ©δΈ­πŸ™‚\"}", "split at {split}");
392        }
393    }
394
395    #[test]
396    fn sse_decoder_rejects_invalid_utf8() {
397        let mut decoder = OpenRouterSseDecoder::new();
398        let error = decoder.push_bytes(b"data: \xc3(\n\n").expect_err("invalid UTF-8");
399        assert_eq!(error.code, "model.openrouter.stream_invalid_utf8");
400    }
401
402    #[test]
403    fn parse_sse_frame_block_collects_multiline_data() {
404        let frame = parse_sse_frame_block("event: message\ndata: first\ndata: second\nid: 1")
405            .expect("frame should parse");
406
407        assert_eq!(frame.event.as_deref(), Some("message"));
408        assert_eq!(frame.data, "first\nsecond");
409        assert_eq!(frame.id.as_deref(), Some("1"));
410    }
411
412    #[test]
413    fn chat_stream_parser_handles_done_sentinel() {
414        let item = parse_chat_stream_frame(&OpenRouterSseFrame {
415            event: None,
416            data: "[DONE]".to_string(),
417            id: None,
418            retry: None,
419        })
420        .expect("frame should parse")
421        .expect("done item should be emitted");
422
423        assert!(matches!(item, OpenRouterChatStreamItem::Done));
424    }
425
426    #[test]
427    fn chat_stream_parser_handles_error_frames() {
428        let item = parse_chat_stream_frame(&OpenRouterSseFrame {
429            event: None,
430            data: json!({
431                "id": "chatcmpl-1",
432                "created": 1,
433                "model": "openai/gpt-5.2",
434                "object": "chat.completion.chunk",
435                "choices": [],
436                "error": {
437                    "message": "Rate limit exceeded",
438                    "code": 429
439                }
440            })
441            .to_string(),
442            id: None,
443            retry: None,
444        })
445        .expect("frame should parse")
446        .expect("error item should be emitted");
447
448        match item {
449            OpenRouterChatStreamItem::Error(error) => {
450                assert_eq!(error.message, "Rate limit exceeded");
451                assert_eq!(error.code, Some(json!(429)));
452                assert_eq!(error.error_type.as_deref(), None);
453            }
454            other => panic!("expected error item, got {other:?}"),
455        }
456    }
457
458    #[test]
459    fn chat_stream_parser_handles_partial_text_and_function_call_arguments() {
460        let item = parse_chat_stream_frame(&OpenRouterSseFrame {
461            event: None,
462            data: json!({
463                "id": "chatcmpl-1",
464                "created": 1,
465                "model": "openai/gpt-5.2",
466                "object": "chat.completion.chunk",
467                "choices": [
468                    {
469                        "index": 0,
470                        "delta": {
471                            "role": "assistant",
472                            "content": "hel",
473                            "audio": {
474                                "id": "aud_1",
475                                "delta": "AAAA"
476                            },
477                            "tool_calls": [
478                                {
479                                    "id": "call_1",
480                                    "type": "function",
481                                    "function": {
482                                        "name": "lookup_weather",
483                                        "arguments": "{\"city\":\"San"
484                                    }
485                                }
486                            ]
487                        }
488                    }
489                ]
490            })
491            .to_string(),
492            id: None,
493            retry: None,
494        })
495        .expect("frame should parse")
496        .expect("chunk should be emitted");
497
498        match item {
499            OpenRouterChatStreamItem::Chunk(chunk) => {
500                let delta = chunk
501                    .choices
502                    .first()
503                    .and_then(|choice| choice.delta.as_ref())
504                    .expect("delta should exist");
505                assert_eq!(delta.role, "assistant");
506                assert_eq!(
507                    delta.content.as_ref(),
508                    Some(&crate::openrouter::chat::OpenRouterChatMessageContent::Text(
509                        "hel".to_string(),
510                    ))
511                );
512                assert_eq!(
513                    delta
514                        .tool_calls
515                        .as_ref()
516                        .and_then(|calls| calls.first())
517                        .and_then(|call| call.function.as_ref())
518                        .and_then(|function| function.arguments.as_deref()),
519                    Some("{\"city\":\"San")
520                );
521                assert_eq!(
522                    delta.extra.get("audio").and_then(|audio| audio.get("delta")),
523                    Some(&json!("AAAA"))
524                );
525            }
526            other => panic!("expected chunk item, got {other:?}"),
527        }
528    }
529
530    #[test]
531    fn chat_stream_parser_allows_partial_tool_call_chunks_without_name() {
532        let item = parse_chat_stream_frame(&OpenRouterSseFrame {
533            event: None,
534            data: json!({
535                "id": "chatcmpl-1",
536                "created": 1,
537                "model": "openai/gpt-5.2",
538                "object": "chat.completion.chunk",
539                "choices": [
540                    {
541                        "index": 0,
542                        "delta": {
543                            "tool_calls": [
544                                {
545                                    "id": "call_1",
546                                    "function": {
547                                        "arguments": "{\"city\":\"Nai"
548                                    }
549                                }
550                            ]
551                        }
552                    }
553                ]
554            })
555            .to_string(),
556            id: None,
557            retry: None,
558        })
559        .expect("frame should parse")
560        .expect("chunk should be emitted");
561
562        match item {
563            OpenRouterChatStreamItem::Chunk(chunk) => {
564                let function = chunk
565                    .choices
566                    .first()
567                    .and_then(|choice| choice.delta.as_ref())
568                    .and_then(|delta| delta.tool_calls.as_ref())
569                    .and_then(|calls| calls.first())
570                    .and_then(|call| call.function.as_ref())
571                    .expect("function should exist");
572
573                assert_eq!(function.name.as_deref(), None);
574                assert_eq!(function.arguments.as_deref(), Some("{\"city\":\"Nai"));
575            }
576            other => panic!("expected chunk item, got {other:?}"),
577        }
578    }
579
580    #[test]
581    fn responses_stream_parser_handles_reasoning_and_annotation_events() {
582        let reasoning = parse_responses_stream_frame(&OpenRouterSseFrame {
583            event: None,
584            data: json!({
585                "type": "response.reasoning_text.delta",
586                "output_index": 0,
587                "item_id": "item-1",
588                "content_index": 0,
589                "delta": "Thinking...",
590                "sequence_number": 4
591            })
592            .to_string(),
593            id: None,
594            retry: None,
595        })
596        .expect("reasoning frame should parse")
597        .expect("reasoning event should be emitted");
598
599        match reasoning {
600            OpenRouterResponsesStreamItem::Event(event) => {
601                assert_eq!(event.kind, "response.reasoning_text.delta");
602                assert_eq!(event.delta.as_deref(), Some("Thinking..."));
603            }
604            other => panic!("expected reasoning event, got {other:?}"),
605        }
606
607        let annotation = parse_responses_stream_frame(&OpenRouterSseFrame {
608            event: None,
609            data: json!({
610                "type": "response.output_text.annotation.added",
611                "output_index": 0,
612                "item_id": "item-1",
613                "content_index": 0,
614                "annotation_index": 0,
615                "annotation": {
616                    "type": "url_citation",
617                    "url": "https://example.com",
618                    "title": "Example"
619                },
620                "sequence_number": 5
621            })
622            .to_string(),
623            id: None,
624            retry: None,
625        })
626        .expect("annotation frame should parse")
627        .expect("annotation event should be emitted");
628
629        match annotation {
630            OpenRouterResponsesStreamItem::Event(event) => {
631                assert_eq!(event.kind, "response.output_text.annotation.added");
632                assert_eq!(event.annotation_index, Some(0));
633                assert_eq!(
634                    event.annotation.as_ref().and_then(|annotation| annotation.get("type")),
635                    Some(&json!("url_citation"))
636                );
637            }
638            other => panic!("expected annotation event, got {other:?}"),
639        }
640    }
641}