switchyard-translation 0.3.0

Pure Rust request, response, and stream translation for Switchyard
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Streaming codec for OpenAI Chat Completions chunks.

use serde_json::{Map, Value, json};

use crate::LlmResponseChunk;
use crate::codecs::common::{first_nonempty_string, reasoning_text_from_details};
use crate::codecs::stream::{
    StreamCodec, StreamTranslationState, record_source_identity, state_source_is, string_field,
    target_model_or_source_model,
};
use crate::format::{FormatId, WireFormat};
use crate::llm::Usage;

/// Stream codec for OpenAI Chat Completions chunks.
pub struct OpenAiChatStreamCodec;

impl StreamCodec for OpenAiChatStreamCodec {
    fn format(&self) -> FormatId {
        WireFormat::OpenAiChat.into()
    }

    fn decode_event(
        &self,
        state: &mut StreamTranslationState,
        event: &Value,
    ) -> Vec<LlmResponseChunk> {
        decode_openai_chat_stream(state, event)
    }

    fn encode_event(
        &self,
        state: &mut StreamTranslationState,
        event: LlmResponseChunk,
    ) -> Vec<Value> {
        encode_openai_chat_stream(state, event)
    }

    fn finish(&self, state: &mut StreamTranslationState) -> Vec<Value> {
        finish_openai_chat_stream(state)
    }
}

// Decodes one OpenAI Chat chunk into neutral streaming events.
fn decode_openai_chat_stream(
    state: &mut StreamTranslationState,
    event: &Value,
) -> Vec<LlmResponseChunk> {
    let Some(object) = event.as_object() else {
        return vec![LlmResponseChunk::DecodeError {
            message: "OpenAI stream event is not an object".to_string(),
        }];
    };

    // Upstream error frames carry no choices, so without this they would decode to a bare
    // `MessageStart` and the error text would be dropped.
    if let Some(error) = object.get("error") {
        return vec![LlmResponseChunk::StreamError {
            message: error
                .get("message")
                .and_then(Value::as_str)
                .unwrap_or("unknown OpenAI stream error")
                .to_string(),
        }];
    }

    let mut out = Vec::new();
    let mut identity_changed = false;
    if state.model.is_none() {
        state.model = string_field(object, "model");
        identity_changed |= state.model.is_some();
    }
    if state.message_id.is_none() {
        state.message_id = string_field(object, "id");
        identity_changed |= state.message_id.is_some();
    }
    if !state.saw_message_start || identity_changed {
        state.saw_message_start = true;
        out.push(LlmResponseChunk::MessageStart {
            id: state.message_id.clone(),
            model: state.model.clone(),
        });
    }

    if let Some(usage) = object.get("usage").and_then(Value::as_object) {
        let usage = openai_usage(usage);
        state.usage = usage.clone();
        state.saw_backend_usage = true;
        out.push(LlmResponseChunk::Usage(usage));
    }

    for choice in object
        .get("choices")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
    {
        let Some(choice) = choice.as_object() else {
            continue;
        };
        if let Some(delta) = choice.get("delta").and_then(Value::as_object) {
            if let Some(details) = delta
                .get("reasoning_details")
                .and_then(Value::as_array)
                .filter(|details| !details.is_empty())
            {
                let text = reasoning_text_from_details(details)
                    .or_else(|| {
                        first_nonempty_string(delta, &["reasoning_content", "reasoning"])
                            .map(ToOwned::to_owned)
                    })
                    .unwrap_or_default();
                out.push(LlmResponseChunk::ReasoningDetailsDelta {
                    index: 0,
                    details: details.clone(),
                    text,
                });
            } else {
                for reasoning_key in ["reasoning_content", "reasoning"] {
                    if let Some(text) = delta.get(reasoning_key).and_then(Value::as_str)
                        && !text.is_empty()
                    {
                        out.push(LlmResponseChunk::ReasoningDelta {
                            index: 0,
                            text: text.to_string(),
                        });
                    }
                }
            }
            if let Some(text) = delta.get("content").and_then(Value::as_str)
                && !text.is_empty()
            {
                out.push(LlmResponseChunk::TextDelta {
                    index: 0,
                    text: text.to_string(),
                });
            }
            if let Some(tool_calls) = delta.get("tool_calls").and_then(Value::as_array) {
                for tool_call in tool_calls {
                    if let Some(tool_call) = tool_call.as_object() {
                        let function = tool_call.get("function").and_then(Value::as_object);
                        let index =
                            tool_call.get("index").and_then(Value::as_u64).unwrap_or(0) as usize;
                        if let Some(name) = function
                            .and_then(|function| function.get("name"))
                            .and_then(Value::as_str)
                            .filter(|name| !name.is_empty())
                        {
                            state
                                .pending_chat_tool_names
                                .entry(index)
                                .or_default()
                                .push_str(name);
                        }
                        let arguments_delta = function
                            .and_then(|function| function.get("arguments"))
                            .and_then(Value::as_str)
                            .map(ToOwned::to_owned);
                        out.push(LlmResponseChunk::ToolCallDelta {
                            index,
                            id: tool_call
                                .get("id")
                                .and_then(Value::as_str)
                                .map(ToOwned::to_owned),
                            // Names may continue after arguments begin; emit them at finish_reason.
                            name: None,
                            arguments_delta,
                        });
                    }
                }
            }
        }
        if let Some(reason) = choice.get("finish_reason").and_then(Value::as_str) {
            for (index, name) in std::mem::take(&mut state.pending_chat_tool_names) {
                out.push(LlmResponseChunk::ToolCallDelta {
                    index,
                    id: None,
                    name: Some(name),
                    arguments_delta: None,
                });
            }
            out.push(LlmResponseChunk::MessageStop {
                reason: Some(reason.to_string()),
            });
        }
    }
    out
}

// Encodes neutral streaming events into OpenAI Chat chunks.
fn encode_openai_chat_stream(
    state: &mut StreamTranslationState,
    event: LlmResponseChunk,
) -> Vec<Value> {
    // An in-band error is terminal: once the error is emitted, drop every later chunk.
    if state.errored {
        return Vec::new();
    }
    match event {
        LlmResponseChunk::MessageStart { id, model } => {
            record_source_identity(state, id, model);
            // `finish_openai_chat_stream` uses this flag to decide whether a clean EOF needs a
            // synthesized terminal chunk. Set it on the encode path as well as the decode path.
            state.saw_message_start = true;
            if state.emitted_message_start
                || (!state_source_is(state, WireFormat::AnthropicMessages)
                    && !state_source_is(state, WireFormat::OpenAiResponses))
            {
                Vec::new()
            } else {
                state.emitted_message_start = true;
                vec![openai_stream_chunk(
                    state,
                    json!({"role": "assistant"}),
                    None,
                    None,
                )]
            }
        }
        LlmResponseChunk::TextDelta { text, .. } => {
            vec![openai_stream_chunk(
                state,
                json!({"content": text}),
                None,
                None,
            )]
        }
        LlmResponseChunk::ReasoningDelta { text, .. } => {
            vec![openai_stream_chunk(
                state,
                json!({"reasoning_content": text}),
                None,
                None,
            )]
        }
        LlmResponseChunk::ReasoningDetailsDelta { details, text, .. } => {
            // Chat cannot replay Anthropic signature fragments or an encrypted item's
            // id announcement without its payload.
            let details: Vec<Value> = details
                .into_iter()
                .filter(|detail| match detail.get("type").and_then(Value::as_str) {
                    Some("anthropic.signature_delta") => false,
                    Some("reasoning.encrypted") => detail.get("data").is_some(),
                    _ => true,
                })
                .collect();
            if details.is_empty() && text.is_empty() {
                return Vec::new();
            }
            let details_text = reasoning_text_from_details(&details);
            let mut delta = json!({"reasoning_details": details});
            if !text.is_empty() && details_text.as_deref() != Some(text.as_str()) {
                delta["reasoning"] = Value::String(text);
            }
            vec![openai_stream_chunk(state, delta, None, None)]
        }
        LlmResponseChunk::ToolCallDelta {
            index,
            id,
            name,
            arguments_delta,
        } => {
            let tool = state.tool_states.entry(index).or_default();
            // Repeated full names would be concatenated by Chat clients as new fragments.
            let name = name.filter(|name| tool.name.as_ref() != Some(name));
            if name.is_some() {
                tool.name = name.clone();
            }
            // The source index counts every content block (Anthropic) or output item
            // (Responses), so text ahead of the first tool call shifts it. Chat clients use
            // the index as a subscript into `tool_calls`, so number calls in that array
            // instead, in order of first appearance.
            let chat_index = match tool.chat_tool_index {
                Some(chat_index) => chat_index,
                None => {
                    let chat_index = state.next_chat_tool_index;
                    state.next_chat_tool_index += 1;
                    state.tool_states.entry(index).or_default().chat_tool_index = Some(chat_index);
                    chat_index
                }
            };
            vec![openai_tool_call_chunk(
                state,
                chat_index,
                id,
                name,
                arguments_delta,
            )]
        }
        LlmResponseChunk::Usage(usage) => {
            state.usage = usage;
            state.saw_backend_usage = true;
            if state.finished {
                vec![openai_usage_chunk(state)]
            } else {
                Vec::new()
            }
        }
        LlmResponseChunk::MessageStop { reason } => {
            if state.finished {
                return Vec::new();
            }
            state.finished = true;
            vec![openai_stream_chunk(
                state,
                json!({}),
                Some(openai_finish_reason(reason.as_deref())),
                state.saw_backend_usage.then(|| openai_usage_value(state)),
            )]
        }
        LlmResponseChunk::DecodeError { message } | LlmResponseChunk::StreamError { message } => {
            // An in-band error is terminal: emit the error, then nothing further.
            state.finished = true; // finish() adds no success events
            state.errored = true; // the entry guard drops any later chunk
            vec![json!({"error": {"message": message}})]
        }
    }
}

// Emits a terminal chunk if the source stream ended before a stop event arrived.
fn finish_openai_chat_stream(state: &mut StreamTranslationState) -> Vec<Value> {
    if state.finished || !state.saw_message_start {
        return Vec::new();
    }
    state.finished = true;
    vec![openai_stream_chunk(
        state,
        json!({}),
        Some(openai_finish_reason(state.stop_reason.as_deref())),
        state.saw_backend_usage.then(|| openai_usage_value(state)),
    )]
}

// Normalizes OpenAI token usage fields.
fn openai_usage(usage: &Map<String, Value>) -> Usage {
    let cached_input_tokens = usage
        .get("prompt_tokens_details")
        .and_then(|details| details.get("cached_tokens"))
        .and_then(Value::as_u64);
    let cache_creation_input_tokens = usage
        .get("prompt_tokens_details")
        .and_then(|details| {
            details
                .get("cache_write_tokens")
                .or_else(|| details.get("cache_creation_tokens"))
        })
        .and_then(Value::as_u64);
    Usage {
        input_tokens: usage
            .get("prompt_tokens")
            .and_then(Value::as_u64)
            .map(|tokens| {
                tokens
                    .saturating_sub(cached_input_tokens.unwrap_or(0))
                    .saturating_sub(cache_creation_input_tokens.unwrap_or(0))
            }),
        cache: Usage::cache_details(cached_input_tokens, cache_creation_input_tokens),
        output_tokens: usage.get("completion_tokens").and_then(Value::as_u64),
        total_tokens: usage.get("total_tokens").and_then(Value::as_u64),
        reasoning_tokens: usage
            .get("completion_tokens_details")
            .and_then(|details| details.get("reasoning_tokens"))
            .or_else(|| {
                usage
                    .get("output_tokens_details")
                    .and_then(|details| details.get("reasoning_tokens"))
            })
            .and_then(Value::as_u64),
    }
}

// Builds a single OpenAI Chat stream chunk payload.
fn openai_stream_chunk(
    state: &StreamTranslationState,
    delta: Value,
    finish_reason: Option<String>,
    usage: Option<Value>,
) -> Value {
    let mut payload = json!({
        "id": openai_stream_id(state),
        "object": "chat.completion.chunk",
        "created": 0,
        "model": target_model_or_source_model(state),
        "choices": [{
            "index": 0,
            "delta": delta,
            "finish_reason": finish_reason,
        }],
    });
    if let Some(usage) = usage {
        payload["usage"] = usage;
    }
    payload
}

// Builds the usage-only chunk OpenAI emits after the terminal choices chunk.
fn openai_usage_chunk(state: &StreamTranslationState) -> Value {
    let mut payload = openai_stream_chunk(state, json!({}), None, Some(openai_usage_value(state)));
    payload["choices"] = json!([]);
    payload
}

// Builds an OpenAI Chat tool-call delta chunk.
fn openai_tool_call_chunk(
    state: &StreamTranslationState,
    index: usize,
    id: Option<String>,
    name: Option<String>,
    arguments: Option<String>,
) -> Value {
    let mut function = Map::new();
    if let Some(name) = name {
        function.insert("name".to_string(), Value::String(name));
    }
    if let Some(arguments) = arguments {
        function.insert("arguments".to_string(), Value::String(arguments));
    }
    let mut tool_call = Map::new();
    tool_call.insert("index".to_string(), json!(index));
    tool_call.insert("type".to_string(), json!("function"));
    tool_call.insert("function".to_string(), Value::Object(function));
    if let Some(id) = id {
        tool_call.insert("id".to_string(), Value::String(id));
    }
    openai_stream_chunk(
        state,
        json!({"tool_calls": [Value::Object(tool_call)]}),
        None,
        None,
    )
}

// Builds OpenAI usage payloads from normalized and provider-extra state.
fn openai_usage_value(state: &StreamTranslationState) -> Value {
    let cache_creation_tokens = state.usage.cache_creation_input_tokens().unwrap_or(0);
    let cache_read_tokens = state.usage.cached_input_tokens().unwrap_or(0);
    let prompt_tokens =
        state.usage.input_tokens.unwrap_or(0) + cache_creation_tokens + cache_read_tokens;
    let completion_tokens = state.usage.output_tokens.unwrap_or(0);
    let mut usage = json!({
        "prompt_tokens": prompt_tokens,
        "completion_tokens": completion_tokens,
        "total_tokens": state.usage.total_tokens.unwrap_or(prompt_tokens + completion_tokens),
    });
    if let Some(reasoning_tokens) = state.usage.reasoning_tokens {
        usage["completion_tokens_details"] = json!({
            "reasoning_tokens": reasoning_tokens,
        });
    }
    if state.usage.cache_creation_input_tokens().is_some()
        || state.usage.cached_input_tokens().is_some()
    {
        usage["prompt_tokens_details"] = json!({
            "cached_tokens": cache_read_tokens,
            "cache_creation_tokens": cache_creation_tokens,
        });
    }
    usage
}

// Converts any upstream message ID into an OpenAI-looking stream ID.
fn openai_stream_id(state: &StreamTranslationState) -> String {
    let Some(id) = state.message_id.as_deref() else {
        return "chatcmpl_switchyard".to_string();
    };
    if id.starts_with("chatcmpl") {
        id.to_string()
    } else if let Some(rest) = id.strip_prefix("msg_").or_else(|| id.strip_prefix("resp_")) {
        format!("chatcmpl_{rest}")
    } else {
        format!("chatcmpl_{id}")
    }
}

// Maps provider stop reasons into OpenAI's finish-reason vocabulary.
fn openai_finish_reason(reason: Option<&str>) -> String {
    match reason {
        Some("end_turn") | Some("stop_sequence") | None => "stop".to_string(),
        Some("max_tokens") => "length".to_string(),
        Some("tool_use") => "tool_calls".to_string(),
        Some("refusal") => "content_filter".to_string(),
        Some(other) => other.to_string(),
    }
}