Skip to main content

switchyard_translation/codecs/anthropic/
buffered.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Buffered codec for Anthropic Messages request and response JSON.
5
6use serde_json::{Map, Value, json};
7use switchyard_protocol::MAX_IR_TEMPERATURE;
8
9use super::{DEFAULT_TEMPERATURE, MAX_TEMPERATURE};
10use crate::codecs::common::{
11    ANTHROPIC_REQUEST_KEY, is_anthropic_request, is_known_role_name, provider_extensions,
12    scale_temperature, text_from_blocks,
13};
14use crate::codecs::openai_chat::{decode_file_source, decode_image_source};
15use crate::codecs::structured_output::decode_openai_schema_enforcement;
16use crate::codecs::{
17    DecodedRequest, DecodedResponse, EncodedRequest, EncodedResponse, FormatCodec,
18};
19use crate::diagnostic::TranslationDiagnostic;
20use crate::error::{Result, TranslationError};
21use crate::format::{FormatId, WireFormat};
22use crate::llm::{
23    AggLlmResponse, ContentBlock, FileSource, ImageSource, InstructionBlock, LlmRequest,
24    MediaSource, Message, OutputParams, ProviderExtensions, ReasoningParams, ResponseOutput, Role,
25    SamplingParams, StopReason, Tool, ToolCall, ToolChoice, ToolDefinition, ToolResult, Usage,
26};
27use crate::policy::{DeterministicIdPolicy, TranslationPolicy};
28use crate::util::{
29    capture_request_preservation, capture_response_preservation, desanitize_anthropic_tool_use_id,
30    embed_preservation, exact_preserved_request, exact_preserved_response,
31    sanitize_anthropic_tool_use_id,
32};
33use crate::util::{
34    json_string, push_lossy, reject_responses_native_input_item, stable_id, string_value,
35    validate_request_capabilities,
36};
37use base64::{Engine as _, engine::general_purpose::STANDARD};
38
39/// Format codec for Anthropic Messages payloads.
40pub struct AnthropicMessagesCodec;
41
42impl FormatCodec for AnthropicMessagesCodec {
43    fn format(&self) -> FormatId {
44        WireFormat::AnthropicMessages.into()
45    }
46
47    fn decode_request(&self, body: &Value, policy: &TranslationPolicy) -> Result<DecodedRequest> {
48        let body = crate::util::object(body, "$")?;
49        if body
50            .get("fallback_credit_token")
51            .is_some_and(|value| !value.is_null())
52            && body.get("fallbacks").is_some_and(|value| !value.is_null())
53        {
54            return Err(TranslationError::InvalidValue {
55                path: "$.fallback_credit_token".to_string(),
56                message: "fallback_credit_token cannot be combined with fallbacks".to_string(),
57            });
58        }
59        let mut diagnostics = Vec::new();
60        let max_output_tokens = body
61            .get("max_tokens")
62            .map(|value| {
63                value
64                    .as_u64()
65                    .ok_or_else(|| TranslationError::InvalidValue {
66                        path: "$.max_tokens".to_string(),
67                        message: "expected a non-negative integer".to_string(),
68                    })
69            })
70            .transpose()?;
71        let response_format = decode_anthropic_output_format(body, &mut diagnostics, policy)?;
72        let mut request = LlmRequest {
73            model: body
74                .get("model")
75                .and_then(Value::as_str)
76                .filter(|model| !model.is_empty())
77                .map(ToOwned::to_owned),
78            output: OutputParams {
79                max_output_tokens,
80                is_schema_enforced: response_format.as_ref().map(|_| true),
81                response_format,
82            },
83            sampling: SamplingParams {
84                temperature: body
85                    .get("temperature")
86                    .and_then(Value::as_f64)
87                    .map(|value| scale_temperature(value, MAX_TEMPERATURE, MAX_IR_TEMPERATURE)),
88                top_p: body.get("top_p").and_then(Value::as_f64),
89                top_k: body.get("top_k").and_then(Value::as_i64),
90            },
91            reasoning: ReasoningParams {
92                effort: body
93                    .get("output_config")
94                    .and_then(Value::as_object)
95                    .and_then(|object| object.get("effort"))
96                    .and_then(Value::as_str)
97                    .map(ToOwned::to_owned),
98                raw: body.get("thinking").cloned(),
99            },
100            stream: body.get("stream").and_then(Value::as_bool).unwrap_or(false),
101            preservation: capture_request_preservation(
102                WireFormat::AnthropicMessages,
103                &Value::Object(body.clone()),
104                policy,
105            ),
106            ..LlmRequest::default()
107        };
108        if let Some(system) = body.get("system")
109            && let Some(content) = decode_anthropic_system(system)?
110        {
111            request.instructions.push(InstructionBlock {
112                role: Role::System,
113                content,
114            });
115        }
116        if let Some(messages) = body.get("messages") {
117            let messages = messages
118                .as_array()
119                .ok_or_else(|| TranslationError::InvalidType {
120                    path: "$.messages".to_string(),
121                    expected: "array",
122                })?;
123            let mut generated_id = 0;
124            for (index, message) in messages.iter().enumerate() {
125                let Some(message) = message.as_object() else {
126                    push_lossy(
127                        &mut diagnostics,
128                        policy,
129                        format!("Anthropic message at index {index} is not an object"),
130                    )?;
131                    continue;
132                };
133                // Request decoding enforces the provider contract: an unknown
134                // role is rejected rather than coerced to `user`. Anthropic
135                // Messages only defines `user`/`assistant`, but other known
136                // role names stay lenient (mapped to `user`) to preserve
137                // historical cross-format behaviour.
138                let role = match message.get("role").and_then(Value::as_str) {
139                    Some("assistant") => Role::Assistant,
140                    None => Role::User,
141                    Some(other) if is_known_role_name(other) => Role::User,
142                    Some(other) => {
143                        return Err(TranslationError::unsupported_role(
144                            format!("$.messages[{index}].role"),
145                            other,
146                        ));
147                    }
148                };
149                generated_id += 1;
150                let content = decode_anthropic_content(
151                    message
152                        .get("content")
153                        .unwrap_or(&Value::String(String::new())),
154                    role,
155                    generated_id,
156                    &mut diagnostics,
157                    policy,
158                )?;
159                request.messages.push(Message::new(role, content));
160            }
161        }
162        request.tools = decode_anthropic_tools(body.get("tools"));
163        request.tool_choice = body.get("tool_choice").map(decode_anthropic_tool_choice);
164        request.extensions.fields = provider_extensions(
165            body,
166            &[
167                "model",
168                "messages",
169                "system",
170                "tools",
171                "tool_choice",
172                "max_tokens",
173                "temperature",
174                "top_p",
175                "top_k",
176                "thinking",
177                "output_config",
178                "output_format",
179                "stream",
180                // OpenAI-only identity fields must not leak through Anthropic decoding.
181                "safety_identifier",
182            ],
183        );
184        if let Some(is_disabled) = body
185            .get("tool_choice")
186            .and_then(|choice| choice.get("disable_parallel_tool_use"))
187            .and_then(Value::as_bool)
188        {
189            request
190                .extensions
191                .fields
192                .insert("parallel_tool_calls".to_string(), Value::Bool(!is_disabled));
193        }
194        request
195            .extensions
196            .fields
197            .insert(ANTHROPIC_REQUEST_KEY.to_string(), Value::Bool(true));
198
199        Ok(DecodedRequest {
200            request,
201            diagnostics,
202        })
203    }
204
205    fn encode_request(
206        &self,
207        request: &LlmRequest,
208        policy: &TranslationPolicy,
209    ) -> Result<EncodedRequest> {
210        if let Some(body) =
211            exact_preserved_request(&request.preservation, WireFormat::AnthropicMessages, policy)
212        {
213            return Ok(EncodedRequest {
214                body,
215                diagnostics: Vec::new(),
216            });
217        }
218        let mut diagnostics = Vec::new();
219        validate_request_capabilities(request, &mut diagnostics, policy)?;
220        let allowed = crate::codecs::common::allowed_function_tools(request)?;
221        let (tools, tool_choice) = allowed.as_ref().map_or(
222            (request.tools.as_slice(), request.tool_choice.as_ref()),
223            |(tools, choice)| (tools.as_slice(), Some(choice)),
224        );
225        let mut body = Map::new();
226        if let Some(model) = &request.model {
227            body.insert("model".to_string(), Value::String(model.clone()));
228        }
229        let system_text = request
230            .instructions
231            .iter()
232            .flat_map(|instruction| instruction.content.iter())
233            .chain(
234                request
235                    .messages
236                    .iter()
237                    .filter(|message| matches!(message.role, Role::System | Role::Developer))
238                    .flat_map(|message| message.content.iter()),
239            )
240            .filter_map(|block| match block {
241                ContentBlock::Text { text } | ContentBlock::Refusal { text } => Some(text.as_str()),
242                _ => None,
243            })
244            .collect::<Vec<_>>()
245            .join("\n\n");
246        if !system_text.is_empty() {
247            body.insert("system".to_string(), Value::String(system_text));
248        }
249        // Anthropic `system` is a text field, so other instruction content is dropped.
250        let instructions = request
251            .instructions
252            .iter()
253            .enumerate()
254            .map(|(index, block)| (block.role, &block.content, "instruction", index));
255        let inline = request
256            .messages
257            .iter()
258            .enumerate()
259            .filter(|(_, message)| matches!(message.role, Role::System | Role::Developer))
260            .map(|(index, message)| (message.role, &message.content, "message", index));
261        for (role, content, kind, index) in instructions.chain(inline) {
262            for block in content {
263                if !matches!(
264                    block,
265                    ContentBlock::Text { .. } | ContentBlock::Refusal { .. }
266                ) {
267                    push_lossy(
268                        &mut diagnostics,
269                        policy,
270                        format!(
271                            "Anthropic system prompt accepts only text; dropped non-text content from {role} {kind} {index}"
272                        ),
273                    )?;
274                }
275            }
276        }
277
278        body.insert(
279            "messages".to_string(),
280            Value::Array(encode_anthropic_messages(
281                &request.messages,
282                &mut diagnostics,
283                policy,
284            )?),
285        );
286
287        if !tools.is_empty() {
288            body.insert("tools".to_string(), encode_anthropic_tools(tools)?);
289        }
290        let parallel_tool_calls = request
291            .extensions
292            .fields
293            .get("parallel_tool_calls")
294            .and_then(Value::as_bool);
295        if tool_choice.is_some() || (parallel_tool_calls.is_some() && !tools.is_empty()) {
296            let mut choice = encode_anthropic_tool_choice(tool_choice.unwrap_or(&ToolChoice::Auto));
297            if let Some(is_enabled) = parallel_tool_calls
298                && let Some(object) = choice.as_object_mut()
299                && object.get("type").and_then(Value::as_str) != Some("none")
300            {
301                object.insert(
302                    "disable_parallel_tool_use".to_string(),
303                    Value::Bool(!is_enabled),
304                );
305            }
306            body.insert("tool_choice".to_string(), choice);
307        }
308        if is_anthropic_request(request) {
309            for field in [
310                "inference_geo",
311                "service_tier",
312                "stop_sequences",
313                "metadata",
314                "cache_control",
315                "container",
316                "speed",
317                "diagnostics",
318                "fallback_credit_token",
319            ] {
320                if let Some(value) = request.extensions.fields.get(field) {
321                    body.insert(field.to_string(), value.clone());
322                }
323            }
324        }
325        if let Some(stop_sequences) =
326            anthropic_stop_sequences_from_extensions(&request.extensions.fields)
327        {
328            body.entry("stop_sequences").or_insert(stop_sequences);
329        }
330        if let Some(max_tokens) = request.output.max_output_tokens {
331            body.insert("max_tokens".to_string(), json!(max_tokens));
332        } else {
333            body.insert("max_tokens".to_string(), json!(64_000));
334        }
335        if let Some(value) = request
336            .sampling
337            .temperature
338            .map(|value| scale_temperature(value, MAX_IR_TEMPERATURE, MAX_TEMPERATURE))
339            && value != DEFAULT_TEMPERATURE
340        {
341            push_lossy(
342                &mut diagnostics,
343                policy,
344                format!(
345                    "deprecated temperature parameter with non-default value {value} is omitted from Anthropic Messages requests"
346                ),
347            )?;
348        }
349        if let Some(value) = request.sampling.top_p {
350            body.insert("top_p".to_string(), json!(value));
351        }
352        if let Some(value) = request.sampling.top_k {
353            body.insert("top_k".to_string(), json!(value));
354        }
355        if request.stream {
356            body.insert("stream".to_string(), Value::Bool(true));
357        }
358        // Native thinking controls the mode independently of output effort.
359        // Other codecs store their own provider's reasoning object in `raw`.
360        if is_anthropic_request(request)
361            && let Some(thinking) = &request.reasoning.raw
362        {
363            body.insert("thinking".to_string(), thinking.clone());
364        }
365        if let Some(effort) = &request.reasoning.effort {
366            body.entry("thinking".to_string())
367                .or_insert_with(|| json!({"type": "adaptive"}));
368            body.insert("output_config".to_string(), json!({"effort": effort}));
369        }
370        if let Some(response_format) = &request.output.response_format
371            && let Some(format) = encode_anthropic_output_format(
372                response_format,
373                request.output.is_schema_enforced,
374                &mut diagnostics,
375                policy,
376            )?
377        {
378            let output_config = body
379                .entry("output_config".to_string())
380                .or_insert_with(|| Value::Object(Map::new()));
381            let Some(output_config) = output_config.as_object_mut() else {
382                return Err(TranslationError::InvalidType {
383                    path: "$.output_config".to_string(),
384                    expected: "object",
385                });
386            };
387            output_config.insert("format".to_string(), format);
388        } else if request.output.response_format.is_none()
389            && request.output.is_schema_enforced == Some(true)
390        {
391            push_lossy(
392                &mut diagnostics,
393                policy,
394                "Structured-output schema enforcement requires a response format with a schema",
395            )?;
396        }
397
398        let body = embed_preservation(Value::Object(body), &request.preservation, policy);
399        Ok(EncodedRequest { body, diagnostics })
400    }
401
402    fn decode_response(
403        &self,
404        body: &Value,
405        _policy: &TranslationPolicy,
406    ) -> Result<DecodedResponse> {
407        let body = crate::util::object(body, "$")?;
408        let mut content = Vec::new();
409        if let Some(blocks) = body.get("content").and_then(Value::as_array) {
410            for (index, block) in blocks.iter().enumerate() {
411                if let Some(block) = block.as_object() {
412                    content.extend(decode_anthropic_content_block(
413                        block,
414                        Role::Assistant,
415                        index + 1,
416                        &mut Vec::new(),
417                        &TranslationPolicy::default(),
418                    )?);
419                }
420            }
421        }
422        if content.is_empty() {
423            content.push(ContentBlock::Text {
424                text: String::new(),
425            });
426        }
427        let response = AggLlmResponse {
428            id: body
429                .get("id")
430                .and_then(Value::as_str)
431                .map(ToOwned::to_owned),
432            model: body
433                .get("model")
434                .and_then(Value::as_str)
435                .map(ToOwned::to_owned),
436            outputs: vec![ResponseOutput {
437                url_citations: Vec::new(),
438                role: Role::Assistant,
439                content,
440                stop_reason: Some(map_anthropic_stop_reason(
441                    body.get("stop_reason").and_then(Value::as_str),
442                )),
443            }],
444            usage: decode_anthropic_usage(body.get("usage")),
445            extensions: ProviderExtensions {
446                fields: provider_extensions(
447                    body,
448                    &[
449                        "id",
450                        "type",
451                        "role",
452                        "model",
453                        "content",
454                        "stop_reason",
455                        "usage",
456                    ],
457                ),
458            },
459            preservation: capture_response_preservation(
460                WireFormat::AnthropicMessages,
461                &Value::Object(body.clone()),
462                _policy,
463            ),
464        };
465        Ok(DecodedResponse {
466            response,
467            diagnostics: Vec::new(),
468        })
469    }
470
471    fn encode_response(
472        &self,
473        response: &AggLlmResponse,
474        _policy: &TranslationPolicy,
475    ) -> Result<EncodedResponse> {
476        super::super::responses::validate_response_output(response, WireFormat::AnthropicMessages)?;
477        if let Some(body) = exact_preserved_response(
478            &response.preservation,
479            WireFormat::AnthropicMessages,
480            _policy,
481        ) {
482            return Ok(EncodedResponse {
483                body,
484                diagnostics: Vec::new(),
485            });
486        }
487        let output = response.first_output();
488        let content = output
489            .map(|output| encode_anthropic_content(&output.content))
490            .transpose()?
491            .unwrap_or_else(|| vec![json!({"type": "text", "text": ""})]);
492        let normalized_stop_reason = output.and_then(|output| output.stop_reason);
493        let body = json!({
494            "id": response.id.clone().unwrap_or_else(|| "msg_switchyard".to_string()),
495            "type": "message",
496            "role": "assistant",
497            "model": response.model.clone().unwrap_or_else(|| "unknown".to_string()),
498            "content": content,
499            "stop_reason": normalized_stop_reason
500                .map(anthropic_stop_reason)
501                .unwrap_or("end_turn"),
502            "stop_sequence": Value::Null,
503            "stop_details": normalized_stop_reason
504                .map(|reason| {
505                    anthropic_stop_details(reason, response.extensions.fields.get("stop_details"))
506                })
507                .unwrap_or(Value::Null),
508            "usage": encode_anthropic_usage(&response.usage),
509        });
510        Ok(EncodedResponse {
511            body: embed_preservation(body, &response.preservation, _policy),
512            diagnostics: Vec::new(),
513        })
514    }
515}
516
517// Reads the current `output_config.format`, or the beta `output_format` it replaced,
518// into the neutral OpenAI-shaped response format.
519fn decode_anthropic_output_format(
520    body: &Map<String, Value>,
521    diagnostics: &mut Vec<TranslationDiagnostic>,
522    policy: &TranslationPolicy,
523) -> Result<Option<Value>> {
524    let Some(format) = body
525        .get("output_config")
526        .and_then(Value::as_object)
527        .and_then(|config| config.get("format"))
528        .or_else(|| body.get("output_format"))
529    else {
530        return Ok(None);
531    };
532    let Some(format) = format.as_object() else {
533        push_lossy(
534            diagnostics,
535            policy,
536            "Anthropic structured output format is not an object; the requested format was dropped",
537        )?;
538        return Ok(None);
539    };
540    if format.get("type").and_then(Value::as_str) != Some("json_schema") {
541        push_lossy(
542            diagnostics,
543            policy,
544            "Anthropic structured output maps only a json_schema format; the requested format was dropped",
545        )?;
546        return Ok(None);
547    }
548    // A non-object schema would reach the upstream as a malformed `json_schema.schema`.
549    let Some(schema) = format.get("schema").filter(|schema| schema.is_object()) else {
550        push_lossy(
551            diagnostics,
552            policy,
553            "Anthropic structured output requires format.schema to be an object; the requested format was dropped",
554        )?;
555        return Ok(None);
556    };
557    Ok(Some(json!({
558        "type": "json_schema",
559        "json_schema": {
560            // Anthropic identifies the schema by position; the neutral shape needs a name.
561            "name": "response",
562            "schema": schema.clone(),
563        },
564    })))
565}
566
567/// Maps the neutral OpenAI-shaped JSON schema to Anthropic's output format.
568fn encode_anthropic_output_format(
569    response_format: &Value,
570    enforcement: Option<bool>,
571    diagnostics: &mut Vec<TranslationDiagnostic>,
572    policy: &TranslationPolicy,
573) -> Result<Option<Value>> {
574    let Some(json_schema) = response_format
575        .as_object()
576        .filter(|format| format.get("type").and_then(Value::as_str) == Some("json_schema"))
577        .and_then(|format| format.get("json_schema"))
578        .and_then(Value::as_object)
579    else {
580        push_lossy(
581            diagnostics,
582            policy,
583            "Anthropic structured output requires an OpenAI JSON schema response format",
584        )?;
585        return Ok(None);
586    };
587    let Some(schema) = json_schema.get("schema") else {
588        push_lossy(
589            diagnostics,
590            policy,
591            "Anthropic structured output requires json_schema.schema",
592        )?;
593        return Ok(None);
594    };
595
596    if enforcement.or_else(|| decode_openai_schema_enforcement(Some(response_format)))
597        == Some(false)
598    {
599        push_lossy(
600            diagnostics,
601            policy,
602            "Anthropic structured output enforces the schema; advisory schema enforcement was strengthened",
603        )?;
604    }
605    let mut schema = schema.clone();
606    if strip_anthropic_unsupported_constraints(&mut schema) {
607        push_lossy(
608            diagnostics,
609            policy,
610            "Anthropic structured output dropped unsupported JSON Schema constraints",
611        )?;
612    }
613    Ok(Some(json!({"type": "json_schema", "schema": schema})))
614}
615
616/// Removes constraints unsupported by Anthropic's structured-output grammar.
617fn strip_anthropic_unsupported_constraints(value: &mut Value) -> bool {
618    match value {
619        Value::Object(object) => {
620            let mut removed = false;
621            for key in ["minimum", "maximum", "minLength", "maxLength"] {
622                removed |= object.remove(key).is_some();
623            }
624            // Property/definition names and literal values are not schema keywords.
625            for (key, value) in object.iter_mut() {
626                match key.as_str() {
627                    "properties" | "patternProperties" | "$defs" | "definitions"
628                    | "dependentSchemas" | "dependencies" => {
629                        if let Value::Object(schemas) = value {
630                            for schema in schemas.values_mut() {
631                                removed |= strip_anthropic_unsupported_constraints(schema);
632                            }
633                        }
634                    }
635                    "items"
636                    | "additionalItems"
637                    | "prefixItems"
638                    | "contains"
639                    | "additionalProperties"
640                    | "unevaluatedItems"
641                    | "unevaluatedProperties"
642                    | "propertyNames"
643                    | "allOf"
644                    | "anyOf"
645                    | "oneOf"
646                    | "not"
647                    | "if"
648                    | "then"
649                    | "else"
650                    | "contentSchema" => {
651                        removed |= strip_anthropic_unsupported_constraints(value);
652                    }
653                    _ => {}
654                }
655            }
656            removed
657        }
658        Value::Array(values) => {
659            let mut removed = false;
660            for value in values {
661                removed |= strip_anthropic_unsupported_constraints(value);
662            }
663            removed
664        }
665        _ => false,
666    }
667}
668
669// Decodes Anthropic's `system` field into instruction blocks.
670fn decode_anthropic_system(value: &Value) -> Result<Option<Vec<ContentBlock>>> {
671    match value {
672        Value::String(text) if !text.is_empty() => {
673            Ok(Some(vec![ContentBlock::Text { text: text.clone() }]))
674        }
675        Value::String(_) | Value::Null => Ok(None),
676        Value::Array(blocks) => {
677            let mut content = Vec::new();
678            for block in blocks {
679                if let Some(block) = block.as_object()
680                    && block.get("type").and_then(Value::as_str) == Some("text")
681                {
682                    let text = block
683                        .get("text")
684                        .and_then(Value::as_str)
685                        .unwrap_or_default()
686                        .to_string();
687                    content.push(ContentBlock::Text { text });
688                }
689            }
690            Ok((!content.is_empty()).then_some(content))
691        }
692        _ => Err(TranslationError::InvalidType {
693            path: "$.system".to_string(),
694            expected: "string or array of text blocks",
695        }),
696    }
697}
698
699// Decodes Anthropic message content into normalized content blocks.
700fn decode_anthropic_content(
701    value: &Value,
702    role: Role,
703    generated_counter: usize,
704    diagnostics: &mut Vec<TranslationDiagnostic>,
705    policy: &TranslationPolicy,
706) -> Result<Vec<ContentBlock>> {
707    match value {
708        Value::String(text) => Ok(vec![ContentBlock::Text { text: text.clone() }]),
709        Value::Null => Ok(vec![ContentBlock::Text {
710            text: String::new(),
711        }]),
712        Value::Array(blocks) => {
713            let mut content = Vec::new();
714            for (index, block) in blocks.iter().enumerate() {
715                let Some(block) = block.as_object() else {
716                    push_lossy(
717                        diagnostics,
718                        policy,
719                        format!("Anthropic content block {index} is not an object"),
720                    )?;
721                    continue;
722                };
723                content.extend(decode_anthropic_content_block(
724                    block,
725                    role,
726                    generated_counter + index,
727                    diagnostics,
728                    policy,
729                )?);
730            }
731            if content.is_empty() {
732                content.push(ContentBlock::Text {
733                    text: String::new(),
734                });
735            }
736            Ok(content)
737        }
738        other => Ok(vec![ContentBlock::Text {
739            text: string_value(other).unwrap_or_default(),
740        }]),
741    }
742}
743
744// Decodes one Anthropic content block into one or more IR blocks.
745fn decode_anthropic_content_block(
746    block: &Map<String, Value>,
747    _role: Role,
748    generated_counter: usize,
749    _diagnostics: &mut Vec<TranslationDiagnostic>,
750    policy: &TranslationPolicy,
751) -> Result<Vec<ContentBlock>> {
752    Ok(match block.get("type").and_then(Value::as_str) {
753        Some("text") => vec![ContentBlock::Text {
754            text: block
755                .get("text")
756                .and_then(Value::as_str)
757                .unwrap_or_default()
758                .to_string(),
759        }],
760        Some("thinking") => vec![ContentBlock::Reasoning {
761            text: block
762                .get("thinking")
763                .and_then(Value::as_str)
764                .unwrap_or_default()
765                .to_string(),
766            signature: block
767                .get("signature")
768                .and_then(Value::as_str)
769                .filter(|signature| !signature.is_empty())
770                .map(ToOwned::to_owned),
771            details: Vec::new(),
772        }],
773        Some("tool_use") => vec![ContentBlock::ToolCall(ToolCall {
774            id: block
775                .get("id")
776                .and_then(Value::as_str)
777                .filter(|id| !id.is_empty())
778                .map(desanitize_anthropic_tool_use_id)
779                .unwrap_or_else(|| match &policy.deterministic_ids {
780                    DeterministicIdPolicy::GenerateStable { prefix } => {
781                        stable_id(prefix, generated_counter)
782                    }
783                    DeterministicIdPolicy::Preserve => String::new(),
784                }),
785            name: block
786                .get("name")
787                .and_then(Value::as_str)
788                .unwrap_or_default()
789                .to_string(),
790            arguments: block.get("input").cloned().unwrap_or_else(|| json!({})),
791        })],
792        Some("tool_result") => vec![ContentBlock::ToolResult(ToolResult {
793            tool_call_id: block
794                .get("tool_use_id")
795                .and_then(Value::as_str)
796                .map(desanitize_anthropic_tool_use_id)
797                .unwrap_or_default(),
798            content: decode_tool_result_content(block.get("content").unwrap_or(&Value::Null)),
799            is_error: block.get("is_error").and_then(Value::as_bool),
800        })],
801        Some("image") => vec![ContentBlock::Image {
802            source: ImageSource::Raw(Value::Object(block.clone())),
803        }],
804        Some("input_image") | Some("image_url") => decode_image_source(block)
805            .map(|source| vec![ContentBlock::Image { source }])
806            .unwrap_or_default(),
807        Some("input_file") | Some("file") => vec![ContentBlock::File {
808            source: decode_file_source(block),
809        }],
810        Some("document") => vec![ContentBlock::File {
811            source: decode_anthropic_file_source(block),
812        }],
813        _ => vec![ContentBlock::Unknown {
814            provider: WireFormat::AnthropicMessages.into(),
815            raw: Value::Object(block.clone()),
816        }],
817    })
818}
819
820// Preserves supported Anthropic tool-result blocks in the neutral IR.
821fn decode_tool_result_content(value: &Value) -> Vec<ContentBlock> {
822    match value {
823        Value::String(text) => vec![ContentBlock::Text { text: text.clone() }],
824        Value::Array(blocks) => {
825            let mut content = Vec::new();
826            for block in blocks {
827                if let Some(block) = block.as_object() {
828                    match block.get("type").and_then(Value::as_str) {
829                        Some("text") => content.push(ContentBlock::Text {
830                            text: block
831                                .get("text")
832                                .and_then(Value::as_str)
833                                .unwrap_or_default()
834                                .to_string(),
835                        }),
836                        Some("image") => content.push(ContentBlock::Image {
837                            source: ImageSource::Raw(Value::Object(block.clone())),
838                        }),
839                        Some("document") => content.push(ContentBlock::File {
840                            source: decode_anthropic_file_source(block),
841                        }),
842                        _ => content.push(ContentBlock::Unknown {
843                            provider: WireFormat::AnthropicMessages.into(),
844                            raw: Value::Object(block.clone()),
845                        }),
846                    }
847                }
848            }
849            content
850        }
851        Value::Null => vec![ContentBlock::Text {
852            text: String::new(),
853        }],
854        other => vec![ContentBlock::Text {
855            text: json_string(other),
856        }],
857    }
858}
859
860// Keeps Anthropic document fields together for same-format re-encoding.
861fn decode_anthropic_file_source(block: &Map<String, Value>) -> FileSource {
862    FileSource::Raw(Value::Object(block.clone()))
863}
864
865// Decodes Anthropic tool definitions into normalized tool definitions.
866fn decode_anthropic_tools(value: Option<&Value>) -> Vec<Tool> {
867    value
868        .and_then(Value::as_array)
869        .into_iter()
870        .flatten()
871        .filter_map(Value::as_object)
872        .filter_map(|tool| {
873            if tool
874                .get("type")
875                .and_then(Value::as_str)
876                .is_some_and(|kind| kind != "custom")
877            {
878                return Some(Tool::Provider {
879                    provider: WireFormat::AnthropicMessages.into(),
880                    raw: Value::Object(tool.clone()),
881                });
882            }
883            let name = tool.get("name").and_then(Value::as_str)?.to_string();
884            (!name.is_empty()).then(|| {
885                Tool::Function(ToolDefinition {
886                    name,
887                    description: tool
888                        .get("description")
889                        .and_then(Value::as_str)
890                        .map(ToOwned::to_owned),
891                    parameters: tool
892                        .get("input_schema")
893                        .cloned()
894                        .unwrap_or_else(|| json!({})),
895                    strict: tool.get("strict").and_then(Value::as_bool),
896                })
897            })
898        })
899        .collect()
900}
901
902// Decodes Anthropic tool-choice values into normalized policy.
903fn decode_anthropic_tool_choice(value: &Value) -> ToolChoice {
904    match value {
905        Value::String(text) if text == "auto" => ToolChoice::Auto,
906        Value::String(text) if text == "any" => ToolChoice::Required,
907        Value::String(text) if text == "none" => ToolChoice::None,
908        Value::Object(object) => match object.get("type").and_then(Value::as_str) {
909            Some("auto") => ToolChoice::Auto,
910            Some("any") => ToolChoice::Required,
911            Some("none") => ToolChoice::None,
912            Some("tool") => object
913                .get("name")
914                .and_then(Value::as_str)
915                .map(|name| ToolChoice::Tool {
916                    name: name.to_string(),
917                })
918                .unwrap_or_else(|| ToolChoice::Raw(value.clone())),
919            _ => ToolChoice::Raw(value.clone()),
920        },
921        _ => ToolChoice::Raw(value.clone()),
922    }
923}
924
925// Encodes one normalized message into Anthropic message JSON.
926fn encode_anthropic_message(
927    message: &Message,
928    diagnostics: &mut Vec<TranslationDiagnostic>,
929    policy: &TranslationPolicy,
930) -> Result<Value> {
931    let role = match message.role {
932        Role::Assistant => "assistant",
933        Role::User | Role::Tool | Role::System | Role::Developer => "user",
934    };
935    let content = encode_anthropic_content_with_policy(&message.content, diagnostics, policy)?;
936    let simple_text = content.len() == 1
937        && content
938            .first()
939            .and_then(Value::as_object)
940            .and_then(|object| object.get("type"))
941            .and_then(Value::as_str)
942            == Some("text");
943    let content = if simple_text {
944        content
945            .first()
946            .and_then(Value::as_object)
947            .and_then(|object| object.get("text"))
948            .cloned()
949            .unwrap_or_else(|| Value::String(String::new()))
950    } else {
951        Value::Array(content)
952    };
953    Ok(json!({"role": role, "content": content}))
954}
955
956// Encodes messages while grouping adjacent tool-result-only messages correctly.
957fn encode_anthropic_messages(
958    messages: &[Message],
959    diagnostics: &mut Vec<TranslationDiagnostic>,
960    policy: &TranslationPolicy,
961) -> Result<Vec<Value>> {
962    let mut encoded = Vec::new();
963    let mut index = 0;
964
965    while let Some(message) = messages.get(index) {
966        // Inline instructions are emitted in the top-level system field.
967        if matches!(message.role, Role::System | Role::Developer) {
968            index += 1;
969            continue;
970        }
971        if !message_is_tool_result_only(message) {
972            encoded.push(encode_anthropic_message(message, diagnostics, policy)?);
973            index += 1;
974            continue;
975        }
976
977        let mut content = Vec::new();
978        while let Some(tool_message) = messages.get(index) {
979            if matches!(tool_message.role, Role::System | Role::Developer) {
980                index += 1;
981                continue;
982            }
983            if !message_is_tool_result_only(tool_message) {
984                break;
985            }
986            content.extend(encode_anthropic_content_with_policy(
987                &tool_message.content,
988                diagnostics,
989                policy,
990            )?);
991            index += 1;
992        }
993        encoded.push(json!({"role": "user", "content": content}));
994    }
995
996    Ok(encoded)
997}
998
999// Maps preserved OpenAI-style stop extensions to Anthropic stop sequences.
1000fn anthropic_stop_sequences_from_extensions(extensions: &Map<String, Value>) -> Option<Value> {
1001    match extensions.get("stop") {
1002        Some(Value::String(stop)) => Some(json!([stop])),
1003        Some(Value::Array(stops)) => Some(Value::Array(stops.clone())),
1004        _ => None,
1005    }
1006}
1007
1008// Checks whether a message contains only tool-result blocks.
1009fn message_is_tool_result_only(message: &Message) -> bool {
1010    (message.role == Role::Tool || message.role == Role::User)
1011        && !message.content.is_empty()
1012        && message
1013            .content
1014            .iter()
1015            .all(|block| matches!(block, ContentBlock::ToolResult(_)))
1016}
1017
1018// Encodes content while applying lossy-conversion policy to unknown blocks.
1019fn encode_anthropic_content_with_policy(
1020    content: &[ContentBlock],
1021    diagnostics: &mut Vec<TranslationDiagnostic>,
1022    policy: &TranslationPolicy,
1023) -> Result<Vec<Value>> {
1024    let mut blocks = Vec::new();
1025    for block in content {
1026        crate::codecs::openai_media::validate_media(block, WireFormat::AnthropicMessages)?;
1027        match block {
1028            ContentBlock::Unknown { provider, raw } => {
1029                reject_responses_native_input_item(provider, raw, WireFormat::AnthropicMessages)?;
1030                push_lossy(
1031                    diagnostics,
1032                    policy,
1033                    "unknown content block encoded as text for Anthropic",
1034                )?;
1035                blocks.push(json!({"type": "text", "text": json_string(raw)}));
1036            }
1037            other => blocks.extend(encode_one_anthropic_block(other)?),
1038        }
1039    }
1040    if blocks.is_empty() {
1041        blocks.push(json!({"type": "text", "text": ""}));
1042    }
1043    Ok(blocks)
1044}
1045
1046fn encode_anthropic_file(source: &FileSource) -> Result<Value> {
1047    match source {
1048        FileSource::FileData { data, filename } => {
1049            let (media_type, data) = split_base64_data_uri(data)
1050                .unwrap_or_else(|| (document_media_type(filename.as_deref()), data.as_str()));
1051            let source = match media_type {
1052                "text/plain" => {
1053                    let bytes =
1054                        STANDARD
1055                            .decode(data)
1056                            .map_err(|_| TranslationError::InvalidValue {
1057                                path: "file_data".into(),
1058                                message: "invalid base64 text document".into(),
1059                            })?;
1060                    let text =
1061                        String::from_utf8(bytes).map_err(|_| TranslationError::InvalidValue {
1062                            path: "file_data".into(),
1063                            message: "text document must be UTF-8".into(),
1064                        })?;
1065                    json!({"type": "text", "media_type": media_type, "data": text})
1066                }
1067                "application/pdf" => {
1068                    json!({"type": "base64", "media_type": media_type, "data": data})
1069                }
1070                _ => {
1071                    return Err(TranslationError::LossyConversion(
1072                        "Anthropic requires PDF or plain-text documents".into(),
1073                    ));
1074                }
1075            };
1076            let mut block = json!({"type": "document", "source": source});
1077            if let Some(filename) = filename {
1078                block["title"] = filename.clone().into();
1079            }
1080            Ok(block)
1081        }
1082        FileSource::Raw(raw) if raw.get("type").and_then(Value::as_str) == Some("input_file") => {
1083            let url = raw.get("file_url").and_then(Value::as_str).ok_or_else(|| {
1084                TranslationError::LossyConversion("unsupported Anthropic document source".into())
1085            })?;
1086            let mut block = json!({"type": "document", "source": {"type": "url", "url": url}});
1087            if let Some(filename) = raw.get("filename") {
1088                block["title"] = filename.clone();
1089            }
1090            Ok(block)
1091        }
1092        FileSource::Raw(raw) => Ok(raw.clone()),
1093        FileSource::FileId(file_id) => Ok(json!({
1094            "type": "document", "source": {"type": "file", "file_id": file_id}
1095        })),
1096    }
1097}
1098
1099// Encodes content without producing diagnostics for response paths.
1100fn encode_anthropic_content(content: &[ContentBlock]) -> Result<Vec<Value>> {
1101    let mut blocks = Vec::new();
1102    for block in content {
1103        crate::codecs::openai_media::validate_media(block, WireFormat::AnthropicMessages)?;
1104        blocks.extend(encode_one_anthropic_response_block(block)?);
1105    }
1106    if blocks.is_empty() {
1107        blocks.push(json!({"type": "text", "text": ""}));
1108    }
1109    Ok(blocks)
1110}
1111
1112// Encodes response content, where synthetic reasoning may be shown to clients.
1113fn encode_one_anthropic_response_block(block: &ContentBlock) -> Result<Vec<Value>> {
1114    match block {
1115        ContentBlock::Reasoning {
1116            text,
1117            signature: None,
1118            ..
1119        } => Ok(vec![json!({
1120            "type": "thinking",
1121            "thinking": text,
1122            "signature": "",
1123        })]),
1124        other => encode_one_anthropic_block(other),
1125    }
1126}
1127
1128// Encodes a single normalized content block into Anthropic block JSON.
1129fn encode_one_anthropic_block(block: &ContentBlock) -> Result<Vec<Value>> {
1130    Ok(match block {
1131        ContentBlock::Text { text } | ContentBlock::Refusal { text } => {
1132            vec![json!({"type": "text", "text": text})]
1133        }
1134        ContentBlock::Reasoning {
1135            text,
1136            signature: Some(signature),
1137            ..
1138        } if !signature.is_empty() => vec![json!({
1139            "type": "thinking",
1140            "thinking": text,
1141            "signature": signature,
1142        })],
1143        ContentBlock::Reasoning { .. } => Vec::new(),
1144        ContentBlock::ToolCall(call) => vec![json!({
1145            "type": "tool_use",
1146            "id": sanitize_anthropic_tool_use_id(&call.id),
1147            "name": call.name,
1148            "input": anthropic_tool_input(&call.arguments),
1149        })],
1150        ContentBlock::ToolResult(result) => {
1151            let content = if result.content.iter().all(|block| {
1152                matches!(
1153                    block,
1154                    ContentBlock::Text { .. } | ContentBlock::Refusal { .. }
1155                )
1156            }) {
1157                Value::String(text_from_blocks(&result.content, " "))
1158            } else {
1159                let mut content = Vec::new();
1160                for block in &result.content {
1161                    content.extend(encode_one_anthropic_tool_result_block(block)?);
1162                }
1163                Value::Array(content)
1164            };
1165            let mut item = json!({
1166                "type": "tool_result",
1167                "tool_use_id": sanitize_anthropic_tool_use_id(&result.tool_call_id),
1168                "content": content,
1169            });
1170            if let Some(is_error) = result.is_error {
1171                item["is_error"] = Value::Bool(is_error);
1172            }
1173            vec![item]
1174        }
1175        ContentBlock::Image { source } => vec![match source {
1176            ImageSource::Url { url, .. } => match split_base64_data_uri(url) {
1177                Some((media_type, data)) => json!({
1178                    "type": "image",
1179                    "source": {"type": "base64", "media_type": media_type, "data": data},
1180                }),
1181                None => json!({"type": "image", "source": {"type": "url", "url": url}}),
1182            },
1183            ImageSource::Base64 { media_type, data } => json!({
1184                "type": "image",
1185                "source": {
1186                    "type": "base64",
1187                    "media_type": media_type.clone().unwrap_or_else(|| "image/png".to_string()),
1188                    "data": data,
1189                },
1190            }),
1191            ImageSource::Raw(raw) => raw.clone(),
1192        }],
1193        ContentBlock::File { source } => vec![encode_anthropic_file(source)?],
1194        ContentBlock::Audio { source } => vec![match source {
1195            MediaSource::Url { url, media_type } => {
1196                json!({"type": "audio", "source": {"type": "url", "url": url, "media_type": media_type}})
1197            }
1198            MediaSource::Base64 { media_type, data } => json!({
1199                "type": "audio",
1200                "source": {
1201                    "type": "base64",
1202                    "media_type": media_type.clone().unwrap_or_else(|| "audio/mpeg".to_string()),
1203                    "data": data,
1204                },
1205            }),
1206            MediaSource::Raw(raw) => raw.clone(),
1207        }],
1208        ContentBlock::Video { source } => vec![match source {
1209            MediaSource::Url { url, media_type } => {
1210                json!({"type": "video", "source": {"type": "url", "url": url, "media_type": media_type}})
1211            }
1212            MediaSource::Base64 { media_type, data } => json!({
1213                "type": "video",
1214                "source": {
1215                    "type": "base64",
1216                    "media_type": media_type.clone().unwrap_or_else(|| "video/mp4".to_string()),
1217                    "data": data,
1218                },
1219            }),
1220            MediaSource::Raw(raw) => raw.clone(),
1221        }],
1222        ContentBlock::Mcp(_) => {
1223            return Err(TranslationError::LossyConversion(
1224                "MCP history encoding is not implemented".into(),
1225            ));
1226        }
1227        ContentBlock::Unknown { raw, .. } => vec![raw.clone()],
1228    })
1229}
1230
1231// Encodes only provider-safe block shapes inside Anthropic tool results.
1232fn encode_one_anthropic_tool_result_block(block: &ContentBlock) -> Result<Vec<Value>> {
1233    match block {
1234        ContentBlock::Text { .. }
1235        | ContentBlock::Refusal { .. }
1236        | ContentBlock::Image { .. }
1237        | ContentBlock::File { .. } => encode_one_anthropic_block(block),
1238        ContentBlock::Unknown { provider, raw }
1239            if provider.as_str() == WireFormat::AnthropicMessages.as_str() =>
1240        {
1241            Ok(vec![raw.clone()])
1242        }
1243        ContentBlock::Unknown { raw, .. } => {
1244            Ok(vec![json!({"type": "text", "text": json_string(raw)})])
1245        }
1246        ContentBlock::Mcp(_) => Err(TranslationError::LossyConversion(
1247            "MCP history encoding is not implemented".into(),
1248        )),
1249        ContentBlock::Reasoning { .. }
1250        | ContentBlock::Audio { .. }
1251        | ContentBlock::Video { .. }
1252        | ContentBlock::ToolCall(_)
1253        | ContentBlock::ToolResult(_) => Ok(Vec::new()),
1254    }
1255}
1256
1257// Anthropic accepts PDF and plain-text documents; a file with no media type is a PDF
1258// unless its name says otherwise.
1259fn document_media_type(filename: Option<&str>) -> &'static str {
1260    match filename
1261        .and_then(|name| name.rsplit_once('.'))
1262        .map(|(_, ext)| ext)
1263    {
1264        Some(ext) if ext.eq_ignore_ascii_case("txt") || ext.eq_ignore_ascii_case("md") => {
1265            "text/plain"
1266        }
1267        _ => "application/pdf",
1268    }
1269}
1270
1271// Splits `data:<media type>[;<parameter>...];base64,<payload>`, the form OpenAI-compatible
1272// clients use for inline images. A percent-encoded payload has to be decoded before it is
1273// base64, and a data URI with no media type leaves Anthropic's `media_type` with nothing to
1274// carry, so both keep the handling they had before and are relayed as-is.
1275fn split_base64_data_uri(url: &str) -> Option<(&str, &str)> {
1276    let (metadata, data) = url.strip_prefix("data:")?.split_once(',')?;
1277    let parameters = metadata.strip_suffix(";base64")?;
1278    let media_type = parameters
1279        .split_once(';')
1280        .map_or(parameters, |(media_type, _)| media_type);
1281    if media_type.is_empty() || data.contains('%') {
1282        return None;
1283    }
1284    Some((media_type, data))
1285}
1286
1287// Anthropic requires `tool_use.input` to be object-shaped, while OpenAI and
1288// Responses commonly carry function-call arguments as JSON strings.
1289fn anthropic_tool_input(arguments: &Value) -> Value {
1290    match arguments {
1291        Value::Object(object) => Value::Object(object.clone()),
1292        Value::String(text) => serde_json::from_str::<Value>(text)
1293            .map_or_else(|_| json!({"raw": text}), ensure_anthropic_tool_input_object),
1294        Value::Null => json!({}),
1295        other => json!({"value": other}),
1296    }
1297}
1298
1299// Preserve valid objects and wrap every other JSON shape in a dictionary so
1300// translated requests satisfy Anthropic's schema without discarding payloads.
1301fn ensure_anthropic_tool_input_object(arguments: Value) -> Value {
1302    match arguments {
1303        Value::Object(_) => arguments,
1304        Value::Null => json!({}),
1305        other => json!({"value": other}),
1306    }
1307}
1308
1309// Encodes normalized tool definitions into Anthropic tool JSON.
1310fn encode_anthropic_tools(tools: &[Tool]) -> Result<Value> {
1311    let mut names = std::collections::HashSet::new();
1312    Ok(Value::Array(
1313        tools
1314            .iter()
1315            .map(|tool| {
1316                if let Tool::Provider { provider, raw } = tool
1317                    && provider.as_str() == WireFormat::AnthropicMessages.as_str()
1318                {
1319                    return Ok(raw.clone());
1320                }
1321                let tool = tool.function().ok_or_else(|| {
1322                    TranslationError::LossyConversion(
1323                        "MCP and provider tool encoding is not implemented".into(),
1324                    )
1325                })?;
1326                if !names.insert(tool.name.as_str()) {
1327                    return Err(TranslationError::InvalidValue {
1328                        path: "$.tools".to_string(),
1329                        message: format!("duplicate tool name: {:?}", tool.name),
1330                    });
1331                }
1332                let mut item = json!({
1333                    "name": tool.name,
1334                    "description": tool.description.clone().unwrap_or_default(),
1335                    "input_schema": tool.parameters,
1336                });
1337                if let Some(strict) = tool.strict {
1338                    item["strict"] = Value::Bool(strict);
1339                }
1340                Ok(item)
1341            })
1342            .collect::<Result<_>>()?,
1343    ))
1344}
1345
1346// Encodes normalized tool choice into Anthropic tool-choice JSON.
1347fn encode_anthropic_tool_choice(choice: &ToolChoice) -> Value {
1348    match choice {
1349        ToolChoice::Auto => json!({"type": "auto"}),
1350        ToolChoice::Required => json!({"type": "any"}),
1351        ToolChoice::None => json!({"type": "none"}),
1352        ToolChoice::Tool { name } => json!({"type": "tool", "name": name}),
1353        ToolChoice::Raw(value) => value.clone(),
1354    }
1355}
1356
1357// Normalizes Anthropic usage fields.
1358fn decode_anthropic_usage(value: Option<&Value>) -> Usage {
1359    let Some(value) = value.and_then(Value::as_object) else {
1360        return Usage::default();
1361    };
1362    let input_tokens = value.get("input_tokens").and_then(Value::as_u64);
1363    let cached_input_tokens = value.get("cache_read_input_tokens").and_then(Value::as_u64);
1364    let cache_creation_input_tokens = value
1365        .get("cache_creation_input_tokens")
1366        .and_then(Value::as_u64);
1367    let output_tokens = value.get("output_tokens").and_then(Value::as_u64);
1368    Usage {
1369        provider_cost: crate::codecs::common::provider_cost(value),
1370        input_tokens,
1371        cache: crate::codecs::common::cache_usage_details(
1372            value,
1373            cached_input_tokens,
1374            cache_creation_input_tokens,
1375        ),
1376        output_tokens,
1377        total_tokens: input_tokens.zip(output_tokens).map(|(input, output)| {
1378            input
1379                + cached_input_tokens.unwrap_or(0)
1380                + cache_creation_input_tokens.unwrap_or(0)
1381                + output
1382        }),
1383        reasoning_tokens: value.get("output_tokens_details").and_then(|details| {
1384            details
1385                .get("thinking_tokens")
1386                .and_then(Value::as_u64)
1387                .or_else(|| details.get("reasoning_tokens").and_then(Value::as_u64))
1388        }),
1389    }
1390}
1391
1392// Encodes normalized usage into Anthropic usage JSON.
1393fn encode_anthropic_usage(usage: &Usage) -> Value {
1394    let mut value = json!({
1395        "input_tokens": usage.input_tokens.unwrap_or(0),
1396        "output_tokens": usage.output_tokens.unwrap_or(0),
1397    });
1398    if let Some(cached_tokens) = usage.cached_input_tokens() {
1399        value["cache_read_input_tokens"] = json!(cached_tokens);
1400    }
1401    if let Some(cache_creation_tokens) = usage.cache_creation_input_tokens() {
1402        value["cache_creation_input_tokens"] = json!(cache_creation_tokens);
1403    }
1404    if let Some(thinking_tokens) = usage.reasoning_tokens {
1405        value["output_tokens_details"] = json!({"thinking_tokens": thinking_tokens});
1406    }
1407    crate::codecs::common::encode_usage_metadata(value, usage)
1408}
1409
1410// Maps Anthropic stop reasons to normalized stop reasons.
1411fn map_anthropic_stop_reason(reason: Option<&str>) -> StopReason {
1412    match reason {
1413        Some("max_tokens") => StopReason::MaxTokens,
1414        Some("tool_use") => StopReason::ToolUse,
1415        Some("refusal") => StopReason::ContentFilter,
1416        Some("end_turn") | None => StopReason::EndTurn,
1417        _ => StopReason::Unknown,
1418    }
1419}
1420
1421// Maps normalized stop reasons back to Anthropic's vocabulary.
1422fn anthropic_stop_reason(reason: StopReason) -> &'static str {
1423    match reason {
1424        StopReason::MaxTokens => "max_tokens",
1425        StopReason::ToolUse => "tool_use",
1426        StopReason::ContentFilter => "refusal",
1427        StopReason::EndTurn | StopReason::Error | StopReason::Unknown => "end_turn",
1428    }
1429}
1430
1431// Emits the metadata object Anthropic pairs with a `refusal` stop reason.
1432//
1433// An Anthropic source keeps its `stop_details` in provider extensions, so replay that
1434// object and preserve the named policy category and its explanation. Only a refusal
1435// synthesized from a provider that reports no category falls back to the null form,
1436// which Anthropic documents as the normal value for a refusal that maps to no named
1437// category.
1438fn anthropic_stop_details(reason: StopReason, source: Option<&Value>) -> Value {
1439    match reason {
1440        StopReason::ContentFilter => source
1441            .filter(|details| !details.is_null())
1442            .cloned()
1443            .unwrap_or_else(|| {
1444                json!({
1445                    "type": "refusal",
1446                    "category": Value::Null,
1447                    "explanation": Value::Null,
1448                })
1449            }),
1450        _ => Value::Null,
1451    }
1452}