use serde_json::{Map, Value};
#[must_use]
pub fn request_to_chat(body: &Value) -> Value {
let Some(obj) = body.as_object() else {
return body.clone();
};
let mut out = obj.clone();
let mut messages: Vec<Value> = Vec::new();
if let Some(instructions) = obj.get("instructions").and_then(Value::as_str) {
messages.push(serde_json::json!({ "role": "system", "content": instructions }));
}
match obj.get("input") {
Some(Value::String(s)) => {
messages.push(serde_json::json!({ "role": "user", "content": s }));
}
Some(Value::Array(turns)) => {
for turn in turns {
if let Some(m) = turn_to_message(turn) {
messages.push(m);
}
}
}
_ => {}
}
if let Some(Value::Array(tools)) = obj.get("tools") {
let converted: Vec<Value> = tools.iter().filter_map(tool_to_chat).collect();
if converted.len() == tools.len() {
out.insert("tools".to_owned(), Value::Array(converted));
}
}
if let Some(tc) = obj.get("tool_choice") {
match tool_choice_to_chat(tc) {
Some(v) => {
out.insert("tool_choice".to_owned(), v);
}
None => {
out.remove("tool_choice");
}
}
}
if !messages.is_empty() {
out.insert("messages".to_owned(), Value::Array(messages));
}
out.remove("input");
out.remove("instructions");
if let Some(max) = out.remove("max_output_tokens") {
out.insert("max_tokens".to_owned(), max);
}
if let Some(effort) = obj
.get("reasoning")
.and_then(Value::as_object)
.and_then(|r| r.get("effort"))
.and_then(Value::as_str)
{
out.insert(
"reasoning_effort".to_owned(),
Value::String(effort.to_owned()),
);
out.remove("reasoning");
}
Value::Object(out)
}
fn turn_to_message(turn: &Value) -> Option<Value> {
let obj = turn.as_object()?;
match obj.get("type").and_then(Value::as_str) {
Some("function_call") => return function_call_to_chat(obj),
Some("function_call_output") => return function_output_to_chat(obj),
_ => {}
}
let role = obj.get("role").and_then(Value::as_str).unwrap_or("user");
let content = match obj.get("content") {
Some(Value::String(s)) => Value::String(s.clone()),
Some(Value::Array(parts)) => {
if parts
.iter()
.all(|p| p.get("type").and_then(Value::as_str) != Some("input_image"))
{
let text: String = parts
.iter()
.filter_map(|p| p.get("text").and_then(Value::as_str))
.collect::<Vec<_>>()
.join("");
Value::String(text)
} else {
Value::Array(parts.iter().filter_map(part_to_chat).collect())
}
}
_ => return None,
};
Some(serde_json::json!({ "role": role, "content": content }))
}
fn tool_to_chat(tool: &Value) -> Option<Value> {
let obj = tool.as_object()?;
if obj.contains_key("function") {
return Some(tool.clone());
}
if obj.get("type").and_then(Value::as_str) != Some("function") {
return None;
}
let mut f = serde_json::Map::new();
f.insert("name".to_owned(), obj.get("name")?.clone());
if let Some(d) = obj.get("description") {
f.insert("description".to_owned(), d.clone());
}
if let Some(p) = obj.get("parameters") {
f.insert("parameters".to_owned(), p.clone());
}
if let Some(st) = obj.get("strict") {
f.insert("strict".to_owned(), st.clone());
}
Some(serde_json::json!({ "type": "function", "function": Value::Object(f) }))
}
fn tool_choice_to_chat(tc: &Value) -> Option<Value> {
match tc {
Value::String(_) => Some(tc.clone()),
Value::Object(o) => {
if o.contains_key("function") {
return Some(tc.clone()); }
if o.get("type").and_then(Value::as_str) != Some("function") {
return None; }
Some(serde_json::json!({
"type": "function", "function": { "name": o.get("name")?.clone() }
}))
}
_ => None,
}
}
fn function_call_to_chat(item: &serde_json::Map<String, Value>) -> Option<Value> {
Some(serde_json::json!({
"role": "assistant",
"content": Value::Null,
"tool_calls": [{
"id": item.get("call_id").or_else(|| item.get("id"))?.clone(),
"type": "function",
"function": {
"name": item.get("name")?.clone(),
"arguments": item.get("arguments").cloned()
.unwrap_or_else(|| Value::String("{}".to_owned())),
},
}],
}))
}
fn function_output_to_chat(item: &serde_json::Map<String, Value>) -> Option<Value> {
let output = match item.get("output") {
Some(Value::String(s)) => s.clone(),
Some(other) => other.to_string(),
None => return None,
};
Some(serde_json::json!({
"role": "tool",
"tool_call_id": item.get("call_id")?.clone(),
"content": output,
}))
}
fn part_to_chat(part: &Value) -> Option<Value> {
match part.get("type").and_then(Value::as_str) {
Some("input_text" | "output_text" | "text") => Some(serde_json::json!({
"type": "text",
"text": part.get("text").and_then(Value::as_str).unwrap_or_default(),
})),
Some("input_image") => {
let url = part.get("image_url").and_then(|u| {
u.as_str()
.map(str::to_owned)
.or_else(|| u.get("url").and_then(Value::as_str).map(str::to_owned))
})?;
Some(serde_json::json!({ "type": "image_url", "image_url": { "url": url } }))
}
_ => None,
}
}
#[must_use]
pub fn has_untranslatable_content(body: &Value) -> bool {
if let Some(Value::Array(tools)) = body.get("tools")
&& tools.iter().any(|t| tool_to_chat(t).is_none())
{
return true;
}
if let Some(tc) = body.get("tool_choice")
&& tool_choice_to_chat(tc).is_none()
{
return true;
}
if body.get("previous_response_id").is_some() {
return true;
}
let Some(Value::Array(turns)) = body.get("input") else {
return false;
};
turns.iter().any(|turn| {
let Some(obj) = turn.as_object() else {
return true;
};
if obj.contains_key("type") && !obj.contains_key("role") {
return turn_to_message(turn).is_none();
}
if !matches!(
obj.get("role").and_then(Value::as_str),
Some("user" | "assistant" | "system" | "developer")
) {
return true;
}
match obj.get("content") {
Some(Value::String(_)) => false,
Some(Value::Array(parts)) => parts.iter().any(|p| {
!matches!(
p.get("type").and_then(Value::as_str),
Some("input_text" | "output_text" | "text" | "input_image")
)
}),
_ => true,
}
})
}
#[must_use]
pub fn response_from_chat(chat: &Value) -> Value {
let text = chat
.pointer("/choices/0/message/content")
.and_then(Value::as_str)
.unwrap_or_default();
let model = chat
.get("model")
.and_then(Value::as_str)
.unwrap_or_default();
let id = chat.get("id").and_then(Value::as_str).unwrap_or("resp_0");
let in_tokens = chat
.pointer("/usage/prompt_tokens")
.and_then(Value::as_u64)
.unwrap_or(0);
let out_tokens = chat
.pointer("/usage/completion_tokens")
.and_then(Value::as_u64)
.unwrap_or(0);
let mut resp = Map::new();
resp.insert("id".to_owned(), Value::String(id.to_owned()));
resp.insert("object".to_owned(), Value::String("response".to_owned()));
resp.insert("model".to_owned(), Value::String(model.to_owned()));
let mut output: Vec<Value> = Vec::new();
if !text.is_empty() {
output.push(serde_json::json!({
"type": "message",
"id": format!("msg_{id}"),
"status": "completed",
"role": "assistant",
"content": [{ "type": "output_text", "text": text, "annotations": [] }],
}));
}
let tool_calls = chat
.pointer("/choices/0/message/tool_calls")
.and_then(Value::as_array);
if let Some(calls) = tool_calls {
for (i, call) in calls.iter().enumerate() {
output.push(serde_json::json!({
"type": "function_call",
"id": format!("fc_{id}_{i}"),
"status": "completed",
"call_id": call.get("id").cloned().unwrap_or(Value::Null),
"name": call.pointer("/function/name").cloned().unwrap_or(Value::Null),
"arguments": call
.pointer("/function/arguments")
.cloned()
.unwrap_or_else(|| Value::String("{}".to_owned())),
}));
}
}
if output.is_empty() {
output.push(serde_json::json!({
"type": "message",
"id": format!("msg_{id}"),
"status": "completed",
"role": "assistant",
"content": [{ "type": "output_text", "text": "", "annotations": [] }],
}));
}
let truncated = chat
.pointer("/choices/0/finish_reason")
.and_then(Value::as_str)
== Some("length");
if truncated {
resp.insert("status".to_owned(), Value::String("incomplete".to_owned()));
resp.insert(
"incomplete_details".to_owned(),
serde_json::json!({ "reason": "max_output_tokens" }),
);
} else {
resp.insert("status".to_owned(), Value::String("completed".to_owned()));
}
resp.insert("output".to_owned(), Value::Array(output));
resp.insert("output_text".to_owned(), Value::String(text.to_owned()));
resp.insert(
"usage".to_owned(),
serde_json::json!({
"input_tokens": in_tokens,
"output_tokens": out_tokens,
"total_tokens": in_tokens + out_tokens,
}),
);
Value::Object(resp)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_single_turn_string_shorthand_becomes_a_user_message() {
let out = request_to_chat(&serde_json::json!({
"model": "gpt-5.5", "input": "write a haiku",
}));
assert_eq!(out["messages"][0]["role"], "user");
assert_eq!(out["messages"][0]["content"], "write a haiku");
assert!(
out.get("input").is_none(),
"the Responses field must not leak downstream"
);
}
#[test]
fn instructions_become_a_leading_system_message() {
let out = request_to_chat(&serde_json::json!({
"model": "gpt-5.5",
"instructions": "be terse",
"input": [{ "role": "user", "content": "hi" }],
}));
assert_eq!(out["messages"][0]["role"], "system");
assert_eq!(out["messages"][0]["content"], "be terse");
assert_eq!(out["messages"][1]["role"], "user");
assert!(out.get("instructions").is_none());
}
#[test]
fn an_image_survives_translation_instead_of_being_silently_dropped() {
let out = request_to_chat(&serde_json::json!({
"model": "gpt-5.5",
"input": [{ "role": "user", "content": [
{ "type": "input_text", "text": "what is this?" },
{ "type": "input_image", "image_url": "data:image/png;base64,AAAA" },
]}],
}));
let parts = out["messages"][0]["content"]
.as_array()
.expect("mixed content stays a typed array");
assert_eq!(parts.len(), 2, "{parts:?}");
assert_eq!(parts[0]["type"], "text");
assert_eq!(parts[1]["type"], "image_url");
assert_eq!(parts[1]["image_url"]["url"], "data:image/png;base64,AAAA");
}
#[test]
fn content_we_cannot_represent_is_flagged_for_passthrough() {
let with_file = serde_json::json!({
"input": [{ "role": "user", "content": [
{ "type": "input_text", "text": "summarise" },
{ "type": "input_file", "file_id": "file_123" },
]}],
});
assert!(has_untranslatable_content(&with_file));
let text_and_image = serde_json::json!({
"input": [{ "role": "user", "content": [
{ "type": "input_text", "text": "hi" },
{ "type": "input_image", "image_url": "data:..." },
]}],
});
assert!(
!has_untranslatable_content(&text_and_image),
"text and images ARE representable — they must still be gated"
);
assert!(!has_untranslatable_content(
&serde_json::json!({ "input": "plain" })
));
}
#[test]
fn a_tool_round_trip_survives_in_both_directions() {
let out = request_to_chat(&serde_json::json!({
"model": "gpt-5.5",
"tools": [{
"type": "function", "name": "get_weather",
"description": "look up weather",
"parameters": { "type": "object", "properties": { "city": { "type": "string" } } },
}],
"input": [
{ "role": "user", "content": "weather in Paris?" },
{ "type": "function_call", "call_id": "call_1", "name": "get_weather",
"arguments": "{\"city\":\"Paris\"}" },
{ "type": "function_call_output", "call_id": "call_1", "output": "22C" },
],
}));
assert_eq!(out["tools"][0]["type"], "function");
assert_eq!(out["tools"][0]["function"]["name"], "get_weather");
assert_eq!(out["tools"][0]["function"]["parameters"]["type"], "object");
let msgs = out["messages"].as_array().expect("messages");
assert_eq!(msgs.len(), 3);
assert_eq!(msgs[1]["role"], "assistant");
assert_eq!(msgs[1]["tool_calls"][0]["id"], "call_1");
assert_eq!(msgs[1]["tool_calls"][0]["function"]["name"], "get_weather");
assert_eq!(msgs[2]["role"], "tool");
assert_eq!(msgs[2]["tool_call_id"], "call_1");
assert_eq!(msgs[2]["content"], "22C");
}
#[test]
fn a_tool_call_in_the_reply_comes_back_as_a_function_call_item() {
let chat = serde_json::json!({
"id": "chatcmpl_1", "model": "openai/gpt-5.5",
"choices": [{ "message": {
"role": "assistant", "content": null,
"tool_calls": [{
"id": "call_9", "type": "function",
"function": { "name": "get_weather", "arguments": "{\"city\":\"Paris\"}" },
}],
}}],
"usage": { "prompt_tokens": 10, "completion_tokens": 5 },
});
let out = response_from_chat(&chat);
let item = &out["output"][0];
assert_eq!(item["type"], "function_call");
assert_eq!(item["call_id"], "call_9");
assert_eq!(item["name"], "get_weather");
assert_eq!(item["arguments"], "{\"city\":\"Paris\"}");
assert_eq!(out["status"], "completed");
}
#[test]
fn text_alongside_a_tool_call_keeps_both() {
let chat = serde_json::json!({
"id": "c", "model": "m",
"choices": [{ "message": {
"content": "let me check",
"tool_calls": [{ "id": "c1", "function": { "name": "f", "arguments": "{}" } }],
}}],
});
let out = response_from_chat(&chat);
assert_eq!(out["output"][0]["type"], "message");
assert_eq!(out["output"][0]["content"][0]["text"], "let me check");
assert_eq!(out["output"][1]["type"], "function_call");
}
#[test]
fn a_truncated_reply_is_the_only_incomplete_one() {
let chat = serde_json::json!({
"id": "c", "model": "m",
"choices": [{ "finish_reason": "length", "message": { "content": "cut off mid-" } }],
});
let out = response_from_chat(&chat);
assert_eq!(out["status"], "incomplete");
assert_eq!(out["incomplete_details"]["reason"], "max_output_tokens");
}
#[test]
fn tool_choice_is_translated_not_passed_through_in_the_wrong_shape() {
let out = request_to_chat(&serde_json::json!({
"input": "hi",
"tools": [{ "type": "function", "name": "f" }],
"tool_choice": { "type": "function", "name": "f" },
}));
assert_eq!(out["tool_choice"]["type"], "function");
assert_eq!(out["tool_choice"]["function"]["name"], "f");
for word in ["auto", "none", "required"] {
let out = request_to_chat(&serde_json::json!({
"input": "hi", "tool_choice": word,
}));
assert_eq!(out["tool_choice"], word);
}
}
#[test]
fn a_tool_choice_we_cannot_express_routes_to_passthrough() {
assert!(has_untranslatable_content(&serde_json::json!({
"input": "hi",
"tool_choice": { "type": "file_search" },
})));
assert!(!has_untranslatable_content(&serde_json::json!({
"input": "hi",
"tools": [{ "type": "function", "name": "f" }],
"tool_choice": { "type": "function", "name": "f" },
})));
}
#[test]
fn hosted_tools_still_take_passthrough() {
assert!(has_untranslatable_content(&serde_json::json!({
"input": "search for it",
"tools": [
{ "type": "function", "name": "f" },
{ "type": "web_search" },
],
})));
}
#[test]
fn function_tools_are_now_gated_rather_than_passed_through() {
assert!(!has_untranslatable_content(&serde_json::json!({
"input": [
{ "role": "user", "content": "weather?" },
{ "type": "function_call", "call_id": "c1", "name": "f", "arguments": "{}" },
{ "type": "function_call_output", "call_id": "c1", "output": "22C" },
],
"tools": [{ "type": "function", "name": "f" }],
})));
}
#[test]
fn a_malformed_tool_item_routes_to_passthrough_rather_than_vanishing() {
let no_call_id = serde_json::json!({
"input": [{ "type": "function_call", "name": "f", "arguments": "{}" }],
});
assert!(has_untranslatable_content(&no_call_id));
let no_name = serde_json::json!({
"input": [{ "type": "function_call", "call_id": "c1", "arguments": "{}" }],
});
assert!(has_untranslatable_content(&no_name));
let no_output = serde_json::json!({
"input": [{ "type": "function_call_output", "call_id": "c1" }],
});
assert!(has_untranslatable_content(&no_output));
let ok = serde_json::json!({
"input": [
{ "type": "function_call", "call_id": "c1", "name": "f", "arguments": "{}" },
{ "type": "function_call_output", "call_id": "c1", "output": "42" },
],
});
assert!(!has_untranslatable_content(&ok));
}
#[test]
fn every_allowed_turn_actually_produces_a_message() {
let body = serde_json::json!({
"input": [
{ "role": "user", "content": "hi" },
{ "role": "assistant", "content": [{ "type": "output_text", "text": "yes" }] },
{ "type": "function_call", "call_id": "c1", "name": "f", "arguments": "{}" },
{ "type": "function_call_output", "call_id": "c1", "output": "42" },
],
});
assert!(!has_untranslatable_content(&body));
let turns = body["input"].as_array().expect("array");
let out = request_to_chat(&body);
assert_eq!(
out["messages"].as_array().expect("messages").len(),
turns.len(),
"every allowed turn must survive translation"
);
}
#[test]
fn reasoning_items_still_take_passthrough() {
assert!(has_untranslatable_content(&serde_json::json!({
"input": [{ "type": "reasoning", "summary": [] }],
})));
}
#[test]
fn a_tool_using_request_is_not_translated_when_hosted() {
assert!(!has_untranslatable_content(&serde_json::json!({
"input": "hi",
"tools": [{ "type": "function", "name": "get_weather" }],
})));
assert!(has_untranslatable_content(&serde_json::json!({
"input": "hi",
"tools": [{ "type": "computer_use_preview" }],
})));
}
#[test]
fn typed_item_turns_are_not_translated() {
for item in [
serde_json::json!({ "type": "reasoning", "summary": [] }),
serde_json::json!({ "type": "web_search_call", "id": "ws_1" }),
] {
assert!(
has_untranslatable_content(&serde_json::json!({ "input": [item.clone()] })),
"must not translate {item}"
);
}
}
#[test]
fn stateful_threading_is_not_translated() {
assert!(has_untranslatable_content(&serde_json::json!({
"input": "and then?", "previous_response_id": "resp_abc",
})));
}
#[test]
fn plain_conversations_are_still_translated_and_gated() {
assert!(!has_untranslatable_content(
&serde_json::json!({ "input": "hi" })
));
assert!(!has_untranslatable_content(&serde_json::json!({
"input": [
{ "role": "user", "content": "hi" },
{ "role": "assistant", "content": "hello" },
{ "role": "user", "content": [
{ "type": "input_text", "text": "and this?" },
{ "type": "input_image", "image_url": "data:..." },
]},
],
})));
}
#[test]
fn typed_content_parts_are_flattened_to_text() {
let out = request_to_chat(&serde_json::json!({
"model": "gpt-5.5",
"input": [{ "role": "user", "content": [
{ "type": "input_text", "text": "part one " },
{ "type": "input_text", "text": "part two" },
]}],
}));
assert_eq!(out["messages"][0]["content"], "part one part two");
}
#[test]
fn max_output_tokens_is_renamed_not_dropped() {
let out = request_to_chat(&serde_json::json!({
"model": "gpt-5.5", "input": "hi", "max_output_tokens": 256,
}));
assert_eq!(out["max_tokens"], 256);
assert!(out.get("max_output_tokens").is_none());
}
#[test]
fn nested_reasoning_effort_is_flattened_for_the_provider_layer() {
let out = request_to_chat(&serde_json::json!({
"model": "gpt-5.5", "input": "hi", "reasoning": { "effort": "high" },
}));
assert_eq!(out["reasoning_effort"], "high");
assert!(out.get("reasoning").is_none());
}
#[test]
fn unknown_fields_survive_the_crossing() {
let out = request_to_chat(&serde_json::json!({
"model": "gpt-5.5", "input": "hi", "metadata": { "run": "abc" }, "store": false,
}));
assert_eq!(out["metadata"]["run"], "abc");
assert_eq!(out["store"], false);
}
#[test]
fn the_reply_carries_text_in_both_places_a_client_looks() {
let chat = serde_json::json!({
"id": "chatcmpl_1", "model": "openai/gpt-5.5",
"choices": [{ "index": 0, "message": { "role": "assistant", "content": "42" } }],
"usage": { "prompt_tokens": 10, "completion_tokens": 3 },
});
let out = response_from_chat(&chat);
assert_eq!(out["object"], "response");
assert_eq!(out["status"], "completed");
assert_eq!(out["output"][0]["content"][0]["text"], "42");
assert_eq!(out["output"][0]["content"][0]["type"], "output_text");
assert_eq!(out["output_text"], "42");
}
#[test]
fn usage_is_renamed_or_the_call_looks_free() {
let chat = serde_json::json!({
"id": "c", "model": "m",
"choices": [{ "message": { "content": "x" } }],
"usage": { "prompt_tokens": 1200, "completion_tokens": 300 },
});
let out = response_from_chat(&chat);
assert_eq!(out["usage"]["input_tokens"], 1200);
assert_eq!(out["usage"]["output_tokens"], 300);
assert_eq!(out["usage"]["total_tokens"], 1500);
}
#[test]
fn a_round_trip_preserves_the_conversation() {
let original = serde_json::json!({
"model": "gpt-5.5",
"instructions": "be terse",
"input": [
{ "role": "user", "content": "first" },
{ "role": "assistant", "content": "ok" },
{ "role": "user", "content": "second" },
],
});
let chat = request_to_chat(&original);
let msgs = chat["messages"].as_array().expect("messages");
assert_eq!(msgs.len(), 4, "system + three turns");
assert_eq!(msgs[3]["content"], "second");
assert_eq!(msgs[2]["role"], "assistant");
}
}