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 body.get("stop_reason").and_then(Value::as_str) == Some("refusal") {
423            content.push(ContentBlock::Refusal {
424                text: decode_anthropic_refusal(body.get("stop_details")),
425            });
426        }
427        if content.is_empty() {
428            content.push(ContentBlock::Text {
429                text: String::new(),
430            });
431        }
432        let response = AggLlmResponse {
433            id: body
434                .get("id")
435                .and_then(Value::as_str)
436                .map(ToOwned::to_owned),
437            model: body
438                .get("model")
439                .and_then(Value::as_str)
440                .map(ToOwned::to_owned),
441            outputs: vec![ResponseOutput {
442                url_citations: Vec::new(),
443                role: Role::Assistant,
444                content,
445                stop_reason: Some(map_anthropic_stop_reason(
446                    body.get("stop_reason").and_then(Value::as_str),
447                )),
448            }],
449            usage: decode_anthropic_usage(body.get("usage")),
450            extensions: ProviderExtensions {
451                fields: provider_extensions(
452                    body,
453                    &[
454                        "id",
455                        "type",
456                        "role",
457                        "model",
458                        "content",
459                        "stop_reason",
460                        "stop_details",
461                        "usage",
462                    ],
463                ),
464            },
465            preservation: capture_response_preservation(
466                WireFormat::AnthropicMessages,
467                &Value::Object(body.clone()),
468                _policy,
469            ),
470        };
471        Ok(DecodedResponse {
472            response,
473            diagnostics: Vec::new(),
474        })
475    }
476
477    fn encode_response(
478        &self,
479        response: &AggLlmResponse,
480        _policy: &TranslationPolicy,
481    ) -> Result<EncodedResponse> {
482        super::super::responses::validate_response_output(response, WireFormat::AnthropicMessages)?;
483        if let Some(body) = exact_preserved_response(
484            &response.preservation,
485            WireFormat::AnthropicMessages,
486            _policy,
487        ) {
488            return Ok(EncodedResponse {
489                body,
490                diagnostics: Vec::new(),
491            });
492        }
493        let output = response.first_output();
494        let (content, refusal) = output
495            .map(|output| encode_anthropic_content(&output.content))
496            .transpose()?
497            .unwrap_or_else(|| (vec![json!({"type": "text", "text": ""})], None));
498        let normalized_stop_reason = if refusal.is_some() {
499            Some(StopReason::ContentFilter)
500        } else {
501            output.and_then(|output| output.stop_reason)
502        };
503        let body = json!({
504            "id": response.id.clone().unwrap_or_else(|| "msg_switchyard".to_string()),
505            "type": "message",
506            "role": "assistant",
507            "model": response.model.clone().unwrap_or_else(|| "unknown".to_string()),
508            "content": content,
509            "stop_reason": normalized_stop_reason
510                .map(anthropic_stop_reason)
511                .unwrap_or("end_turn"),
512            "stop_sequence": Value::Null,
513            "stop_details": normalized_stop_reason
514                .map(|reason| anthropic_stop_details(reason, refusal.as_deref()))
515                .unwrap_or(Value::Null),
516            "usage": encode_anthropic_usage(&response.usage),
517        });
518        Ok(EncodedResponse {
519            body: embed_preservation(body, &response.preservation, _policy),
520            diagnostics: Vec::new(),
521        })
522    }
523}
524
525// Reads the current `output_config.format`, or the beta `output_format` it replaced,
526// into the neutral OpenAI-shaped response format.
527fn decode_anthropic_output_format(
528    body: &Map<String, Value>,
529    diagnostics: &mut Vec<TranslationDiagnostic>,
530    policy: &TranslationPolicy,
531) -> Result<Option<Value>> {
532    let Some(format) = body
533        .get("output_config")
534        .and_then(Value::as_object)
535        .and_then(|config| config.get("format"))
536        .or_else(|| body.get("output_format"))
537    else {
538        return Ok(None);
539    };
540    let Some(format) = format.as_object() else {
541        push_lossy(
542            diagnostics,
543            policy,
544            "Anthropic structured output format is not an object; the requested format was dropped",
545        )?;
546        return Ok(None);
547    };
548    if format.get("type").and_then(Value::as_str) != Some("json_schema") {
549        push_lossy(
550            diagnostics,
551            policy,
552            "Anthropic structured output maps only a json_schema format; the requested format was dropped",
553        )?;
554        return Ok(None);
555    }
556    // A non-object schema would reach the upstream as a malformed `json_schema.schema`.
557    let Some(schema) = format.get("schema").filter(|schema| schema.is_object()) else {
558        push_lossy(
559            diagnostics,
560            policy,
561            "Anthropic structured output requires format.schema to be an object; the requested format was dropped",
562        )?;
563        return Ok(None);
564    };
565    Ok(Some(json!({
566        "type": "json_schema",
567        "json_schema": {
568            // Anthropic identifies the schema by position; the neutral shape needs a name.
569            "name": "response",
570            "schema": schema.clone(),
571        },
572    })))
573}
574
575/// Maps the neutral OpenAI-shaped JSON schema to Anthropic's output format.
576fn encode_anthropic_output_format(
577    response_format: &Value,
578    enforcement: Option<bool>,
579    diagnostics: &mut Vec<TranslationDiagnostic>,
580    policy: &TranslationPolicy,
581) -> Result<Option<Value>> {
582    let Some(json_schema) = response_format
583        .as_object()
584        .filter(|format| format.get("type").and_then(Value::as_str) == Some("json_schema"))
585        .and_then(|format| format.get("json_schema"))
586        .and_then(Value::as_object)
587    else {
588        push_lossy(
589            diagnostics,
590            policy,
591            "Anthropic structured output requires an OpenAI JSON schema response format",
592        )?;
593        return Ok(None);
594    };
595    let Some(schema) = json_schema.get("schema") else {
596        push_lossy(
597            diagnostics,
598            policy,
599            "Anthropic structured output requires json_schema.schema",
600        )?;
601        return Ok(None);
602    };
603
604    if enforcement.or_else(|| decode_openai_schema_enforcement(Some(response_format)))
605        == Some(false)
606    {
607        push_lossy(
608            diagnostics,
609            policy,
610            "Anthropic structured output enforces the schema; advisory schema enforcement was strengthened",
611        )?;
612    }
613    let mut schema = schema.clone();
614    if strip_anthropic_unsupported_constraints(&mut schema) {
615        push_lossy(
616            diagnostics,
617            policy,
618            "Anthropic structured output dropped unsupported JSON Schema constraints",
619        )?;
620    }
621    Ok(Some(json!({"type": "json_schema", "schema": schema})))
622}
623
624/// Removes constraints unsupported by Anthropic's structured-output grammar.
625fn strip_anthropic_unsupported_constraints(value: &mut Value) -> bool {
626    match value {
627        Value::Object(object) => {
628            let mut removed = false;
629            for key in ["minimum", "maximum", "minLength", "maxLength"] {
630                removed |= object.remove(key).is_some();
631            }
632            // Property/definition names and literal values are not schema keywords.
633            for (key, value) in object.iter_mut() {
634                match key.as_str() {
635                    "properties" | "patternProperties" | "$defs" | "definitions"
636                    | "dependentSchemas" | "dependencies" => {
637                        if let Value::Object(schemas) = value {
638                            for schema in schemas.values_mut() {
639                                removed |= strip_anthropic_unsupported_constraints(schema);
640                            }
641                        }
642                    }
643                    "items"
644                    | "additionalItems"
645                    | "prefixItems"
646                    | "contains"
647                    | "additionalProperties"
648                    | "unevaluatedItems"
649                    | "unevaluatedProperties"
650                    | "propertyNames"
651                    | "allOf"
652                    | "anyOf"
653                    | "oneOf"
654                    | "not"
655                    | "if"
656                    | "then"
657                    | "else"
658                    | "contentSchema" => {
659                        removed |= strip_anthropic_unsupported_constraints(value);
660                    }
661                    _ => {}
662                }
663            }
664            removed
665        }
666        Value::Array(values) => {
667            let mut removed = false;
668            for value in values {
669                removed |= strip_anthropic_unsupported_constraints(value);
670            }
671            removed
672        }
673        _ => false,
674    }
675}
676
677// Decodes Anthropic's `system` field into instruction blocks.
678fn decode_anthropic_system(value: &Value) -> Result<Option<Vec<ContentBlock>>> {
679    match value {
680        Value::String(text) if !text.is_empty() => {
681            Ok(Some(vec![ContentBlock::Text { text: text.clone() }]))
682        }
683        Value::String(_) | Value::Null => Ok(None),
684        Value::Array(blocks) => {
685            let mut content = Vec::new();
686            for block in blocks {
687                if let Some(block) = block.as_object()
688                    && block.get("type").and_then(Value::as_str) == Some("text")
689                {
690                    let text = block
691                        .get("text")
692                        .and_then(Value::as_str)
693                        .unwrap_or_default()
694                        .to_string();
695                    content.push(ContentBlock::Text { text });
696                }
697            }
698            Ok((!content.is_empty()).then_some(content))
699        }
700        _ => Err(TranslationError::InvalidType {
701            path: "$.system".to_string(),
702            expected: "string or array of text blocks",
703        }),
704    }
705}
706
707// Decodes Anthropic message content into normalized content blocks.
708fn decode_anthropic_content(
709    value: &Value,
710    role: Role,
711    generated_counter: usize,
712    diagnostics: &mut Vec<TranslationDiagnostic>,
713    policy: &TranslationPolicy,
714) -> Result<Vec<ContentBlock>> {
715    match value {
716        Value::String(text) => Ok(vec![ContentBlock::Text { text: text.clone() }]),
717        Value::Null => Ok(vec![ContentBlock::Text {
718            text: String::new(),
719        }]),
720        Value::Array(blocks) => {
721            let mut content = Vec::new();
722            for (index, block) in blocks.iter().enumerate() {
723                let Some(block) = block.as_object() else {
724                    push_lossy(
725                        diagnostics,
726                        policy,
727                        format!("Anthropic content block {index} is not an object"),
728                    )?;
729                    continue;
730                };
731                content.extend(decode_anthropic_content_block(
732                    block,
733                    role,
734                    generated_counter + index,
735                    diagnostics,
736                    policy,
737                )?);
738            }
739            if content.is_empty() {
740                content.push(ContentBlock::Text {
741                    text: String::new(),
742                });
743            }
744            Ok(content)
745        }
746        other => Ok(vec![ContentBlock::Text {
747            text: string_value(other).unwrap_or_default(),
748        }]),
749    }
750}
751
752// Decodes one Anthropic content block into one or more IR blocks.
753fn decode_anthropic_content_block(
754    block: &Map<String, Value>,
755    _role: Role,
756    generated_counter: usize,
757    _diagnostics: &mut Vec<TranslationDiagnostic>,
758    policy: &TranslationPolicy,
759) -> Result<Vec<ContentBlock>> {
760    Ok(match block.get("type").and_then(Value::as_str) {
761        Some("text") => vec![ContentBlock::Text {
762            text: block
763                .get("text")
764                .and_then(Value::as_str)
765                .unwrap_or_default()
766                .to_string(),
767        }],
768        Some("thinking") => vec![ContentBlock::Reasoning {
769            text: block
770                .get("thinking")
771                .and_then(Value::as_str)
772                .unwrap_or_default()
773                .to_string(),
774            signature: block
775                .get("signature")
776                .and_then(Value::as_str)
777                .filter(|signature| !signature.is_empty())
778                .map(ToOwned::to_owned),
779            details: Vec::new(),
780        }],
781        Some("tool_use") => vec![ContentBlock::ToolCall(ToolCall {
782            id: block
783                .get("id")
784                .and_then(Value::as_str)
785                .filter(|id| !id.is_empty())
786                .map(desanitize_anthropic_tool_use_id)
787                .unwrap_or_else(|| match &policy.deterministic_ids {
788                    DeterministicIdPolicy::GenerateStable { prefix } => {
789                        stable_id(prefix, generated_counter)
790                    }
791                    DeterministicIdPolicy::Preserve => String::new(),
792                }),
793            name: block
794                .get("name")
795                .and_then(Value::as_str)
796                .unwrap_or_default()
797                .to_string(),
798            arguments: block.get("input").cloned().unwrap_or_else(|| json!({})),
799        })],
800        Some("tool_result") => vec![ContentBlock::ToolResult(ToolResult {
801            tool_call_id: block
802                .get("tool_use_id")
803                .and_then(Value::as_str)
804                .map(desanitize_anthropic_tool_use_id)
805                .unwrap_or_default(),
806            content: decode_tool_result_content(block.get("content").unwrap_or(&Value::Null)),
807            is_error: block.get("is_error").and_then(Value::as_bool),
808        })],
809        Some("image") => vec![ContentBlock::Image {
810            source: ImageSource::Raw(Value::Object(block.clone())),
811        }],
812        Some("input_image") | Some("image_url") => decode_image_source(block)
813            .map(|source| vec![ContentBlock::Image { source }])
814            .unwrap_or_default(),
815        Some("input_file") | Some("file") => vec![ContentBlock::File {
816            source: decode_file_source(block),
817        }],
818        Some("document") => vec![ContentBlock::File {
819            source: decode_anthropic_file_source(block),
820        }],
821        _ => vec![ContentBlock::Unknown {
822            provider: WireFormat::AnthropicMessages.into(),
823            raw: Value::Object(block.clone()),
824        }],
825    })
826}
827
828// Preserves supported Anthropic tool-result blocks in the neutral IR.
829fn decode_tool_result_content(value: &Value) -> Vec<ContentBlock> {
830    match value {
831        Value::String(text) => vec![ContentBlock::Text { text: text.clone() }],
832        Value::Array(blocks) => {
833            let mut content = Vec::new();
834            for block in blocks {
835                if let Some(block) = block.as_object() {
836                    match block.get("type").and_then(Value::as_str) {
837                        Some("text") => content.push(ContentBlock::Text {
838                            text: block
839                                .get("text")
840                                .and_then(Value::as_str)
841                                .unwrap_or_default()
842                                .to_string(),
843                        }),
844                        Some("image") => content.push(ContentBlock::Image {
845                            source: ImageSource::Raw(Value::Object(block.clone())),
846                        }),
847                        Some("document") => content.push(ContentBlock::File {
848                            source: decode_anthropic_file_source(block),
849                        }),
850                        _ => content.push(ContentBlock::Unknown {
851                            provider: WireFormat::AnthropicMessages.into(),
852                            raw: Value::Object(block.clone()),
853                        }),
854                    }
855                }
856            }
857            content
858        }
859        Value::Null => vec![ContentBlock::Text {
860            text: String::new(),
861        }],
862        other => vec![ContentBlock::Text {
863            text: json_string(other),
864        }],
865    }
866}
867
868// Keeps Anthropic document fields together for same-format re-encoding.
869fn decode_anthropic_file_source(block: &Map<String, Value>) -> FileSource {
870    FileSource::Raw(Value::Object(block.clone()))
871}
872
873// Decodes Anthropic tool definitions into normalized tool definitions.
874fn decode_anthropic_tools(value: Option<&Value>) -> Vec<Tool> {
875    value
876        .and_then(Value::as_array)
877        .into_iter()
878        .flatten()
879        .filter_map(Value::as_object)
880        .filter_map(|tool| {
881            if tool
882                .get("type")
883                .and_then(Value::as_str)
884                .is_some_and(|kind| kind != "custom")
885            {
886                return Some(Tool::Provider {
887                    provider: WireFormat::AnthropicMessages.into(),
888                    raw: Value::Object(tool.clone()),
889                });
890            }
891            let name = tool.get("name").and_then(Value::as_str)?.to_string();
892            (!name.is_empty()).then(|| {
893                Tool::Function(ToolDefinition {
894                    name,
895                    description: tool
896                        .get("description")
897                        .and_then(Value::as_str)
898                        .map(ToOwned::to_owned),
899                    parameters: tool
900                        .get("input_schema")
901                        .cloned()
902                        .unwrap_or_else(|| json!({})),
903                    strict: tool.get("strict").and_then(Value::as_bool),
904                })
905            })
906        })
907        .collect()
908}
909
910// Decodes Anthropic tool-choice values into normalized policy.
911fn decode_anthropic_tool_choice(value: &Value) -> ToolChoice {
912    match value {
913        Value::String(text) if text == "auto" => ToolChoice::Auto,
914        Value::String(text) if text == "any" => ToolChoice::Required,
915        Value::String(text) if text == "none" => ToolChoice::None,
916        Value::Object(object) => match object.get("type").and_then(Value::as_str) {
917            Some("auto") => ToolChoice::Auto,
918            Some("any") => ToolChoice::Required,
919            Some("none") => ToolChoice::None,
920            Some("tool") => object
921                .get("name")
922                .and_then(Value::as_str)
923                .map(|name| ToolChoice::Tool {
924                    name: name.to_string(),
925                })
926                .unwrap_or_else(|| ToolChoice::Raw(value.clone())),
927            _ => ToolChoice::Raw(value.clone()),
928        },
929        _ => ToolChoice::Raw(value.clone()),
930    }
931}
932
933// Encodes one normalized message into Anthropic message JSON.
934fn encode_anthropic_message(
935    message: &Message,
936    diagnostics: &mut Vec<TranslationDiagnostic>,
937    policy: &TranslationPolicy,
938) -> Result<Value> {
939    let role = match message.role {
940        Role::Assistant => "assistant",
941        Role::User | Role::Tool | Role::System | Role::Developer => "user",
942    };
943    let content = encode_anthropic_content_with_policy(&message.content, diagnostics, policy)?;
944    let simple_text = content.len() == 1
945        && content
946            .first()
947            .and_then(Value::as_object)
948            .and_then(|object| object.get("type"))
949            .and_then(Value::as_str)
950            == Some("text");
951    let content = if simple_text {
952        content
953            .first()
954            .and_then(Value::as_object)
955            .and_then(|object| object.get("text"))
956            .cloned()
957            .unwrap_or_else(|| Value::String(String::new()))
958    } else {
959        Value::Array(content)
960    };
961    Ok(json!({"role": role, "content": content}))
962}
963
964// Encodes messages while grouping adjacent tool-result-only messages correctly.
965fn encode_anthropic_messages(
966    messages: &[Message],
967    diagnostics: &mut Vec<TranslationDiagnostic>,
968    policy: &TranslationPolicy,
969) -> Result<Vec<Value>> {
970    let mut encoded = Vec::new();
971    let mut index = 0;
972
973    while let Some(message) = messages.get(index) {
974        // Inline instructions are emitted in the top-level system field.
975        if matches!(message.role, Role::System | Role::Developer) {
976            index += 1;
977            continue;
978        }
979        if !message_is_tool_result_only(message) {
980            encoded.push(encode_anthropic_message(message, diagnostics, policy)?);
981            index += 1;
982            continue;
983        }
984
985        let mut content = Vec::new();
986        while let Some(tool_message) = messages.get(index) {
987            if matches!(tool_message.role, Role::System | Role::Developer) {
988                index += 1;
989                continue;
990            }
991            if !message_is_tool_result_only(tool_message) {
992                break;
993            }
994            content.extend(encode_anthropic_content_with_policy(
995                &tool_message.content,
996                diagnostics,
997                policy,
998            )?);
999            index += 1;
1000        }
1001        encoded.push(json!({"role": "user", "content": content}));
1002    }
1003
1004    Ok(encoded)
1005}
1006
1007// Maps preserved OpenAI-style stop extensions to Anthropic stop sequences.
1008fn anthropic_stop_sequences_from_extensions(extensions: &Map<String, Value>) -> Option<Value> {
1009    match extensions.get("stop") {
1010        Some(Value::String(stop)) => Some(json!([stop])),
1011        Some(Value::Array(stops)) => Some(Value::Array(stops.clone())),
1012        _ => None,
1013    }
1014}
1015
1016// Checks whether a message contains only tool-result blocks.
1017fn message_is_tool_result_only(message: &Message) -> bool {
1018    (message.role == Role::Tool || message.role == Role::User)
1019        && !message.content.is_empty()
1020        && message
1021            .content
1022            .iter()
1023            .all(|block| matches!(block, ContentBlock::ToolResult(_)))
1024}
1025
1026// Encodes content while applying lossy-conversion policy to unknown blocks.
1027fn encode_anthropic_content_with_policy(
1028    content: &[ContentBlock],
1029    diagnostics: &mut Vec<TranslationDiagnostic>,
1030    policy: &TranslationPolicy,
1031) -> Result<Vec<Value>> {
1032    let mut blocks = Vec::new();
1033    for block in content {
1034        crate::codecs::openai_media::validate_media(block, WireFormat::AnthropicMessages)?;
1035        match block {
1036            ContentBlock::Unknown { provider, raw } => {
1037                reject_responses_native_input_item(provider, raw, WireFormat::AnthropicMessages)?;
1038                push_lossy(
1039                    diagnostics,
1040                    policy,
1041                    "unknown content block encoded as text for Anthropic",
1042                )?;
1043                blocks.push(json!({"type": "text", "text": json_string(raw)}));
1044            }
1045            other => blocks.extend(encode_one_anthropic_block(other)?),
1046        }
1047    }
1048    if blocks.is_empty() {
1049        blocks.push(json!({"type": "text", "text": ""}));
1050    }
1051    Ok(blocks)
1052}
1053
1054fn encode_anthropic_file(source: &FileSource) -> Result<Value> {
1055    match source {
1056        FileSource::FileData { data, filename } => {
1057            let (media_type, data) = split_base64_data_uri(data)
1058                .unwrap_or_else(|| (document_media_type(filename.as_deref()), data.as_str()));
1059            let source = match media_type {
1060                "text/plain" => {
1061                    let bytes =
1062                        STANDARD
1063                            .decode(data)
1064                            .map_err(|_| TranslationError::InvalidValue {
1065                                path: "file_data".into(),
1066                                message: "invalid base64 text document".into(),
1067                            })?;
1068                    let text =
1069                        String::from_utf8(bytes).map_err(|_| TranslationError::InvalidValue {
1070                            path: "file_data".into(),
1071                            message: "text document must be UTF-8".into(),
1072                        })?;
1073                    json!({"type": "text", "media_type": media_type, "data": text})
1074                }
1075                "application/pdf" => {
1076                    json!({"type": "base64", "media_type": media_type, "data": data})
1077                }
1078                _ => {
1079                    return Err(TranslationError::LossyConversion(
1080                        "Anthropic requires PDF or plain-text documents".into(),
1081                    ));
1082                }
1083            };
1084            let mut block = json!({"type": "document", "source": source});
1085            if let Some(filename) = filename {
1086                block["title"] = filename.clone().into();
1087            }
1088            Ok(block)
1089        }
1090        FileSource::Raw(raw) if raw.get("type").and_then(Value::as_str) == Some("input_file") => {
1091            let url = raw.get("file_url").and_then(Value::as_str).ok_or_else(|| {
1092                TranslationError::LossyConversion("unsupported Anthropic document source".into())
1093            })?;
1094            let mut block = json!({"type": "document", "source": {"type": "url", "url": url}});
1095            if let Some(filename) = raw.get("filename") {
1096                block["title"] = filename.clone();
1097            }
1098            Ok(block)
1099        }
1100        FileSource::Raw(raw) => Ok(raw.clone()),
1101        FileSource::FileId(file_id) => Ok(json!({
1102            "type": "document", "source": {"type": "file", "file_id": file_id}
1103        })),
1104    }
1105}
1106
1107// Encodes content without producing diagnostics for response paths.
1108fn encode_anthropic_content(content: &[ContentBlock]) -> Result<(Vec<Value>, Option<String>)> {
1109    let mut blocks = Vec::new();
1110    let mut refusal = None::<String>;
1111    for block in content {
1112        crate::codecs::openai_media::validate_media(block, WireFormat::AnthropicMessages)?;
1113        if let ContentBlock::Refusal { text } = block {
1114            refusal.get_or_insert_with(String::new).push_str(text);
1115        } else {
1116            blocks.extend(encode_one_anthropic_response_block(block)?);
1117        }
1118    }
1119    if blocks.is_empty() && refusal.is_none() {
1120        blocks.push(json!({"type": "text", "text": ""}));
1121    }
1122    Ok((blocks, refusal))
1123}
1124
1125// Encodes response content, where synthetic reasoning may be shown to clients.
1126fn encode_one_anthropic_response_block(block: &ContentBlock) -> Result<Vec<Value>> {
1127    match block {
1128        ContentBlock::Reasoning {
1129            text,
1130            signature: None,
1131            ..
1132        } => Ok(vec![json!({
1133            "type": "thinking",
1134            "thinking": text,
1135            "signature": "",
1136        })]),
1137        other => encode_one_anthropic_block(other),
1138    }
1139}
1140
1141// Encodes a single normalized content block into Anthropic block JSON.
1142fn encode_one_anthropic_block(block: &ContentBlock) -> Result<Vec<Value>> {
1143    Ok(match block {
1144        ContentBlock::Text { text } | ContentBlock::Refusal { text } => {
1145            vec![json!({"type": "text", "text": text})]
1146        }
1147        ContentBlock::Reasoning {
1148            text,
1149            signature: Some(signature),
1150            ..
1151        } if !signature.is_empty() => vec![json!({
1152            "type": "thinking",
1153            "thinking": text,
1154            "signature": signature,
1155        })],
1156        ContentBlock::Reasoning { .. } => Vec::new(),
1157        ContentBlock::ToolCall(call) => vec![json!({
1158            "type": "tool_use",
1159            "id": sanitize_anthropic_tool_use_id(&call.id),
1160            "name": call.name,
1161            "input": anthropic_tool_input(&call.arguments),
1162        })],
1163        ContentBlock::ToolResult(result) => {
1164            let content = if result.content.iter().all(|block| {
1165                matches!(
1166                    block,
1167                    ContentBlock::Text { .. } | ContentBlock::Refusal { .. }
1168                )
1169            }) {
1170                Value::String(text_from_blocks(&result.content, " "))
1171            } else {
1172                let mut content = Vec::new();
1173                for block in &result.content {
1174                    content.extend(encode_one_anthropic_tool_result_block(block)?);
1175                }
1176                Value::Array(content)
1177            };
1178            let mut item = json!({
1179                "type": "tool_result",
1180                "tool_use_id": sanitize_anthropic_tool_use_id(&result.tool_call_id),
1181                "content": content,
1182            });
1183            if let Some(is_error) = result.is_error {
1184                item["is_error"] = Value::Bool(is_error);
1185            }
1186            vec![item]
1187        }
1188        ContentBlock::Image { source } => vec![match source {
1189            ImageSource::Url { url, .. } => match split_base64_data_uri(url) {
1190                Some((media_type, data)) => json!({
1191                    "type": "image",
1192                    "source": {"type": "base64", "media_type": media_type, "data": data},
1193                }),
1194                None => json!({"type": "image", "source": {"type": "url", "url": url}}),
1195            },
1196            ImageSource::Base64 { media_type, data } => json!({
1197                "type": "image",
1198                "source": {
1199                    "type": "base64",
1200                    "media_type": media_type.clone().unwrap_or_else(|| "image/png".to_string()),
1201                    "data": data,
1202                },
1203            }),
1204            ImageSource::Raw(raw) => raw.clone(),
1205        }],
1206        ContentBlock::File { source } => vec![encode_anthropic_file(source)?],
1207        ContentBlock::Audio { source } => vec![match source {
1208            MediaSource::Url { url, media_type } => {
1209                json!({"type": "audio", "source": {"type": "url", "url": url, "media_type": media_type}})
1210            }
1211            MediaSource::Base64 { media_type, data } => json!({
1212                "type": "audio",
1213                "source": {
1214                    "type": "base64",
1215                    "media_type": media_type.clone().unwrap_or_else(|| "audio/mpeg".to_string()),
1216                    "data": data,
1217                },
1218            }),
1219            MediaSource::Raw(raw) => raw.clone(),
1220        }],
1221        ContentBlock::Video { source } => vec![match source {
1222            MediaSource::Url { url, media_type } => {
1223                json!({"type": "video", "source": {"type": "url", "url": url, "media_type": media_type}})
1224            }
1225            MediaSource::Base64 { media_type, data } => json!({
1226                "type": "video",
1227                "source": {
1228                    "type": "base64",
1229                    "media_type": media_type.clone().unwrap_or_else(|| "video/mp4".to_string()),
1230                    "data": data,
1231                },
1232            }),
1233            MediaSource::Raw(raw) => raw.clone(),
1234        }],
1235        ContentBlock::Mcp(_) => {
1236            return Err(TranslationError::LossyConversion(
1237                "MCP history encoding is not implemented".into(),
1238            ));
1239        }
1240        ContentBlock::Unknown { raw, .. } => vec![raw.clone()],
1241    })
1242}
1243
1244// Encodes only provider-safe block shapes inside Anthropic tool results.
1245fn encode_one_anthropic_tool_result_block(block: &ContentBlock) -> Result<Vec<Value>> {
1246    match block {
1247        ContentBlock::Text { .. }
1248        | ContentBlock::Refusal { .. }
1249        | ContentBlock::Image { .. }
1250        | ContentBlock::File { .. } => encode_one_anthropic_block(block),
1251        ContentBlock::Unknown { provider, raw }
1252            if provider.as_str() == WireFormat::AnthropicMessages.as_str() =>
1253        {
1254            Ok(vec![raw.clone()])
1255        }
1256        ContentBlock::Unknown { raw, .. } => {
1257            Ok(vec![json!({"type": "text", "text": json_string(raw)})])
1258        }
1259        ContentBlock::Mcp(_) => Err(TranslationError::LossyConversion(
1260            "MCP history encoding is not implemented".into(),
1261        )),
1262        ContentBlock::Reasoning { .. }
1263        | ContentBlock::Audio { .. }
1264        | ContentBlock::Video { .. }
1265        | ContentBlock::ToolCall(_)
1266        | ContentBlock::ToolResult(_) => Ok(Vec::new()),
1267    }
1268}
1269
1270// Anthropic accepts PDF and plain-text documents; a file with no media type is a PDF
1271// unless its name says otherwise.
1272fn document_media_type(filename: Option<&str>) -> &'static str {
1273    match filename
1274        .and_then(|name| name.rsplit_once('.'))
1275        .map(|(_, ext)| ext)
1276    {
1277        Some(ext) if ext.eq_ignore_ascii_case("txt") || ext.eq_ignore_ascii_case("md") => {
1278            "text/plain"
1279        }
1280        _ => "application/pdf",
1281    }
1282}
1283
1284// Splits `data:<media type>[;<parameter>...];base64,<payload>`, the form OpenAI-compatible
1285// clients use for inline images. A percent-encoded payload has to be decoded before it is
1286// base64, and a data URI with no media type leaves Anthropic's `media_type` with nothing to
1287// carry, so both keep the handling they had before and are relayed as-is.
1288fn split_base64_data_uri(url: &str) -> Option<(&str, &str)> {
1289    let (metadata, data) = url.strip_prefix("data:")?.split_once(',')?;
1290    let parameters = metadata.strip_suffix(";base64")?;
1291    let media_type = parameters
1292        .split_once(';')
1293        .map_or(parameters, |(media_type, _)| media_type);
1294    if media_type.is_empty() || data.contains('%') {
1295        return None;
1296    }
1297    Some((media_type, data))
1298}
1299
1300// Anthropic requires `tool_use.input` to be object-shaped, while OpenAI and
1301// Responses commonly carry function-call arguments as JSON strings.
1302fn anthropic_tool_input(arguments: &Value) -> Value {
1303    match arguments {
1304        Value::Object(object) => Value::Object(object.clone()),
1305        Value::String(text) => serde_json::from_str::<Value>(text)
1306            .map_or_else(|_| json!({"raw": text}), ensure_anthropic_tool_input_object),
1307        Value::Null => json!({}),
1308        other => json!({"value": other}),
1309    }
1310}
1311
1312// Preserve valid objects and wrap every other JSON shape in a dictionary so
1313// translated requests satisfy Anthropic's schema without discarding payloads.
1314fn ensure_anthropic_tool_input_object(arguments: Value) -> Value {
1315    match arguments {
1316        Value::Object(_) => arguments,
1317        Value::Null => json!({}),
1318        other => json!({"value": other}),
1319    }
1320}
1321
1322// Encodes normalized tool definitions into Anthropic tool JSON.
1323fn encode_anthropic_tools(tools: &[Tool]) -> Result<Value> {
1324    let mut names = std::collections::HashSet::new();
1325    Ok(Value::Array(
1326        tools
1327            .iter()
1328            .map(|tool| {
1329                if let Tool::Provider { provider, raw } = tool
1330                    && provider.as_str() == WireFormat::AnthropicMessages.as_str()
1331                {
1332                    return Ok(raw.clone());
1333                }
1334                let tool = tool.function().ok_or_else(|| {
1335                    TranslationError::LossyConversion(
1336                        "MCP and provider tool encoding is not implemented".into(),
1337                    )
1338                })?;
1339                if !names.insert(tool.name.as_str()) {
1340                    return Err(TranslationError::InvalidValue {
1341                        path: "$.tools".to_string(),
1342                        message: format!("duplicate tool name: {:?}", tool.name),
1343                    });
1344                }
1345                let mut item = json!({
1346                    "name": tool.name,
1347                    "description": tool.description.clone().unwrap_or_default(),
1348                    "input_schema": tool.parameters,
1349                });
1350                if let Some(strict) = tool.strict {
1351                    item["strict"] = Value::Bool(strict);
1352                }
1353                Ok(item)
1354            })
1355            .collect::<Result<_>>()?,
1356    ))
1357}
1358
1359// Encodes normalized tool choice into Anthropic tool-choice JSON.
1360fn encode_anthropic_tool_choice(choice: &ToolChoice) -> Value {
1361    match choice {
1362        ToolChoice::Auto => json!({"type": "auto"}),
1363        ToolChoice::Required => json!({"type": "any"}),
1364        ToolChoice::None => json!({"type": "none"}),
1365        ToolChoice::Tool { name } => json!({"type": "tool", "name": name}),
1366        ToolChoice::Raw(value) => value.clone(),
1367    }
1368}
1369
1370// Normalizes Anthropic usage fields.
1371fn decode_anthropic_usage(value: Option<&Value>) -> Usage {
1372    let Some(value) = value.and_then(Value::as_object) else {
1373        return Usage::default();
1374    };
1375    let input_tokens = value.get("input_tokens").and_then(Value::as_u64);
1376    let cached_input_tokens = value.get("cache_read_input_tokens").and_then(Value::as_u64);
1377    let cache_creation_input_tokens = value
1378        .get("cache_creation_input_tokens")
1379        .and_then(Value::as_u64);
1380    let output_tokens = value.get("output_tokens").and_then(Value::as_u64);
1381    Usage {
1382        provider_cost: crate::codecs::common::provider_cost(value),
1383        input_tokens,
1384        cache: crate::codecs::common::cache_usage_details(
1385            value,
1386            cached_input_tokens,
1387            cache_creation_input_tokens,
1388        ),
1389        output_tokens,
1390        total_tokens: input_tokens.zip(output_tokens).map(|(input, output)| {
1391            input
1392                + cached_input_tokens.unwrap_or(0)
1393                + cache_creation_input_tokens.unwrap_or(0)
1394                + output
1395        }),
1396        reasoning_tokens: value.get("output_tokens_details").and_then(|details| {
1397            details
1398                .get("thinking_tokens")
1399                .and_then(Value::as_u64)
1400                .or_else(|| details.get("reasoning_tokens").and_then(Value::as_u64))
1401        }),
1402    }
1403}
1404
1405// Encodes normalized usage into Anthropic usage JSON.
1406fn encode_anthropic_usage(usage: &Usage) -> Value {
1407    let mut value = json!({
1408        "input_tokens": usage.input_tokens.unwrap_or(0),
1409        "output_tokens": usage.output_tokens.unwrap_or(0),
1410    });
1411    if let Some(cached_tokens) = usage.cached_input_tokens() {
1412        value["cache_read_input_tokens"] = json!(cached_tokens);
1413    }
1414    if let Some(cache_creation_tokens) = usage.cache_creation_input_tokens() {
1415        value["cache_creation_input_tokens"] = json!(cache_creation_tokens);
1416    }
1417    if let Some(thinking_tokens) = usage.reasoning_tokens {
1418        value["output_tokens_details"] = json!({"thinking_tokens": thinking_tokens});
1419    }
1420    crate::codecs::common::encode_usage_metadata(value, usage)
1421}
1422
1423// Anthropic refusal details: https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback
1424pub(super) fn decode_anthropic_refusal(details: Option<&Value>) -> String {
1425    let category = details
1426        .and_then(|details| details.get("category"))
1427        .and_then(Value::as_str);
1428    let explanation = details
1429        .and_then(|details| details.get("explanation"))
1430        .and_then(Value::as_str);
1431    match (category, explanation) {
1432        (Some(category), Some(explanation)) => format!("{category}: {explanation}"),
1433        (Some(text), None) | (None, Some(text)) => text.to_string(),
1434        (None, None) => String::new(),
1435    }
1436}
1437
1438// Maps Anthropic stop reasons to normalized stop reasons.
1439fn map_anthropic_stop_reason(reason: Option<&str>) -> StopReason {
1440    match reason {
1441        Some("max_tokens") => StopReason::MaxTokens,
1442        Some("tool_use") => StopReason::ToolUse,
1443        Some("refusal") => StopReason::ContentFilter,
1444        Some("end_turn") | None => StopReason::EndTurn,
1445        _ => StopReason::Unknown,
1446    }
1447}
1448
1449// Maps normalized stop reasons back to Anthropic's vocabulary.
1450fn anthropic_stop_reason(reason: StopReason) -> &'static str {
1451    match reason {
1452        StopReason::MaxTokens => "max_tokens",
1453        StopReason::ToolUse => "tool_use",
1454        StopReason::ContentFilter => "refusal",
1455        StopReason::EndTurn | StopReason::Error | StopReason::Unknown => "end_turn",
1456    }
1457}
1458
1459// Emits the metadata object Anthropic pairs with a `refusal` stop reason.
1460//
1461// The IR refusal text is opaque; a category prefix must not be parsed back out.
1462fn anthropic_stop_details(reason: StopReason, explanation: Option<&str>) -> Value {
1463    match reason {
1464        StopReason::ContentFilter => json!({
1465            "type": "refusal",
1466            "category": Value::Null,
1467            "explanation": explanation,
1468        }),
1469        _ => Value::Null,
1470    }
1471}