causa_protocol/translation/streaming/
decoder.rs1use std::collections::VecDeque;
2
3use causa_kernel::{ModelInvokeError, ModelInvokeErrorKind, StreamDelta};
4use serde_json::Value;
5
6use super::{
7 anthropic::Anthropic,
8 chat::Chat,
9 common::{located, misused, undecodable},
10 responses::Responses,
11};
12use crate::{Protocol, translation::sse_parser::SseParser};
13
14#[derive(Clone, Copy, Debug)]
20#[non_exhaustive]
21pub struct StreamLimits {
22 pub max_line_bytes: usize,
24 pub max_event_bytes: usize,
26 pub max_total_bytes: usize,
28 pub max_output_bytes: usize,
30 pub max_items: usize,
32 pub max_pending_deltas: usize,
34}
35
36impl Default for StreamLimits {
37 fn default() -> Self {
38 Self {
39 max_line_bytes: 32 * 1024 * 1024,
40 max_event_bytes: 32 * 1024 * 1024,
41 max_total_bytes: 64 * 1024 * 1024,
42 max_output_bytes: 16 * 1024 * 1024,
43 max_items: 1024,
44 max_pending_deltas: 4096,
45 }
46 }
47}
48
49enum Assembly {
50 Chat(Chat),
51 Responses(Responses),
52 Anthropic(Anthropic),
53}
54
55pub struct StreamDecoder {
59 parser: SseParser,
60 assembly: Assembly,
61 pending: VecDeque<StreamDelta>,
62 limits: StreamLimits,
63 total: usize,
64 events: usize,
65 terminal: bool,
66 failed: bool,
67}
68
69impl StreamDecoder {
70 pub fn new(protocol: Protocol, limits: StreamLimits) -> Result<Self, ModelInvokeError> {
72 if [
73 limits.max_line_bytes,
74 limits.max_event_bytes,
75 limits.max_total_bytes,
76 limits.max_output_bytes,
77 limits.max_items,
78 limits.max_pending_deltas,
79 ]
80 .contains(&0)
81 {
82 return Err(misused("stream limits must be positive"));
83 }
84 let assembly = match protocol {
85 Protocol::OpenAiChatCompletions => Assembly::Chat(Chat::new(limits)),
86 Protocol::OpenAiResponses => Assembly::Responses(Responses::new(limits)),
87 Protocol::AnthropicMessages => Assembly::Anthropic(Anthropic::new(limits)),
88 };
89 Ok(Self {
90 parser: SseParser::new().with_limits(limits.max_line_bytes, limits.max_event_bytes),
91 assembly,
92 pending: VecDeque::new(),
93 limits,
94 total: 0,
95 events: 0,
96 terminal: false,
97 failed: false,
98 })
99 }
100
101 pub fn decode(&mut self, input: &mut &[u8]) -> Result<Option<StreamDelta>, ModelInvokeError> {
104 if self.failed {
105 return Ok(None);
106 }
107 let result = self.decode_inner(input);
108 if result.is_err() {
109 self.failed = true;
110 self.pending.clear();
111 }
112 result
113 }
114
115 fn decode_inner(&mut self, input: &mut &[u8]) -> Result<Option<StreamDelta>, ModelInvokeError> {
116 if let Some(delta) = self.pending.pop_front() {
117 return Ok(Some(delta));
118 }
119 if self.terminal {
120 return Ok(None);
121 }
122 loop {
123 let before = input.len();
124 let remaining = self.limits.max_total_bytes - self.total;
127 if remaining == 0 && !input.is_empty() {
128 return Err(undecodable("stream exceeds max_total_bytes"));
129 }
130 let mut bounded = &input[..input.len().min(remaining)];
131 let bounded_len = bounded.len();
132 let parsed = self.parser.decode(&mut bounded);
133 let consumed = bounded_len - bounded.len();
134 *input = &input[consumed..];
135 self.total += consumed;
136 let Some(event) = parsed? else {
137 if self.total == self.limits.max_total_bytes && !input.is_empty() {
138 return Err(undecodable("stream exceeds max_total_bytes"));
139 }
140 return Ok(None);
141 };
142 self.events += 1;
143 let deltas = match &mut self.assembly {
144 Assembly::Chat(state) => state.event(&event),
145 Assembly::Responses(state) => state.event(&event),
146 Assembly::Anthropic(state) => state.event(&event),
147 }
148 .map_err(|error| located(error, self.events, &event))?;
149 if deltas.len() > self.limits.max_pending_deltas {
150 return Err(undecodable("stream exceeds max_pending_deltas"));
151 }
152 self.terminal = deltas.iter().any(|d| matches!(d, StreamDelta::Done { .. }));
153 self.pending.extend(deltas);
154 if let Some(delta) = self.pending.pop_front() {
155 return Ok(Some(delta));
156 }
157 if input.is_empty() || input.len() == before {
158 return Ok(None);
159 }
160 }
161 }
162
163 pub fn finish(&mut self) -> Result<(), ModelInvokeError> {
166 if self.failed {
167 return Err(misused("stream decoder is fused after an error"));
168 }
169 if self.terminal {
170 return Ok(());
171 }
172 self.failed = true;
173 self.parser.finish()?;
174 Err(ModelInvokeError::new(
175 ModelInvokeErrorKind::UnknownOutcome,
176 "stream ended without a provider terminal",
177 ))
178 }
179
180 pub fn is_terminal(&self) -> bool {
182 self.terminal
183 }
184}
185
186pub fn configure_stream_request(
191 protocol: Protocol,
192 body: &mut Value,
193) -> Result<(), ModelInvokeError> {
194 let object = body
195 .as_object_mut()
196 .ok_or_else(|| misused("stream request must be an object"))?;
197 object.insert("stream".into(), Value::Bool(true));
198 if protocol == Protocol::OpenAiChatCompletions {
199 let options = object
200 .entry("stream_options")
201 .or_insert_with(|| serde_json::json!({}));
202 if !options.is_object() {
203 *options = serde_json::json!({});
204 }
205 options
206 .as_object_mut()
207 .expect("stream_options is an object")
208 .insert("include_usage".into(), Value::Bool(true));
209 }
210 Ok(())
211}