1use std::collections::BTreeMap;
7use std::sync::Arc;
8
9use serde::{Deserialize, Serialize};
10use serde_json::{Map, Value, json};
11
12use crate::LlmResponseChunk;
13use crate::codecs::anthropic::AnthropicMessagesStreamCodec;
14use crate::codecs::openai_chat::OpenAiChatStreamCodec;
15use crate::codecs::responses::OpenAiResponsesStreamCodec;
16use crate::engine::{FormatRegistry, TranslationEngine};
17use crate::error::{Result, TranslationError};
18use crate::format::{FormatId, WireFormat};
19use crate::llm::Usage;
20
21#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
23pub struct StreamTranslationState {
24 pub source: Option<FormatId>,
25 pub target: Option<FormatId>,
26 pub model: Option<String>,
28 pub message_id: Option<String>,
30 pub target_model: Option<String>,
33 pub target_message_id: Option<String>,
35 pub saw_message_start: bool,
36 pub emitted_message_start: bool,
37 pub finished: bool,
38 pub errored: bool,
40 pub usage: Usage,
41
42 pub(crate) output_tokens_seen: u64,
43 pub(crate) saw_backend_usage: bool,
44 pub(crate) stop_reason: Option<String>,
45 pub(crate) stop_details: Option<Value>,
48 pub(crate) emitted_message_delta: bool,
49
50 pub(crate) next_content_index: usize,
51 pub(crate) text_block_index: Option<usize>,
52 pub(crate) text_block_started: bool,
53 pub(crate) emitted_content_block: bool,
54 pub(crate) tool_states: BTreeMap<usize, StreamToolState>,
55 #[serde(default)]
56 pub(crate) pending_chat_tool_names: BTreeMap<usize, String>,
57 #[serde(default)]
58 pub(crate) active_anthropic_tool: Option<usize>,
59 #[serde(default)]
60 pub(crate) deferred_anthropic_tools: Vec<usize>,
61 #[serde(default)]
63 pub(crate) empty_anthropic_tool_inputs: std::collections::BTreeSet<usize>,
64 pub(crate) decoded_reasoning: BTreeMap<usize, String>,
67 pub(crate) decoded_reasoning_encrypted: std::collections::BTreeSet<usize>,
69 pub(crate) decoded_tool_call: bool,
72 #[serde(default)]
74 pub(crate) decoded_response_text: BTreeMap<usize, BTreeMap<usize, String>>,
75
76 pub(crate) response_created: bool,
77 pub(crate) response_text_started: bool,
78 pub(crate) response_text_output_index: Option<usize>,
79 pub(crate) response_text: String,
80 pub(crate) response_reasoning: BTreeMap<usize, ResponseReasoningState>,
84 pub(crate) decoded_reasoning_ids: std::collections::BTreeSet<usize>,
86 pub(crate) next_response_output_index: usize,
87 pub(crate) response_sequence_number: u64,
88 pub(crate) next_chat_tool_index: usize,
89
90 pub(crate) reasoning_block_index: Option<usize>,
91 pub(crate) reasoning_block_started: bool,
92}
93
94#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
96pub(crate) struct ResponseReasoningState {
97 pub(crate) started: bool,
99 pub(crate) summary_started: bool,
102 pub(crate) output_index: Option<usize>,
103 pub(crate) item_id: Option<String>,
106 pub(crate) text: String,
107 pub(crate) encrypted: Option<String>,
110 #[serde(default)]
111 pub(crate) anthropic_signature: Option<String>,
112 #[serde(default)]
115 pub(crate) pending_text: String,
116}
117
118#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
120pub(crate) struct StreamToolState {
121 pub(crate) id: Option<String>,
122 pub(crate) name: Option<String>,
123 pub(crate) arguments: String,
124 pub(crate) decoded_arguments: String,
132 #[serde(default)]
133 pub(crate) has_decoded_identity: bool,
134 #[serde(default)]
138 pub(crate) decoded_custom_call: bool,
139 pub(crate) pending_arguments: String,
140 pub(crate) started: bool,
141 pub(crate) content_index: Option<usize>,
142 pub(crate) chat_tool_index: Option<usize>,
146 pub(crate) response_output_index: Option<usize>,
147 pub(crate) response_item_id: Option<String>,
148}
149
150impl StreamTranslationState {
151 pub fn new(source: impl Into<FormatId>, target: impl Into<FormatId>) -> Self {
153 Self {
154 source: Some(source.into()),
155 target: Some(target.into()),
156 ..Self::default()
157 }
158 }
159}
160
161#[derive(Default)]
163pub struct StreamTranslationEngine {
164 engine: TranslationEngine,
165}
166
167pub trait StreamCodec: Send + Sync {
169 fn format(&self) -> FormatId;
171
172 fn is_terminal_event(&self, event: &Value) -> bool;
174
175 fn sse_done_is_terminal(&self) -> bool;
180
181 fn stamp_streamed_response_model(&self, event: &mut Value, served_model: &str);
185
186 fn decode_event(
188 &self,
189 state: &mut StreamTranslationState,
190 event: &Value,
191 ) -> Vec<LlmResponseChunk>;
192
193 fn encode_event(
195 &self,
196 state: &mut StreamTranslationState,
197 event: LlmResponseChunk,
198 ) -> Vec<Value>;
199
200 fn observe_replayed_event(
208 &self,
209 state: &mut StreamTranslationState,
210 _raw: &Value,
211 normalized: Vec<LlmResponseChunk>,
212 ) {
213 let replayed_terminal = normalized
214 .iter()
215 .any(|chunk| matches!(chunk, LlmResponseChunk::MessageStop { .. }));
216 for chunk in normalized {
217 drop(self.encode_event(state, chunk));
218 }
219 if replayed_terminal {
220 state.finished = true;
221 }
222 }
223
224 fn finish(&self, state: &mut StreamTranslationState) -> Vec<Value>;
233}
234
235#[derive(Default)]
237pub struct StreamCodecRegistry {
238 codecs: BTreeMap<FormatId, Arc<dyn StreamCodec>>,
239}
240
241impl StreamCodecRegistry {
242 pub fn new() -> Self {
244 Self::default()
245 }
246
247 pub fn with_builtins() -> Self {
249 let mut registry = Self::new();
250 registry.register(OpenAiChatStreamCodec);
251 registry.register(AnthropicMessagesStreamCodec);
252 registry.register(OpenAiResponsesStreamCodec);
253 registry
254 }
255
256 pub fn register(&mut self, codec: impl StreamCodec + 'static) {
258 self.codecs.insert(codec.format(), Arc::new(codec));
259 }
260
261 pub fn codec(&self, format: impl Into<FormatId>) -> Result<Arc<dyn StreamCodec>> {
263 let format = format.into();
264 self.codecs.get(&format).cloned().ok_or_else(|| {
265 TranslationError::Other(format!("no stream codec registered for {format}"))
266 })
267 }
268}
269
270impl StreamTranslationEngine {
271 pub fn new(registry: StreamCodecRegistry) -> Self {
273 Self {
274 engine: TranslationEngine::with_registries(FormatRegistry::with_builtins(), registry),
275 }
276 }
277
278 pub fn translate_event(
280 &self,
281 state: &mut StreamTranslationState,
282 source: impl Into<FormatId>,
283 target: impl Into<FormatId>,
284 event: &Value,
285 ) -> Result<Vec<Value>> {
286 self.engine.translate_event(state, source, target, event)
287 }
288
289 pub fn finish(
291 &self,
292 state: &mut StreamTranslationState,
293 target: impl Into<FormatId>,
294 ) -> Result<Vec<Value>> {
295 self.engine.finish_stream(state, target)
296 }
297
298 pub fn translate_event_with_builtins(
300 state: &mut StreamTranslationState,
301 source: impl Into<FormatId>,
302 target: impl Into<FormatId>,
303 event: &Value,
304 ) -> Vec<Value> {
305 Self::default()
306 .translate_event(state, source, target, event)
307 .unwrap_or_else(|error| vec![json!({"error": {"message": error.to_string()}})])
308 }
309}
310
311pub fn decode_stream_event(
313 state: &mut StreamTranslationState,
314 source: impl Into<FormatId>,
315 event: &Value,
316) -> Vec<LlmResponseChunk> {
317 let source = source.into();
318 StreamCodecRegistry::with_builtins()
319 .codec(source)
320 .map(|codec| codec.decode_event(state, event))
321 .unwrap_or_else(|error| {
322 vec![LlmResponseChunk::DecodeError {
325 message: error.to_string(),
326 }]
327 })
328}
329
330pub(crate) fn encode_response_stream_event(
331 state: &mut StreamTranslationState,
332 target_codec: &dyn StreamCodec,
333 target: &FormatId,
334 event: crate::LlmResponseStreamEvent,
335) -> Vec<Value> {
336 if state.errored {
337 return Vec::new();
338 }
339 let (preservation, normalized) = event.into_parts();
340 if let Some(preservation) = preservation {
341 let (source, raw) = preservation.into_parts();
342 if let Err(error) = super::responses::validate_stream_output(&source, target, &raw) {
343 return target_codec.encode_event(
344 state,
345 LlmResponseChunk::DecodeError {
346 message: error.to_string(),
347 },
348 );
349 }
350 let has_decode_error = normalized
352 .iter()
353 .any(|chunk| matches!(chunk, LlmResponseChunk::DecodeError { .. }));
354 if &source == target && !has_decode_error {
355 target_codec.observe_replayed_event(state, &raw, normalized);
360 return vec![raw];
361 }
362 }
363
364 normalized
365 .into_iter()
366 .flat_map(|chunk| target_codec.encode_event(state, chunk))
367 .collect()
368}
369
370pub fn encode_stream_event(
372 state: &mut StreamTranslationState,
373 target: impl Into<FormatId>,
374 event: LlmResponseChunk,
375) -> Vec<Value> {
376 StreamCodecRegistry::with_builtins()
377 .codec(target)
378 .map(|codec| codec.encode_event(state, event))
379 .unwrap_or_else(|error| vec![json!({"error": {"message": error.to_string()}})])
380}
381
382pub(crate) fn record_source_identity(
384 state: &mut StreamTranslationState,
385 id: Option<String>,
386 model: Option<String>,
387) {
388 if id.is_some() {
389 state.message_id = id;
390 }
391 if model.is_some() {
392 state.model = model;
393 }
394}
395
396pub(crate) fn target_model_or_source_model(state: &StreamTranslationState) -> String {
398 state
399 .target_model
400 .clone()
401 .or_else(|| state.model.clone())
402 .unwrap_or_else(|| "unknown".to_string())
403}
404
405pub(crate) fn target_message_id_or_source_message_id(
407 state: &StreamTranslationState,
408) -> Option<&str> {
409 state
410 .target_message_id
411 .as_deref()
412 .or(state.message_id.as_deref())
413}
414
415pub(crate) fn state_source_is(state: &StreamTranslationState, format: WireFormat) -> bool {
417 let format_id: FormatId = format.into();
418 match &state.source {
419 Some(source) => source == &format_id,
420 None => false,
421 }
422}
423
424pub(crate) fn string_field(object: &Map<String, Value>, key: &str) -> Option<String> {
426 object
427 .get(key)
428 .and_then(Value::as_str)
429 .filter(|value| !value.is_empty())
430 .map(ToOwned::to_owned)
431}