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