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 decode_event(
174 &self,
175 state: &mut StreamTranslationState,
176 event: &Value,
177 ) -> Vec<LlmResponseChunk>;
178
179 fn encode_event(
181 &self,
182 state: &mut StreamTranslationState,
183 event: LlmResponseChunk,
184 ) -> Vec<Value>;
185
186 fn observe_replayed_event(
194 &self,
195 state: &mut StreamTranslationState,
196 _raw: &Value,
197 normalized: Vec<LlmResponseChunk>,
198 ) {
199 let replayed_terminal = normalized
200 .iter()
201 .any(|chunk| matches!(chunk, LlmResponseChunk::MessageStop { .. }));
202 for chunk in normalized {
203 drop(self.encode_event(state, chunk));
204 }
205 if replayed_terminal {
206 state.finished = true;
207 }
208 }
209
210 fn finish(&self, state: &mut StreamTranslationState) -> Vec<Value>;
219}
220
221#[derive(Default)]
223pub struct StreamCodecRegistry {
224 codecs: BTreeMap<FormatId, Arc<dyn StreamCodec>>,
225}
226
227impl StreamCodecRegistry {
228 pub fn new() -> Self {
230 Self::default()
231 }
232
233 pub fn with_builtins() -> Self {
235 let mut registry = Self::new();
236 registry.register(OpenAiChatStreamCodec);
237 registry.register(AnthropicMessagesStreamCodec);
238 registry.register(OpenAiResponsesStreamCodec);
239 registry
240 }
241
242 pub fn register(&mut self, codec: impl StreamCodec + 'static) {
244 self.codecs.insert(codec.format(), Arc::new(codec));
245 }
246
247 pub fn codec(&self, format: impl Into<FormatId>) -> Result<Arc<dyn StreamCodec>> {
249 let format = format.into();
250 self.codecs.get(&format).cloned().ok_or_else(|| {
251 TranslationError::Other(format!("no stream codec registered for {format}"))
252 })
253 }
254}
255
256impl StreamTranslationEngine {
257 pub fn new(registry: StreamCodecRegistry) -> Self {
259 Self {
260 engine: TranslationEngine::with_registries(FormatRegistry::with_builtins(), registry),
261 }
262 }
263
264 pub fn translate_event(
266 &self,
267 state: &mut StreamTranslationState,
268 source: impl Into<FormatId>,
269 target: impl Into<FormatId>,
270 event: &Value,
271 ) -> Result<Vec<Value>> {
272 self.engine.translate_event(state, source, target, event)
273 }
274
275 pub fn finish(
277 &self,
278 state: &mut StreamTranslationState,
279 target: impl Into<FormatId>,
280 ) -> Result<Vec<Value>> {
281 self.engine.finish_stream(state, target)
282 }
283
284 pub fn translate_event_with_builtins(
286 state: &mut StreamTranslationState,
287 source: impl Into<FormatId>,
288 target: impl Into<FormatId>,
289 event: &Value,
290 ) -> Vec<Value> {
291 Self::default()
292 .translate_event(state, source, target, event)
293 .unwrap_or_else(|error| vec![json!({"error": {"message": error.to_string()}})])
294 }
295}
296
297pub fn decode_stream_event(
299 state: &mut StreamTranslationState,
300 source: impl Into<FormatId>,
301 event: &Value,
302) -> Vec<LlmResponseChunk> {
303 let source = source.into();
304 StreamCodecRegistry::with_builtins()
305 .codec(source)
306 .map(|codec| codec.decode_event(state, event))
307 .unwrap_or_else(|error| {
308 vec![LlmResponseChunk::DecodeError {
311 message: error.to_string(),
312 }]
313 })
314}
315
316pub(crate) fn encode_response_stream_event(
317 state: &mut StreamTranslationState,
318 target_codec: &dyn StreamCodec,
319 target: &FormatId,
320 event: crate::LlmResponseStreamEvent,
321) -> Vec<Value> {
322 if state.errored {
323 return Vec::new();
324 }
325 let (preservation, normalized) = event.into_parts();
326 if let Some(preservation) = preservation {
327 let (source, raw) = preservation.into_parts();
328 if let Err(error) = super::responses::validate_stream_output(&source, target, &raw) {
329 return target_codec.encode_event(
330 state,
331 LlmResponseChunk::DecodeError {
332 message: error.to_string(),
333 },
334 );
335 }
336 let has_decode_error = normalized
338 .iter()
339 .any(|chunk| matches!(chunk, LlmResponseChunk::DecodeError { .. }));
340 if &source == target && !has_decode_error {
341 target_codec.observe_replayed_event(state, &raw, normalized);
346 return vec![raw];
347 }
348 }
349
350 normalized
351 .into_iter()
352 .flat_map(|chunk| target_codec.encode_event(state, chunk))
353 .collect()
354}
355
356pub fn encode_stream_event(
358 state: &mut StreamTranslationState,
359 target: impl Into<FormatId>,
360 event: LlmResponseChunk,
361) -> Vec<Value> {
362 StreamCodecRegistry::with_builtins()
363 .codec(target)
364 .map(|codec| codec.encode_event(state, event))
365 .unwrap_or_else(|error| vec![json!({"error": {"message": error.to_string()}})])
366}
367
368pub(crate) fn record_source_identity(
370 state: &mut StreamTranslationState,
371 id: Option<String>,
372 model: Option<String>,
373) {
374 if id.is_some() {
375 state.message_id = id;
376 }
377 if model.is_some() {
378 state.model = model;
379 }
380}
381
382pub(crate) fn target_model_or_source_model(state: &StreamTranslationState) -> String {
384 state
385 .target_model
386 .clone()
387 .or_else(|| state.model.clone())
388 .unwrap_or_else(|| "unknown".to_string())
389}
390
391pub(crate) fn target_message_id_or_source_message_id(
393 state: &StreamTranslationState,
394) -> Option<&str> {
395 state
396 .target_message_id
397 .as_deref()
398 .or(state.message_id.as_deref())
399}
400
401pub(crate) fn state_source_is(state: &StreamTranslationState, format: WireFormat) -> bool {
403 let format_id: FormatId = format.into();
404 match &state.source {
405 Some(source) => source == &format_id,
406 None => false,
407 }
408}
409
410pub(crate) fn string_field(object: &Map<String, Value>, key: &str) -> Option<String> {
412 object
413 .get(key)
414 .and_then(Value::as_str)
415 .filter(|value| !value.is_empty())
416 .map(ToOwned::to_owned)
417}