Skip to main content

switchyard_translation/codecs/openai_chat/
buffered.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Buffered codec for OpenAI Chat Completions request and response JSON.
5
6use serde_json::{Map, Value, json};
7use switchyard_protocol::MAX_IR_TEMPERATURE;
8
9use super::MAX_TEMPERATURE;
10use crate::codecs::common::{
11    first_nonempty_string, is_known_role_name, provider_extensions, reasoning_text_from_blocks,
12    reasoning_text_from_details, scale_temperature, text_from_blocks,
13};
14use crate::codecs::openai_media::{
15    ImagePayload, file_payload, file_source_text, image_payload, image_source_text,
16};
17use crate::codecs::structured_output::{decode_openai_schema_enforcement, encode_openai_format};
18use crate::codecs::{
19    DecodedRequest, DecodedResponse, EncodedRequest, EncodedResponse, FormatCodec,
20};
21use crate::diagnostic::TranslationDiagnostic;
22use crate::error::{Result, TranslationError};
23use crate::format::{FormatId, WireFormat};
24use crate::llm::{
25    AggLlmResponse, ContentBlock, FileSource, ImageSource, InstructionBlock, LlmRequest,
26    MediaSource, Message, OutputParams, ProviderExtensions, ReasoningParams, ResponseOutput, Role,
27    SamplingParams, StopReason, Tool, ToolCall, ToolChoice, ToolDefinition, ToolResult, Usage,
28};
29use crate::policy::{DeterministicIdPolicy, TranslationPolicy};
30use crate::util::{
31    capture_request_preservation, capture_response_preservation, embed_preservation,
32    exact_preserved_request, exact_preserved_response, json_string, object, push_lossy,
33    reject_responses_native_input_item, stable_id, string_value, validate_request_capabilities,
34};
35
36/// Format codec for OpenAI Chat Completions payloads.
37pub struct OpenAiChatCodec;
38
39impl FormatCodec for OpenAiChatCodec {
40    fn format(&self) -> FormatId {
41        WireFormat::OpenAiChat.into()
42    }
43
44    fn decode_request(&self, body: &Value, policy: &TranslationPolicy) -> Result<DecodedRequest> {
45        let body = object(body, "$")?;
46        if let Some(n) = body.get("n") {
47            let n = n.as_u64().ok_or_else(|| TranslationError::InvalidValue {
48                path: "$.n".to_string(),
49                message: "expected a non-negative integer".to_string(),
50            })?;
51            if n > 1 {
52                return Err(TranslationError::InvalidValue {
53                    path: "$.n".to_string(),
54                    message: "multiple OpenAI Chat choices are not supported; set `n` to 1"
55                        .to_string(),
56                });
57            }
58        }
59        let mut diagnostics = Vec::new();
60        let mut request = LlmRequest {
61            model: body
62                .get("model")
63                .and_then(Value::as_str)
64                .filter(|model| !model.is_empty())
65                .map(ToOwned::to_owned),
66            stream: body.get("stream").and_then(Value::as_bool).unwrap_or(false),
67            sampling: SamplingParams {
68                temperature: body
69                    .get("temperature")
70                    .and_then(Value::as_f64)
71                    .map(|value| scale_temperature(value, MAX_TEMPERATURE, MAX_IR_TEMPERATURE)),
72                top_p: body.get("top_p").and_then(Value::as_f64),
73                top_k: None,
74            },
75            output: OutputParams {
76                max_output_tokens: body
77                    .get("max_completion_tokens")
78                    .or_else(|| body.get("max_tokens"))
79                    .and_then(Value::as_u64),
80                response_format: body.get("response_format").cloned(),
81                is_schema_enforced: decode_openai_schema_enforcement(body.get("response_format")),
82            },
83            reasoning: ReasoningParams {
84                effort: body
85                    .get("reasoning_effort")
86                    .and_then(Value::as_str)
87                    .map(ToOwned::to_owned),
88                raw: None,
89            },
90            preservation: capture_request_preservation(
91                WireFormat::OpenAiChat,
92                &Value::Object(body.clone()),
93                policy,
94            ),
95            ..LlmRequest::default()
96        };
97
98        if let Some(messages) = body.get("messages") {
99            let messages = messages
100                .as_array()
101                .ok_or_else(|| TranslationError::InvalidType {
102                    path: "$.messages".to_string(),
103                    expected: "array",
104                })?;
105            let mut generated_id = 0;
106            for (index, message) in messages.iter().enumerate() {
107                let Some(message) = message.as_object() else {
108                    push_lossy(
109                        &mut diagnostics,
110                        policy,
111                        format!("OpenAI message at index {index} is not an object"),
112                    )?;
113                    continue;
114                };
115                let role = role_from_openai(
116                    message.get("role").and_then(Value::as_str),
117                    &format!("$.messages[{index}].role"),
118                )?;
119                let mut content = decode_openai_content(
120                    message.get("content").unwrap_or(&Value::Null),
121                    WireFormat::OpenAiChat,
122                    &mut diagnostics,
123                    policy,
124                    format!("$.messages[{index}].content"),
125                )?;
126                prepend_openai_reasoning_blocks(&mut content, message);
127                if role == Role::Assistant
128                    && let Some(tool_calls) = message.get("tool_calls").and_then(Value::as_array)
129                {
130                    if is_empty_text_only(&content) {
131                        content.clear();
132                    }
133                    for tool_call in tool_calls {
134                        generated_id += 1;
135                        if let Some(call) =
136                            decode_openai_tool_call(tool_call, generated_id, policy)?
137                        {
138                            content.push(ContentBlock::ToolCall(call));
139                        }
140                    }
141                }
142                if role == Role::Tool {
143                    let tool_call_id = message
144                        .get("tool_call_id")
145                        .and_then(Value::as_str)
146                        .unwrap_or_default()
147                        .to_string();
148                    request.messages.push(Message::new(
149                        Role::User,
150                        vec![ContentBlock::ToolResult(ToolResult {
151                            tool_call_id,
152                            content,
153                            is_error: message.get("is_error").and_then(Value::as_bool),
154                        })],
155                    ));
156                    continue;
157                }
158                // Leading system and developer messages are top-level instructions.
159                // Later ones stay in place as messages.
160                if matches!(role, Role::System | Role::Developer) && request.messages.is_empty() {
161                    request
162                        .instructions
163                        .push(InstructionBlock { role, content });
164                } else {
165                    request.messages.push(Message::new(role, content));
166                }
167            }
168        }
169
170        request.tools = decode_openai_tools(body.get("tools"), &mut diagnostics, policy)?
171            .into_iter()
172            .map(Tool::from)
173            .collect();
174        request.tool_choice = body.get("tool_choice").map(decode_openai_tool_choice);
175        request.extensions.fields = provider_extensions(
176            body,
177            &[
178                "model",
179                "messages",
180                "stream",
181                "temperature",
182                "top_p",
183                "max_completion_tokens",
184                "max_tokens",
185                "response_format",
186                "reasoning_effort",
187                "tools",
188                "tool_choice",
189            ],
190        );
191
192        Ok(DecodedRequest {
193            request,
194            diagnostics,
195        })
196    }
197
198    fn encode_request(
199        &self,
200        request: &LlmRequest,
201        policy: &TranslationPolicy,
202    ) -> Result<EncodedRequest> {
203        if let Some(body) =
204            exact_preserved_request(&request.preservation, WireFormat::OpenAiChat, policy)
205        {
206            return Ok(EncodedRequest {
207                body,
208                diagnostics: Vec::new(),
209            });
210        }
211        let mut diagnostics = Vec::new();
212        validate_request_capabilities(request, &mut diagnostics, policy)?;
213        let allowed = match &request.tool_choice {
214            Some(ToolChoice::Raw(choice))
215                if choice.get("type").and_then(Value::as_str) == Some("allowed_tools")
216                    && choice.get("allowed_tools").is_some() =>
217            {
218                None
219            }
220            _ => crate::codecs::common::allowed_function_tools(request)?,
221        };
222        let (tools, tool_choice) = allowed.as_ref().map_or(
223            (request.tools.as_slice(), request.tool_choice.as_ref()),
224            |(tools, choice)| (tools.as_slice(), Some(choice)),
225        );
226        let mut body = Map::new();
227        if let Some(model) = &request.model {
228            body.insert("model".to_string(), Value::String(model.clone()));
229        }
230
231        let mut messages = Vec::new();
232        for instruction in &request.instructions {
233            let role = match instruction.role {
234                Role::Developer => "developer",
235                _ => "system",
236            };
237            messages.push(json!({
238                "role": role,
239                "content": text_from_blocks(&instruction.content, "\n\n"),
240            }));
241        }
242        for message in &request.messages {
243            messages.extend(encode_message_to_openai(message, &mut diagnostics, policy)?);
244        }
245        body.insert("messages".to_string(), Value::Array(messages));
246
247        if !tools.is_empty() {
248            body.insert("tools".to_string(), encode_openai_tools(tools)?);
249            if let Some(choice) = tool_choice {
250                body.insert("tool_choice".to_string(), encode_openai_tool_choice(choice));
251            }
252        }
253        if let Some(value) = request.output.max_output_tokens {
254            body.insert("max_completion_tokens".to_string(), json!(value));
255        }
256        if let Some(value) = request.sampling.temperature {
257            let value = scale_temperature(value, MAX_IR_TEMPERATURE, MAX_TEMPERATURE);
258            body.insert("temperature".to_string(), json!(value));
259        }
260        if let Some(value) = request.sampling.top_p {
261            body.insert("top_p".to_string(), json!(value));
262        }
263        if request.stream {
264            body.insert("stream".to_string(), Value::Bool(true));
265        }
266        if let Some(effort) = &request.reasoning.effort {
267            body.insert(
268                "reasoning_effort".to_string(),
269                Value::String(effort.clone()),
270            );
271        }
272        if let Some(format) = encode_openai_format(&request.output, &mut diagnostics, policy)? {
273            body.insert("response_format".to_string(), format);
274        }
275        copy_openai_chat_request_extensions(&mut body, &request.extensions.fields);
276
277        let body = embed_preservation(Value::Object(body), &request.preservation, policy);
278        Ok(EncodedRequest { body, diagnostics })
279    }
280
281    fn decode_response(
282        &self,
283        body: &Value,
284        _policy: &TranslationPolicy,
285    ) -> Result<DecodedResponse> {
286        let object = object(body, "$")?;
287        // `abort`, `error` and `repetition` mean the generation did not complete.
288        if let Some(reason @ ("abort" | "error" | "repetition")) = object
289            .get("choices")
290            .and_then(Value::as_array)
291            .and_then(|choices| choices.first())
292            .and_then(|choice| choice.get("finish_reason"))
293            .and_then(Value::as_str)
294        {
295            return Err(TranslationError::UpstreamFailure {
296                error: json!({ "message": format!("provider finished with finish_reason \"{reason}\"") }),
297            });
298        }
299        let mut response = AggLlmResponse {
300            id: object
301                .get("id")
302                .and_then(Value::as_str)
303                .map(ToOwned::to_owned),
304            model: object
305                .get("model")
306                .and_then(Value::as_str)
307                .map(ToOwned::to_owned),
308            outputs: Vec::new(),
309            usage: decode_openai_usage(object.get("usage")),
310            extensions: ProviderExtensions {
311                fields: provider_extensions(object, &["id", "model", "choices", "usage"]),
312            },
313            preservation: capture_response_preservation(
314                WireFormat::OpenAiChat,
315                &Value::Object(object.clone()),
316                _policy,
317            ),
318        };
319        if let Some(choice) = object
320            .get("choices")
321            .and_then(Value::as_array)
322            .and_then(|choices| choices.first())
323            .and_then(Value::as_object)
324        {
325            let message = choice
326                .get("message")
327                .and_then(Value::as_object)
328                .cloned()
329                .unwrap_or_default();
330            let refusal = message
331                .get("refusal")
332                .and_then(Value::as_str)
333                .filter(|text| !text.is_empty());
334            let mut content = match message.get("content") {
335                // decode_openai_content would turn absent response text into an empty text block.
336                None | Some(Value::Null) => Vec::new(),
337                Some(content) => decode_openai_content(
338                    content,
339                    WireFormat::OpenAiChat,
340                    &mut Vec::new(),
341                    &TranslationPolicy::default(),
342                    "$.choices[0].message.content",
343                )?,
344            };
345            prepend_openai_reasoning_blocks(&mut content, &message);
346            if let Some(text) = refusal {
347                content.push(ContentBlock::Refusal {
348                    text: text.to_string(),
349                });
350            }
351            if let Some(tool_calls) = message.get("tool_calls").and_then(Value::as_array) {
352                for (index, tool_call) in tool_calls.iter().enumerate() {
353                    if let Some(call) = decode_openai_tool_call(
354                        tool_call,
355                        index + 1,
356                        &TranslationPolicy::default(),
357                    )? {
358                        content.push(ContentBlock::ToolCall(call));
359                    }
360                }
361            }
362            let finish_reason = choice.get("finish_reason").and_then(Value::as_str);
363            let stop_reason = if refusal.is_some() && matches!(finish_reason, Some("stop") | None) {
364                StopReason::ContentFilter
365            } else {
366                map_openai_finish_reason(finish_reason)
367            };
368            response.outputs.push(ResponseOutput {
369                url_citations: message
370                    .get("annotations")
371                    .and_then(Value::as_array)
372                    .into_iter()
373                    .flatten()
374                    .filter(|annotation| annotation["type"] == "url_citation")
375                    .filter_map(|annotation| {
376                        serde_json::from_value(annotation["url_citation"].clone()).ok()
377                    })
378                    .collect(),
379                role: Role::Assistant,
380                content,
381                stop_reason: Some(stop_reason),
382            });
383        }
384
385        Ok(DecodedResponse {
386            response,
387            diagnostics: Vec::new(),
388        })
389    }
390
391    fn encode_response(
392        &self,
393        response: &AggLlmResponse,
394        _policy: &TranslationPolicy,
395    ) -> Result<EncodedResponse> {
396        super::super::responses::validate_response_output(response, WireFormat::OpenAiChat)?;
397        if let Some(body) =
398            exact_preserved_response(&response.preservation, WireFormat::OpenAiChat, _policy)
399        {
400            return Ok(EncodedResponse {
401                body,
402                diagnostics: Vec::new(),
403            });
404        }
405        let output = response.first_output();
406        let mut content = String::new();
407        let mut refusal = None::<String>;
408        let mut url_citations = output
409            .map(|output| output.url_citations.clone())
410            .unwrap_or_default();
411        let mut content_offset = 0;
412        if let Some(output) = output {
413            for block in &output.content {
414                match block {
415                    ContentBlock::Text { text } => {
416                        content.push_str(text);
417                        content_offset += text.chars().count();
418                    }
419                    ContentBlock::Refusal { text } => {
420                        refusal.get_or_insert_with(String::new).push_str(text);
421                        let refusal_len = text.chars().count();
422                        // IR offsets include refusal text; Chat content excludes it.
423                        for citation in &mut url_citations {
424                            citation.start_index -= refusal_len
425                                .min(citation.start_index.saturating_sub(content_offset));
426                            citation.end_index -=
427                                refusal_len.min(citation.end_index.saturating_sub(content_offset));
428                        }
429                        url_citations.retain(|citation| citation.start_index < citation.end_index);
430                    }
431                    ContentBlock::Unknown { raw, .. } => {
432                        if let Some(text) = raw.as_str() {
433                            content.push_str(text);
434                            content_offset += text.chars().count();
435                        }
436                    }
437                    _ => {}
438                }
439            }
440        }
441        let tool_calls = output
442            .map(|output| {
443                output
444                    .content
445                    .iter()
446                    .filter_map(|block| match block {
447                        ContentBlock::ToolCall(call) => Some(json!({
448                            "id": call.id,
449                            "type": "function",
450                            "function": {
451                                "name": call.name,
452                                "arguments": json_string(&call.arguments),
453                            },
454                        })),
455                        _ => None,
456                    })
457                    .collect::<Vec<_>>()
458            })
459            .unwrap_or_default();
460        let mut message = json!({
461            "role": "assistant",
462            "content": if content.is_empty() && (!tool_calls.is_empty() || refusal.is_some()) {
463                Value::Null
464            } else {
465                Value::String(content)
466            },
467        });
468        if let Some(refusal) = refusal {
469            message["refusal"] = Value::String(refusal);
470        }
471        if !url_citations.is_empty() {
472            message["annotations"] = Value::Array(
473                url_citations
474                    .iter()
475                    .map(|citation| json!({"type": "url_citation", "url_citation": citation}))
476                    .collect(),
477            );
478        }
479        if let Some(reasoning) = output
480            .map(|output| reasoning_text_from_blocks(&output.content, "\n"))
481            .filter(|reasoning| !reasoning.is_empty())
482        {
483            message["reasoning_content"] = Value::String(reasoning);
484        }
485        if let Some(details) = output
486            .map(|output| reasoning_details_from_blocks(&output.content))
487            .filter(|details| !details.is_empty())
488        {
489            message["reasoning_details"] = Value::Array(details);
490        }
491        if !tool_calls.is_empty() {
492            message["tool_calls"] = Value::Array(tool_calls);
493        }
494
495        let body = json!({
496            "id": response.id.clone().unwrap_or_else(|| "chatcmpl_switchyard".to_string()),
497            "object": "chat.completion",
498            "created": 0,
499            "model": response.model.clone().unwrap_or_else(|| "unknown".to_string()),
500            "choices": [{
501                "index": 0,
502                "message": message,
503                "finish_reason": output
504                    .and_then(|output| output.stop_reason)
505                    .map(openai_finish_reason)
506                    .unwrap_or("stop"),
507            }],
508            "usage": encode_openai_usage(&response.usage),
509        });
510        Ok(EncodedResponse {
511            body: embed_preservation(body, &response.preservation, _policy),
512            diagnostics: Vec::new(),
513        })
514    }
515}
516
517// Pulls OpenAI-compatible reasoning fields into private reasoning IR blocks.
518fn prepend_openai_reasoning_blocks(content: &mut Vec<ContentBlock>, object: &Map<String, Value>) {
519    if let Some(details) = object
520        .get("reasoning_details")
521        .and_then(Value::as_array)
522        .filter(|details| !details.is_empty())
523    {
524        let text = reasoning_text_from_details(details)
525            .or_else(|| {
526                first_nonempty_string(object, &["reasoning_content", "reasoning"])
527                    .map(ToOwned::to_owned)
528            })
529            .unwrap_or_default();
530        let signature = details.iter().find_map(|detail| {
531            detail
532                .get("signature")
533                .and_then(Value::as_str)
534                .filter(|signature| !signature.is_empty())
535                .map(ToOwned::to_owned)
536        });
537        content.insert(
538            0,
539            ContentBlock::Reasoning {
540                text,
541                signature,
542                details: details.clone(),
543            },
544        );
545        return;
546    }
547
548    if let Some(text) = first_nonempty_string(object, &["reasoning_content", "reasoning"]) {
549        content.insert(
550            0,
551            ContentBlock::Reasoning {
552                text: text.to_string(),
553                signature: None,
554                details: Vec::new(),
555            },
556        );
557    }
558}
559
560// Returns structured reasoning details in their original order.
561fn reasoning_details_from_blocks(content: &[ContentBlock]) -> Vec<Value> {
562    content
563        .iter()
564        .filter_map(|block| match block {
565            ContentBlock::Reasoning { details, .. } => Some(details.as_slice()),
566            _ => None,
567        })
568        .flatten()
569        .cloned()
570        .collect()
571}
572
573/// Decodes OpenAI role strings into normalized roles.
574///
575/// Unknown role strings are rejected with [`TranslationError::InvalidValue`] so
576/// the router returns the same `invalid_value` error the provider would, rather
577/// than silently coercing an invalid role to `user`. A missing role and
578/// known-but-unmapped roles (e.g. the legacy `function` role) keep their
579/// historical mapping to `user`. `path` points at the offending field.
580pub(crate) fn role_from_openai(role: Option<&str>, path: &str) -> Result<Role> {
581    match role {
582        Some("system") => Ok(Role::System),
583        Some("developer") => Ok(Role::Developer),
584        Some("assistant") => Ok(Role::Assistant),
585        Some("tool") => Ok(Role::Tool),
586        None => Ok(Role::User),
587        Some(other) if is_known_role_name(other) => Ok(Role::User),
588        Some(other) => Err(TranslationError::unsupported_role(path, other)),
589    }
590}
591
592/// Decodes OpenAI-style content into normalized content blocks.
593pub(crate) fn decode_openai_content(
594    content: &Value,
595    provider: WireFormat,
596    diagnostics: &mut Vec<TranslationDiagnostic>,
597    policy: &TranslationPolicy,
598    path: impl Into<String>,
599) -> Result<Vec<ContentBlock>> {
600    let path = path.into();
601    match content {
602        Value::Null => Ok(vec![ContentBlock::Text {
603            text: String::new(),
604        }]),
605        Value::String(text) => Ok(vec![ContentBlock::Text { text: text.clone() }]),
606        Value::Array(blocks) => {
607            let mut content = Vec::new();
608            for (index, block) in blocks.iter().enumerate() {
609                let Some(block) = block.as_object() else {
610                    push_lossy(
611                        diagnostics,
612                        policy,
613                        format!("content block at {path}[{index}] is not an object"),
614                    )?;
615                    continue;
616                };
617                match block.get("type").and_then(Value::as_str) {
618                    Some("text") | Some("input_text") | Some("output_text") => {
619                        content.push(ContentBlock::Text {
620                            text: block
621                                .get("text")
622                                .and_then(Value::as_str)
623                                .unwrap_or_default()
624                                .to_string(),
625                        });
626                    }
627                    Some("refusal") => {
628                        content.push(ContentBlock::Refusal {
629                            text: block
630                                .get("refusal")
631                                .and_then(Value::as_str)
632                                .unwrap_or_default()
633                                .to_string(),
634                        });
635                    }
636                    Some("image_url") | Some("input_image") => {
637                        if let Some(source) = decode_image_source(block) {
638                            content.push(ContentBlock::Image { source });
639                        }
640                    }
641                    Some("input_audio") => content.push(ContentBlock::Audio {
642                        source: MediaSource::Raw(Value::Object(block.clone())),
643                    }),
644                    Some("file") | Some("input_file") => {
645                        content.push(ContentBlock::File {
646                            source: decode_file_source(block),
647                        });
648                    }
649                    _ => content.push(ContentBlock::Unknown {
650                        provider: provider.into(),
651                        raw: Value::Object(block.clone()),
652                    }),
653                }
654            }
655            if content.is_empty() {
656                Ok(vec![ContentBlock::Text {
657                    text: String::new(),
658                }])
659            } else {
660                Ok(content)
661            }
662        }
663        other => Ok(vec![ContentBlock::Text {
664            text: string_value(other).unwrap_or_default(),
665        }]),
666    }
667}
668
669/// Decodes OpenAI image block shapes into normalized image sources.
670pub(crate) fn decode_image_source(block: &Map<String, Value>) -> Option<ImageSource> {
671    if let Some(image_url) = block.get("image_url") {
672        if let Some(url) = image_url.as_str() {
673            return Some(ImageSource::Url {
674                url: url.to_string(),
675                detail: block
676                    .get("detail")
677                    .and_then(Value::as_str)
678                    .map(ToOwned::to_owned),
679            });
680        }
681        if let Some(payload) = image_url.as_object() {
682            return payload
683                .get("url")
684                .and_then(Value::as_str)
685                .map(|url| ImageSource::Url {
686                    url: url.to_string(),
687                    detail: payload
688                        .get("detail")
689                        .or_else(|| block.get("detail"))
690                        .and_then(Value::as_str)
691                        .map(ToOwned::to_owned),
692                });
693        }
694    }
695    if let Some(image_url) = block.get("image_url").and_then(Value::as_str) {
696        return Some(ImageSource::Url {
697            url: image_url.to_string(),
698            detail: block
699                .get("detail")
700                .and_then(Value::as_str)
701                .map(ToOwned::to_owned),
702        });
703    }
704    Some(ImageSource::Raw(Value::Object(block.clone())))
705}
706
707/// Decodes OpenAI file block shapes into normalized file sources.
708///
709/// Accepts both the Chat shape, which nests the payload under a `file` object,
710/// and the Responses shape, which carries `file_id`/`file_data`/`filename`
711/// directly on the block. Returns `FileSource::Raw` when neither shape carries a
712/// field this can normalize.
713pub(crate) fn decode_file_source(block: &Map<String, Value>) -> FileSource {
714    if let Some(file) = block.get("file").and_then(Value::as_object) {
715        if let Some(file_id) = file.get("file_id").and_then(Value::as_str) {
716            return FileSource::FileId(file_id.to_string());
717        }
718        if let Some(file_data) = file.get("file_data").and_then(Value::as_str) {
719            return FileSource::FileData {
720                data: file_data.to_string(),
721                filename: file
722                    .get("filename")
723                    .and_then(Value::as_str)
724                    .map(ToOwned::to_owned),
725            };
726        }
727        return FileSource::Raw(Value::Object(file.clone()));
728    }
729    // A Chat block never reaches here with these keys, having matched the nested
730    // branch above.
731    if let Some(file_id) = block.get("file_id").and_then(Value::as_str) {
732        return FileSource::FileId(file_id.to_string());
733    }
734    if let Some(file_data) = block.get("file_data").and_then(Value::as_str) {
735        return FileSource::FileData {
736            data: file_data.to_string(),
737            filename: block
738                .get("filename")
739                .and_then(Value::as_str)
740                .map(ToOwned::to_owned),
741        };
742    }
743    FileSource::Raw(Value::Object(block.clone()))
744}
745
746/// Decodes one OpenAI tool call into a normalized tool call.
747pub(crate) fn decode_openai_tool_call(
748    tool_call: &Value,
749    generated_counter: usize,
750    policy: &TranslationPolicy,
751) -> Result<Option<ToolCall>> {
752    let Some(tool_call) = tool_call.as_object() else {
753        return Ok(None);
754    };
755    let function = tool_call
756        .get("function")
757        .and_then(Value::as_object)
758        .cloned()
759        .unwrap_or_default();
760    let id = tool_call
761        .get("id")
762        .and_then(Value::as_str)
763        .filter(|id| !id.is_empty())
764        .map(ToOwned::to_owned)
765        .unwrap_or_else(|| match &policy.deterministic_ids {
766            DeterministicIdPolicy::GenerateStable { prefix } => {
767                stable_id(prefix, generated_counter)
768            }
769            DeterministicIdPolicy::Preserve => String::new(),
770        });
771    // A custom (freeform) call has `custom.name` and a raw `custom.input` string. Carry the
772    // input as the single `input` argument, the same way Responses custom calls are carried.
773    let custom = tool_call.get("custom").and_then(Value::as_object);
774    let arguments = match custom {
775        Some(custom) => json!({
776            crate::codex_custom_tools::INPUT_ARGUMENT:
777                custom.get("input").and_then(Value::as_str).unwrap_or_default()
778        }),
779        None => function
780            .get("arguments")
781            .map(parse_arguments)
782            .unwrap_or_else(|| json!({})),
783    };
784    let name = custom
785        .unwrap_or(&function)
786        .get("name")
787        .and_then(Value::as_str)
788        .unwrap_or_default()
789        .to_string();
790    Ok(Some(ToolCall {
791        id,
792        name,
793        arguments,
794    }))
795}
796
797/// Parses stringified tool-call arguments when possible.
798pub(crate) fn parse_arguments(value: &Value) -> Value {
799    match value {
800        Value::String(text) => serde_json::from_str(text).unwrap_or_else(|_| value.clone()),
801        other => other.clone(),
802    }
803}
804
805/// Decodes OpenAI tool definitions into normalized tool definitions.
806pub(crate) fn decode_openai_tools(
807    tools: Option<&Value>,
808    _diagnostics: &mut Vec<TranslationDiagnostic>,
809    _policy: &TranslationPolicy,
810) -> Result<Vec<ToolDefinition>> {
811    let Some(tools) = tools.and_then(Value::as_array) else {
812        return Ok(Vec::new());
813    };
814    let mut definitions = Vec::new();
815    for tool in tools {
816        let Some(tool) = tool.as_object() else {
817            continue;
818        };
819        let function = tool
820            .get("function")
821            .and_then(Value::as_object)
822            .cloned()
823            .unwrap_or_else(|| tool.clone());
824        let name = function
825            .get("name")
826            .and_then(Value::as_str)
827            .unwrap_or_default()
828            .to_string();
829        if name.is_empty() {
830            continue;
831        }
832        definitions.push(ToolDefinition {
833            name,
834            description: function
835                .get("description")
836                .and_then(Value::as_str)
837                .map(ToOwned::to_owned),
838            parameters: function
839                .get("parameters")
840                .cloned()
841                .unwrap_or_else(|| json!({})),
842            strict: function.get("strict").and_then(Value::as_bool),
843        });
844    }
845    Ok(definitions)
846}
847
848/// Decodes OpenAI tool-choice values into normalized policy.
849pub(crate) fn decode_openai_tool_choice(value: &Value) -> ToolChoice {
850    match value {
851        Value::String(text) if text == "auto" => ToolChoice::Auto,
852        Value::String(text) if text == "required" => ToolChoice::Required,
853        Value::String(text) if text == "none" => ToolChoice::None,
854        Value::Object(object) => object
855            .get("function")
856            .and_then(Value::as_object)
857            .and_then(|function| function.get("name"))
858            .and_then(Value::as_str)
859            .map(|name| ToolChoice::Tool {
860                name: name.to_string(),
861            })
862            .unwrap_or_else(|| ToolChoice::Raw(value.clone())),
863        _ => ToolChoice::Raw(value.clone()),
864    }
865}
866
867/// Encodes one normalized message into one or more OpenAI messages.
868pub(crate) fn encode_message_to_openai(
869    message: &Message,
870    diagnostics: &mut Vec<TranslationDiagnostic>,
871    policy: &TranslationPolicy,
872) -> Result<Vec<Value>> {
873    if message_has_tool_results(message) {
874        return encode_message_with_tool_results_to_openai(message, diagnostics, policy);
875    }
876
877    Ok(vec![encode_message_without_tool_results_to_openai(
878        message,
879        diagnostics,
880        policy,
881    )?])
882}
883
884// Splits mixed content so OpenAI tool-result messages stay separate.
885fn encode_message_with_tool_results_to_openai(
886    message: &Message,
887    diagnostics: &mut Vec<TranslationDiagnostic>,
888    policy: &TranslationPolicy,
889) -> Result<Vec<Value>> {
890    let mut out = Vec::new();
891    let mut pending_content = Vec::new();
892
893    for block in &message.content {
894        if let ContentBlock::ToolResult(result) = block {
895            out.push(json!({
896                "role": "tool",
897                "tool_call_id": result.tool_call_id,
898                "content": text_from_blocks(&result.content, " "),
899            }));
900            let non_text = result
901                .content
902                .iter()
903                .filter(|block| {
904                    !matches!(
905                        block,
906                        ContentBlock::Text { .. } | ContentBlock::Refusal { .. }
907                    )
908                })
909                .cloned()
910                .collect::<Vec<_>>();
911            if !non_text.is_empty() {
912                push_lossy(
913                    diagnostics,
914                    policy,
915                    "OpenAI Chat tool messages only support text; non-text tool-result content was moved to a user message",
916                )?;
917                pending_content.extend(non_text);
918            }
919        } else {
920            pending_content.push(block.clone());
921        }
922    }
923
924    push_pending_openai_message(
925        &mut out,
926        message.role,
927        &mut pending_content,
928        diagnostics,
929        policy,
930    )?;
931    Ok(out)
932}
933
934// Flushes accumulated non-tool-result content as a normal OpenAI message.
935fn push_pending_openai_message(
936    out: &mut Vec<Value>,
937    role: Role,
938    pending_content: &mut Vec<ContentBlock>,
939    diagnostics: &mut Vec<TranslationDiagnostic>,
940    policy: &TranslationPolicy,
941) -> Result<()> {
942    if pending_content.is_empty() {
943        return Ok(());
944    }
945
946    let message = Message::new(role, std::mem::take(pending_content));
947    out.push(encode_message_without_tool_results_to_openai(
948        &message,
949        diagnostics,
950        policy,
951    )?);
952    Ok(())
953}
954
955// Encodes a normalized message that has no tool-result blocks.
956fn encode_message_without_tool_results_to_openai(
957    message: &Message,
958    diagnostics: &mut Vec<TranslationDiagnostic>,
959    policy: &TranslationPolicy,
960) -> Result<Value> {
961    let role = match message.role {
962        Role::System => "system",
963        Role::Developer => "developer",
964        Role::Assistant => "assistant",
965        Role::Tool => "tool",
966        Role::User => "user",
967    };
968    let tool_calls = message
969        .content
970        .iter()
971        .filter_map(|block| match block {
972            ContentBlock::ToolCall(call) => Some(json!({
973                "id": call.id,
974                "type": "function",
975                "function": {
976                    "name": call.name,
977                    "arguments": json_string(&call.arguments),
978                },
979            })),
980            _ => None,
981        })
982        .collect::<Vec<_>>();
983    let content_blocks = message
984        .content
985        .iter()
986        .filter(|block| {
987            !matches!(
988                block,
989                ContentBlock::ToolCall(_) | ContentBlock::Reasoning { .. }
990            )
991        })
992        .cloned()
993        .collect::<Vec<_>>();
994    let mut message_json = json!({
995        "role": role,
996        "content": encode_openai_content(&content_blocks, message.role, diagnostics, policy)?,
997    });
998    encode_openai_message_reasoning(&mut message_json, &message.content);
999    if !tool_calls.is_empty() {
1000        message_json["tool_calls"] = Value::Array(tool_calls);
1001        if message_json["content"] == Value::String(String::new()) {
1002            message_json["content"] = Value::Null;
1003        }
1004    }
1005    Ok(message_json)
1006}
1007
1008// Adds either plaintext reasoning or structured details to an OpenAI Chat message.
1009fn encode_openai_message_reasoning(message: &mut Value, content: &[ContentBlock]) {
1010    let details = reasoning_details_from_blocks(content);
1011    if details.is_empty() {
1012        encode_openai_message_plaintext_reasoning(message, content);
1013    } else {
1014        encode_openai_message_structured_reasoning(message, content, details);
1015    }
1016}
1017
1018// Adds reasoning blocks that have no structured provider representation.
1019fn encode_openai_message_plaintext_reasoning(message: &mut Value, content: &[ContentBlock]) {
1020    let reasoning = content
1021        .iter()
1022        .filter_map(|block| match block {
1023            ContentBlock::Reasoning {
1024                text,
1025                signature: None,
1026                ..
1027            } => Some(text.as_str()),
1028            _ => None,
1029        })
1030        .collect::<Vec<_>>()
1031        .join("\n");
1032    if !reasoning.is_empty() {
1033        message["reasoning"] = Value::String(reasoning);
1034    }
1035}
1036
1037// Adds exact provider details and text that cannot be recovered from those details.
1038fn encode_openai_message_structured_reasoning(
1039    message: &mut Value,
1040    content: &[ContentBlock],
1041    details: Vec<Value>,
1042) {
1043    message["reasoning_details"] = Value::Array(details);
1044    let fallback = content
1045        .iter()
1046        .filter_map(|block| match block {
1047            ContentBlock::Reasoning { text, details, .. }
1048                if !details.is_empty()
1049                    && reasoning_text_from_details(details).as_deref() != Some(text.as_str())
1050                    && !text.is_empty() =>
1051            {
1052                Some(text.as_str())
1053            }
1054            _ => None,
1055        })
1056        .collect::<Vec<_>>()
1057        .join("\n");
1058    if !fallback.is_empty() {
1059        message["reasoning"] = Value::String(fallback);
1060    }
1061}
1062
1063// Checks whether any block in a message is a tool result.
1064fn message_has_tool_results(message: &Message) -> bool {
1065    message
1066        .content
1067        .iter()
1068        .any(|block| matches!(block, ContentBlock::ToolResult(_)))
1069}
1070
1071// Copies Chat-compatible extension fields preserved in the IR.
1072fn copy_openai_chat_request_extensions(
1073    body: &mut Map<String, Value>,
1074    extensions: &Map<String, Value>,
1075) {
1076    for field in [
1077        // Template switches for llama.cpp, vLLM and SGLang, such as `enable_thinking`.
1078        "chat_template_kwargs",
1079        "metadata",
1080        "parallel_tool_calls",
1081        "prompt_cache_key",
1082        "prompt_cache_retention",
1083        "safety_identifier",
1084        "service_tier",
1085        "store",
1086        "stream_options",
1087        // `top_logprobs` is only valid alongside `logprobs`.
1088        "logprobs",
1089        "top_logprobs",
1090        "user",
1091    ] {
1092        if let Some(value) = extensions.get(field) {
1093            body.entry(field.to_string())
1094                .or_insert_with(|| value.clone());
1095        }
1096    }
1097    if let Some(stop_sequences) = extensions.get("stop_sequences") {
1098        body.entry("stop").or_insert_with(|| stop_sequences.clone());
1099    }
1100}
1101
1102// Detects placeholder empty text generated while decoding assistant tool calls.
1103fn is_empty_text_only(content: &[ContentBlock]) -> bool {
1104    matches!(content, [ContentBlock::Text { text }] if text.is_empty())
1105}
1106
1107/// Encodes normalized content into OpenAI Chat content JSON.
1108pub(crate) fn encode_openai_content(
1109    content: &[ContentBlock],
1110    role: Role,
1111    diagnostics: &mut Vec<TranslationDiagnostic>,
1112    policy: &TranslationPolicy,
1113) -> Result<Value> {
1114    if content
1115        .iter()
1116        .any(|block| matches!(block, ContentBlock::Mcp(_)))
1117    {
1118        return Err(TranslationError::LossyConversion(
1119            "MCP history encoding is not implemented".into(),
1120        ));
1121    }
1122    let has_non_text = content.iter().any(|block| {
1123        matches!(
1124            block,
1125            ContentBlock::Image { .. }
1126                | ContentBlock::Audio { .. }
1127                | ContentBlock::Video { .. }
1128                | ContentBlock::File { .. }
1129                | ContentBlock::Unknown { .. }
1130        )
1131    });
1132    if !has_non_text {
1133        return Ok(Value::String(text_from_blocks(content, "\n")));
1134    }
1135    if role != Role::User {
1136        for block in content {
1137            if let ContentBlock::Unknown { provider, raw } = block {
1138                reject_responses_native_input_item(provider, raw, WireFormat::OpenAiChat)?;
1139            }
1140        }
1141        push_lossy(
1142            diagnostics,
1143            policy,
1144            "OpenAI Chat only supports text content for non-user messages",
1145        )?;
1146        return Ok(Value::String(text_from_blocks(content, "\n")));
1147    }
1148    let mut blocks = Vec::new();
1149    for block in content {
1150        crate::codecs::openai_media::validate_media(block, WireFormat::OpenAiChat)?;
1151        match block {
1152            ContentBlock::Text { text } => blocks.push(json!({"type": "text", "text": text})),
1153            ContentBlock::Refusal { text } => blocks.push(json!({"type": "text", "text": text})),
1154            ContentBlock::Image { source } => match openai_image_part(source) {
1155                Some(part) => blocks.push(part),
1156                None => {
1157                    push_lossy(
1158                        diagnostics,
1159                        policy,
1160                        "OpenAI Chat codec could not map image content",
1161                    )?;
1162                    blocks.push(openai_text_part(&image_source_text(source)));
1163                }
1164            },
1165            ContentBlock::File { source } => match openai_file_part(source) {
1166                Some(part) => blocks.push(part),
1167                None => {
1168                    push_lossy(
1169                        diagnostics,
1170                        policy,
1171                        "OpenAI Chat codec could not map file content",
1172                    )?;
1173                    blocks.push(openai_text_part(&file_source_text(source)));
1174                }
1175            },
1176            ContentBlock::Audio { source } => {
1177                blocks.push(crate::codecs::openai_media::audio_part(source)?);
1178            }
1179            ContentBlock::Video { source } => {
1180                push_lossy(
1181                    diagnostics,
1182                    policy,
1183                    "OpenAI Chat codec does not have a stable video request mapping yet",
1184                )?;
1185                blocks.push(openai_text_part(&media_source_text(source)));
1186            }
1187            ContentBlock::Mcp(_) => {
1188                return Err(TranslationError::LossyConversion(
1189                    "MCP history encoding is not implemented".into(),
1190                ));
1191            }
1192            ContentBlock::Unknown { provider, raw } => {
1193                reject_responses_native_input_item(provider, raw, WireFormat::OpenAiChat)?;
1194                push_lossy(
1195                    diagnostics,
1196                    policy,
1197                    "unknown content block encoded as text for OpenAI Chat",
1198                )?;
1199                blocks.push(openai_text_part(&json_string(raw)));
1200            }
1201            ContentBlock::Reasoning { .. }
1202            | ContentBlock::ToolCall(_)
1203            | ContentBlock::ToolResult(_) => {}
1204        }
1205    }
1206    Ok(Value::Array(blocks))
1207}
1208
1209// Builds an OpenAI text content part.
1210fn openai_text_part(text: &str) -> Value {
1211    json!({"type": "text", "text": text})
1212}
1213
1214fn openai_image_part(source: &ImageSource) -> Option<Value> {
1215    let ImagePayload { url, detail } = image_payload(source)?;
1216    let mut image_url = json!({});
1217    image_url["url"] = Value::String(url);
1218    if let Some(detail) = detail {
1219        image_url["detail"] = Value::String(detail);
1220    }
1221    let mut part = json!({"type": "image_url"});
1222    part["image_url"] = image_url;
1223    Some(part)
1224}
1225
1226fn openai_file_part(source: &FileSource) -> Option<Value> {
1227    let mut part = json!({"type": "file"});
1228    part["file"] = Value::Object(file_payload(source)?);
1229    Some(part)
1230}
1231
1232// Converts unsupported media sources to deterministic text fallback content.
1233fn media_source_text(source: &MediaSource) -> String {
1234    match source {
1235        MediaSource::Url { url, media_type } => json_string(&json!({
1236            "url": url,
1237            "media_type": media_type,
1238        })),
1239        MediaSource::Base64 { media_type, data } => json_string(&json!({
1240            "media_type": media_type,
1241            "data": data,
1242        })),
1243        MediaSource::Raw(raw) => json_string(raw),
1244    }
1245}
1246
1247/// Encodes normalized tool definitions into OpenAI tool JSON.
1248pub(crate) fn encode_openai_tools(tools: &[Tool]) -> Result<Value> {
1249    let mut names = std::collections::HashSet::new();
1250    Ok(Value::Array(
1251        tools
1252            .iter()
1253            .map(|tool| {
1254                let tool = tool.function().ok_or_else(|| {
1255                    TranslationError::LossyConversion(
1256                        "MCP and provider tool encoding is not implemented".into(),
1257                    )
1258                })?;
1259                if !names.insert(tool.name.as_str()) {
1260                    return Err(TranslationError::InvalidValue {
1261                        path: "$.tools".to_string(),
1262                        message: format!("duplicate tool name: {:?}", tool.name),
1263                    });
1264                }
1265                let mut function = json!({
1266                    "name": tool.name,
1267                    "description": tool.description.clone().unwrap_or_default(),
1268                    "parameters": tool.parameters,
1269                });
1270                if let Some(strict) = tool.strict {
1271                    function["strict"] = Value::Bool(strict);
1272                }
1273                Ok(json!({"type": "function", "function": function}))
1274            })
1275            .collect::<Result<_>>()?,
1276    ))
1277}
1278
1279/// Encodes normalized tool choice into OpenAI Chat JSON.
1280pub(crate) fn encode_openai_tool_choice(choice: &ToolChoice) -> Value {
1281    match choice {
1282        ToolChoice::Auto => Value::String("auto".to_string()),
1283        ToolChoice::Required => Value::String("required".to_string()),
1284        ToolChoice::None => Value::String("none".to_string()),
1285        ToolChoice::Tool { name } => json!({"type": "function", "function": {"name": name}}),
1286        ToolChoice::Raw(value) => value.clone(),
1287    }
1288}
1289
1290/// Normalizes OpenAI usage fields.
1291pub(crate) fn decode_openai_usage(value: Option<&Value>) -> Usage {
1292    let Some(value) = value.and_then(Value::as_object) else {
1293        return Usage::default();
1294    };
1295    let cached_input_tokens = value
1296        .get("prompt_tokens_details")
1297        .and_then(|details| details.get("cached_tokens"))
1298        .and_then(Value::as_u64);
1299    let cache_creation_input_tokens = value
1300        .get("prompt_tokens_details")
1301        .and_then(|details| {
1302            details
1303                .get("cache_write_tokens")
1304                .or_else(|| details.get("cache_creation_tokens"))
1305        })
1306        .and_then(Value::as_u64);
1307    Usage {
1308        provider_cost: crate::codecs::common::provider_cost(value),
1309        input_tokens: value
1310            .get("prompt_tokens")
1311            .and_then(Value::as_u64)
1312            .map(|tokens| {
1313                tokens
1314                    .saturating_sub(cached_input_tokens.unwrap_or(0))
1315                    .saturating_sub(cache_creation_input_tokens.unwrap_or(0))
1316            }),
1317        cache: crate::codecs::common::cache_usage_details(
1318            value,
1319            cached_input_tokens,
1320            cache_creation_input_tokens,
1321        ),
1322        output_tokens: value.get("completion_tokens").and_then(Value::as_u64),
1323        total_tokens: value.get("total_tokens").and_then(Value::as_u64),
1324        reasoning_tokens: value
1325            .get("completion_tokens_details")
1326            .and_then(|details| details.get("reasoning_tokens"))
1327            .or_else(|| {
1328                value
1329                    .get("output_tokens_details")
1330                    .and_then(|details| details.get("reasoning_tokens"))
1331            })
1332            .and_then(Value::as_u64),
1333    }
1334}
1335
1336/// Encodes normalized usage into OpenAI Chat usage JSON.
1337pub(crate) fn encode_openai_usage(usage: &Usage) -> Value {
1338    let prompt_tokens = usage.input_tokens.unwrap_or(0)
1339        + usage.cached_input_tokens().unwrap_or(0)
1340        + usage.cache_creation_input_tokens().unwrap_or(0);
1341    let mut value = json!({
1342        "prompt_tokens": prompt_tokens,
1343        "completion_tokens": usage.output_tokens.unwrap_or(0),
1344        "total_tokens": usage
1345            .total_tokens
1346            .or_else(|| Some(prompt_tokens + usage.output_tokens.unwrap_or(0)))
1347            .unwrap_or(0),
1348    });
1349    if usage.cached_input_tokens().is_some() || usage.cache_creation_input_tokens().is_some() {
1350        value["prompt_tokens_details"] = json!({
1351            "cached_tokens": usage.cached_input_tokens().unwrap_or(0),
1352            "cache_write_tokens": usage.cache_creation_input_tokens().unwrap_or(0),
1353        });
1354    }
1355    if let Some(reasoning_tokens) = usage.reasoning_tokens {
1356        value["completion_tokens_details"] = json!({
1357            "reasoning_tokens": reasoning_tokens,
1358        });
1359    }
1360    crate::codecs::common::encode_usage_metadata(value, usage)
1361}
1362
1363/// Maps OpenAI finish reasons to normalized stop reasons.
1364pub(crate) fn map_openai_finish_reason(reason: Option<&str>) -> StopReason {
1365    match reason {
1366        Some("length") => StopReason::MaxTokens,
1367        Some("tool_calls") | Some("function_call") => StopReason::ToolUse,
1368        Some("content_filter") => StopReason::ContentFilter,
1369        Some("stop") | None => StopReason::EndTurn,
1370        _ => StopReason::Unknown,
1371    }
1372}
1373
1374/// Maps normalized stop reasons back to OpenAI's vocabulary.
1375pub(crate) fn openai_finish_reason(reason: StopReason) -> &'static str {
1376    match reason {
1377        StopReason::MaxTokens => "length",
1378        StopReason::ToolUse => "tool_calls",
1379        StopReason::ContentFilter => "content_filter",
1380        StopReason::EndTurn | StopReason::Unknown | StopReason::Error => "stop",
1381    }
1382}