switchyard_llm_client/
observed_translation.rs1use std::sync::LazyLock;
7
8use serde_json::Value;
9use switchyard_protocol::{AggLlmResponse, LlmRequest, ProviderExtensions};
10use switchyard_translation::{Result, TranslationEngine, TranslationPolicy, WireFormat};
11
12use crate::metrics;
13
14static ENGINE: LazyLock<TranslationEngine> = LazyLock::new(TranslationEngine::default);
15static POLICY: LazyLock<TranslationPolicy> = LazyLock::new(TranslationPolicy::default);
16
17pub fn encode_request(request: &LlmRequest, format: WireFormat) -> Result<Value> {
18 let encoded = ENGINE.encode_request(format, request, &POLICY)?;
19 metrics::record_translation_diagnostics(&encoded.diagnostics, "request_encode", format);
20 Ok(encoded.body)
21}
22
23pub fn decode_response(body: &Value, format: WireFormat) -> Result<AggLlmResponse> {
24 let decoded = ENGINE.decode_response(format, body, &POLICY)?;
25 metrics::record_translation_diagnostics(&decoded.diagnostics, "response_decode", format);
26 Ok(decoded.response)
27}
28
29pub fn decode_request(body: &Value, format: WireFormat) -> Result<LlmRequest> {
30 let decoded = ENGINE.decode_request(format, body, &POLICY)?;
31 metrics::record_translation_diagnostics(&decoded.diagnostics, "request_decode", format);
32 Ok(decoded.request)
33}
34
35pub fn encode_response(
37 response: &AggLlmResponse,
38 format: WireFormat,
39 served_model: Option<&str>,
40 request_extensions: &ProviderExtensions,
41) -> Result<Value> {
42 let mut encoded =
43 ENGINE.encode_response_with_extensions(format, response, request_extensions, &POLICY)?;
44 metrics::record_translation_diagnostics(&encoded.diagnostics, "response_encode", format);
45 if let (Some(model), Value::Object(body)) = (served_model, &mut encoded.body) {
46 body.insert("model".to_string(), Value::String(model.to_string()));
47 }
48 Ok(encoded.body)
49}