Switchyard lets LLM applications route traffic across models and providers while preserving native OpenAI and Anthropic API compatibility - enabling flexible model selection, benchmarking, and cost/performance optimization.
Rust
fix(translation): add missing Responses item IDs and text completion (#749)
Elyas Mehtabuddin56d17af9bb1b
diff --git a/crates/switchyard-server/tests/server.rs b/crates/switchyard-server/tests/server.rsindex fee47a1d3..661c59f25 100644--- a/crates/switchyard-server/tests/server.rs+++ b/crates/switchyard-server/tests/server.rs@@ -4226,6 +4226,7 @@ async fn responses_stream_error_does_not_emit_success_terminal_events() -> TestRlet body = response.text()?;assert_in_order(body, &["before", "upstream stream failed"]);for event_type in [+ "response.output_text.done","response.content_part.done","response.output_item.done","response.completed",@@ -4754,13 +4755,10 @@ fn sse_events(body: &str) -> Vec<Value> {.collect()}-// The end-to-end contract for Codex tool namespaces, in one request.-//-// Two MCP servers expose the same tool name, so the flat upstream can only tell-// them apart by the namespace folded into each name. Everything naming a tool —-// the definitions, the recorded call in history, and the forced tool choice —-// has to use that same spelling, and the response has to split it back into the-// name and namespace Codex dispatches on.+// Two MCP servers expose `search`, so the upstream needs a qualified name for+// each tool. Tool definitions, history, and the forced tool choice must use the+// same qualified names. Response items and argument completions must contain+// the tool name and namespace that Codex uses to select the tool.#[tokio::test]async fn responses_round_trips_codex_tool_namespaces() -> TestResult {const MODEL: &str = "model/mcp-namespaces";@@ -4834,6 +4832,17 @@ async fn responses_round_trips_codex_tool_namespaces() -> TestResult {assert_eq!(item["name"], "search", "{event_type}");assert_eq!(item["namespace"], "mcp__b", "{event_type}");}+ let arguments_done = events+ .iter()+ .find(|event| event["type"] == "response.function_call_arguments.done");+ assert_eq!(+ arguments_done.map(|event| &event["name"]),+ Some(&json!("search"))+ );+ assert_eq!(+ arguments_done.map(|event| &event["namespace"]),+ Some(&json!("mcp__b"))+ );let completed = events.iter().find(|event| event["type"] == "response.completed")diff --git a/crates/switchyard-translation/src/codecs/responses/stream.rs b/crates/switchyard-translation/src/codecs/responses/stream.rsindex df507ecb4..608d0f6a8 100644--- a/crates/switchyard-translation/src/codecs/responses/stream.rs+++ b/crates/switchyard-translation/src/codecs/responses/stream.rs@@ -405,21 +405,31 @@ fn finish_responses_stream(state: &mut StreamTranslationState) -> Vec<Value> {if state.response_text_started&& let Some(output_index) = state.response_text_output_index{+ let item_id = responses_item_id(state, "msg", output_index);+ out.push(json!({+ "type": "response.output_text.done",+ "item_id": item_id,+ "output_index": output_index,+ "content_index": 0,+ "text": state.response_text,+ "logprobs": [],+ }));out.push(json!({"type": "response.content_part.done",+ "item_id": item_id,"output_index": output_index,"content_index": 0,- "part": {"type": "output_text", "text": state.response_text},+ "part": {"type": "output_text", "text": state.response_text, "annotations": [], "logprobs": []},}));out.push(json!({"type": "response.output_item.done","output_index": output_index,"item": {"type": "message",- "id": responses_item_id(state, "msg", output_index),+ "id": item_id,"role": "assistant","status": status,- "content": [{"type": "output_text", "text": state.response_text}],+ "content": [{"type": "output_text", "text": state.response_text, "annotations": [], "logprobs": []}],},}));}@@ -484,7 +494,7 @@ fn finish_responses_stream(state: &mut StreamTranslationState) -> Vec<Value> {"id": responses_item_id(state, "msg", output_index),"role": "assistant","status": status,- "content": [{"type": "output_text", "text": state.response_text}],+ "content": [{"type": "output_text", "text": state.response_text, "annotations": [], "logprobs": []}],}),));}@@ -494,14 +504,20 @@ fn finish_responses_stream(state: &mut StreamTranslationState) -> Vec<Value> {continue;}let output_index = tool.response_output_index.unwrap_or(0);+ let item_id = tool+ .response_item_id+ .clone()+ .unwrap_or_else(|| responses_item_id(state, "fc", output_index));out.push(json!({"type": "response.function_call_arguments.done",+ "item_id": item_id,"output_index": output_index,+ "name": tool.name.clone().unwrap_or_default(),"arguments": tool.arguments,}));let item = json!({"type": "function_call",- "id": tool.response_item_id.clone().unwrap_or_else(|| responses_item_id(state, "fc", output_index)),+ "id": item_id,"call_id": tool.id.clone().unwrap_or_else(|| format!("call_{output_index}")),"name": tool.name.clone().unwrap_or_default(),"arguments": tool.arguments,@@ -788,17 +804,20 @@ fn encode_responses_text_delta(state: &mut StreamTranslationState, text: String)}));out.push(json!({"type": "response.content_part.added",+ "item_id": responses_item_id(state, "msg", output_index),"output_index": output_index,"content_index": 0,- "part": {"type": "output_text", "text": ""},+ "part": {"type": "output_text", "text": "", "annotations": [], "logprobs": []},}));}state.response_text.push_str(&text);out.push(json!({"type": "response.output_text.delta",+ "item_id": responses_item_id(state, "msg", state.response_text_output_index.unwrap_or(0)),"output_index": state.response_text_output_index.unwrap_or(0),"content_index": 0,"delta": text,+ "logprobs": [],}));out}@@ -942,6 +961,7 @@ fn encode_responses_tool_delta(if !tool.pending_arguments.is_empty() {out.push(json!({"type": "response.function_call_arguments.delta",+ "item_id": tool.response_item_id,"output_index": output_index,"delta": tool.pending_arguments,}));@@ -955,6 +975,7 @@ fn encode_responses_tool_delta({out.push(json!({"type": "response.function_call_arguments.delta",+ "item_id": tool.response_item_id,"output_index": output_index,"delta": tool.pending_arguments,}));diff --git a/crates/switchyard-translation/src/codex_namespaces.rs b/crates/switchyard-translation/src/codex_namespaces.rsindex faaff5f77..a16507f26 100644--- a/crates/switchyard-translation/src/codex_namespaces.rs+++ b/crates/switchyard-translation/src/codex_namespaces.rs@@ -139,12 +139,11 @@ pub fn qualified_tool_origins(origins}-/// Rewrite `function_call` names back to the Codex tool name plus namespace.+/// Restore the Codex tool name and namespace on function calls and argument completions.///-/// Walks the whole value, covering a buffered body and each streaming event,-/// where the item is nested under `item` (`response.output_item.added` /-/// `.done`) or `response.output` (`response.completed`). An existing-/// `namespace` is never overwritten.+/// Walks the whole value, covering `function_call` items in buffered responses+/// and streaming events, plus the top-level name in+/// `response.function_call_arguments.done`. Preserves an existing `namespace`.pub fn restore_qualified_tool_names(body: &mut Value, origins: &HashMap<String, (String, String)>) {if origins.is_empty() {return;@@ -156,8 +155,10 @@ pub fn restore_qualified_tool_names(body: &mut Value, origins: &HashMap<String,}}Value::Object(object) => {- if object.get("type").and_then(Value::as_str) == Some("function_call")- && let Some(name) = object.get("name").and_then(Value::as_str)+ if matches!(+ object.get("type").and_then(Value::as_str),+ Some("function_call" | "response.function_call_arguments.done")+ ) && let Some(name) = object.get("name").and_then(Value::as_str)&& let Some((tool, namespace)) = origins.get(name){object.insert("name".to_string(), Value::String(tool.clone()));diff --git a/crates/switchyard-translation/tests/stream_translation.rs b/crates/switchyard-translation/tests/stream_translation.rsindex fe751f969..9d5425803 100644--- a/crates/switchyard-translation/tests/stream_translation.rs+++ b/crates/switchyard-translation/tests/stream_translation.rs@@ -1825,6 +1825,153 @@ fn responses_incomplete_event_translates_to_chat_length_finish() -> TestResult {Ok(())}+// Interleave text and two tool calls to check that deltas keep the right item IDs.+// Completion events must include the full text and tool arguments, and the final+// response must preserve each item's ID.+#[test]+fn translated_responses_text_and_tool_events_keep_item_identity_until_done() -> TestResult {+ let cases = [+ (+ WireFormat::OpenAiChat,+ vec![+ json!({"id":"chat_1","model":"model/local","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"}}]}),+ json!({"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_a","type":"function","function":{"name":"lookup","arguments":"{"}}]}}]}),+ json!({"choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"id":"call_b","type":"function","function":{"name":"weather","arguments":"{"}}]}}]}),+ json!({"choices":[{"index":0,"delta":{"content":"lo"}}]}),+ json!({"choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"\"city\":\"Paris\"}"}}]}}]}),+ json!({"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"id\":1}"}}]}}]}),+ json!({"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}),+ ],+ ),+ (+ WireFormat::AnthropicMessages,+ vec![+ json!({"type":"message_start","message":{"id":"msg_1","model":"model/local","role":"assistant","content":[],"usage":{"input_tokens":1,"output_tokens":0}}}),+ json!({"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}),+ json!({"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hel"}}),+ json!({"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"lo"}}),+ json!({"type":"content_block_stop","index":0}),+ json!({"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"call_a","name":"lookup","input":{}}}),+ json!({"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"call_b","name":"weather","input":{}}}),+ json!({"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{"}}),+ json!({"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"{"}}),+ json!({"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"\"city\":\"Paris\"}"}}),+ json!({"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"\"id\":1}"}}),+ json!({"type":"content_block_stop","index":1}),+ json!({"type":"content_block_stop","index":2}),+ json!({"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":1}}),+ json!({"type":"message_stop"}),+ ],+ ),+ ];+ for (source, upstream) in cases {+ let engine = TranslationEngine::default();+ let target = WireFormat::OpenAiResponses;+ let mut state = StreamTranslationState::new(source, target);+ let mut events = Vec::new();+ for event in upstream {+ events.extend(engine.translate_event(&mut state, source, target, &event)?);+ }+ events.extend(engine.finish_stream(&mut state, target)?);+ assert!(engine.finish_stream(&mut state, target)?.is_empty());+ let items = events+ .iter()+ .filter(|event| event["type"] == "response.output_item.added")+ .map(|event| {+ (+ event["output_index"].as_u64().unwrap_or_default(),+ &event["item"],+ )+ })+ .collect::<HashMap<_, _>>();+ assert_eq!(items.len(), 3);+ for (sequence, event) in events.iter().enumerate() {+ assert_eq!(event["sequence_number"], sequence);+ let kind = event["type"].as_str().unwrap_or_default();+ if kind.starts_with("response.output_text.")+ || kind.starts_with("response.content_part.")+ || kind.starts_with("response.function_call_arguments.")+ {+ let index = event["output_index"]+ .as_u64()+ .ok_or("missing output index")?;+ assert_eq!(event["item_id"], items[&index]["id"], "{source:?}: {kind}");+ }+ if kind.starts_with("response.output_text.") {+ assert_eq!(event["content_index"], 0);+ assert_eq!(event["logprobs"], json!([]));+ }+ if kind.starts_with("response.content_part.") {+ assert_eq!(event["part"]["annotations"], json!([]));+ assert_eq!(event["part"]["logprobs"], json!([]));+ }+ }+ let text_events = events+ .iter()+ .filter(|event| event["output_index"] == 0)+ .map(|event| event["type"].as_str().unwrap_or_default())+ .collect::<Vec<_>>();+ assert_eq!(+ text_events,+ [+ "response.output_item.added",+ "response.content_part.added",+ "response.output_text.delta",+ "response.output_text.delta",+ "response.output_text.done",+ "response.content_part.done",+ "response.output_item.done"+ ]+ );+ let text_done = events+ .iter()+ .find(|event| event["type"] == "response.output_text.done")+ .ok_or("missing text completion")?;+ assert_eq!(text_done["text"], "Hello");+ for (index, name, call_id, arguments) in [+ (1, "lookup", "call_a", r#"{"id":1}"#),+ (2, "weather", "call_b", r#"{"city":"Paris"}"#),+ ] {+ let tool_events = events+ .iter()+ .filter(|event| event["output_index"] == index)+ .collect::<Vec<_>>();+ assert_eq!(+ tool_events+ .iter()+ .map(|event| event["type"].as_str().unwrap_or_default())+ .collect::<Vec<_>>(),+ [+ "response.output_item.added",+ "response.function_call_arguments.delta",+ "response.function_call_arguments.delta",+ "response.function_call_arguments.done",+ "response.output_item.done"+ ]+ );+ let done = tool_events[3];+ assert_eq!(done["name"], name);+ assert_eq!(done["arguments"], arguments);+ assert_eq!(tool_events[4]["item"]["id"], items[&index]["id"]);+ assert_eq!(tool_events[4]["item"]["call_id"], call_id);+ }+ let completed = events.last().ok_or("missing response completion")?;+ assert_eq!(completed["type"], "response.completed");+ let output = completed["response"]["output"]+ .as_array()+ .ok_or("missing final output")?;+ assert_eq!(output.len(), 3);+ assert_eq!(+ output[0]["content"][0],+ json!({"type":"output_text","text":"Hello","annotations":[],"logprobs":[]})+ );+ for (index, item) in output.iter().enumerate() {+ assert_eq!(item["id"], items[&(index as u64)]["id"]);+ }+ }+ Ok(())+}+// A completion event must not repeat function-call arguments from delta events.#[test]fn responses_decode_emits_tool_arguments_once() -> TestResult {