codex-convert-proxy 0.1.4

A high-performance proxy server that converts between different AI API formats
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//! Message conversion utilities for Responses API → Chat API.

use crate::error::ConversionError;
use crate::types::chat_api::{
    ChatMessage, Content, ContentBlock, FunctionCall, ImageUrlField, ImageUrlObject, MessageRole,
    ToolCall,
};
use crate::types::response_api::{
    Content as ResponseContent, ContentPart, InputItemOrString, Tool,
};

/// Convert input (with optional instructions) to Chat messages.
///
/// Returns:
/// - `messages`: The converted chat messages
/// - `extracted_tools`: Tools extracted from `tool_search_output` items
pub fn convert_input_to_messages(
    input: InputItemOrString,
    instructions: Option<String>,
    enforce_tool_result_adjacency: bool,
) -> Result<(Vec<ChatMessage>, Vec<Tool>), ConversionError> {
    let mut messages = Vec::new();
    #[allow(unused_mut)]
    let mut extracted_tools: Vec<Tool> = Vec::new();
    let mut pending_tool_calls: Option<Vec<ToolCall>> = None;
    let mut emitted_tool_call_ids: std::collections::HashSet<String> =
        std::collections::HashSet::new();
    let mut emitted_tool_call_names: std::collections::HashMap<String, String> =
        std::collections::HashMap::new();

    // Add system message from instructions
    if let Some(inst) = instructions {
        messages.push(ChatMessage {
            role: MessageRole::System,
            content: Content::String(inst),
            name: None,
            annotations: None,
            tool_calls: None,
            tool_call_id: None,
            function_call: None,
            refusal: None,
        });
    }

    // Convert input items
    match input {
        InputItemOrString::String(s) => {
            messages.push(ChatMessage {
                role: MessageRole::User,
                content: Content::String(s),
                name: None,
                annotations: None,
                tool_calls: None,
                tool_call_id: None,
                function_call: None,
                refusal: None,
            });
        }
        InputItemOrString::Array(items) => {

            for mut item in items {
                match item.item_type {
                    crate::types::response_api::InputItemType::Message => {
                        let role = match item.role.as_deref() {
                            Some("developer") => MessageRole::Developer,
                            Some("system") => MessageRole::System,
                            Some("assistant") => MessageRole::Assistant,
                            Some("tool") => MessageRole::Tool,
                            Some("user") | None => MessageRole::User,
                            Some("unknown") => MessageRole::Unknown,
                            Some("critic") => MessageRole::Critic,
                            Some("discriminator") => MessageRole::Discriminator,
                            Some(other) => {
                                return Err(ConversionError::InvalidFormat(format!(
                                    "unsupported message role: {other}"
                                )));
                            }
                        };

                        // tool_call_id is only valid on role=tool per Chat API spec
                        // (ChatCompletionRequestToolMessage). Avoid leaking it to other roles.
                        let tool_call_id_for_msg = if matches!(role, MessageRole::Tool) {
                            item.call_id.clone()
                        } else {
                            None
                        };

                        let content = extract_content(&item.content)?;

                        // If we have pending tool calls and now receive an assistant message,
                        // merge them into ONE assistant message. Some providers require
                        // tool outputs to immediately follow the assistant tool_calls message.
                        if enforce_tool_result_adjacency && role == MessageRole::Assistant {
                            if let Some(tool_calls) = pending_tool_calls.take() {
                                for tc in &tool_calls {
                                    emitted_tool_call_ids.insert(tc.id.clone());
                                    emitted_tool_call_names.insert(tc.id.clone(), tc.function.name.clone());
                                }
                                messages.push(ChatMessage {
                                    role,
                                    content,
                                    name: item.name,
                                    annotations: None,
                                    tool_calls: Some(tool_calls),
                                    tool_call_id: tool_call_id_for_msg.clone(),
                                    function_call: None,
                                    refusal: None,
                                });
                                tracing::debug!(
                                    "[REQUEST_CONVERT] merged assistant message with pending tool_calls to keep tool result adjacency"
                                );
                                continue;
                            }
                        } else if let Some(tool_calls) = pending_tool_calls.take() {
                            // Flush pending tool calls before non-assistant message items
                            for tc in &tool_calls {
                                emitted_tool_call_ids.insert(tc.id.clone());
                                emitted_tool_call_names.insert(tc.id.clone(), tc.function.name.clone());
                            }
                            messages.push(ChatMessage {
                                role: MessageRole::Assistant,
                                content: Content::String(String::new()),
                                name: None,
                                annotations: None,
                                tool_calls: Some(tool_calls),
                                tool_call_id: None,
                                function_call: None,
                                refusal: None,
                            });
                        }

                        messages.push(ChatMessage {
                            role,
                            content,
                            name: item.name,
                            annotations: None,
                            tool_calls: None,
                            tool_call_id: tool_call_id_for_msg,
                            function_call: None,
                            refusal: None,
                        });
                    }
                    crate::types::response_api::InputItemType::FunctionCall => {
                        // Accumulate FunctionCall items into pending_tool_calls
                        let arguments = item.arguments.unwrap_or_default();
                        let name = item
                            .name
                            .ok_or_else(|| ConversionError::MissingField("name".to_string()))?;
                        // Use call_id to match FunctionCallOutput's call_id reference
                        let id = item.call_id.or(item.id).unwrap_or_else(|| format!("call_{}", uuid::Uuid::new_v4()));

                        let tool_call = ToolCall {
                            id,
                            tool_type: "function".to_string(),
                            function: FunctionCall { name, arguments },
                        };

                        pending_tool_calls.get_or_insert_with(Vec::new).push(tool_call);
                    }
                    crate::types::response_api::InputItemType::FunctionCallOutput => {
                        let call_id = item
                            .call_id
                            .clone()
                            .unwrap_or_else(|| format!("call_{}", uuid::Uuid::new_v4()));
                        let output_name = item
                            .name
                            .clone()
                            .or_else(|| emitted_tool_call_names.get(&call_id).cloned())
                            .unwrap_or_else(|| "unknown_tool".to_string());

                        // Flush pending tool calls before FunctionCallOutput
                        if let Some(tool_calls) = pending_tool_calls.take() {
                            for tc in &tool_calls {
                                emitted_tool_call_ids.insert(tc.id.clone());
                                emitted_tool_call_names.insert(tc.id.clone(), tc.function.name.clone());
                            }
                            messages.push(ChatMessage {
                                role: MessageRole::Assistant,
                                content: Content::String(String::new()),
                                name: None,
                                annotations: None,
                                tool_calls: Some(tool_calls),
                                tool_call_id: None,
                                function_call: None,
                                refusal: None,
                            });
                        }

                        // Some providers require a preceding assistant.tool_calls message
                        // before each tool result. If missing in the current input window,
                        // synthesize a minimal one to preserve protocol validity.
                        if enforce_tool_result_adjacency && !emitted_tool_call_ids.contains(&call_id) {
                            tracing::warn!(
                                "[REQUEST_CONVERT] function_call_output without preceding function_call, synthesizing assistant tool_call (call_id={}, name={})",
                                call_id,
                                output_name
                            );
                            let synthetic_tool_call = ToolCall {
                                id: call_id.clone(),
                                tool_type: "function".to_string(),
                                function: FunctionCall {
                                    name: output_name.clone(),
                                    arguments: "{}".to_string(),
                                },
                            };
                            messages.push(ChatMessage {
                                role: MessageRole::Assistant,
                                content: Content::String(String::new()),
                                name: None,
                                annotations: None,
                                tool_calls: Some(vec![synthetic_tool_call]),
                                tool_call_id: None,
                                function_call: None,
                                refusal: None,
                            });
                            emitted_tool_call_ids.insert(call_id.clone());
                        }

                        messages.push(ChatMessage {
                            role: MessageRole::Tool,
                            content: Content::String(item.output.unwrap_or_default()),
                            name: item.name,
                            annotations: None,
                            tool_calls: None,
                            tool_call_id: Some(call_id.clone()),
                            function_call: None,
                            refusal: None,
                        });
                        tracing::debug!(
                            "[REQUEST_CONVERT] emitted tool result message (call_id={}, name={})",
                            call_id,
                            output_name
                        );
                    }
                    // --- Unsupported InputItemType variants ---
                    // These are valid Response API types but not supported for Chat API conversion.
                    // Log warning with item id if available for debugging.
                    // --- Unsupported InputItemType variants ---
                    // These are valid Response API types but not supported for Chat API conversion.
                    // We skip them with a warning so the request can continue processing.
                    // These items typically represent internal/server-side features that don't
                    // affect the actual conversation flow when skipped.
                    crate::types::response_api::InputItemType::ComputerCall => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping computer_call input item (id={:?}), \
                            computer use feature not supported in Chat API",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::ComputerCallOutput => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping computer_call_output input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::FileSearchCall => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping file_search_call input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::WebSearchCall => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping web_search_call input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::CodeInterpreterCall => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping code_interpreter_call input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::Reasoning => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping reasoning input item (id={:?}), \
                            reasoning items are for context but cannot be converted to Chat API format",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::ToolSearchCall => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping tool_search_call input item (id={:?}, call_id={:?}), \
                            tool_search_call is an output item type",
                            item.id,
                            item.call_id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::ToolSearchOutput => {
                        // Extract tools from tool_search_output and merge them
                        if let Some(tools) = item.tools.take() {
                            let count = tools.len();
                            extracted_tools.extend(tools);
                            tracing::debug!(
                                "[REQUEST_CONVERT] extracted {} tools from tool_search_output (id={:?})",
                                count,
                                item.id
                            );
                        } else {
                            tracing::debug!(
                                "[REQUEST_CONVERT] tool_search_output has no tools (id={:?})",
                                item.id
                            );
                        }
                        // tool_search_output is just a tool carrier - no message emitted
                        continue;
                    }
                    crate::types::response_api::InputItemType::ImageGenerationCall => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping image_generation_call input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::LocalShellCall => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping local_shell_call input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::LocalShellCallOutput => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping local_shell_call_output input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::ShellCall => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping shell_call input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::ShellCallOutput => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping shell_call_output input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::McpListTools => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping mcp_list_tools input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::McpApprovalRequest => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping mcp_approval_request input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::McpApprovalResponse => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping mcp_approval_response input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::McpCall => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping mcp_call input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::CustomToolCall => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping custom_tool_call input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::CustomToolCallOutput => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping custom_tool_call_output input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::ApplyPatchCall => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping apply_patch_call input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::ApplyPatchCallOutput => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping apply_patch_call_output input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::Compaction => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping compaction input item (id={:?})",
                            item.id
                        );
                        continue;
                    }
                    crate::types::response_api::InputItemType::Unknown => {
                        tracing::warn!(
                            "[REQUEST_CONVERT] skipping unknown input item type (id={:?}), \
                            this may be a new type not yet supported by the proxy",
                            item.id
                        );
                        continue;
                    }
                }
            }

            // Handle any remaining tool calls
            if let Some(tool_calls) = pending_tool_calls {
                for tc in &tool_calls {
                    emitted_tool_call_ids.insert(tc.id.clone());
                    emitted_tool_call_names.insert(tc.id.clone(), tc.function.name.clone());
                }
                messages.push(ChatMessage {
                    role: MessageRole::Assistant,
                    content: Content::String(String::new()),
                    name: None,
                    annotations: None,
                    tool_calls: Some(tool_calls),
                    tool_call_id: None,
                    function_call: None,
                    refusal: None,
                });
            }
            tracing::debug!(
                "[REQUEST_CONVERT] input array converted: messages={}, emitted_tool_calls={}",
                messages.len(),
                emitted_tool_call_ids.len()
            );
        }
    }

    Ok((messages, extracted_tools))
}

/// Extract text content from Response API content.
pub fn extract_content(content: &Option<ResponseContent>) -> Result<Content, ConversionError> {
    match content {
        Some(ResponseContent::String(s)) => Ok(Content::String(s.clone())),
        Some(ResponseContent::Array(parts)) => {
            let mut blocks: Vec<ContentBlock> = Vec::new();
            for part in parts {
                match part {
                    ContentPart::InputText { text } => blocks.push(ContentBlock {
                        block_type: "text".to_string(),
                        text: Some(text.clone()),
                        image_url: None,
                        input_audio: None,
                        file: None,
                        refusal: None,
                    }),
                    ContentPart::OutputText { text, .. } => blocks.push(ContentBlock {
                        block_type: "text".to_string(),
                        text: Some(text.clone()),
                        image_url: None,
                        input_audio: None,
                        file: None,
                        refusal: None,
                    }),
                    ContentPart::InputImage { image_url } => blocks.push(ContentBlock {
                        block_type: "image_url".to_string(),
                        text: None,
                        image_url: Some(ImageUrlField::Object(ImageUrlObject {
                            url: image_url.clone(),
                            detail: None,
                        })),
                        input_audio: None,
                        file: None,
                        refusal: None,
                    }),
                    ContentPart::InputFile { file_url, file_id } => {
                        let file_ref = file_url
                            .as_ref()
                            .or(file_id.as_ref())
                            .cloned()
                            .unwrap_or_else(|| "unknown_file".to_string());
                        blocks.push(ContentBlock {
                            block_type: "text".to_string(),
                            text: Some(format!("[input_file] {}", file_ref)),
                            image_url: None,
                            input_audio: None,
                            file: None,
                            refusal: None,
                        });
                    }
                }
            }

            if blocks.is_empty() {
                Ok(Content::String(String::new()))
            } else if blocks.len() == 1 && blocks[0].block_type == "text" {
                Ok(Content::String(blocks[0].text.clone().unwrap_or_default()))
            } else {
                Ok(Content::Array(blocks))
            }
        }
        None => Ok(Content::String(String::new())),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::response_api::{Content as ResponseContent, ContentPart};

    #[test]
    fn test_extract_content_image_url_serializes_as_object() {
        // OpenAI `ChatCompletionRequestMessageContentPartImage.image_url` is a
        // required object `{url, detail?}`, not a string.
        let content = ResponseContent::Array(vec![
            ContentPart::InputText { text: "see this:".into() },
            ContentPart::InputImage { image_url: "https://example.com/x.png".into() },
        ]);
        let chat_content = extract_content(&Some(content)).unwrap();
        let json = serde_json::to_value(&chat_content).unwrap();
        let arr = json.as_array().expect("array content");
        let image_block = arr
            .iter()
            .find(|b| b["type"] == "image_url")
            .expect("image_url block present");
        assert!(image_block["image_url"].is_object(), "image_url must be object: {image_block}");
        assert_eq!(image_block["image_url"]["url"], "https://example.com/x.png");
    }

    #[test]
    fn test_unknown_role_returns_error() {
        let input = InputItemOrString::Array(vec![crate::types::response_api::InputItem {
            id: None,
            item_type: crate::types::response_api::InputItemType::Message,
            role: Some("alien".to_string()),
            content: Some(ResponseContent::String("hi".into())),
            name: None,
            arguments: None,
            call_id: None,
            output: None,
            namespace: None,
            tools: None,
        }]);
        let err = convert_input_to_messages(input, None, false)
            .expect_err("unknown role must fail");
        assert!(matches!(err, ConversionError::InvalidFormat(_)));
    }
}