llm-bridge-core 0.2.3

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
//! Anthropic → `OpenAI` request transform.
//!
//! Contains the `anthropic_to_openai()` function, Anthropic request types,
//! and the `deserialize_system` helper.

#![allow(clippy::too_many_lines)]

use std::collections::HashMap;

use bytes::Bytes;
use serde::Deserialize;
use serde_json::json;

use super::response_transforms::extract_text_from_content;
use crate::model::{TransformError, TransformRequest, TransformResponse, validate_json_depth};

// ---------------------------------------------------------------------------
// Anthropic request types (input)
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
pub(crate) struct AnthropicMessage {
    pub(crate) role: String,
    pub(crate) content: Option<serde_json::Value>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct AnthropicToolDef {
    pub(crate) name: String,
    #[serde(default)]
    pub(crate) description: Option<String>,
    #[serde(default, rename = "input_schema")]
    pub(crate) input_schema: Option<serde_json::Value>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct AnthropicToolChoice {
    #[serde(rename = "type")]
    pub(crate) choice_type: String,
    #[serde(default)]
    pub(crate) name: Option<String>,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub(crate) struct AnthropicThinkingConfig {
    #[serde(rename = "type")]
    pub(crate) thinking_type: String,
    #[serde(default)]
    pub(crate) budget_tokens: Option<u64>,
    #[serde(default)]
    pub(crate) display: Option<String>,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub(crate) struct AnthropicBody {
    pub(crate) model: String,
    pub(crate) messages: Vec<AnthropicMessage>,
    #[serde(default)]
    pub(crate) max_tokens: Option<u64>,
    #[serde(default)]
    pub(crate) temperature: Option<f64>,
    #[serde(default)]
    pub(crate) top_p: Option<f64>,
    #[serde(default, deserialize_with = "deserialize_system")]
    pub(crate) system: Option<String>,
    #[serde(default)]
    pub(crate) stop_sequences: Option<Vec<String>>,
    #[serde(default)]
    pub(crate) stream: Option<bool>,
    #[serde(default)]
    pub(crate) tools: Option<Vec<AnthropicToolDef>>,
    #[serde(default)]
    pub(crate) tool_choice: Option<AnthropicToolChoice>,
    #[serde(default)]
    pub(crate) thinking: Option<AnthropicThinkingConfig>,
}

// ---------------------------------------------------------------------------
// Deserialization helpers
// ---------------------------------------------------------------------------

/// Deserialize `system` field which may be a plain string (legacy) or an
/// array of content blocks (newer Anthropic API format).
pub(crate) fn deserialize_system<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let opt = Option::<serde_json::Value>::deserialize(deserializer)?;
    Ok(opt.map(|v| match v {
        serde_json::Value::String(s) => s,
        serde_json::Value::Array(blocks) => blocks
            .iter()
            .filter_map(|b| b.get("text").and_then(|t| t.as_str()))
            .collect::<Vec<_>>()
            .join("\n"),
        other => format!("{other:?}"),
    }))
}

// ---------------------------------------------------------------------------
// Body parsing
// ---------------------------------------------------------------------------

pub(crate) fn parse_anthropic_body(body: &Bytes) -> Result<AnthropicBody, TransformError> {
    let value: serde_json::Value = serde_json::from_slice(body)
        .map_err(|_| TransformError::InvalidFormat("invalid JSON body".into()))?;
    validate_json_depth(&value)?;
    serde_json::from_value(value)
        .map_err(|_| TransformError::InvalidFormat("invalid request structure".into()))
}

// ---------------------------------------------------------------------------
// Anthropic → OpenAI
// ---------------------------------------------------------------------------

/// Transform an Anthropic Messages request to an `OpenAI` Chat Completions request.
///
/// Maps headers, path, and body per spec [10 §2.4.1, §2.4.2].
///
/// # Errors
///
/// Returns `TransformError::InvalidFormat` if the request body cannot be parsed
/// as Anthropic JSON or if content blocks have missing required fields.
pub fn anthropic_to_openai(req: &TransformRequest) -> Result<TransformResponse, TransformError> {
    let body: AnthropicBody = parse_anthropic_body(&req.body)?;

    // Validate messages array length (prevents unbounded memory allocation).
    if body.messages.len() > crate::model::MAX_MESSAGES_COUNT {
        return Err(TransformError::BufferLimitExceeded(format!(
            "messages array length {} exceeds maximum of {}",
            body.messages.len(),
            crate::model::MAX_MESSAGES_COUNT
        )));
    }

    // Header mapping: x-api-key -> Authorization: Bearer
    let mut headers = HashMap::new();
    if let Some(api_key) = req.headers.get("x-api-key") {
        headers.insert("authorization".to_string(), format!("Bearer {api_key}"));
    }
    headers.insert("content-type".to_string(), "application/json".to_string());

    // Path mapping: /v1/messages -> /v1/chat/completions
    let path = "/v1/chat/completions".to_string();

    // Body mapping
    let mut messages: Vec<serde_json::Value> = Vec::new();

    // system -> messages[0].role=system
    if let Some(ref system) = body.system {
        messages.push(json!({
            "role": "system",
            "content": system,
        }));
    }

    for msg in &body.messages {
        match &msg.content {
            None | Some(serde_json::Value::Null) => {
                messages.push(json!({
                    "role": msg.role,
                    "content": ""
                }));
            }
            Some(serde_json::Value::String(s)) => {
                messages.push(json!({
                    "role": msg.role,
                    "content": s.clone()
                }));
            }
            Some(serde_json::Value::Array(blocks)) => {
                let mut text_parts = String::new();
                let mut tool_calls: Vec<serde_json::Value> = Vec::new();
                let mut tool_result_messages: Vec<serde_json::Value> = Vec::new();

                for block in blocks {
                    let block_type =
                        block.get("type").and_then(|v| v.as_str()).ok_or_else(|| {
                            TransformError::MissingRequiredField("content block 'type'".to_string())
                        })?;

                    match block_type {
                        "text" => {
                            let text =
                                block.get("text").and_then(|v| v.as_str()).ok_or_else(|| {
                                    TransformError::MissingRequiredField(
                                        "text block 'text' field".to_string(),
                                    )
                                })?;
                            if !text_parts.is_empty() {
                                text_parts.push('\n');
                            }
                            text_parts.push_str(text);
                        }
                        "tool_use" => {
                            let id = block.get("id").and_then(|v| v.as_str()).ok_or_else(|| {
                                TransformError::MissingRequiredField(
                                    "tool_use block 'id' field".to_string(),
                                )
                            })?;
                            let name =
                                block.get("name").and_then(|v| v.as_str()).ok_or_else(|| {
                                    TransformError::MissingRequiredField(
                                        "tool_use block 'name' field".to_string(),
                                    )
                                })?;
                            let input = block
                                .get("input")
                                .cloned()
                                .unwrap_or(serde_json::Value::Object(serde_json::Map::new()));

                            tool_calls.push(json!({
                                "id": id,
                                "type": "function",
                                "function": {
                                    "name": name,
                                    "arguments": serde_json::to_string(&input).map_err(|e| {
                                        TransformError::InvalidFormat(format!("tool_use input serialization: {e}"))
                                    })?,
                                },
                            }));
                        }
                        "tool_result" => {
                            let tool_use_id = block
                                .get("tool_use_id")
                                .and_then(|v| v.as_str())
                                .ok_or_else(|| {
                                    TransformError::MissingRequiredField(
                                        "tool_result block 'tool_use_id' field".to_string(),
                                    )
                                })?;
                            let content = block
                                .get("content")
                                .cloned()
                                .unwrap_or(serde_json::Value::String(String::new()));
                            let text = extract_text_from_content(&content);

                            tool_result_messages.push(json!({
                                "role": "tool",
                                "tool_call_id": tool_use_id,
                                "content": text,
                            }));
                        }
                        "image" => {
                            tracing::debug!("lossy downgrade: skipping image content block");
                        }
                        _ => {
                            tracing::debug!(
                                "lossy downgrade: skipping unsupported Anthropic content block \
                                 type '{block_type}'"
                            );
                        }
                    }
                }

                let has_tool_calls = !tool_calls.is_empty();
                let has_text = !text_parts.is_empty();

                if has_text || has_tool_calls || tool_result_messages.is_empty() {
                    let mut obj = serde_json::Map::new();
                    obj.insert(
                        "role".to_string(),
                        serde_json::Value::String(msg.role.clone()),
                    );
                    if has_tool_calls {
                        obj.insert(
                            "tool_calls".to_string(),
                            serde_json::Value::Array(tool_calls),
                        );
                    }
                    if has_text {
                        obj.insert("content".to_string(), serde_json::Value::String(text_parts));
                    }
                    if !obj.contains_key("content") {
                        obj.insert(
                            "content".to_string(),
                            serde_json::Value::String(String::new()),
                        );
                    }
                    messages.push(serde_json::Value::Object(obj));
                }

                messages.extend(tool_result_messages);
            }
            other => {
                return Err(TransformError::InvalidFormat(format!(
                    "unexpected content type: {other:?}"
                )));
            }
        }
    }

    let mut body_obj = serde_json::Map::new();
    body_obj.insert("model".to_string(), serde_json::Value::String(body.model));
    body_obj.insert("messages".to_string(), serde_json::Value::Array(messages));

    if let Some(max_tokens) = body.max_tokens {
        body_obj.insert(
            "max_tokens".to_string(),
            serde_json::Value::Number(max_tokens.into()),
        );
    }
    if let Some(temperature) = body.temperature {
        body_obj.insert(
            "temperature".to_string(),
            serde_json::Value::Number(
                serde_json::Number::from_f64(temperature)
                    .map_or(serde_json::Number::from(0), |n| n),
            ),
        );
    }
    if let Some(top_p) = body.top_p {
        body_obj.insert(
            "top_p".to_string(),
            serde_json::Value::Number(
                serde_json::Number::from_f64(top_p).map_or(serde_json::Number::from(0), |n| n),
            ),
        );
    }
    if let Some(ref stop) = body.stop_sequences {
        body_obj.insert("stop".to_string(), json!(stop));
    }
    if let Some(stream) = body.stream {
        body_obj.insert("stream".to_string(), serde_json::Value::Bool(stream));
    }
    if let Some(ref thinking) = body.thinking {
        let enable_thinking = match thinking.thinking_type.as_str() {
            "enabled" | "adaptive" => true,
            "disabled" => false,
            other => {
                return Err(TransformError::InvalidFormat(format!(
                    "unsupported Anthropic thinking type: {other}"
                )));
            }
        };
        body_obj.insert(
            "enable_thinking".to_string(),
            serde_json::Value::Bool(enable_thinking),
        );
    }
    if let Some(ref tools) = body.tools {
        let openai_tools = tools
            .iter()
            .map(|tool| {
                let mut function = serde_json::Map::new();
                function.insert(
                    "name".to_string(),
                    serde_json::Value::String(tool.name.clone()),
                );
                if let Some(description) = &tool.description {
                    function.insert(
                        "description".to_string(),
                        serde_json::Value::String(description.clone()),
                    );
                }
                if let Some(parameters) = &tool.input_schema {
                    function.insert("parameters".to_string(), parameters.clone());
                }

                json!({
                    "type": "function",
                    "function": serde_json::Value::Object(function),
                })
            })
            .collect::<Vec<_>>();
        body_obj.insert("tools".to_string(), serde_json::Value::Array(openai_tools));
    }
    if let Some(ref tool_choice) = body.tool_choice {
        let openai_tool_choice = match tool_choice.choice_type.as_str() {
            "auto" => serde_json::Value::String("auto".to_string()),
            "any" => serde_json::Value::String("required".to_string()),
            "none" => serde_json::Value::String("none".to_string()),
            "tool" => {
                let Some(name) = tool_choice.name.as_ref() else {
                    return Err(TransformError::MissingRequiredField(
                        "tool_choice.name for type 'tool'".to_string(),
                    ));
                };
                json!({
                    "type": "function",
                    "function": {
                        "name": name,
                    },
                })
            }
            other => {
                return Err(TransformError::InvalidFormat(format!(
                    "unsupported Anthropic tool_choice type: {other}"
                )));
            }
        };
        body_obj.insert("tool_choice".to_string(), openai_tool_choice);
    }

    let body_bytes = serde_json::to_vec(&serde_json::Value::Object(body_obj))
        .map_err(|e| TransformError::InvalidFormat(format!("response serialization: {e}")))?;

    Ok(TransformResponse {
        headers,
        path,
        body: Bytes::from(body_bytes),
    })
}