llm-bridge-core 0.2.4

Protocol transform library for LLM API translation between Anthropic and OpenAI.
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! Responses API SSE → Anthropic SSE streaming transform.
//!
//! Maps Responses API streaming events to the Anthropic Messages SSE event sequence.
//! The main event mappings are:
//!
//! | Responses event | Anthropic event |
//! |---|---|
//! | `response.created` / `response.in_progress` | `message_start` |
//! | `response.output_item.added` (message) | `content_block_start` (text) |
//! | `response.output_item.added` (function_call) | `content_block_start` (tool_use) |
//! | `response.output_text.delta` | `content_block_delta` (text_delta) |
//! | `response.reasoning_text.delta` | `content_block_delta` (thinking_delta) |
//! | `response.function_call_arguments.delta` | `content_block_delta` (input_json_delta) |
//! | `response.output_text.done` | `content_block_stop` |
//! | `response.reasoning_text.done` | `content_block_stop` |
//! | `response.function_call_arguments.done` | `content_block_stop` |
//! | `response.completed` / `response.incomplete` | `message_delta` + `message_stop` |
//! | `error` | `error` |

#![allow(clippy::too_many_lines)]

use std::collections::BTreeMap;

use serde::Deserialize;
use serde_json::json;

use super::SseFrame;
use crate::model::{StreamState, TransformError};

// ---------------------------------------------------------------------------
// Responses SSE event types
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
struct ResponsesEvent {
    #[serde(rename = "type")]
    event_type: String,
    #[serde(default)]
    response: Option<serde_json::Value>,
    #[serde(default)]
    output_index: Option<usize>,
    #[serde(default)]
    item: Option<serde_json::Value>,
    #[serde(default)]
    content_index: Option<usize>,
    #[serde(default)]
    part: Option<serde_json::Value>,
    #[serde(default)]
    item_id: Option<String>,
    #[serde(default)]
    delta: Option<String>,
    #[serde(default)]
    text: Option<String>,
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    arguments: Option<String>,
    #[serde(default)]
    call_id: Option<String>,
    #[serde(default)]
    code: Option<String>,
    #[serde(default)]
    message: Option<String>,
    #[serde(default)]
    incomplete_details: Option<serde_json::Value>,
}

// ---------------------------------------------------------------------------
// Per-block state tracking
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
struct BlockState {
    kind: ResponsesBlockKind,
    index: usize,
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum ResponsesBlockKind {
    Text,
    Reasoning,
    ToolUse,
}

// ---------------------------------------------------------------------------
// Transform entry point
// ---------------------------------------------------------------------------

pub(crate) fn transform_responses_stream_to_anthropic(
    frames: &[SseFrame],
    state: &mut StreamState,
) -> Result<Vec<u8>, TransformError> {
    if state.finished {
        return Ok(Vec::new());
    }

    let mut out = Vec::with_capacity(1024);
    let mut block_counter: usize = 0;
    // Track block_index per (output_index, content_index, kind) combo
    // Using kind as a string key to separate text/reasoning/tool_use blocks.
    let mut block_map: BTreeMap<(usize, usize, &'static str), usize> = BTreeMap::new();
    // Track whether a reasoning block has been started per output_index.
    let mut reasoning_block_index: BTreeMap<usize, usize> = BTreeMap::new();

    for frame in frames {
        let event: ResponsesEvent = serde_json::from_slice(frame.data.as_bytes()).map_err(|e| {
            TransformError::InvalidFormat(format!("Responses SSE event parse: {e}"))
        })?;

        match event.event_type.as_str() {
            "response.created" | "response.in_progress" => {
                if let Some(ref response) = event.response {
                    if let Some(id) = response.get("id").and_then(|v| v.as_str()) {
                        state.message_id = Some(id.to_string());
                    }
                    if let Some(model) = response.get("model").and_then(|v| v.as_str()) {
                        state.model_name = Some(model.to_string());
                    }
                    if let Some(usage) = response.get("usage") {
                        if let Some(input_tokens) = usage
                            .get("input_tokens")
                            .and_then(serde_json::Value::as_u64)
                        {
                            state.last_usage.input_tokens = input_tokens;
                        }
                        if let Some(output_tokens) = usage
                            .get("output_tokens")
                            .and_then(serde_json::Value::as_u64)
                        {
                            state.last_usage.output_tokens = output_tokens;
                        }
                        if let Some(cached) = usage
                            .get("prompt_tokens_details")
                            .and_then(|d| d.get("cached_tokens"))
                            .and_then(serde_json::Value::as_u64)
                        {
                            state.last_usage.cached_tokens = cached;
                        }
                        if let Some(reasoning) = usage
                            .get("completion_tokens_details")
                            .and_then(|d| d.get("reasoning_tokens"))
                            .and_then(serde_json::Value::as_u64)
                        {
                            state.last_usage.reasoning_tokens = reasoning;
                        }
                    }
                }
                if !state.started {
                    state.started = true;
                    append_anthropic_sse(
                        &mut out,
                        Some("message_start"),
                        &json!({
                            "type": "message_start",
                            "message": {
                                "id": state.message_id.as_deref().unwrap_or("resp_dummy"),
                                "type": "message",
                                "role": "assistant",
                                "model": state.model_name.as_deref().unwrap_or("unknown"),
                                "content": [],
                                "stop_reason": null,
                                "stop_sequence": null,
                                "usage": {
                                    "input_tokens": state.last_usage.input_tokens,
                                    "output_tokens": state.last_usage.output_tokens,
                                },
                            },
                        }),
                    )?;
                }
            }

            "response.output_item.added" => {
                let output_index = event.output_index.unwrap_or(0);
                if let Some(ref item) = event.item {
                    let item_type = item.get("type").and_then(|v| v.as_str()).unwrap_or("");
                    let block_kind = match item_type {
                        "message" => ResponsesBlockKind::Text,
                        "function_call" => ResponsesBlockKind::ToolUse,
                        other => {
                            tracing::debug!(
                                "lossy downgrade: skipping Responses SSE output item type \
                                 '{other}'"
                            );
                            continue;
                        }
                    };

                    let content_index = event.content_index.unwrap_or(0);
                    let kind_tag = match block_kind {
                        ResponsesBlockKind::Text => "text",
                        ResponsesBlockKind::ToolUse => "tool_use",
                        ResponsesBlockKind::Reasoning => unreachable!(),
                    };
                    let key = (output_index, content_index, kind_tag);
                    let block_index = block_counter;
                    block_map.insert(key, block_index);

                    state
                        .content_block_kinds
                        .insert(block_index, crate::model::StreamContentBlockKind::Text);

                    match block_kind {
                        ResponsesBlockKind::Text => {
                            append_anthropic_sse(
                                &mut out,
                                Some("content_block_start"),
                                &json!({
                                    "type": "content_block_start",
                                    "index": block_index,
                                    "content_block": {
                                        "type": "text",
                                        "text": "",
                                    },
                                }),
                            )?;
                        }
                        ResponsesBlockKind::ToolUse => {
                            let call_id =
                                item.get("call_id").and_then(|v| v.as_str()).unwrap_or("");
                            let tool_name = item.get("name").and_then(|v| v.as_str()).unwrap_or("");
                            append_anthropic_sse(
                                &mut out,
                                Some("content_block_start"),
                                &json!({
                                    "type": "content_block_start",
                                    "index": block_index,
                                    "content_block": {
                                        "type": "tool_use",
                                        "id": call_id,
                                        "name": tool_name,
                                        "input": {},
                                    },
                                }),
                            )?;
                        }
                        ResponsesBlockKind::Reasoning => unreachable!(),
                    }

                    block_counter += 1;
                }
            }

            "response.output_text.delta" => {
                let output_index = event.output_index.unwrap_or(0);
                let content_index = event.content_index.unwrap_or(0);
                let key = (output_index, content_index, "text");
                if let Some(&block_index) = block_map.get(&key) {
                    let delta = event.delta.as_deref().unwrap_or("");
                    append_anthropic_sse(
                        &mut out,
                        Some("content_block_delta"),
                        &json!({
                            "type": "content_block_delta",
                            "index": block_index,
                            "delta": {
                                "type": "text_delta",
                                "text": delta,
                            },
                        }),
                    )?;
                }
            }

            "response.reasoning_text.delta" => {
                let output_index = event.output_index.unwrap_or(0);
                let content_index = event.content_index.unwrap_or(0);
                let key = (output_index, content_index, "reasoning");

                let block_index = if let Some(&idx) = block_map.get(&key) {
                    idx
                } else {
                    let idx = block_counter;
                    block_map.insert(key, idx);
                    reasoning_block_index.insert(output_index, idx);
                    state
                        .content_block_kinds
                        .insert(idx, crate::model::StreamContentBlockKind::Thinking);
                    append_anthropic_sse(
                        &mut out,
                        Some("content_block_start"),
                        &json!({
                            "type": "content_block_start",
                            "index": idx,
                            "content_block": {
                                "type": "thinking",
                                "thinking": "",
                            },
                        }),
                    )?;
                    block_counter += 1;
                    idx
                };

                let delta = event.delta.as_deref().unwrap_or("");
                append_anthropic_sse(
                    &mut out,
                    Some("content_block_delta"),
                    &json!({
                        "type": "content_block_delta",
                        "index": block_index,
                        "delta": {
                            "type": "thinking_delta",
                            "thinking": delta,
                        },
                    }),
                )?;
            }

            "response.function_call_arguments.delta" => {
                let output_index = event.output_index.unwrap_or(0);
                let content_index = event.content_index.unwrap_or(0);
                let key = (output_index, content_index, "tool_use");
                if let Some(&block_index) = block_map.get(&key) {
                    let delta = event.delta.as_deref().unwrap_or("");
                    append_anthropic_sse(
                        &mut out,
                        Some("content_block_delta"),
                        &json!({
                            "type": "content_block_delta",
                            "index": block_index,
                            "delta": {
                                "type": "input_json_delta",
                                "partial_json": delta,
                            },
                        }),
                    )?;
                }
            }

            "response.output_text.done" => {
                let output_index = event.output_index.unwrap_or(0);
                let content_index = event.content_index.unwrap_or(0);
                let key = (output_index, content_index, "text");
                if let Some(&block_index) = block_map.get(&key) {
                    append_anthropic_sse(
                        &mut out,
                        Some("content_block_stop"),
                        &json!({
                            "type": "content_block_stop",
                            "index": block_index,
                        }),
                    )?;
                }
            }

            "response.reasoning_text.done" => {
                let output_index = event.output_index.unwrap_or(0);
                if let Some(&block_index) = reasoning_block_index.get(&output_index) {
                    append_anthropic_sse(
                        &mut out,
                        Some("content_block_stop"),
                        &json!({
                            "type": "content_block_stop",
                            "index": block_index,
                        }),
                    )?;
                }
            }

            "response.function_call_arguments.done" => {
                let output_index = event.output_index.unwrap_or(0);
                let content_index = event.content_index.unwrap_or(0);
                let key = (output_index, content_index, "tool_use");
                if let Some(&block_index) = block_map.get(&key) {
                    append_anthropic_sse(
                        &mut out,
                        Some("content_block_stop"),
                        &json!({
                            "type": "content_block_stop",
                            "index": block_index,
                        }),
                    )?;
                }
            }

            "response.output_item.done" => {
                // No direct Anthropic equivalent — content_block_stop already emitted.
            }

            "response.content_part.added" | "response.content_part.done" => {
                // Internal Responses lifecycle — no Anthropic mapping needed.
            }

            "response.completed" | "response.incomplete" => {
                let stop_reason = if event.event_type == "response.incomplete" {
                    "max_tokens"
                } else {
                    "end_turn"
                };

                if let Some(ref response) = event.response {
                    if let Some(usage) = response.get("usage") {
                        if let Some(input_tokens) = usage
                            .get("input_tokens")
                            .and_then(serde_json::Value::as_u64)
                        {
                            state.last_usage.input_tokens = input_tokens;
                        }
                        if let Some(output_tokens) = usage
                            .get("output_tokens")
                            .and_then(serde_json::Value::as_u64)
                        {
                            state.last_usage.output_tokens = output_tokens;
                        }
                        if let Some(cached) = usage
                            .get("prompt_tokens_details")
                            .and_then(|d| d.get("cached_tokens"))
                            .and_then(serde_json::Value::as_u64)
                        {
                            state.last_usage.cached_tokens = cached;
                        }
                        if let Some(reasoning) = usage
                            .get("completion_tokens_details")
                            .and_then(|d| d.get("reasoning_tokens"))
                            .and_then(serde_json::Value::as_u64)
                        {
                            state.last_usage.reasoning_tokens = reasoning;
                        }
                    }
                }

                append_anthropic_sse(
                    &mut out,
                    Some("message_delta"),
                    &json!({
                        "type": "message_delta",
                        "delta": {
                            "stop_reason": stop_reason,
                            "stop_sequence": null,
                        },
                        "usage": {
                            "output_tokens": state.last_usage.output_tokens,
                        },
                    }),
                )?;

                append_anthropic_sse(
                    &mut out,
                    Some("message_stop"),
                    &json!({
                        "type": "message_stop",
                    }),
                )?;

                if !state.finished {
                    state.finished = true;
                }
            }

            "error" => {
                let code = event.code.as_deref().unwrap_or("api_error");
                let message = event
                    .message
                    .as_deref()
                    .unwrap_or("Responses API stream error");
                append_anthropic_sse(
                    &mut out,
                    Some("error"),
                    &json!({
                        "type": "error",
                        "error": {
                            "type": code,
                            "message": message,
                        },
                    }),
                )?;
                if !state.finished {
                    state.finished = true;
                }
            }

            "ping" => {
                // Responses ping — no Anthropic equivalent needed.
            }

            other => {
                tracing::debug!(
                    "lossy downgrade: skipping unsupported Responses SSE event type '{other}'"
                );
            }
        }
    }

    Ok(out)
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn append_anthropic_sse(
    out: &mut Vec<u8>,
    event: Option<&str>,
    data: &serde_json::Value,
) -> Result<(), TransformError> {
    let serialized = serde_json::to_vec(data)
        .map_err(|e| TransformError::InvalidFormat(format!("Anthropic SSE serialization: {e}")))?;

    if let Some(ev) = event {
        out.extend_from_slice(b"event: ");
        out.extend_from_slice(ev.as_bytes());
        out.push(b'\n');
    }
    out.extend_from_slice(b"data: ");
    out.extend_from_slice(&serialized);
    out.extend_from_slice(b"\n\n");

    Ok(())
}