1use std::collections::HashMap;
7
8use serde_json::{Map, Value, json};
9use switchyard_protocol::MAX_IR_TEMPERATURE;
10
11use super::MAX_TEMPERATURE;
12use crate::codecs::common::{
13 collect_responses_reasoning_text, encrypted_reasoning_data, encrypted_reasoning_item_id,
14 is_anthropic_request, is_known_role_name, provider_extensions, reasoning_text_from_blocks,
15 scale_temperature, text_from_blocks,
16};
17use crate::codecs::openai_chat::{decode_file_source, decode_image_source};
18use crate::codecs::openai_media::{
19 ImagePayload, file_payload, file_source_text, image_payload, image_source_text,
20};
21use crate::codecs::structured_output::{decode_openai_schema_enforcement, encode_openai_format};
22use crate::codecs::{
23 DecodedRequest, DecodedResponse, EncodedRequest, EncodedResponse, FormatCodec,
24};
25use crate::diagnostic::TranslationDiagnostic;
26use crate::error::{Result, TranslationError};
27use crate::format::{FormatId, WireFormat};
28use crate::llm::{
29 AggLlmResponse, ContentBlock, FileSource, ImageSource, LlmRequest, MediaSource, Message,
30 OutputParams, ProviderExtensions, ReasoningParams, ResponseOutput, Role, SamplingParams,
31 StopReason, Tool, ToolCall, ToolChoice, ToolDefinition, ToolResult, Usage,
32};
33use crate::policy::{DeterministicIdPolicy, TranslationPolicy};
34use crate::util::{
35 capture_request_preservation, capture_response_preservation, embed_preservation,
36 exact_preserved_request, exact_preserved_response, is_responses_native_input_item, json_string,
37 push_lossy, stable_id, string_value, validate_request_capabilities,
38};
39
40pub struct OpenAiResponsesCodec;
42
43impl FormatCodec for OpenAiResponsesCodec {
44 fn format(&self) -> FormatId {
45 WireFormat::OpenAiResponses.into()
46 }
47
48 fn decode_request(&self, body: &Value, policy: &TranslationPolicy) -> Result<DecodedRequest> {
49 let body = crate::util::object(body, "$")?;
50 let mut diagnostics = Vec::new();
51 let response_format = decode_responses_text_format(body.get("text"));
52 let mut request = LlmRequest {
53 model: body
54 .get("model")
55 .and_then(Value::as_str)
56 .filter(|model| !model.is_empty())
57 .map(ToOwned::to_owned),
58 output: OutputParams {
59 max_output_tokens: body.get("max_output_tokens").and_then(Value::as_u64),
60 is_schema_enforced: decode_openai_schema_enforcement(response_format.as_ref()),
61 response_format,
62 },
63 reasoning: ReasoningParams {
64 effort: body
65 .get("reasoning")
66 .and_then(Value::as_object)
67 .and_then(|object| object.get("effort"))
68 .and_then(Value::as_str)
69 .map(ToOwned::to_owned),
70 raw: body.get("reasoning").cloned(),
71 },
72 sampling: SamplingParams {
73 temperature: body
74 .get("temperature")
75 .and_then(Value::as_f64)
76 .map(|value| scale_temperature(value, MAX_TEMPERATURE, MAX_IR_TEMPERATURE)),
77 top_p: body.get("top_p").and_then(Value::as_f64),
78 top_k: None,
79 },
80 stream: body.get("stream").and_then(Value::as_bool).unwrap_or(false),
81 preservation: capture_request_preservation(
82 WireFormat::OpenAiResponses,
83 &Value::Object(body.clone()),
84 policy,
85 ),
86 ..LlmRequest::default()
87 };
88 if let Some(instructions) = body.get("instructions").and_then(Value::as_str)
89 && !instructions.is_empty()
90 {
91 request.instructions.push(crate::llm::InstructionBlock {
92 role: Role::System,
93 content: vec![ContentBlock::Text {
94 text: instructions.to_string(),
95 }],
96 });
97 }
98 let stored_state = body
101 .get("previous_response_id")
102 .and_then(Value::as_str)
103 .is_some_and(|id| !id.is_empty());
104 let mut custom_call_outputs = Vec::new();
105 request.messages = decode_responses_input(
106 body.get("input").unwrap_or(&Value::String(String::new())),
107 stored_state,
108 &mut custom_call_outputs,
109 &mut diagnostics,
110 policy,
111 )?;
112 let mut tool_namespaces = Map::new();
113 let mut custom_tools = Map::new();
114 request.tools =
115 decode_responses_tools(body.get("tools"), &mut tool_namespaces, &mut custom_tools)
116 .into_iter()
117 .map(Tool::from)
118 .collect();
119 let mut additional_tools = Vec::new();
124 if let Some(items) = body.get("input").and_then(Value::as_array) {
125 for item in items {
126 if let Some(item) = item.as_object()
127 && item.get("type").and_then(Value::as_str) == Some("additional_tools")
128 && let Some(tools) = item.get("tools").and_then(Value::as_array)
129 {
130 request.tools.extend(
131 decode_responses_tools(
132 Some(&Value::Array(tools.clone())),
133 &mut tool_namespaces,
134 &mut custom_tools,
135 )
136 .into_iter()
137 .map(Tool::from),
138 );
139 additional_tools.extend(tools.iter().cloned());
140 }
141 }
142 }
143 request.tool_choice = body
144 .get("tool_choice")
145 .and_then(decode_responses_tool_choice);
146 request.extensions.fields = provider_extensions(
147 body,
148 &[
149 "model",
150 "instructions",
151 "input",
152 "tools",
153 "tool_choice",
154 "max_output_tokens",
155 "text",
156 "reasoning",
157 "temperature",
158 "top_p",
159 "stream",
160 ],
161 );
162 crate::codex_namespaces::attach_tool_namespaces(&mut request.extensions, tool_namespaces);
163 crate::codex_custom_tools::attach_custom_tools(&mut request.extensions, custom_tools);
164 crate::codex_custom_tools::attach_custom_call_outputs(
165 &mut request.extensions,
166 custom_call_outputs,
167 );
168 crate::codex_custom_tools::attach_additional_tools(
169 &mut request.extensions,
170 additional_tools,
171 );
172 Ok(DecodedRequest {
173 request,
174 diagnostics,
175 })
176 }
177
178 fn encode_request(
179 &self,
180 request: &LlmRequest,
181 policy: &TranslationPolicy,
182 ) -> Result<EncodedRequest> {
183 if let Some(body) =
184 exact_preserved_request(&request.preservation, WireFormat::OpenAiResponses, policy)
185 {
186 return Ok(EncodedRequest {
187 body,
188 diagnostics: Vec::new(),
189 });
190 }
191 let mut diagnostics = Vec::new();
192 validate_request_capabilities(request, &mut diagnostics, policy)?;
193 let mut body = Map::new();
194 if let Some(model) = &request.model {
195 body.insert("model".to_string(), Value::String(model.clone()));
196 }
197 let instructions = request
198 .instructions
199 .iter()
200 .flat_map(|instruction| instruction.content.iter())
201 .filter_map(|block| match block {
202 ContentBlock::Text { text } | ContentBlock::Refusal { text } => Some(text.as_str()),
203 _ => None,
204 })
205 .collect::<Vec<_>>()
206 .join("\n\n");
207 if !instructions.is_empty() {
208 body.insert("instructions".to_string(), Value::String(instructions));
209 }
210 body.insert(
211 "input".to_string(),
212 encode_responses_input(
213 &request.messages,
214 &mut diagnostics,
215 policy,
216 crate::codex_namespaces::tool_namespaces(&request.extensions),
217 &crate::codex_custom_tools::custom_tool_names(&request.extensions),
218 crate::codex_custom_tools::custom_call_outputs(&request.extensions),
219 )?,
220 );
221 if let Some(additional) = crate::codex_custom_tools::additional_tools(&request.extensions) {
222 let item = json!({
225 "type": "additional_tools",
226 "role": "developer",
227 "tools": additional,
228 });
229 match body.get_mut("input") {
230 Some(Value::Array(input)) => input.insert(0, item),
231 _ => body
232 .insert("input".to_string(), Value::Array(vec![item]))
233 .map_or((), |_| ()),
234 }
235 } else if !request.tools.is_empty() {
236 body.insert(
237 "tools".to_string(),
238 encode_responses_tools(
239 &request.tools,
240 crate::codex_namespaces::tool_namespaces(&request.extensions),
241 crate::codex_custom_tools::custom_tools(&request.extensions),
242 )?,
243 );
244 }
245 if let Some(choice) = &request.tool_choice
246 && let Some(choice) = encode_responses_tool_choice(
247 choice,
248 crate::codex_namespaces::tool_namespaces(&request.extensions),
249 crate::codex_custom_tools::custom_tools(&request.extensions),
250 )
251 {
252 body.insert("tool_choice".to_string(), choice);
253 }
254 if let Some(max_output_tokens) = request.output.max_output_tokens {
255 body.insert("max_output_tokens".to_string(), json!(max_output_tokens));
256 }
257 if let Some(response_format) =
258 encode_openai_format(&request.output, &mut diagnostics, policy)?
259 {
260 body.insert(
261 "text".to_string(),
262 json!({"format": encode_responses_text_format(&response_format)}),
263 );
264 }
265 let mut reasoning = if is_anthropic_request(request) {
268 let mut reasoning = Map::new();
269 if request
270 .reasoning
271 .raw
272 .as_ref()
273 .and_then(|thinking| thinking.get("type"))
274 .and_then(Value::as_str)
275 == Some("disabled")
276 {
277 reasoning.insert("effort".to_string(), json!("none"));
278 }
279 reasoning
280 } else {
281 request
282 .reasoning
283 .raw
284 .as_ref()
285 .and_then(Value::as_object)
286 .cloned()
287 .unwrap_or_default()
288 };
289 if let Some(effort) = &request.reasoning.effort {
290 reasoning.insert("effort".to_string(), json!(effort));
291 }
292 if !reasoning.is_empty() {
293 body.insert("reasoning".to_string(), Value::Object(reasoning));
294 }
295 if let Some(value) = request.sampling.temperature {
296 let value = scale_temperature(value, MAX_IR_TEMPERATURE, MAX_TEMPERATURE);
297 body.insert("temperature".to_string(), json!(value));
298 }
299 if let Some(value) = request.sampling.top_p {
300 body.insert("top_p".to_string(), json!(value));
301 }
302 if request.stream {
303 body.insert("stream".to_string(), Value::Bool(true));
304 }
305 copy_responses_request_extensions(&mut body, &request.extensions.fields);
306
307 let body = embed_preservation(Value::Object(body), &request.preservation, policy);
308 Ok(EncodedRequest { body, diagnostics })
309 }
310
311 fn decode_response(&self, body: &Value, policy: &TranslationPolicy) -> Result<DecodedResponse> {
312 let body = crate::util::object(body, "$")?;
313 if body.get("status").and_then(Value::as_str) == Some("failed") {
316 return Err(TranslationError::UpstreamFailure {
317 error: body
318 .get("error")
319 .filter(|error| error.is_object())
320 .cloned()
321 .unwrap_or_else(|| {
322 json!({ "message": "provider reported status \"failed\" without error details" })
323 }),
324 });
325 }
326 let mut diagnostics = Vec::new();
327 let mut content = Vec::new();
328 let mut role = Role::Assistant;
329 let mut stop_reason = None;
330 let mut has_output = false;
331 let mut url_citations = Vec::new();
332 let mut text_offset = 0;
333 if let Some(items) = body.get("output").and_then(Value::as_array) {
334 for item in items {
335 if let Some(output) = decode_responses_output_item(item, &mut diagnostics, policy)?
336 {
337 has_output = true;
338 role = output.role;
339 for mut citation in output.url_citations {
340 citation.start_index += text_offset;
341 citation.end_index += text_offset;
342 url_citations.push(citation);
343 }
344 text_offset += output
345 .content
346 .iter()
347 .map(|block| match block {
348 ContentBlock::Text { text } | ContentBlock::Refusal { text } => {
349 text.chars().count()
350 }
351 _ => 0,
352 })
353 .sum::<usize>();
354 content.extend(output.content);
355 if output.stop_reason.is_some() && stop_reason != Some(StopReason::ToolUse) {
356 stop_reason = output.stop_reason;
357 }
358 }
359 }
360 }
361 if body.get("status").and_then(Value::as_str) == Some("incomplete") {
363 match body
364 .get("incomplete_details")
365 .and_then(|details| details.get("reason"))
366 .and_then(Value::as_str)
367 {
368 Some("max_output_tokens") => stop_reason = Some(StopReason::MaxTokens),
369 Some("content_filter") => stop_reason = Some(StopReason::ContentFilter),
370 _ => {}
371 }
372 }
373 let outputs = vec![if has_output {
374 ResponseOutput {
375 url_citations,
376 role,
377 content,
378 stop_reason,
379 }
380 } else {
381 ResponseOutput {
382 url_citations: Vec::new(),
383 role: Role::Assistant,
384 content: vec![ContentBlock::Text {
385 text: String::new(),
386 }],
387 stop_reason: stop_reason.or(Some(StopReason::EndTurn)),
389 }
390 }];
391 let response = AggLlmResponse {
392 id: body
393 .get("id")
394 .and_then(Value::as_str)
395 .map(ToOwned::to_owned),
396 model: body
397 .get("model")
398 .and_then(Value::as_str)
399 .map(ToOwned::to_owned),
400 outputs,
401 usage: decode_responses_usage(body.get("usage")),
402 extensions: ProviderExtensions {
403 fields: provider_extensions(
404 body,
405 &["id", "model", "object", "output", "usage", "status"],
406 ),
407 },
408 preservation: capture_response_preservation(
409 WireFormat::OpenAiResponses,
410 &Value::Object(body.clone()),
411 policy,
412 ),
413 };
414 Ok(DecodedResponse {
415 response,
416 diagnostics,
417 })
418 }
419
420 fn encode_response(
421 &self,
422 response: &AggLlmResponse,
423 _policy: &TranslationPolicy,
424 ) -> Result<EncodedResponse> {
425 if let Some(body) =
426 exact_preserved_response(&response.preservation, WireFormat::OpenAiResponses, _policy)
427 {
428 return Ok(EncodedResponse {
429 body,
430 diagnostics: Vec::new(),
431 });
432 }
433 let is_truncated = matches!(
434 response
435 .first_output()
436 .and_then(|output| output.stop_reason),
437 Some(StopReason::MaxTokens)
438 );
439 let status = if is_truncated {
440 "incomplete"
441 } else {
442 "completed"
443 };
444 let incomplete_details = is_truncated.then(|| json!({ "reason": "max_output_tokens" }));
445 Ok(EncodedResponse {
446 body: embed_preservation(
447 json!({
448 "id": response.id.clone().unwrap_or_else(|| "resp_switchyard".to_string()),
449 "object": "response",
450 "created_at": 0,
451 "model": response.model.clone().unwrap_or_else(|| "unknown".to_string()),
452 "status": status,
453 "incomplete_details": incomplete_details,
454 "output": encode_responses_output(&response.outputs),
455 "usage": encode_responses_usage(&response.usage),
456 "parallel_tool_calls": true,
457 "tool_choice": "auto",
458 "tools": [],
459 }),
460 &response.preservation,
461 _policy,
462 ),
463 diagnostics: Vec::new(),
464 })
465 }
466}
467
468fn decode_responses_input(
470 value: &Value,
471 stored_state: bool,
472 custom_call_outputs: &mut Vec<String>,
473 diagnostics: &mut Vec<TranslationDiagnostic>,
474 policy: &TranslationPolicy,
475) -> Result<Vec<Message>> {
476 match value {
477 Value::String(text) => Ok(vec![Message::text(Role::User, text)]),
478 Value::Array(items) => {
479 let mut messages = Vec::new();
480 let mut pending_tool_calls = Vec::new();
481 let mut pending_tool_outputs = Vec::new();
482 let mut deferred_messages = Vec::new();
483 let mut pending_reasoning: Vec<ContentBlock> = Vec::new();
484 for (index, item) in items.iter().enumerate() {
485 let Some(item) = item.as_object() else {
486 push_lossy(
487 diagnostics,
488 policy,
489 format!("Responses input item {index} is not an object"),
490 )?;
491 continue;
492 };
493 let item_type = match item.get("type") {
494 Some(Value::String(item_type)) => Some(item_type.as_str()),
495 Some(_) => {
496 return Err(TranslationError::InvalidType {
497 path: format!("$.input[{index}].type"),
498 expected: "a string",
499 });
500 }
501 None => None,
502 };
503 let is_message = item_type == Some("message")
504 || (item_type.is_none()
505 && item.contains_key("role")
506 && item.contains_key("content"));
507 match item_type {
508 _ if is_message => {
509 let role = request_role_from_responses(
510 item.get("role").and_then(Value::as_str),
511 &format!("$.input[{index}].role"),
512 )?;
513 let content_value = item.get("content").unwrap_or(&Value::Null);
514 if is_responses_native_input_item(content_value) {
515 return Err(TranslationError::InvalidValue {
516 path: format!("$.input[{index}].content.type"),
517 message: "native Responses items must be top-level input items"
518 .to_string(),
519 });
520 }
521 if let Some(content_index) = content_value.as_array().and_then(|blocks| {
522 blocks.iter().position(is_responses_native_input_item)
523 }) {
524 return Err(TranslationError::InvalidValue {
525 path: format!("$.input[{index}].content[{content_index}].type"),
526 message: "native Responses items must be top-level input items"
527 .to_string(),
528 });
529 }
530 let mut content = decode_responses_content(content_value);
531 if matches!(role, Role::System | Role::Developer)
535 && !(pending_tool_calls.is_empty()
536 && pending_tool_outputs.is_empty()
537 && pending_reasoning.is_empty())
538 {
539 deferred_messages.push(Message::new(role, content));
540 continue;
541 }
542 if role == Role::Assistant
546 && pending_tool_calls.is_empty()
547 && !pending_reasoning.is_empty()
548 {
549 let mut merged = std::mem::take(&mut pending_reasoning);
550 merged.append(&mut content);
551 content = merged;
552 if pending_tool_outputs.is_empty() {
554 messages.append(&mut deferred_messages);
555 }
556 }
557 if role != Role::Assistant {
558 flush_unattached_responses_reasoning(
559 &mut messages,
560 &mut pending_tool_calls,
561 &mut pending_tool_outputs,
562 &mut deferred_messages,
563 &mut pending_reasoning,
564 );
565 }
566 push_responses_non_tool_message(
567 &mut messages,
568 &mut pending_tool_calls,
569 &mut pending_tool_outputs,
570 &mut deferred_messages,
571 &mut pending_reasoning,
572 Message {
573 role,
574 content,
575 phase: if role == Role::Assistant {
576 item.get("phase").and_then(Value::as_str).map(str::to_owned)
577 } else {
578 None
579 },
580 },
581 );
582 }
583 Some("reasoning") => {
584 if !pending_tool_outputs.is_empty() {
588 flush_responses_tool_block(
589 &mut messages,
590 &mut pending_tool_calls,
591 &mut pending_tool_outputs,
592 &mut deferred_messages,
593 &mut pending_reasoning,
594 );
595 }
596 pending_reasoning.extend(decode_responses_reasoning_item(item));
597 }
598 Some("function_call") => {
599 if !pending_tool_outputs.is_empty() {
600 flush_responses_tool_block(
601 &mut messages,
602 &mut pending_tool_calls,
603 &mut pending_tool_outputs,
604 &mut deferred_messages,
605 &mut pending_reasoning,
606 );
607 }
608 let id = item
609 .get("call_id")
610 .and_then(Value::as_str)
611 .filter(|id| !id.is_empty())
612 .map(ToOwned::to_owned)
613 .unwrap_or_else(|| match &policy.deterministic_ids {
614 DeterministicIdPolicy::GenerateStable { prefix } => {
615 stable_id(prefix, index + 1)
616 }
617 DeterministicIdPolicy::Preserve => String::new(),
618 });
619 let name = item
623 .get("name")
624 .and_then(Value::as_str)
625 .unwrap_or_default()
626 .to_string();
627 let name = match item
628 .get("namespace")
629 .and_then(Value::as_str)
630 .filter(|namespace| !namespace.is_empty())
631 {
632 Some(namespace) => {
633 crate::codex_namespaces::qualified_tool_name(namespace, &name)
634 }
635 None => name,
636 };
637 pending_tool_calls.push(ToolCall {
638 id,
639 name,
640 arguments: item.get("arguments").cloned().unwrap_or_else(|| json!({})),
641 });
642 }
643 kind @ (Some("function_call_output") | Some("custom_tool_call_output")) => {
644 let tool_call_id = item
645 .get("call_id")
646 .and_then(Value::as_str)
647 .unwrap_or_default()
648 .to_string();
649 let content = match item.get("output") {
652 Some(output @ Value::Array(_)) => decode_responses_content(output),
653 output => vec![ContentBlock::Text {
654 text: output.map(json_string).unwrap_or_default(),
655 }],
656 };
657 let answers_pending_call = pending_tool_calls
662 .iter()
663 .any(|call| call.id == tool_call_id);
664 if !answers_pending_call && !stored_state {
665 let output_text = text_from_blocks(&content, " ");
666 let message = Message::text(
667 Role::User,
668 format!("Tool result {tool_call_id}: {output_text}"),
669 );
670 push_responses_non_tool_message(
671 &mut messages,
672 &mut pending_tool_calls,
673 &mut pending_tool_outputs,
674 &mut deferred_messages,
675 &mut pending_reasoning,
676 message,
677 );
678 continue;
679 }
680 if !answers_pending_call && kind == Some("custom_tool_call_output") {
683 custom_call_outputs.push(tool_call_id.clone());
684 }
685 pending_tool_outputs.push(ToolResult {
686 tool_call_id,
687 content,
688 is_error: None,
689 });
690 }
691 Some("custom_tool_call") => {
692 if !pending_tool_outputs.is_empty() {
695 flush_responses_tool_block(
696 &mut messages,
697 &mut pending_tool_calls,
698 &mut pending_tool_outputs,
699 &mut deferred_messages,
700 &mut pending_reasoning,
701 );
702 }
703 let id = item
704 .get("call_id")
705 .and_then(Value::as_str)
706 .filter(|id| !id.is_empty())
707 .map(ToOwned::to_owned)
708 .unwrap_or_else(|| match &policy.deterministic_ids {
709 DeterministicIdPolicy::GenerateStable { prefix } => {
710 stable_id(prefix, index + 1)
711 }
712 DeterministicIdPolicy::Preserve => String::new(),
713 });
714 let name = item
715 .get("name")
716 .and_then(Value::as_str)
717 .unwrap_or_default()
718 .to_string();
719 let input = item
720 .get("input")
721 .and_then(Value::as_str)
722 .unwrap_or_default()
723 .to_string();
724 pending_tool_calls.push(ToolCall {
725 id,
726 name,
727 arguments: json!({crate::codex_custom_tools::INPUT_ARGUMENT: input}),
728 });
729 }
730 None => {
731 return Err(TranslationError::InvalidValue {
732 path: format!("$.input[{index}].type"),
733 message: "missing type discriminator on a non-message input item"
734 .to_string(),
735 });
736 }
737 Some("additional_tools") => {}
740 _ => {
741 let message = Message::new(
742 match item_type {
743 Some(
744 "shell_call"
745 | "apply_patch_call"
746 | "computer_call"
747 | "image_generation_call",
748 ) => Role::Assistant,
749 Some(
750 "shell_call_output"
751 | "apply_patch_call_output"
752 | "computer_call_output",
753 ) => Role::Tool,
754 _ => Role::User,
755 },
756 vec![ContentBlock::Unknown {
757 provider: WireFormat::OpenAiResponses.into(),
758 raw: Value::Object(item.clone()),
759 }],
760 );
761 flush_unattached_responses_reasoning(
762 &mut messages,
763 &mut pending_tool_calls,
764 &mut pending_tool_outputs,
765 &mut deferred_messages,
766 &mut pending_reasoning,
767 );
768 push_responses_non_tool_message(
769 &mut messages,
770 &mut pending_tool_calls,
771 &mut pending_tool_outputs,
772 &mut deferred_messages,
773 &mut pending_reasoning,
774 message,
775 );
776 }
777 }
778 }
779 if !pending_tool_calls.is_empty() || !pending_tool_outputs.is_empty() {
780 flush_responses_tool_block(
781 &mut messages,
782 &mut pending_tool_calls,
783 &mut pending_tool_outputs,
784 &mut deferred_messages,
785 &mut pending_reasoning,
786 );
787 }
788 if !pending_reasoning.is_empty() {
791 messages.push(Message::new(Role::Assistant, pending_reasoning));
792 }
793 messages.append(&mut deferred_messages);
794 Ok(messages)
795 }
796 _ => Err(TranslationError::InvalidType {
797 path: "$.input".to_string(),
798 expected: "string or array",
799 }),
800 }
801}
802
803fn push_responses_non_tool_message(
805 messages: &mut Vec<Message>,
806 pending_tool_calls: &mut Vec<ToolCall>,
807 pending_tool_outputs: &mut Vec<ToolResult>,
808 deferred_messages: &mut Vec<Message>,
809 pending_reasoning: &mut Vec<ContentBlock>,
810 message: Message,
811) {
812 if !pending_tool_calls.is_empty() && pending_tool_outputs.is_empty() {
813 deferred_messages.push(message);
814 return;
815 }
816 if !pending_tool_calls.is_empty() || !pending_tool_outputs.is_empty() {
817 flush_responses_tool_block(
818 messages,
819 pending_tool_calls,
820 pending_tool_outputs,
821 deferred_messages,
822 pending_reasoning,
823 );
824 }
825 messages.push(message);
826}
827
828fn flush_unattached_responses_reasoning(
832 messages: &mut Vec<Message>,
833 pending_tool_calls: &mut Vec<ToolCall>,
834 pending_tool_outputs: &mut Vec<ToolResult>,
835 deferred_messages: &mut Vec<Message>,
836 pending_reasoning: &mut Vec<ContentBlock>,
837) {
838 if pending_reasoning.is_empty() || !pending_tool_calls.is_empty() {
839 return;
840 }
841 let message = Message::new(Role::Assistant, std::mem::take(pending_reasoning));
842 push_responses_non_tool_message(
843 messages,
844 pending_tool_calls,
845 pending_tool_outputs,
846 deferred_messages,
847 pending_reasoning,
848 message,
849 );
850 messages.append(deferred_messages);
852}
853
854fn flush_responses_tool_block(
858 messages: &mut Vec<Message>,
859 pending_tool_calls: &mut Vec<ToolCall>,
860 pending_tool_outputs: &mut Vec<ToolResult>,
861 deferred_messages: &mut Vec<Message>,
862 pending_reasoning: &mut Vec<ContentBlock>,
863) {
864 if !pending_tool_calls.is_empty() {
865 let mut content = std::mem::take(pending_reasoning);
866 content.extend(
867 std::mem::take(pending_tool_calls)
868 .into_iter()
869 .map(ContentBlock::ToolCall),
870 );
871 messages.push(Message::new(Role::Assistant, content));
872 }
873
874 for output in std::mem::take(pending_tool_outputs) {
875 messages.push(Message::new(
876 Role::User,
877 vec![ContentBlock::ToolResult(output)],
878 ));
879 }
880
881 messages.append(deferred_messages);
882}
883
884fn decode_responses_reasoning_item(item: &Map<String, Value>) -> Vec<ContentBlock> {
886 if let Some((text, signature)) = item
887 .get("encrypted_content")
888 .and_then(Value::as_str)
889 .and_then(super::decode_anthropic_thinking)
890 {
891 return vec![ContentBlock::Reasoning {
892 text,
893 signature: Some(signature),
894 details: Vec::new(),
895 }];
896 }
897 let mut parts = Vec::new();
898 collect_responses_reasoning_text(item.get("content"), &mut parts);
899 collect_responses_reasoning_text(item.get("summary"), &mut parts);
900 if let Some(text) = item.get("text").and_then(Value::as_str) {
901 parts.push(text.to_string());
902 }
903 let details = if item.get("encrypted_content").is_some() {
906 vec![Value::Object(item.clone())]
907 } else {
908 Vec::new()
909 };
910 vec![ContentBlock::Reasoning {
911 text: parts.join("\n"),
912 signature: None,
913 details,
914 }]
915}
916
917fn decode_responses_content(value: &Value) -> Vec<ContentBlock> {
919 match value {
920 Value::String(text) => vec![ContentBlock::Text { text: text.clone() }],
921 Value::Array(blocks) => {
922 let mut out = Vec::new();
923 for block in blocks {
924 let Some(block) = block.as_object() else {
925 continue;
926 };
927 match block.get("type").and_then(Value::as_str) {
928 Some("input_text") | Some("output_text") | Some("text") => {
929 out.push(ContentBlock::Text {
930 text: block
931 .get("text")
932 .and_then(Value::as_str)
933 .unwrap_or_default()
934 .to_string(),
935 });
936 }
937 Some("refusal") => out.push(ContentBlock::Refusal {
938 text: block
939 .get("refusal")
940 .and_then(Value::as_str)
941 .unwrap_or_default()
942 .to_string(),
943 }),
944 Some("reasoning_text") | Some("summary_text") => {
945 out.push(ContentBlock::Reasoning {
946 text: block
947 .get("text")
948 .and_then(Value::as_str)
949 .unwrap_or_default()
950 .to_string(),
951 signature: None,
952 details: Vec::new(),
953 });
954 }
955 Some("input_image") => {
956 if let Some(source) = decode_image_source(block) {
957 out.push(ContentBlock::Image { source });
958 }
959 }
960 Some("input_audio") => out.push(ContentBlock::Audio {
961 source: MediaSource::Raw(Value::Object(block.clone())),
962 }),
963 Some("input_file") => out.push(ContentBlock::File {
964 source: decode_file_source(block),
965 }),
966 _ => out.push(ContentBlock::Unknown {
967 provider: WireFormat::OpenAiResponses.into(),
968 raw: Value::Object(block.clone()),
969 }),
970 }
971 }
972 if out.is_empty() {
973 out.push(ContentBlock::Text {
974 text: String::new(),
975 });
976 }
977 out
978 }
979 Value::Null => vec![ContentBlock::Text {
980 text: String::new(),
981 }],
982 other => vec![ContentBlock::Text {
983 text: string_value(other).unwrap_or_default(),
984 }],
985 }
986}
987
988fn role_from_responses(role: Option<&str>) -> Role {
992 match role {
993 Some("assistant") => Role::Assistant,
994 Some("system") => Role::System,
995 Some("developer") => Role::Developer,
996 _ => Role::User,
997 }
998}
999
1000fn request_role_from_responses(role: Option<&str>, path: &str) -> Result<Role> {
1008 match role {
1009 Some("assistant") => Ok(Role::Assistant),
1010 Some("system") => Ok(Role::System),
1011 Some("developer") => Ok(Role::Developer),
1012 None => Ok(Role::User),
1013 Some(other) if is_known_role_name(other) => Ok(Role::User),
1014 Some(other) => Err(TranslationError::unsupported_role(path, other)),
1015 }
1016}
1017
1018fn decode_responses_tools(
1026 value: Option<&Value>,
1027 namespaces: &mut Map<String, Value>,
1028 custom_tools: &mut Map<String, Value>,
1029) -> Vec<ToolDefinition> {
1030 let Some(tools) = value.and_then(Value::as_array) else {
1031 return Vec::new();
1032 };
1033 let mut out = Vec::new();
1034 for tool in tools {
1035 let Some(tool) = tool.as_object() else {
1036 continue;
1037 };
1038 if tool.get("type").and_then(Value::as_str) == Some("namespace") {
1039 let container = tool
1042 .get("name")
1043 .and_then(Value::as_str)
1044 .filter(|name| !name.is_empty());
1045 let description = tool.get("description").and_then(Value::as_str);
1046 for mut child in decode_responses_tools(tool.get("tools"), namespaces, custom_tools) {
1047 let already_qualified = namespaces.contains_key(&child.name);
1050 if let Some(container) = container
1051 && !already_qualified
1052 {
1053 let qualified =
1054 crate::codex_namespaces::qualified_tool_name(container, &child.name);
1055 crate::codex_namespaces::record_tool_namespace(
1056 namespaces,
1057 &qualified,
1058 container,
1059 description,
1060 );
1061 child.name = qualified;
1062 }
1063 out.push(child);
1064 }
1065 } else if tool.get("type").and_then(Value::as_str) == Some("custom") {
1066 if let Some(name) = tool
1073 .get("name")
1074 .and_then(Value::as_str)
1075 .filter(|name| !name.is_empty())
1076 {
1077 custom_tools.insert(name.to_string(), Value::Object(tool.clone()));
1078 out.push(ToolDefinition {
1079 name: name.to_string(),
1080 description: tool
1081 .get("description")
1082 .and_then(Value::as_str)
1083 .map(ToOwned::to_owned),
1084 parameters: crate::codex_custom_tools::input_schema(),
1085 strict: None,
1086 });
1087 }
1088 } else if tool.get("type").and_then(Value::as_str) == Some("function") {
1089 if let Some(function) = tool.get("function").and_then(Value::as_object) {
1090 if let Some(name) = function.get("name").and_then(Value::as_str)
1091 && !name.is_empty()
1092 {
1093 out.push(ToolDefinition {
1094 name: name.to_string(),
1095 description: function
1096 .get("description")
1097 .and_then(Value::as_str)
1098 .map(ToOwned::to_owned),
1099 parameters: function
1100 .get("parameters")
1101 .cloned()
1102 .unwrap_or_else(|| json!({})),
1103 strict: function.get("strict").and_then(Value::as_bool),
1104 });
1105 }
1106 } else {
1107 if !push_responses_function_tool(&mut out, tool) {
1108 push_responses_id_tool(&mut out, tool);
1109 }
1110 }
1111 } else if tool.get("type").is_none() && tool.contains_key("name") {
1112 push_responses_function_tool(&mut out, tool);
1113 } else {
1114 push_responses_id_tool(&mut out, tool);
1115 }
1116 }
1117 out
1118}
1119
1120fn push_responses_function_tool(
1122 out: &mut Vec<ToolDefinition>,
1123 tool: &serde_json::Map<String, Value>,
1124) -> bool {
1125 let Some(name) = tool.get("name").and_then(Value::as_str) else {
1126 return false;
1127 };
1128 if name.is_empty() {
1129 return false;
1130 }
1131
1132 out.push(ToolDefinition {
1133 name: name.to_string(),
1134 description: tool
1135 .get("description")
1136 .and_then(Value::as_str)
1137 .map(ToOwned::to_owned),
1138 parameters: tool.get("parameters").cloned().unwrap_or_else(|| json!({})),
1139 strict: tool.get("strict").and_then(Value::as_bool),
1140 });
1141 true
1142}
1143
1144fn push_responses_id_tool(
1146 out: &mut Vec<ToolDefinition>,
1147 tool: &serde_json::Map<String, Value>,
1148) -> bool {
1149 let Some(id) = tool.get("id").and_then(Value::as_str) else {
1150 return false;
1151 };
1152 if id.is_empty() {
1153 return false;
1154 }
1155
1156 out.push(ToolDefinition {
1157 name: id.to_string(),
1158 description: tool
1159 .get("description")
1160 .and_then(Value::as_str)
1161 .map(ToOwned::to_owned),
1162 parameters: tool
1163 .get("inputSchema")
1164 .and_then(Value::as_object)
1165 .and_then(|schema| schema.get("jsonSchema"))
1166 .cloned()
1167 .unwrap_or_else(|| json!({})),
1168 strict: None,
1169 });
1170 true
1171}
1172
1173fn decode_responses_tool_choice(value: &Value) -> Option<ToolChoice> {
1175 match value {
1176 Value::String(text) if text == "auto" => Some(ToolChoice::Auto),
1177 Value::String(text) if text == "required" => Some(ToolChoice::Required),
1178 Value::String(text) if text == "none" => Some(ToolChoice::None),
1179 Value::Object(object) if object.get("type").and_then(Value::as_str) == Some("custom") => {
1180 object
1181 .get("name")
1182 .and_then(Value::as_str)
1183 .map(|name| ToolChoice::Tool {
1184 name: name.to_string(),
1185 })
1186 }
1187 Value::Object(object) if object.get("type").and_then(Value::as_str) == Some("function") => {
1188 object.get("name").and_then(Value::as_str).map(|name| {
1191 match object
1192 .get("namespace")
1193 .and_then(Value::as_str)
1194 .filter(|namespace| !namespace.is_empty())
1195 {
1196 Some(namespace) => ToolChoice::Tool {
1197 name: crate::codex_namespaces::qualified_tool_name(namespace, name),
1198 },
1199 None => ToolChoice::Tool {
1200 name: name.to_string(),
1201 },
1202 }
1203 })
1204 }
1205 Value::Object(object)
1206 if object.get("type").and_then(Value::as_str) == Some("allowed_tools") =>
1207 {
1208 Some(ToolChoice::Raw(value.clone()))
1209 }
1210 Value::Object(_) => None,
1211 _ => Some(ToolChoice::Raw(value.clone())),
1212 }
1213}
1214
1215fn decode_responses_text_format(value: Option<&Value>) -> Option<Value> {
1217 let format = value
1218 .and_then(Value::as_object)
1219 .and_then(|object| object.get("format"))
1220 .and_then(Value::as_object)?;
1221
1222 match format.get("type").and_then(Value::as_str) {
1223 Some("json_schema") => {
1224 if let Some(json_schema) = format.get("json_schema").and_then(Value::as_object) {
1225 return Some(json!({
1226 "type": "json_schema",
1227 "json_schema": Value::Object(json_schema.clone()),
1228 }));
1229 }
1230
1231 let mut json_schema = Map::new();
1232 for field in ["name", "description", "schema", "strict"] {
1233 if let Some(value) = format.get(field) {
1234 json_schema.insert(field.to_string(), value.clone());
1235 }
1236 }
1237 (!json_schema.is_empty()).then_some(json!({
1238 "type": "json_schema",
1239 "json_schema": Value::Object(json_schema),
1240 }))
1241 }
1242 Some("json_object") => Some(json!({"type": "json_object"})),
1243 Some("text") => Some(json!({"type": "text"})),
1244 _ => None,
1245 }
1246}
1247
1248fn encode_responses_text_format(response_format: &Value) -> Value {
1250 let Some(format) = response_format.as_object() else {
1251 return response_format.clone();
1252 };
1253 let Some(response_type) = format
1254 .get("type")
1255 .filter(|value| value.as_str() == Some("json_schema"))
1256 else {
1257 return response_format.clone();
1258 };
1259
1260 let Some(Value::Object(json_schema)) = format.get("json_schema") else {
1261 return response_format.clone();
1262 };
1263 if !matches!(json_schema.get("name"), Some(Value::String(_)))
1264 || !matches!(json_schema.get("schema"), Some(Value::Object(_)))
1265 || json_schema
1266 .get("description")
1267 .is_some_and(|value| !value.is_string())
1268 || json_schema
1269 .get("strict")
1270 .is_some_and(|value| !value.is_boolean())
1271 {
1272 return response_format.clone();
1273 }
1274
1275 let mut output = Map::new();
1276 output.insert("type".to_string(), response_type.clone());
1277 for field in ["name", "description", "schema", "strict"] {
1278 if let Some(value) = json_schema.get(field) {
1279 output.insert(field.to_string(), value.clone());
1280 }
1281 }
1282 Value::Object(output)
1283}
1284
1285fn encode_responses_input(
1287 messages: &[Message],
1288 diagnostics: &mut Vec<TranslationDiagnostic>,
1289 policy: &TranslationPolicy,
1290 namespaces: Option<&Map<String, Value>>,
1291 custom_tools: &std::collections::HashSet<String>,
1292 mut custom_call_ids: std::collections::HashSet<String>,
1293) -> Result<Value> {
1294 let mut encoded = Vec::new();
1301 let mut call_names: HashMap<&str, &str> = HashMap::new();
1304 for message in messages {
1305 for block in &message.content {
1306 if let ContentBlock::ToolCall(call) = block {
1307 call_names.insert(call.id.as_str(), call.name.as_str());
1308 }
1309 }
1310 }
1311 for message in messages {
1312 if let [ContentBlock::Unknown { provider, raw }] = message.content.as_slice()
1315 && provider.as_str() == WireFormat::OpenAiResponses.as_str()
1316 && is_responses_native_input_item(raw)
1317 {
1318 encoded.push(raw.clone());
1319 continue;
1320 }
1321 let content = message
1323 .content
1324 .iter()
1325 .filter(|block| {
1326 !matches!(
1327 block,
1328 ContentBlock::Reasoning {
1329 signature: Some(_),
1330 ..
1331 }
1332 )
1333 })
1334 .cloned()
1335 .collect::<Vec<_>>();
1336 if content.is_empty() {
1337 continue;
1338 }
1339 if content.iter().any(|block| {
1340 matches!(
1341 block,
1342 ContentBlock::ToolCall(_) | ContentBlock::ToolResult(_)
1343 )
1344 }) {
1345 let mut visible_content = Vec::new();
1346 for block in &content {
1347 if let Some(item) = encode_responses_special_input(
1348 block,
1349 namespaces,
1350 &call_names,
1351 custom_tools,
1352 &mut custom_call_ids,
1353 diagnostics,
1354 policy,
1355 )? {
1356 if !visible_content.is_empty() {
1357 let content =
1358 encode_responses_content(&visible_content, diagnostics, policy)?;
1359 encoded.push(encode_responses_message(message, content));
1360 visible_content.clear();
1361 }
1362 encoded.push(item);
1363 } else if !matches!(block, ContentBlock::Reasoning { .. }) {
1364 visible_content.push(block.clone());
1365 }
1366 }
1367 if !visible_content.is_empty() {
1368 let content = encode_responses_content(&visible_content, diagnostics, policy)?;
1369 encoded.push(encode_responses_message(message, content));
1370 }
1371 continue;
1372 }
1373 let mut visible_content = Vec::new();
1374 let mut emitted_special = false;
1375 let mut omitted_reasoning = false;
1376 for block in &content {
1377 if let Some(item) = encode_responses_special_input(
1378 block,
1379 namespaces,
1380 &call_names,
1381 custom_tools,
1382 &mut custom_call_ids,
1383 diagnostics,
1384 policy,
1385 )? {
1386 encoded.push(item);
1387 emitted_special = true;
1388 } else if !matches!(block, ContentBlock::Reasoning { .. }) {
1389 visible_content.push(block.clone());
1390 } else {
1391 omitted_reasoning = true;
1392 }
1393 }
1394 if !visible_content.is_empty()
1395 || (!emitted_special && !omitted_reasoning)
1396 || (message.role == Role::Assistant && message.phase.is_some())
1397 {
1398 let content = encode_responses_content(&visible_content, diagnostics, policy)?;
1399 encoded.push(encode_responses_message(message, content));
1400 }
1401 }
1402 pair_tool_calls_with_outputs(&mut encoded);
1403 Ok(Value::Array(encoded))
1404}
1405
1406fn encode_responses_message(message: &Message, content: Value) -> Value {
1408 let mut item = json!({
1409 "type": "message",
1410 "role": role_to_responses(message.role),
1411 "content": content,
1412 });
1413 if let (Role::Assistant, Some(phase)) = (message.role, &message.phase) {
1414 item["phase"] = json!(phase);
1415 }
1416 item
1417}
1418
1419fn pair_tool_calls_with_outputs(items: &mut Vec<Value>) {
1423 let call_id = |item: &Value, kind: &str| {
1424 (item.get("type").and_then(Value::as_str) == Some(kind))
1425 .then(|| {
1426 item.get("call_id")
1427 .and_then(Value::as_str)
1428 .map(str::to_owned)
1429 })
1430 .flatten()
1431 };
1432 let mut index = 0;
1433 while index < items.len() {
1434 let (id, output_kind) = match call_id(&items[index], "function_call") {
1436 Some(id) => (id, "function_call_output"),
1437 None => match call_id(&items[index], "custom_tool_call") {
1438 Some(id) => (id, "custom_tool_call_output"),
1439 None => {
1440 index += 1;
1441 continue;
1442 }
1443 },
1444 };
1445 let output = items
1446 .iter()
1447 .skip(index + 1)
1448 .take_while(|item| item.get("type").and_then(Value::as_str) != Some("message"))
1449 .position(|item| call_id(item, output_kind).as_deref() == Some(&id))
1450 .map(|offset| index + 1 + offset);
1451 if let Some(output) = output
1452 && output != index + 1
1453 {
1454 let item = items.remove(output);
1455 items.insert(index + 1, item);
1456 }
1457 index += 1;
1458 }
1459}
1460
1461fn encode_responses_special_input(
1463 block: &ContentBlock,
1464 namespaces: Option<&Map<String, Value>>,
1465 call_names: &HashMap<&str, &str>,
1466 custom_tools: &std::collections::HashSet<String>,
1467 custom_call_ids: &mut std::collections::HashSet<String>,
1468 diagnostics: &mut Vec<TranslationDiagnostic>,
1469 policy: &TranslationPolicy,
1470) -> Result<Option<Value>> {
1471 Ok(match block {
1472 ContentBlock::Reasoning {
1473 text,
1474 signature: None,
1475 details,
1476 } => encode_responses_reasoning_input(text, details),
1477 ContentBlock::ToolCall(call) if custom_tools.contains(&call.name) => {
1478 custom_call_ids.insert(call.id.clone());
1480 Some(json!({
1481 "type": "custom_tool_call",
1482 "call_id": call.id,
1483 "name": call.name,
1484 "input": crate::codex_custom_tools::input_from_arguments(&call.arguments),
1485 }))
1486 }
1487 ContentBlock::ToolCall(call) => {
1488 let (name, namespace) = namespaces
1491 .and_then(|namespaces| {
1492 crate::codex_namespaces::split_qualified_name(namespaces, &call.name)
1493 })
1494 .map_or((call.name.as_str(), None), |(name, namespace)| {
1495 (name, Some(namespace))
1496 });
1497 let mut item = json!({
1498 "type": "function_call",
1499 "call_id": call.id,
1500 "name": name,
1501 "arguments": json_string(&call.arguments),
1502 });
1503 if let Some(namespace) = namespace {
1504 item["namespace"] = Value::String(namespace.to_string());
1505 }
1506 Some(item)
1507 }
1508 ContentBlock::ToolResult(result) => {
1509 let mut item = json!({
1512 "type": if custom_call_ids.contains(&result.tool_call_id) {
1513 "custom_tool_call_output"
1514 } else {
1515 "function_call_output"
1516 },
1517 "call_id": result.tool_call_id,
1518 "output": encode_responses_tool_output(&result.content, diagnostics, policy)?,
1519 });
1520 if let Some(name) = call_names.get(result.tool_call_id.as_str()) {
1523 let name = namespaces
1524 .and_then(|namespaces| {
1525 crate::codex_namespaces::split_qualified_name(namespaces, name)
1526 })
1527 .map_or(*name, |(name, _)| name);
1528 item["name"] = Value::String(name.to_string());
1529 }
1530 Some(item)
1531 }
1532 _ => None,
1533 })
1534}
1535
1536fn encode_responses_reasoning_input(text: &str, details: &[Value]) -> Option<Value> {
1539 for detail in details {
1540 let Some(detail) = detail.as_object() else {
1541 continue;
1542 };
1543 if detail.get("type").and_then(Value::as_str) != Some("reasoning") {
1544 continue;
1545 }
1546 let mut item = Map::new();
1547 item.insert("type".to_string(), Value::String("reasoning".to_string()));
1548 for field in ["id", "summary", "encrypted_content"] {
1549 if let Some(value) = detail.get(field) {
1550 item.insert(field.to_string(), value.clone());
1551 }
1552 }
1553 item.entry("summary".to_string())
1554 .or_insert_with(|| Value::Array(Vec::new()));
1555 return Some(Value::Object(item));
1556 }
1557
1558 if text.is_empty() {
1559 return None;
1560 }
1561 Some(json!({
1562 "type": "reasoning",
1563 "summary": [{"type": "summary_text", "text": text}],
1564 }))
1565}
1566
1567fn role_to_responses(role: Role) -> &'static str {
1569 match role {
1570 Role::Assistant => "assistant",
1571 Role::System => "system",
1572 Role::Developer => "developer",
1573 Role::User | Role::Tool => "user",
1574 }
1575}
1576
1577fn encode_responses_content(
1579 content: &[ContentBlock],
1580 diagnostics: &mut Vec<TranslationDiagnostic>,
1581 policy: &TranslationPolicy,
1582) -> Result<Value> {
1583 let has_non_text = content.iter().any(|block| {
1584 !matches!(
1585 block,
1586 ContentBlock::Text { .. }
1587 | ContentBlock::Refusal { .. }
1588 | ContentBlock::Reasoning { .. }
1589 )
1590 });
1591 if !has_non_text {
1592 return Ok(Value::String(text_from_blocks(content, "\n")));
1593 }
1594 let mut blocks = Vec::new();
1595 for block in content {
1596 match block {
1597 ContentBlock::Text { text } => blocks.push(json!({"type": "input_text", "text": text})),
1598 ContentBlock::Refusal { text } => {
1599 blocks.push(json!({"type": "refusal", "refusal": text}));
1600 }
1601 ContentBlock::Image { source } => match responses_image_part(source) {
1602 Some(part) => blocks.push(part),
1603 None => {
1604 push_lossy(
1605 diagnostics,
1606 policy,
1607 "Responses codec could not map image content",
1608 )?;
1609 blocks.push(json!({"type": "input_text", "text": image_source_text(source)}));
1610 }
1611 },
1612 ContentBlock::Audio { source } => {
1613 blocks.push(crate::codecs::openai_media::audio_part(source)?);
1614 }
1615 ContentBlock::Video { source } => blocks.push(match source {
1616 MediaSource::Raw(raw) => json!({"type": "input_text", "text": json_string(raw)}),
1617 MediaSource::Url { url, media_type } => json!({
1618 "type": "input_video",
1619 "video_url": url,
1620 "media_type": media_type,
1621 }),
1622 MediaSource::Base64 { media_type, data } => json!({
1623 "type": "input_video",
1624 "video": {"media_type": media_type, "data": data},
1625 }),
1626 }),
1627 ContentBlock::File { source } => match responses_file_part(source) {
1628 Some(part) => blocks.push(part),
1629 None => {
1630 push_lossy(
1631 diagnostics,
1632 policy,
1633 "Responses codec could not map file content",
1634 )?;
1635 blocks.push(json!({"type": "input_text", "text": file_source_text(source)}));
1636 }
1637 },
1638 ContentBlock::Mcp(_) => {
1639 return Err(TranslationError::LossyConversion(
1640 "MCP history encoding is not implemented".into(),
1641 ));
1642 }
1643 ContentBlock::Unknown { raw, .. } => {
1644 push_lossy(
1645 diagnostics,
1646 policy,
1647 "unknown content block encoded as text for Responses",
1648 )?;
1649 blocks.push(json!({"type": "input_text", "text": json_string(raw)}));
1650 }
1651 ContentBlock::Reasoning { .. }
1652 | ContentBlock::ToolCall(_)
1653 | ContentBlock::ToolResult(_) => {}
1654 }
1655 }
1656 Ok(Value::Array(blocks))
1657}
1658
1659fn encode_responses_tool_output(
1662 content: &[ContentBlock],
1663 diagnostics: &mut Vec<TranslationDiagnostic>,
1664 policy: &TranslationPolicy,
1665) -> Result<Value> {
1666 let text_only = content.iter().all(|block| {
1667 matches!(
1668 block,
1669 ContentBlock::Text { .. } | ContentBlock::Refusal { .. }
1670 )
1671 });
1672 if text_only {
1673 return Ok(Value::String(text_from_blocks(content, " ")));
1674 }
1675 encode_responses_content(content, diagnostics, policy)
1676}
1677
1678fn responses_image_part(source: &ImageSource) -> Option<Value> {
1679 if let ImageSource::Raw(raw) = source
1680 && raw.get("type").and_then(Value::as_str) == Some("input_image")
1681 && raw.get("file_id").and_then(Value::as_str).is_some()
1682 {
1683 return Some(raw.clone());
1684 }
1685 let ImagePayload { url, detail } = image_payload(source)?;
1686 let mut part = json!({"type": "input_image"});
1687 part["image_url"] = Value::String(url);
1688 if let Some(detail) = detail {
1689 part["detail"] = Value::String(detail);
1690 }
1691 Some(part)
1692}
1693
1694fn responses_file_part(source: &FileSource) -> Option<Value> {
1695 let mut part = file_payload(source)?;
1696 part.insert("type".to_string(), Value::String("input_file".to_string()));
1697 Some(Value::Object(part))
1698}
1699
1700fn encode_responses_tools(
1706 tools: &[Tool],
1707 namespaces: Option<&Map<String, Value>>,
1708 custom_tools: Option<&Map<String, Value>>,
1709) -> Result<Value> {
1710 let mut out: Vec<Value> = Vec::new();
1711 let mut containers: Vec<(String, Vec<Value>)> = Vec::new();
1712 for tool in tools {
1713 let tool = tool.function().ok_or_else(|| {
1714 TranslationError::LossyConversion(
1715 "MCP and provider tool encoding is not implemented".into(),
1716 )
1717 })?;
1718 if let Some(custom) = custom_tools.and_then(|custom| custom.get(&tool.name)) {
1720 out.push(custom.clone());
1721 continue;
1722 }
1723 let mut item = json!({
1724 "type": "function",
1725 "name": tool.name,
1726 "description": tool.description.clone().unwrap_or_default(),
1727 "parameters": tool.parameters,
1728 });
1729 if let Some(strict) = tool.strict {
1730 item["strict"] = Value::Bool(strict);
1731 }
1732 let split = namespaces.and_then(|namespaces| {
1733 crate::codex_namespaces::split_qualified_name(namespaces, &tool.name)
1734 });
1735 match split {
1736 None => out.push(item),
1737 Some((name, namespace)) => {
1738 item["name"] = Value::String(name.to_string());
1739 match containers
1740 .iter_mut()
1741 .find(|(existing, _)| *existing == namespace)
1742 {
1743 Some((_, children)) => children.push(item),
1744 None => containers.push((namespace.to_string(), vec![item])),
1745 }
1746 }
1747 }
1748 }
1749 for (namespace, children) in containers {
1750 let description = namespaces
1751 .and_then(|namespaces| {
1752 crate::codex_namespaces::namespace_description(namespaces, &namespace)
1753 })
1754 .unwrap_or_default();
1755 out.push(json!({
1756 "type": "namespace",
1757 "name": namespace,
1758 "description": description,
1759 "tools": children,
1760 }));
1761 }
1762 Ok(Value::Array(out))
1763}
1764
1765fn encode_responses_tool_choice(
1767 choice: &ToolChoice,
1768 namespaces: Option<&Map<String, Value>>,
1769 custom_tools: Option<&Map<String, Value>>,
1770) -> Option<Value> {
1771 match choice {
1772 ToolChoice::Auto => Some(Value::String("auto".to_string())),
1773 ToolChoice::Required => Some(Value::String("required".to_string())),
1774 ToolChoice::None => Some(Value::String("none".to_string())),
1775 ToolChoice::Tool { name } if custom_tools.is_some_and(|tools| tools.contains_key(name)) => {
1776 Some(json!({"type": "custom", "name": name}))
1777 }
1778 ToolChoice::Tool { name } => {
1779 let split = namespaces.and_then(|namespaces| {
1780 crate::codex_namespaces::split_qualified_name(namespaces, name)
1781 });
1782 Some(match split {
1783 Some((tool, namespace)) => {
1784 json!({"type": "function", "name": tool, "namespace": namespace})
1785 }
1786 None => json!({"type": "function", "name": name}),
1787 })
1788 }
1789 ToolChoice::Raw(value) => Some(value.clone()),
1790 }
1791}
1792
1793fn decode_responses_output_item(
1795 item: &Value,
1796 diagnostics: &mut Vec<TranslationDiagnostic>,
1797 policy: &TranslationPolicy,
1798) -> Result<Option<ResponseOutput>> {
1799 let Some(item) = item.as_object() else {
1800 push_lossy(
1801 diagnostics,
1802 policy,
1803 "Responses output item is not an object",
1804 )?;
1805 return Ok(None);
1806 };
1807 match item.get("type").and_then(Value::as_str) {
1808 Some("message") => {
1809 let content = decode_responses_content(item.get("content").unwrap_or(&Value::Null));
1810 let stop_reason = if content
1811 .iter()
1812 .any(|block| matches!(block, ContentBlock::Refusal { .. }))
1813 {
1814 StopReason::ContentFilter
1815 } else {
1816 StopReason::EndTurn
1817 };
1818 Ok(Some(ResponseOutput {
1819 url_citations: decode_responses_url_citations(item.get("content")),
1820 role: role_from_responses(item.get("role").and_then(Value::as_str)),
1821 content,
1822 stop_reason: Some(stop_reason),
1823 }))
1824 }
1825 Some("function_call") => Ok(Some(ResponseOutput {
1826 url_citations: Vec::new(),
1827 role: Role::Assistant,
1828 content: vec![ContentBlock::ToolCall(ToolCall {
1829 id: item
1830 .get("call_id")
1831 .and_then(Value::as_str)
1832 .unwrap_or_default()
1833 .to_string(),
1834 name: item
1835 .get("name")
1836 .and_then(Value::as_str)
1837 .unwrap_or_default()
1838 .to_string(),
1839 arguments: item
1840 .get("arguments")
1841 .map(|value| {
1842 value
1843 .as_str()
1844 .and_then(|text| serde_json::from_str(text).ok())
1845 .unwrap_or_else(|| value.clone())
1846 })
1847 .unwrap_or_else(|| json!({})),
1848 })],
1849 stop_reason: Some(StopReason::ToolUse),
1850 })),
1851 Some("custom_tool_call") => Ok(Some(ResponseOutput {
1852 url_citations: Vec::new(),
1853 role: Role::Assistant,
1854 content: vec![ContentBlock::ToolCall(ToolCall {
1855 id: item
1856 .get("call_id")
1857 .and_then(Value::as_str)
1858 .unwrap_or_default()
1859 .to_string(),
1860 name: item
1861 .get("name")
1862 .and_then(Value::as_str)
1863 .unwrap_or_default()
1864 .to_string(),
1865 arguments: json!({
1866 crate::codex_custom_tools::INPUT_ARGUMENT:
1867 item.get("input").and_then(Value::as_str).unwrap_or_default()
1868 }),
1869 })],
1870 stop_reason: Some(StopReason::ToolUse),
1871 })),
1872 Some("reasoning") => Ok(Some(ResponseOutput {
1873 url_citations: Vec::new(),
1874 role: Role::Assistant,
1875 content: decode_responses_reasoning_item(item),
1876 stop_reason: None,
1877 })),
1878 Some(kind) if super::is_native_output(kind) => Ok(Some(ResponseOutput {
1879 url_citations: Vec::new(),
1880 role: Role::Assistant,
1881 content: vec![ContentBlock::Unknown {
1882 provider: WireFormat::OpenAiResponses.into(),
1883 raw: Value::Object(item.clone()),
1884 }],
1885 stop_reason: None,
1886 })),
1887 _ => Ok(None),
1888 }
1889}
1890
1891fn decode_responses_url_citations(content: Option<&Value>) -> Vec<crate::UrlCitation> {
1892 let mut citations = Vec::new();
1893 let mut text_offset = 0;
1894 for part in content.and_then(Value::as_array).into_iter().flatten() {
1895 for annotation in part
1896 .get("annotations")
1897 .and_then(Value::as_array)
1898 .into_iter()
1899 .flatten()
1900 {
1901 if annotation["type"] == "url_citation"
1902 && let Ok(mut citation) =
1903 serde_json::from_value::<crate::UrlCitation>(annotation.clone())
1904 {
1905 citation.start_index += text_offset;
1906 citation.end_index += text_offset;
1907 citations.push(citation);
1908 }
1909 }
1910 let text = match part.get("type").and_then(Value::as_str) {
1911 Some("input_text" | "output_text" | "text") => part.get("text"),
1912 Some("refusal") => part.get("refusal"),
1913 _ => None,
1914 };
1915 text_offset += text
1916 .and_then(Value::as_str)
1917 .unwrap_or_default()
1918 .chars()
1919 .count();
1920 }
1921 citations
1922}
1923
1924fn encode_responses_output(outputs: &[ResponseOutput]) -> Value {
1926 Value::Array(
1927 outputs
1928 .iter()
1929 .flat_map(|output| {
1930 let has_output_items = output.content.iter().any(|block| {
1931 matches!(block, ContentBlock::ToolCall(_))
1932 || matches!(block, ContentBlock::Unknown { provider, raw }
1933 if provider.as_str() == WireFormat::OpenAiResponses.as_str()
1934 && raw["type"].as_str().is_some_and(super::is_native_output))
1935 });
1936 let mut content = Vec::new();
1937 let mut text_offset = 0;
1938 for block in &output.content {
1939 match block {
1940 ContentBlock::Text { text } => {
1941 let text_end = text_offset + text.chars().count();
1942 let annotations = output
1943 .url_citations
1944 .iter()
1945 .filter(|citation| {
1946 citation.start_index >= text_offset
1947 && citation.end_index <= text_end
1948 })
1949 .map(|citation| {
1950 json!({
1951 "type": "url_citation",
1952 "start_index": citation.start_index - text_offset,
1953 "end_index": citation.end_index - text_offset,
1954 "url": citation.url,
1955 "title": citation.title,
1956 })
1957 })
1958 .collect::<Vec<_>>();
1959 content.push(json!({
1960 "type": "output_text",
1961 "text": text,
1962 "annotations": annotations,
1963 }));
1964 text_offset = text_end;
1965 }
1966 ContentBlock::Refusal { text } => {
1967 content.push(json!({"type": "refusal", "refusal": text}));
1968 text_offset += text.chars().count();
1969 }
1970 _ => {}
1971 }
1972 }
1973 let reasoning = reasoning_text_from_blocks(&output.content, "\n");
1974 let status = if matches!(output.stop_reason, Some(StopReason::MaxTokens)) {
1975 "incomplete"
1976 } else {
1977 "completed"
1978 };
1979 let mut items = Vec::new();
1980
1981 let encrypted_reasoning = output.content.iter().find_map(|block| match block {
1982 ContentBlock::Reasoning { details, .. } => encrypted_reasoning_data(details),
1983 _ => None,
1984 });
1985 let encrypted_reasoning_id = output.content.iter().find_map(|block| match block {
1986 ContentBlock::Reasoning { details, .. } => encrypted_reasoning_item_id(details),
1987 _ => None,
1988 });
1989 let has_signed_reasoning = output.content.iter().any(|block| {
1990 matches!(
1991 block,
1992 ContentBlock::Reasoning {
1993 signature: Some(_),
1994 ..
1995 }
1996 )
1997 });
1998 if has_signed_reasoning {
1999 for (index, block) in output.content.iter().enumerate() {
2000 if let ContentBlock::Reasoning {
2001 text,
2002 signature,
2003 details,
2004 } = block
2005 {
2006 let encrypted = signature
2007 .as_deref()
2008 .map(|signature| super::encode_anthropic_thinking(text, signature))
2009 .or_else(|| encrypted_reasoning_data(details));
2010 let id = encrypted_reasoning_item_id(details)
2011 .unwrap_or_else(|| format!("rs_switchyard_{index}"));
2012 items.push(encode_responses_reasoning_output(
2013 text,
2014 encrypted.as_deref(),
2015 Some(&id),
2016 ));
2017 }
2018 }
2019 } else if !reasoning.is_empty() || encrypted_reasoning.is_some() {
2020 items.push(encode_responses_reasoning_output(
2021 &reasoning,
2022 encrypted_reasoning.as_deref(),
2023 encrypted_reasoning_id.as_deref(),
2024 ));
2025 }
2026
2027 if content.is_empty() && !has_output_items && reasoning.is_empty() {
2028 content.push(json!({"type": "output_text", "text": "", "annotations": []}));
2029 }
2030 if !content.is_empty() {
2031 items.push(json!({
2032 "type": "message",
2033 "id": "msg_switchyard",
2034 "status": status,
2035 "role": role_to_responses(output.role),
2036 "content": content,
2037 }));
2038 }
2039
2040 items.extend(output.content.iter().filter_map(|block| match block {
2041 ContentBlock::ToolCall(call) => Some(json!({
2042 "type": "function_call",
2043 "call_id": call.id,
2044 "name": call.name,
2045 "arguments": json_string_python_style(&call.arguments),
2046 })),
2047 ContentBlock::Unknown { provider, raw }
2048 if provider.as_str() == WireFormat::OpenAiResponses.as_str()
2049 && raw["type"].as_str().is_some_and(super::is_native_output) =>
2050 {
2051 Some(raw.clone())
2052 }
2053 _ => None,
2054 }));
2055
2056 items
2057 })
2058 .collect(),
2059 )
2060}
2061
2062fn encode_responses_reasoning_output(
2065 text: &str,
2066 encrypted: Option<&str>,
2067 item_id: Option<&str>,
2068) -> Value {
2069 let mut summary = Vec::new();
2071 if !text.is_empty() {
2072 summary.push(json!({"type": "summary_text", "text": text}));
2073 }
2074 let mut item = json!({
2076 "type": "reasoning",
2077 "id": item_id.unwrap_or("rs_switchyard"),
2078 "status": "completed",
2079 "summary": summary,
2080 });
2081 if let Some(encrypted) = encrypted {
2082 item["encrypted_content"] = Value::String(encrypted.to_string());
2083 }
2084 item
2085}
2086
2087fn json_string_python_style(value: &Value) -> String {
2089 match value {
2090 Value::Null => "null".to_string(),
2091 Value::Bool(value) => value.to_string(),
2092 Value::Number(value) => value.to_string(),
2093 Value::String(value) => serde_json::to_string(value).unwrap_or_else(|_| value.clone()),
2094 Value::Array(items) => {
2095 let body = items
2096 .iter()
2097 .map(json_string_python_style)
2098 .collect::<Vec<_>>()
2099 .join(", ");
2100 format!("[{body}]")
2101 }
2102 Value::Object(object) => {
2103 let body = object
2104 .iter()
2105 .map(|(key, value)| {
2106 let key = serde_json::to_string(key).unwrap_or_else(|_| format!("\"{key}\""));
2107 format!("{key}: {}", json_string_python_style(value))
2108 })
2109 .collect::<Vec<_>>()
2110 .join(", ");
2111 format!("{{{body}}}")
2112 }
2113 }
2114}
2115
2116fn decode_responses_usage(value: Option<&Value>) -> Usage {
2118 let Some(value) = value.and_then(Value::as_object) else {
2119 return Usage::default();
2120 };
2121 let aggregate_input_tokens = value
2122 .get("input_tokens")
2123 .or_else(|| value.get("prompt_tokens"))
2124 .and_then(Value::as_u64);
2125 let cached_input_tokens = value
2126 .get("input_tokens_details")
2127 .or_else(|| value.get("prompt_tokens_details"))
2128 .and_then(|details| details.get("cached_tokens"))
2129 .and_then(Value::as_u64);
2130 let cache_creation_input_tokens = value
2131 .get("input_tokens_details")
2132 .and_then(|details| details.get("cache_write_tokens"))
2133 .and_then(Value::as_u64)
2134 .or_else(|| {
2135 value.get("prompt_tokens_details").and_then(|details| {
2136 details
2137 .get("cache_write_tokens")
2138 .and_then(Value::as_u64)
2139 .or_else(|| details.get("cache_creation_tokens").and_then(Value::as_u64))
2140 })
2141 });
2142 let input_tokens = aggregate_input_tokens.map(|tokens| {
2143 tokens
2144 .saturating_sub(cached_input_tokens.unwrap_or(0))
2145 .saturating_sub(cache_creation_input_tokens.unwrap_or(0))
2146 });
2147 let output_tokens = value
2148 .get("output_tokens")
2149 .or_else(|| value.get("completion_tokens"))
2150 .and_then(Value::as_u64);
2151 Usage {
2152 provider_cost: crate::codecs::common::provider_cost(value),
2153 input_tokens,
2154 cache: crate::codecs::common::cache_usage_details(
2155 value,
2156 cached_input_tokens,
2157 cache_creation_input_tokens,
2158 ),
2159 output_tokens,
2160 total_tokens: value
2161 .get("total_tokens")
2162 .and_then(Value::as_u64)
2163 .or_else(|| {
2164 aggregate_input_tokens
2165 .zip(output_tokens)
2166 .map(|(input, output)| input + output)
2167 }),
2168 reasoning_tokens: value
2169 .get("output_tokens_details")
2170 .and_then(|details| details.get("reasoning_tokens"))
2171 .or_else(|| {
2172 value
2173 .get("completion_tokens_details")
2174 .and_then(|details| details.get("reasoning_tokens"))
2175 })
2176 .and_then(Value::as_u64),
2177 }
2178}
2179
2180pub(super) fn encode_responses_usage(usage: &Usage) -> Value {
2182 let input_tokens = usage.input_tokens.unwrap_or(0)
2183 + usage.cached_input_tokens().unwrap_or(0)
2184 + usage.cache_creation_input_tokens().unwrap_or(0);
2185 crate::codecs::common::encode_usage_metadata(
2190 json!({
2191 "input_tokens": input_tokens,
2192 "output_tokens": usage.output_tokens.unwrap_or(0),
2193 "total_tokens": usage
2194 .total_tokens
2195 .or_else(|| Some(input_tokens + usage.output_tokens.unwrap_or(0)))
2196 .unwrap_or(0),
2197 "input_tokens_details": {
2198 "cached_tokens": usage.cached_input_tokens().unwrap_or(0),
2199 "cache_write_tokens": usage.cache_creation_input_tokens().unwrap_or(0),
2200 },
2201 "output_tokens_details": {"reasoning_tokens": usage.reasoning_tokens.unwrap_or(0)},
2202 }),
2203 usage,
2204 )
2205}
2206
2207fn copy_responses_request_extensions(
2215 body: &mut Map<String, Value>,
2216 extensions: &Map<String, Value>,
2217) {
2218 for field in [
2219 "include",
2220 "metadata",
2221 "parallel_tool_calls",
2222 "previous_response_id",
2223 "prompt_cache_key",
2224 "prompt_cache_retention",
2225 "safety_identifier",
2226 "service_tier",
2227 "store",
2228 "user",
2229 ] {
2230 if let Some(value) = extensions.get(field) {
2231 body.entry(field.to_string())
2232 .or_insert_with(|| value.clone());
2233 }
2234 }
2235}