Skip to content

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): preserve Responses built-in tool history (#729)

Alex Fournierf8f141ceb7a0
diff --git a/crates/switchyard-translation/src/codecs/anthropic/buffered.rs b/crates/switchyard-translation/src/codecs/anthropic/buffered.rs
index 6c68bf4b9..72f101de4 100644
--- a/crates/switchyard-translation/src/codecs/anthropic/buffered.rs
+++ b/crates/switchyard-translation/src/codecs/anthropic/buffered.rs
@@ -27,7 +27,8 @@ use crate::util::{
sanitize_anthropic_tool_use_id,
};
use crate::util::{
- json_string, push_lossy, stable_id, string_value, validate_request_capabilities,
+ json_string, push_lossy, reject_responses_builtin_tool_item, stable_id, string_value,
+ validate_request_capabilities,
};
/// Format codec for Anthropic Messages payloads.
@@ -846,7 +847,8 @@ fn encode_anthropic_content_with_policy(
let mut blocks = Vec::new();
for block in content {
match block {
- ContentBlock::Unknown { raw, .. } => {
+ ContentBlock::Unknown { provider, raw } => {
+ reject_responses_builtin_tool_item(provider, raw, WireFormat::AnthropicMessages)?;
push_lossy(
diagnostics,
policy,
diff --git a/crates/switchyard-translation/src/codecs/openai_chat/buffered.rs b/crates/switchyard-translation/src/codecs/openai_chat/buffered.rs
index 8793fc4dc..d68c9acbd 100644
--- a/crates/switchyard-translation/src/codecs/openai_chat/buffered.rs
+++ b/crates/switchyard-translation/src/codecs/openai_chat/buffered.rs
@@ -26,8 +26,8 @@ use crate::llm::{
use crate::policy::{DeterministicIdPolicy, TranslationPolicy};
use crate::util::{
capture_request_preservation, capture_response_preservation, embed_preservation,
- exact_preserved_request, exact_preserved_response, json_string, object, push_lossy, stable_id,
- string_value, validate_request_capabilities,
+ exact_preserved_request, exact_preserved_response, json_string, object, push_lossy,
+ reject_responses_builtin_tool_item, stable_id, string_value, validate_request_capabilities,
};
/// Format codec for OpenAI Chat Completions payloads.
@@ -1067,7 +1067,8 @@ pub(crate) fn encode_openai_content(
)?;
blocks.push(openai_text_part(&media_source_text(source)));
}
- ContentBlock::Unknown { raw, .. } => {
+ ContentBlock::Unknown { provider, raw } => {
+ reject_responses_builtin_tool_item(provider, raw, WireFormat::OpenAiChat)?;
push_lossy(
diagnostics,
policy,
diff --git a/crates/switchyard-translation/src/codecs/responses/buffered.rs b/crates/switchyard-translation/src/codecs/responses/buffered.rs
index 2c5440abb..f078d469e 100644
--- a/crates/switchyard-translation/src/codecs/responses/buffered.rs
+++ b/crates/switchyard-translation/src/codecs/responses/buffered.rs
@@ -29,8 +29,8 @@ use crate::llm::{
use crate::policy::{DeterministicIdPolicy, TranslationPolicy};
use crate::util::{
capture_request_preservation, capture_response_preservation, embed_preservation,
- exact_preserved_request, exact_preserved_response, json_string, push_lossy, stable_id,
- string_value, validate_request_capabilities,
+ exact_preserved_request, exact_preserved_response, is_responses_builtin_tool_item, json_string,
+ push_lossy, stable_id, string_value, validate_request_capabilities,
};
/// Format codec for OpenAI Responses payloads.
@@ -480,8 +480,26 @@ fn decode_responses_input(
item.get("role").and_then(Value::as_str),
&format!("$.input[{index}].role"),
)?;
- let content =
- decode_responses_content(item.get("content").unwrap_or(&Value::Null));
+ let content_value = item.get("content").unwrap_or(&Value::Null);
+ if is_responses_builtin_tool_item(content_value) {
+ return Err(TranslationError::InvalidValue {
+ path: format!("$.input[{index}].content.type"),
+ message:
+ "built-in tool items must be top-level Responses input items"
+ .to_string(),
+ });
+ }
+ if let Some(content_index) = content_value.as_array().and_then(|blocks| {
+ blocks.iter().position(is_responses_builtin_tool_item)
+ }) {
+ return Err(TranslationError::InvalidValue {
+ path: format!("$.input[{index}].content[{content_index}].type"),
+ message:
+ "built-in tool items must be top-level Responses input items"
+ .to_string(),
+ });
+ }
+ let content = decode_responses_content(content_value);
// Inline system and developer input items are instructions, not
// conversation turns. Classify them before any state-machine
// transitions so they do not flush pending reasoning or disturb
@@ -1217,6 +1235,16 @@ fn encode_responses_input(
}
}
for message in messages {
+ // The decoder carries each valid top-level built-in tool item as one
+ // provider-qualified block, so replay that block in place.
+ if message.role == Role::User
+ && let [ContentBlock::Unknown { provider, raw }] = message.content.as_slice()
+ && provider.as_str() == WireFormat::OpenAiResponses.as_str()
+ && is_responses_builtin_tool_item(raw)
+ {
+ encoded.push(raw.clone());
+ continue;
+ }
// Anthropic-signed thinking cannot be sent as Responses input.
let content = message
.content
diff --git a/crates/switchyard-translation/src/util.rs b/crates/switchyard-translation/src/util.rs
index 578bba103..3d57fcb17 100644
--- a/crates/switchyard-translation/src/util.rs
+++ b/crates/switchyard-translation/src/util.rs
@@ -99,6 +99,38 @@ pub fn push_lossy(
}
}
+// These Responses history items are valid only as top-level `input` items.
+pub(crate) fn is_responses_builtin_tool_item(item: &Value) -> bool {
+ matches!(
+ item.get("type").and_then(Value::as_str),
+ Some(
+ "apply_patch_call"
+ | "apply_patch_call_output"
+ | "shell_call"
+ | "shell_call_output"
+ | "computer_call"
+ | "computer_call_output"
+ )
+ )
+}
+
+// Prevent provider-specific tool history from being downgraded to target-visible prose.
+pub(crate) fn reject_responses_builtin_tool_item(
+ provider: &FormatId,
+ item: &Value,
+ target: WireFormat,
+) -> Result<()> {
+ if provider.as_str() == WireFormat::OpenAiResponses.as_str()
+ && is_responses_builtin_tool_item(item)
+ {
+ return Err(TranslationError::UnsupportedTranslation {
+ from: WireFormat::OpenAiResponses.into(),
+ to: target.into(),
+ });
+ }
+ Ok(())
+}
+
/// Generates a stable, human-readable ID from a prefix and counter.
pub fn stable_id(prefix: &str, counter: usize) -> String {
format!("{prefix}_{counter:08}")
diff --git a/crates/switchyard-translation/tests/request_translation.rs b/crates/switchyard-translation/tests/request_translation.rs
index 7e70f82a0..0927a7a15 100644
--- a/crates/switchyard-translation/tests/request_translation.rs
+++ b/crates/switchyard-translation/tests/request_translation.rs
@@ -280,6 +280,95 @@ fn anthropic_tool_result_error_survives_target_prompt() -> TestResult {
Ok(())
}
+// Target prompts force normalized re-encoding; built-in tool history must retain its wire shape.
+#[test]
+fn responses_builtin_tool_history_survives_target_prompt() -> TestResult {
+ let engine = TranslationEngine::default();
+ let policy = TranslationPolicy::default();
+ let input = json!([
+ {
+ "type": "apply_patch_call", "call_id": "patch_1",
+ "operation": {"type": "update_file", "path": "src/lib.rs"}
+ },
+ {
+ "type": "apply_patch_call_output", "call_id": "patch_1", "output": "done"
+ },
+ {
+ "type": "shell_call", "call_id": "shell_1",
+ "action": {"commands": ["pwd"]}, "environment": {"type": "local"}
+ },
+ {
+ "type": "shell_call_output", "call_id": "shell_1",
+ "output": [{"stdout": "/workspace", "stderr": "", "outcome": {"type": "exit", "exit_code": 0}}]
+ },
+ {
+ "type": "computer_call", "call_id": "computer_1",
+ "action": {"type": "screenshot"}, "pending_safety_checks": []
+ },
+ {
+ "type": "computer_call_output", "call_id": "computer_1",
+ "output": {"type": "computer_screenshot", "file_id": "file_1"},
+ "acknowledged_safety_checks": []
+ }
+ ]);
+ let body = json!({
+ "model": "route",
+ "instructions": "caller instructions",
+ "input": input
+ });
+ let mut request = engine
+ .decode_request(WireFormat::OpenAiResponses, &body, &policy)?
+ .request;
+
+ prepare_request_for_target(&mut request, &"target".into(), Some("target prompt"));
+
+ let output = engine
+ .encode_request(WireFormat::OpenAiResponses, &request, &policy)?
+ .body;
+ assert_eq!(output["input"], input);
+ assert_eq!(
+ output["instructions"],
+ "target prompt\n\ncaller instructions"
+ );
+
+ for target in [WireFormat::OpenAiChat, WireFormat::AnthropicMessages] {
+ let error = engine
+ .encode_request(target, &request, &policy)
+ .expect_err("built-in Responses tool history must not become target text");
+ assert_eq!(error.kind(), "UnsupportedTranslation");
+ }
+ Ok(())
+}
+
+// Built-in Responses tool history is valid only as top-level input items.
+#[test]
+fn responses_builtin_tool_history_must_be_top_level() {
+ for (content, path) in [
+ (
+ json!([{"type": "shell_call", "call_id": "shell_1"}]),
+ "$.input[0].content[0].type",
+ ),
+ (
+ json!({"type": "shell_call", "call_id": "shell_1"}),
+ "$.input[0].content.type",
+ ),
+ ] {
+ let body = json!({
+ "model": "route",
+ "input": [{"type": "message", "role": "user", "content": content}]
+ });
+ let error = TranslationEngine::default()
+ .decode_request(
+ WireFormat::OpenAiResponses,
+ &body,
+ &TranslationPolicy::default(),
+ )
+ .expect_err("built-in tool history inside message content should be rejected");
+
+ assert!(error.to_string().contains(path));
+ }
+}
+
// Model-only preparation retains provider fields while aligning exact replay with the target.
#[test]
fn preparing_without_a_prompt_preserves_exact_replay() -> TestResult {