Skip to main content

switchyard_translation/
util.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Shared helpers for codec validation, diagnostics, and preservation metadata.
5
6use std::collections::BTreeMap;
7
8use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
9use serde_json::{Map, Value, json};
10use switchyard_protocol::ModelId;
11
12use crate::diagnostic::TranslationDiagnostic;
13use crate::error::{Result, TranslationError};
14use crate::format::{FormatId, WireFormat};
15use crate::llm::{ContentBlock, LlmRequest, Message, PreservationMetadata};
16use crate::policy::{LossyConversionPolicy, PreservationPolicy, TranslationPolicy};
17
18/// Metadata key used to embed exact preserved payloads in provider JSON.
19pub const SWITCHYARD_METADATA_KEY: &str = "_switchyard_translation";
20/// Public alias for the embedded preservation metadata key.
21pub const PRESERVATION_METADATA_KEY: &str = SWITCHYARD_METADATA_KEY;
22
23const ANTHROPIC_TOOL_ID_ENCODING_PREFIX: &str = "sy64_";
24
25/// Reads a JSON object or returns a typed translation error at the given path.
26pub fn object<'a>(value: &'a Value, path: &str) -> Result<&'a Map<String, Value>> {
27    value
28        .as_object()
29        .ok_or_else(|| TranslationError::InvalidType {
30            path: path.to_string(),
31            expected: "object",
32        })
33}
34
35/// Converts JSON scalars to Python-compatible string values where providers do so.
36pub fn string_value(value: &Value) -> Option<String> {
37    match value {
38        Value::String(text) => Some(text.clone()),
39        Value::Null => None,
40        other => Some(match other {
41            Value::Bool(value) => {
42                if *value {
43                    "True".to_string()
44                } else {
45                    "False".to_string()
46                }
47            }
48            _ => other.to_string(),
49        }),
50    }
51}
52
53/// Applies the lossy-conversion policy and records diagnostics when configured.
54pub fn push_lossy(
55    diagnostics: &mut Vec<TranslationDiagnostic>,
56    policy: &TranslationPolicy,
57    message: impl Into<String>,
58) -> Result<()> {
59    let message = message.into();
60    match policy.lossy_conversion_policy {
61        LossyConversionPolicy::AllowWithDiagnostics => {
62            diagnostics.push(TranslationDiagnostic::warning("lossy_conversion", message));
63            Ok(())
64        }
65        LossyConversionPolicy::Reject => Err(TranslationError::LossyConversion(message)),
66    }
67}
68
69// These Responses history items are valid only as top-level `input` items.
70pub(crate) fn is_responses_native_input_item(item: &Value) -> bool {
71    matches!(
72        item.get("type").and_then(Value::as_str),
73        Some(
74            "apply_patch_call"
75                | "apply_patch_call_output"
76                | "shell_call"
77                | "shell_call_output"
78                | "computer_call"
79                | "computer_call_output"
80                | "image_generation_call"
81                | "compaction_trigger"
82        )
83    )
84}
85
86// Prevent provider-specific input from being downgraded to target-visible prose.
87pub(crate) fn reject_responses_native_input_item(
88    provider: &FormatId,
89    item: &Value,
90    target: WireFormat,
91) -> Result<()> {
92    if provider.as_str() == WireFormat::OpenAiResponses.as_str()
93        && is_responses_native_input_item(item)
94    {
95        return Err(TranslationError::UnsupportedTranslation {
96            from: WireFormat::OpenAiResponses.into(),
97            to: target.into(),
98        });
99    }
100    Ok(())
101}
102
103/// Generates a stable, human-readable ID from a prefix and counter.
104pub fn stable_id(prefix: &str, counter: usize) -> String {
105    format!("{prefix}_{counter:08}")
106}
107
108/// Serializes JSON values into provider argument strings.
109pub fn json_string(value: &Value) -> String {
110    match value {
111        Value::String(text) => text.clone(),
112        other => serde_json::to_string(other).unwrap_or_else(|_| other.to_string()),
113    }
114}
115
116/// Checks a request against declared target capabilities.
117pub fn validate_request_capabilities(
118    request: &LlmRequest,
119    diagnostics: &mut Vec<TranslationDiagnostic>,
120    policy: &TranslationPolicy,
121) -> Result<()> {
122    if policy.target_capabilities.supports_tools == Some(false)
123        && (!request.tools.is_empty() || messages_have_tools(&request.messages))
124    {
125        push_lossy(
126            diagnostics,
127            policy,
128            "target format/profile does not support tools",
129        )?;
130    }
131    if policy.target_capabilities.supports_images == Some(false)
132        && messages_have_block(&request.messages, |block| {
133            matches!(block, ContentBlock::Image { .. })
134        })
135    {
136        push_lossy(
137            diagnostics,
138            policy,
139            "target format/profile does not support images",
140        )?;
141    }
142    if policy.target_capabilities.supports_audio == Some(false)
143        && messages_have_block(&request.messages, |block| {
144            matches!(block, ContentBlock::Audio { .. })
145        })
146    {
147        push_lossy(
148            diagnostics,
149            policy,
150            "target format/profile does not support audio",
151        )?;
152    }
153    if policy.target_capabilities.supports_video == Some(false)
154        && messages_have_block(&request.messages, |block| {
155            matches!(block, ContentBlock::Video { .. })
156        })
157    {
158        push_lossy(
159            diagnostics,
160            policy,
161            "target format/profile does not support video",
162        )?;
163    }
164    if policy.target_capabilities.supports_files == Some(false)
165        && messages_have_block(&request.messages, |block| {
166            matches!(block, ContentBlock::File { .. })
167        })
168    {
169        push_lossy(
170            diagnostics,
171            policy,
172            "target format/profile does not support files",
173        )?;
174    }
175    if policy.target_capabilities.supports_reasoning_effort == Some(false)
176        && request.reasoning.effort.is_some()
177    {
178        push_lossy(
179            diagnostics,
180            policy,
181            "target format/profile does not support reasoning effort",
182        )?;
183    }
184    if policy
185        .target_capabilities
186        .supports_json_schema_response_format
187        == Some(false)
188        && request.output.response_format.is_some()
189    {
190        push_lossy(
191            diagnostics,
192            policy,
193            "target format/profile does not support structured response formats",
194        )?;
195    }
196    Ok(())
197}
198
199// Detects whether any message carries tool calls or tool results.
200fn messages_have_tools(messages: &[Message]) -> bool {
201    messages_have_block(messages, |block| {
202        matches!(
203            block,
204            ContentBlock::ToolCall(_) | ContentBlock::ToolResult(_)
205        )
206    })
207}
208
209// Scans message content for a caller-provided block predicate.
210fn messages_have_block(
211    messages: &[Message],
212    mut predicate: impl FnMut(&ContentBlock) -> bool,
213) -> bool {
214    messages
215        .iter()
216        .any(|message| content_has_block(&message.content, &mut predicate))
217}
218
219// Scans content recursively because tool results can contain media blocks.
220fn content_has_block(
221    content: &[ContentBlock],
222    predicate: &mut impl FnMut(&ContentBlock) -> bool,
223) -> bool {
224    content.iter().any(|block| {
225        predicate(block)
226            || match block {
227                ContentBlock::ToolResult(result) => content_has_block(&result.content, predicate),
228                _ => false,
229            }
230    })
231}
232
233/// Captures an exact source request body according to preservation policy.
234pub fn capture_request_preservation(
235    format: impl Into<FormatId>,
236    body: &Value,
237    policy: &TranslationPolicy,
238) -> PreservationMetadata {
239    let mut preservation = extract_preservation(body);
240    if policy.preservation != PreservationPolicy::Disabled {
241        preservation.requests.insert(format.into(), body.clone());
242    }
243    preservation
244}
245
246/// Captures an exact source response body according to preservation policy.
247pub fn capture_response_preservation(
248    format: impl Into<FormatId>,
249    body: &Value,
250    policy: &TranslationPolicy,
251) -> PreservationMetadata {
252    let mut preservation = extract_preservation(body);
253    if policy.preservation != PreservationPolicy::Disabled {
254        preservation.responses.insert(format.into(), body.clone());
255    }
256    preservation
257}
258
259/// Returns an exact preserved request for the target format when available.
260pub fn exact_preserved_request(
261    preservation: &PreservationMetadata,
262    format: impl Into<FormatId>,
263    policy: &TranslationPolicy,
264) -> Option<Value> {
265    let format = format.into();
266    (policy.preservation != PreservationPolicy::Disabled)
267        .then(|| preservation.requests.get(&format).cloned())
268        .flatten()
269}
270
271/// Returns an exact preserved response for the target format when available.
272pub fn exact_preserved_response(
273    preservation: &PreservationMetadata,
274    format: impl Into<FormatId>,
275    policy: &TranslationPolicy,
276) -> Option<Value> {
277    let format = format.into();
278    (policy.preservation != PreservationPolicy::Disabled)
279        .then(|| preservation.responses.get(&format).cloned())
280        .flatten()
281}
282
283/// Applies a selected target model.
284///
285/// Preserved built-in bodies get the new model so exact replay keeps caller fields that are not
286/// represented in the normalized request. Other preserved bodies are removed.
287pub fn prepare_request_for_target(request: &mut LlmRequest, target: &ModelId) {
288    let target = target.to_string();
289    request.model = Some(target.clone());
290    request.preservation.requests.retain(|format, body| {
291        if ![
292            WireFormat::OpenAiChat.as_str(),
293            WireFormat::OpenAiResponses.as_str(),
294            WireFormat::AnthropicMessages.as_str(),
295        ]
296        .contains(&format.as_str())
297        {
298            return false;
299        }
300        let Some(body) = body.as_object_mut() else {
301            return false;
302        };
303        body.insert("model".to_string(), Value::String(target.clone()));
304        true
305    });
306}
307
308/// Embeds preservation metadata into a translated wire body when requested.
309pub fn embed_preservation(
310    mut body: Value,
311    preservation: &PreservationMetadata,
312    policy: &TranslationPolicy,
313) -> Value {
314    if policy.preservation != PreservationPolicy::Embed {
315        return body;
316    }
317    let Ok(envelope) = serde_json::to_value(preservation) else {
318        return body;
319    };
320    let metadata = json!({SWITCHYARD_METADATA_KEY: envelope});
321    if let Some(object) = body.as_object_mut() {
322        match object.get_mut("metadata") {
323            Some(Value::Object(existing)) => {
324                existing.insert(
325                    SWITCHYARD_METADATA_KEY.to_string(),
326                    metadata[SWITCHYARD_METADATA_KEY].clone(),
327                );
328            }
329            _ => {
330                object.insert("metadata".to_string(), metadata);
331            }
332        }
333    }
334    body
335}
336
337/// Extracts embedded preservation metadata from a provider wire body.
338pub fn extract_preservation(body: &Value) -> PreservationMetadata {
339    body.get("metadata")
340        .and_then(Value::as_object)
341        .and_then(|metadata| metadata.get(SWITCHYARD_METADATA_KEY))
342        .cloned()
343        .and_then(|value| serde_json::from_value(value).ok())
344        .unwrap_or_default()
345}
346
347/// Normalizes Anthropic tool-use IDs while keeping tool_use/tool_result pairs aligned.
348pub fn normalize_anthropic_tool_use_ids(value: Value) -> Value {
349    match value {
350        Value::Array(messages) => {
351            let mut id_map = BTreeMap::new();
352            let mut used_ids = BTreeMap::new();
353            Value::Array(
354                messages
355                    .into_iter()
356                    .map(|message| normalize_message_tool_ids(message, &mut id_map, &mut used_ids))
357                    .collect(),
358            )
359        }
360        other => other,
361    }
362}
363
364/// Converts an ID into a reversible Anthropic-safe representation.
365pub fn sanitize_anthropic_tool_use_id(raw: &str) -> String {
366    let is_safe = !raw.is_empty()
367        && raw
368            .bytes()
369            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-');
370    if is_safe && !raw.starts_with(ANTHROPIC_TOOL_ID_ENCODING_PREFIX) {
371        return raw.to_string();
372    }
373
374    format!(
375        "{ANTHROPIC_TOOL_ID_ENCODING_PREFIX}{}",
376        URL_SAFE_NO_PAD.encode(raw.as_bytes())
377    )
378}
379
380/// Restores an ID encoded by [`sanitize_anthropic_tool_use_id`].
381pub(crate) fn desanitize_anthropic_tool_use_id(encoded: &str) -> String {
382    let Some(payload) = encoded.strip_prefix(ANTHROPIC_TOOL_ID_ENCODING_PREFIX) else {
383        return encoded.to_string();
384    };
385
386    URL_SAFE_NO_PAD
387        .decode(payload)
388        .ok()
389        .and_then(|bytes| String::from_utf8(bytes).ok())
390        .unwrap_or_else(|| encoded.to_string())
391}
392
393// Normalizes every content block in one Anthropic message.
394fn normalize_message_tool_ids(
395    message: Value,
396    id_map: &mut BTreeMap<String, String>,
397    used_ids: &mut BTreeMap<String, String>,
398) -> Value {
399    let Value::Object(mut message) = message else {
400        return message;
401    };
402    let Some(content_value) = message.remove("content") else {
403        return Value::Object(message);
404    };
405    let Value::Array(content) = content_value else {
406        message.insert("content".to_string(), content_value);
407        return Value::Object(message);
408    };
409    let normalized = content
410        .into_iter()
411        .map(|block| normalize_tool_block(block, id_map, used_ids).unwrap_or_else(|block| block))
412        .collect::<Vec<_>>();
413    message.insert("content".to_string(), Value::Array(normalized));
414    Value::Object(message)
415}
416
417// Rewrites tool_use/tool_result IDs and leaves unrelated blocks untouched.
418fn normalize_tool_block(
419    block: Value,
420    id_map: &mut BTreeMap<String, String>,
421    used_ids: &mut BTreeMap<String, String>,
422) -> std::result::Result<Value, Value> {
423    let Value::Object(mut block_map) = block else {
424        return Err(block);
425    };
426    match block_map.get("type").and_then(Value::as_str) {
427        Some("tool_use") => {
428            let raw = block_map
429                .get("id")
430                .and_then(Value::as_str)
431                .unwrap_or_default()
432                .to_string();
433            let normalized = mapped_tool_id(&raw, id_map, used_ids);
434            if normalized != raw {
435                block_map.insert("id".to_string(), Value::String(normalized));
436                Ok(Value::Object(block_map))
437            } else {
438                Err(Value::Object(block_map))
439            }
440        }
441        Some("tool_result") => {
442            let raw = block_map
443                .get("tool_use_id")
444                .and_then(Value::as_str)
445                .unwrap_or_default()
446                .to_string();
447            let normalized = mapped_tool_id(&raw, id_map, used_ids);
448            if normalized != raw {
449                block_map.insert("tool_use_id".to_string(), Value::String(normalized));
450                Ok(Value::Object(block_map))
451            } else {
452                Err(Value::Object(block_map))
453            }
454        }
455        _ => Err(Value::Object(block_map)),
456    }
457}
458
459// Gives colliding raw IDs stable, deterministic suffixes.
460fn mapped_tool_id(
461    raw: &str,
462    id_map: &mut BTreeMap<String, String>,
463    used_ids: &mut BTreeMap<String, String>,
464) -> String {
465    if let Some(existing) = id_map.get(raw) {
466        return existing.clone();
467    }
468    let mut candidate = sanitize_anthropic_tool_use_id(raw);
469    if let Some(owner) = used_ids.get(&candidate)
470        && owner != raw
471    {
472        candidate = format!("{}_{}", candidate, stable_suffix(raw));
473    }
474    id_map.insert(raw.to_string(), candidate.clone());
475    used_ids.insert(candidate.clone(), raw.to_string());
476    candidate
477}
478
479// Stable FNV-1a suffix for collision disambiguation.
480fn stable_suffix(raw: &str) -> String {
481    let mut hash: u64 = 1469598103934665603;
482    for byte in raw.as_bytes() {
483        hash ^= u64::from(*byte);
484        hash = hash.wrapping_mul(1099511628211);
485    }
486    format!("{hash:08x}")
487}
488
489#[cfg(test)]
490mod tests {
491    use super::{desanitize_anthropic_tool_use_id, sanitize_anthropic_tool_use_id};
492
493    // Keeps ordinary provider IDs unchanged while making unsafe IDs reversible.
494    #[test]
495    fn anthropic_tool_id_encoding_round_trips() {
496        assert_eq!(
497            sanitize_anthropic_tool_use_id("call_abc-123"),
498            "call_abc-123"
499        );
500
501        for raw in ["", "functions.list_skills:0", "工具/lookup"] {
502            let encoded = sanitize_anthropic_tool_use_id(raw);
503            assert!(
504                encoded
505                    .bytes()
506                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
507            );
508            assert_eq!(desanitize_anthropic_tool_use_id(&encoded), raw);
509        }
510    }
511
512    // Escapes the reserved prefix and leaves malformed encoded values untouched.
513    #[test]
514    fn anthropic_tool_id_encoding_disambiguates_its_prefix() {
515        let raw = "sy64_Zm9v";
516        let encoded = sanitize_anthropic_tool_use_id(raw);
517        assert_ne!(encoded, raw);
518        assert_eq!(desanitize_anthropic_tool_use_id(&encoded), raw);
519        assert_eq!(desanitize_anthropic_tool_use_id("sy64_%%%"), "sy64_%%%");
520    }
521}