Skip to main content

vtcode_llm/providers/anthropic/
compat.rs

1use crate::provider::{
2    AnthropicOptionalStringOverride, AnthropicOptionalU32Override, AnthropicRequestOverrides,
3    AnthropicThinkingDisplayOverride, AnthropicThinkingModeOverride, ContentPart, FinishReason, LLMRequest,
4    LLMResponse, Message, MessageContent, MessageRole, ParallelToolConfig, ToolCall, ToolChoice, ToolDefinition,
5};
6use crate::providers::anthropic_types::{
7    AnthropicOutputConfig, AnthropicOutputFormat, ThinkingConfig, ThinkingDisplay,
8};
9use crate::providers::common::normalize_reasoning_detail_object;
10use serde::ser::SerializeMap;
11use serde::{Deserialize, Serialize, Serializer};
12use serde_json::{Value, json};
13use std::sync::Arc;
14
15/// Anthropic Messages API request.
16#[derive(Debug, Deserialize, Clone)]
17pub struct AnthropicMessagesRequest {
18    pub(crate) model: String,
19    pub(crate) max_tokens: u32,
20    pub(crate) messages: Vec<AnthropicMessage>,
21    #[serde(default)]
22    pub(crate) system: Option<AnthropicSystemPrompt>,
23    #[serde(default)]
24    pub(crate) stream: bool,
25    #[serde(default)]
26    pub(crate) temperature: Option<f32>,
27    #[serde(default)]
28    pub(crate) top_p: Option<f32>,
29    #[serde(default)]
30    pub(crate) top_k: Option<i32>,
31    #[serde(default)]
32    pub(crate) stop_sequences: Option<Vec<String>>,
33    #[serde(default)]
34    pub(crate) tools: Option<Vec<AnthropicTool>>,
35    #[serde(default)]
36    pub(crate) tool_choice: Option<Value>,
37    #[serde(default)]
38    pub(crate) thinking: Option<ThinkingConfig>,
39    #[serde(default)]
40    pub(crate) betas: Option<Vec<String>>,
41    #[serde(default)]
42    pub(crate) context_management: Option<Value>,
43    #[serde(default)]
44    pub(crate) output_config: Option<AnthropicOutputConfig>,
45}
46
47#[derive(Debug, Deserialize, Serialize, Clone)]
48pub struct AnthropicMessage {
49    pub(crate) role: String,
50    pub(crate) content: AnthropicContent,
51}
52
53#[derive(Debug, Deserialize, Serialize, Clone)]
54#[serde(untagged)]
55pub enum AnthropicContent {
56    Text(String),
57    Blocks(Vec<AnthropicContentBlock>),
58}
59
60#[derive(Debug, Deserialize, Serialize, Clone)]
61#[serde(tag = "type")]
62pub enum AnthropicContentBlock {
63    #[serde(rename = "text")]
64    Text {
65        text: String,
66        #[serde(default)]
67        citations: Option<Value>,
68        #[serde(default)]
69        cache_control: Option<Value>,
70    },
71    #[serde(rename = "image")]
72    Image { source: AnthropicImageSource },
73    #[serde(rename = "tool_use")]
74    ToolUse { id: String, name: String, input: Value },
75    #[serde(rename = "tool_result")]
76    ToolResult {
77        tool_use_id: String,
78        content: AnthropicContent,
79        is_error: Option<bool>,
80    },
81    #[serde(rename = "thinking")]
82    Thinking {
83        thinking: String,
84        #[serde(default)]
85        signature: Option<String>,
86    },
87    #[serde(rename = "redacted_thinking")]
88    RedactedThinking { data: String },
89    #[serde(rename = "server_tool_use")]
90    ServerToolUse { id: String, name: String, input: Value },
91    #[serde(rename = "container_upload")]
92    ContainerUpload { file_id: String },
93    #[serde(rename = "code_execution_tool_result")]
94    CodeExecutionToolResult { tool_use_id: String, content: Value },
95    #[serde(rename = "bash_code_execution_tool_result")]
96    BashCodeExecutionToolResult { tool_use_id: String, content: Value },
97    #[serde(rename = "text_editor_code_execution_tool_result")]
98    TextEditorCodeExecutionToolResult { tool_use_id: String, content: Value },
99    #[serde(rename = "web_search_tool_result")]
100    WebSearchToolResult { tool_use_id: String, content: Value },
101    #[serde(rename = "advisor_tool_result")]
102    AdvisorToolResult { tool_use_id: String, content: Value },
103    /// Catch-all for unknown content block types added by the Anthropic API.
104    #[serde(other)]
105    Unknown,
106}
107
108#[derive(Debug, Deserialize, Serialize, Clone)]
109pub struct AnthropicImageSource {
110    r#type: String,
111    media_type: String,
112    data: String,
113}
114
115#[derive(Debug, Deserialize, Serialize, Clone)]
116#[serde(untagged)]
117pub enum AnthropicSystemPrompt {
118    Text(String),
119    Blocks(Vec<AnthropicContentBlock>),
120}
121
122#[derive(Debug, Deserialize, Clone)]
123#[serde(untagged)]
124pub enum AnthropicTool {
125    Advisor {
126        #[serde(rename = "type")]
127        tool_type: String,
128        name: String,
129        model: String,
130        #[serde(default)]
131        max_uses: Option<u32>,
132        #[serde(default)]
133        max_tokens: Option<u32>,
134        #[serde(default)]
135        caching: Option<AnthropicAdvisorCachingCompat>,
136    },
137    Function {
138        name: String,
139        description: Option<String>,
140        input_schema: Value,
141        #[serde(default)]
142        input_examples: Option<Vec<Value>>,
143        #[serde(default)]
144        strict: Option<bool>,
145        #[serde(default)]
146        allowed_callers: Option<Vec<String>>,
147    },
148    Native {
149        #[serde(rename = "type")]
150        tool_type: String,
151        name: String,
152        #[serde(flatten, default)]
153        options: serde_json::Map<String, Value>,
154    },
155}
156
157impl Serialize for AnthropicTool {
158    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
159    where
160        S: Serializer,
161    {
162        match self {
163            Self::Advisor {
164                tool_type,
165                name,
166                model,
167                max_uses,
168                max_tokens,
169                caching,
170            } => {
171                let mut map = serializer.serialize_map(None)?;
172                map.serialize_entry("type", tool_type)?;
173                map.serialize_entry("name", name)?;
174                map.serialize_entry("model", model)?;
175                map.serialize_entry("max_uses", max_uses)?;
176                map.serialize_entry("max_tokens", max_tokens)?;
177                map.serialize_entry("caching", caching)?;
178                map.end()
179            }
180            Self::Function {
181                name,
182                description,
183                input_schema,
184                input_examples,
185                strict,
186                allowed_callers,
187            } => {
188                let mut map = serializer.serialize_map(None)?;
189                map.serialize_entry("name", name)?;
190                map.serialize_entry("description", description)?;
191                map.serialize_entry("input_schema", input_schema)?;
192                map.serialize_entry("input_examples", input_examples)?;
193                map.serialize_entry("strict", strict)?;
194                map.serialize_entry("allowed_callers", allowed_callers)?;
195                map.end()
196            }
197            Self::Native { tool_type, name, options } => {
198                if let Some(key) = ["type", "name"].into_iter().find(|key| options.contains_key(*key)) {
199                    return Err(serde::ser::Error::custom(format!(
200                        "Anthropic native tool extension key '{key}' collides with a reserved wire field"
201                    )));
202                }
203                let mut map = serializer.serialize_map(None)?;
204                map.serialize_entry("type", tool_type)?;
205                map.serialize_entry("name", name)?;
206                for (key, value) in options {
207                    map.serialize_entry(key, value)?;
208                }
209                map.end()
210            }
211        }
212    }
213}
214
215#[derive(Debug, Deserialize, Serialize, Clone)]
216pub struct AnthropicAdvisorCachingCompat {
217    #[serde(rename = "type")]
218    cache_type: String,
219    ttl: String,
220}
221
222#[derive(Debug, Serialize, Clone)]
223pub struct AnthropicMessagesResponse {
224    pub(crate) id: String,
225    pub(crate) r#type: String,
226    pub(crate) role: String,
227    pub(crate) model: String,
228    pub(crate) content: Vec<AnthropicContentBlock>,
229    pub(crate) stop_reason: Option<String>,
230    pub(crate) stop_sequence: Option<String>,
231    pub(crate) usage: AnthropicUsage,
232}
233
234#[derive(Debug, Serialize, Clone)]
235pub struct AnthropicUsage {
236    pub(crate) input_tokens: u32,
237    pub(crate) output_tokens: u32,
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    #[test]
245    fn native_tool_rejects_reserved_extension_keys() {
246        let mut options = serde_json::Map::new();
247        options.insert("type".to_string(), json!("unexpected"));
248        let tool = AnthropicTool::Native {
249            tool_type: "web_search_20250305".to_string(),
250            name: "web_search".to_string(),
251            options,
252        };
253
254        let error = serde_json::to_value(tool).expect_err("reserved extension keys must be rejected");
255        assert!(error.to_string().contains("collides with a reserved wire field"));
256    }
257
258    #[test]
259    fn updates_display_is_only_forwarded_to_models_that_accept_it() {
260        use crate::providers::anthropic::request_builder::{RequestBuilderContext, convert_to_anthropic_format};
261        use vtcode_config::core::{AnthropicConfig, AnthropicPromptCacheSettings};
262
263        let payload_thinking = |model: &str| {
264            let request: AnthropicMessagesRequest = serde_json::from_value(json!({
265                "model": model,
266                "max_tokens": 1024,
267                "messages": [{ "role": "user", "content": "hello" }],
268                "thinking": { "type": "adaptive", "display": "updates" },
269            }))
270            .expect("compat request");
271            let llm_request = convert_anthropic_to_llm_request(request);
272            let anthropic_config = AnthropicConfig::default();
273            let prompt_cache_settings = AnthropicPromptCacheSettings::default();
274            let ctx = RequestBuilderContext {
275                prompt_cache_enabled: false,
276                prompt_cache_settings: &prompt_cache_settings,
277                anthropic_config: &anthropic_config,
278                model,
279                server_side_fallbacks_available: false,
280            };
281            convert_to_anthropic_format(&llm_request, &ctx).expect("payload conversion")["thinking"].clone()
282        };
283
284        assert_eq!(payload_thinking("claude-opus-5-5"), json!({ "type": "adaptive", "display": "updates" }));
285        for model in ["claude-opus-4-8", "claude-sonnet-5", "claude-opus-5"] {
286            assert_eq!(payload_thinking(model), json!({ "type": "adaptive" }), "{model}");
287        }
288    }
289}
290
291#[derive(Debug, Serialize)]
292#[serde(tag = "type")]
293pub enum AnthropicStreamEvent {
294    #[serde(rename = "message_start")]
295    MessageStart { message: AnthropicMessagesResponse },
296    #[serde(rename = "content_block_start")]
297    ContentBlockStart {
298        index: u32,
299        content_block: AnthropicContentBlock,
300    },
301    #[serde(rename = "content_block_delta")]
302    ContentBlockDelta { index: u32, delta: AnthropicContentDelta },
303    #[serde(rename = "content_block_stop")]
304    ContentBlockStop { index: u32 },
305    #[serde(rename = "message_delta")]
306    MessageDelta {
307        delta: AnthropicDelta,
308        usage: AnthropicUsage,
309    },
310    #[serde(rename = "message_stop")]
311    MessageStop,
312    #[serde(rename = "ping")]
313    Ping {},
314    #[serde(rename = "error")]
315    Error { error: AnthropicError },
316}
317
318#[derive(Debug, Serialize)]
319#[serde(tag = "type")]
320pub enum AnthropicContentDelta {
321    #[serde(rename = "text_delta")]
322    TextDelta { text: String },
323    #[serde(rename = "input_json_delta")]
324    InputJsonDelta { partial_json: String },
325    #[serde(rename = "thinking_delta")]
326    ThinkingDelta { thinking: String },
327    #[serde(rename = "signature_delta")]
328    SignatureDelta { signature: String },
329}
330
331#[derive(Debug, Serialize)]
332pub struct AnthropicDelta {
333    pub(crate) stop_reason: Option<String>,
334    pub(crate) stop_sequence: Option<String>,
335}
336
337#[derive(Debug, Serialize)]
338pub struct AnthropicError {
339    pub(crate) r#type: String,
340    pub(crate) message: String,
341}
342
343#[derive(Default)]
344struct ConvertedAnthropicBlocks {
345    content_parts: Vec<ContentPart>,
346    tool_calls: Vec<ToolCall>,
347    reasoning_chunks: Vec<String>,
348    reasoning_details: Vec<Value>,
349    emitted_messages: Vec<Message>,
350}
351
352pub(crate) fn convert_anthropic_to_llm_request(request: AnthropicMessagesRequest) -> LLMRequest {
353    let (tool_choice, parallel_tool_config) = parse_anthropic_tool_choice(request.tool_choice.as_ref());
354    let effort = request.output_config.as_ref().and_then(|config| config.effort.clone());
355    let output_format = request.output_config.as_ref().and_then(|config| {
356        config.format.as_ref().and_then(|format| match format {
357            AnthropicOutputFormat::JsonSchema { schema } => Some(schema.clone()),
358            AnthropicOutputFormat::Unknown => None,
359        })
360    });
361    let task_budget_tokens = request
362        .output_config
363        .as_ref()
364        .and_then(|config| config.task_budget.as_ref())
365        .map(|budget| budget.total);
366    let anthropic_request_overrides = Some(AnthropicRequestOverrides {
367        thinking_mode: compatibility_thinking_mode(&request.model, request.thinking.as_ref()),
368        thinking_display: compatibility_thinking_display(request.thinking.as_ref()),
369        effort: effort
370            .as_ref()
371            .map(|effort| AnthropicOptionalStringOverride::Explicit(effort.clone()))
372            .unwrap_or(AnthropicOptionalStringOverride::Omit),
373        task_budget_tokens: task_budget_tokens
374            .map(AnthropicOptionalU32Override::Explicit)
375            .unwrap_or(AnthropicOptionalU32Override::Omit),
376    });
377
378    let system_prompt = request
379        .system
380        .map(extract_system_prompt_text)
381        .filter(|value| !value.is_empty())
382        .map(Arc::from);
383
384    let mut messages = Vec::new();
385    for anthropic_msg in request.messages {
386        let role = anthropic_role_to_message_role(&anthropic_msg.role);
387
388        match anthropic_msg.content {
389            AnthropicContent::Text(text) => {
390                if !text.is_empty() {
391                    messages.push(Message::base(role, MessageContent::Text(text)));
392                }
393            }
394            AnthropicContent::Blocks(blocks) => {
395                let converted = convert_anthropic_blocks(&blocks);
396                messages.extend(converted.emitted_messages);
397
398                if !converted.content_parts.is_empty()
399                    || !converted.tool_calls.is_empty()
400                    || !converted.reasoning_chunks.is_empty()
401                {
402                    let mut message = Message::base(role, message_content_from_parts(converted.content_parts));
403                    if !converted.tool_calls.is_empty() {
404                        message.tool_calls = Some(converted.tool_calls);
405                    }
406                    if !converted.reasoning_chunks.is_empty() && message.role == MessageRole::Assistant {
407                        message.reasoning = Some(converted.reasoning_chunks.join("\n"));
408                    }
409                    if !converted.reasoning_details.is_empty() && message.role == MessageRole::Assistant {
410                        message.reasoning_details = Some(converted.reasoning_details);
411                    }
412                    messages.push(message);
413                }
414            }
415        }
416    }
417
418    let tools = if let Some(anthropic_tools) = request.tools {
419        let mut converted_tools = Vec::new();
420        for tool in anthropic_tools {
421            let tool_def = match tool {
422                AnthropicTool::Advisor {
423                    tool_type: _,
424                    name: _,
425                    model,
426                    max_uses,
427                    max_tokens,
428                    caching,
429                } => {
430                    let mut options = serde_json::Map::new();
431                    options.insert("model".to_string(), Value::String(model));
432                    if let Some(max_uses) = max_uses {
433                        options.insert("max_uses".to_string(), Value::Number(max_uses.into()));
434                    }
435                    if let Some(max_tokens) = max_tokens {
436                        options.insert("max_tokens".to_string(), Value::Number(max_tokens.into()));
437                    }
438                    if let Some(caching) = caching {
439                        options.insert(
440                            "caching".to_string(),
441                            json!({
442                                "type": caching.cache_type,
443                                "ttl": caching.ttl,
444                            }),
445                        );
446                    }
447                    ToolDefinition {
448                        tool_type: "advisor_20260301".to_string(),
449                        function: None,
450                        allowed_callers: None,
451                        input_examples: None,
452                        web_search: None,
453                        hosted_tool_config: None,
454                        shell: None,
455                        grammar: None,
456                        strict: None,
457                        defer_loading: None,
458                        namespace: None,
459                        advisor: Some(Value::Object(options)),
460                    }
461                }
462                AnthropicTool::Function {
463                    name,
464                    description,
465                    input_schema,
466                    input_examples,
467                    strict,
468                    allowed_callers,
469                } => {
470                    let mut tool = ToolDefinition::function(name, description.unwrap_or_default(), input_schema);
471                    tool.input_examples = input_examples;
472                    tool.strict = strict;
473                    tool.allowed_callers = allowed_callers;
474                    tool
475                }
476                AnthropicTool::Native { tool_type, options, .. } => {
477                    if tool_type.starts_with("web_search_") {
478                        ToolDefinition {
479                            tool_type,
480                            function: None,
481                            allowed_callers: None,
482                            input_examples: None,
483                            web_search: (!options.is_empty()).then_some(Value::Object(options)),
484                            hosted_tool_config: None,
485                            shell: None,
486                            grammar: None,
487                            strict: None,
488                            defer_loading: None,
489                            namespace: None,
490                            advisor: None,
491                        }
492                    } else if tool_type.starts_with("code_execution_") || tool_type.starts_with("memory_") {
493                        ToolDefinition {
494                            tool_type,
495                            function: None,
496                            allowed_callers: None,
497                            input_examples: None,
498                            web_search: None,
499                            hosted_tool_config: None,
500                            shell: None,
501                            grammar: None,
502                            strict: None,
503                            defer_loading: None,
504                            namespace: None,
505                            advisor: None,
506                        }
507                    } else {
508                        continue;
509                    }
510                }
511            };
512            converted_tools.push(tool_def);
513        }
514        if converted_tools.is_empty() {
515            None
516        } else {
517            Some(Arc::new(converted_tools))
518        }
519    } else {
520        None
521    };
522
523    LLMRequest {
524        messages: Arc::new(messages),
525        system_prompt,
526        tools,
527        model: request.model,
528        max_tokens: Some(request.max_tokens),
529        temperature: request.temperature,
530        stream: request.stream,
531        output_format,
532        tool_choice,
533        parallel_tool_calls: None,
534        parallel_tool_config,
535        reasoning_effort: None,
536        effort,
537        verbosity: None,
538        do_sample: None,
539        top_p: request.top_p,
540        top_k: request.top_k,
541        presence_penalty: None,
542        frequency_penalty: None,
543        stop_sequences: request.stop_sequences,
544        thinking_budget: None,
545        betas: request.betas,
546        context_management: request.context_management,
547        coding_agent_settings: None,
548        metadata: None,
549        previous_response_id: None,
550        response_store: None,
551        responses_include: None,
552        service_tier: None,
553        prompt_cache_key: None,
554        prompt_cache_profile: None,
555        fallbacks: None,
556        fallback_credit_token: None,
557        anthropic_request_overrides,
558    }
559}
560
561pub(crate) fn convert_llm_to_anthropic_response(response: LLMResponse) -> AnthropicMessagesResponse {
562    use uuid::Uuid;
563
564    let mut content_blocks = Vec::new();
565    let mut preserved_reasoning = false;
566
567    if let Some(reasoning_details) = response.reasoning_details.as_ref() {
568        for detail in reasoning_details {
569            let Some(normalized) = normalize_reasoning_detail_object(&Value::String(detail.clone())) else {
570                continue;
571            };
572
573            match normalized.get("type").and_then(|value| value.as_str()) {
574                Some("thinking") => {
575                    let thinking = normalized
576                        .get("thinking")
577                        .and_then(|value| value.as_str())
578                        .unwrap_or_default()
579                        .to_string();
580                    let signature = normalized
581                        .get("signature")
582                        .and_then(|value| value.as_str())
583                        .map(ToOwned::to_owned);
584                    content_blocks.push(AnthropicContentBlock::Thinking { thinking, signature });
585                    preserved_reasoning = true;
586                }
587                Some("redacted_thinking") => {
588                    let data = normalized
589                        .get("data")
590                        .and_then(|value| value.as_str())
591                        .unwrap_or_default()
592                        .to_string();
593                    content_blocks.push(AnthropicContentBlock::RedactedThinking { data });
594                    preserved_reasoning = true;
595                }
596                _ => {}
597            }
598        }
599    }
600
601    if !preserved_reasoning
602        && let Some(reasoning) = response.reasoning.as_ref()
603        && !reasoning.trim().is_empty()
604    {
605        content_blocks.push(AnthropicContentBlock::Thinking { thinking: reasoning.clone(), signature: None });
606    }
607
608    if let Some(content) = response.content.as_ref()
609        && !content.is_empty()
610    {
611        content_blocks.push(AnthropicContentBlock::Text {
612            text: content.clone(),
613            citations: None,
614            cache_control: None,
615        });
616    }
617
618    if let Some(tool_calls) = response.tool_calls.as_ref() {
619        for call in tool_calls {
620            if let Some(func) = &call.function {
621                let input = call
622                    .parsed_arguments()
623                    .unwrap_or_else(|_| Value::String(func.arguments.clone()));
624                content_blocks.push(AnthropicContentBlock::ToolUse {
625                    id: call.id.clone(),
626                    name: func.name.clone(),
627                    input,
628                });
629            }
630        }
631    }
632
633    let usage = response.usage.unwrap_or_default();
634    let model = if response.model.trim().is_empty() {
635        "unknown".to_string()
636    } else {
637        response.model
638    };
639
640    AnthropicMessagesResponse {
641        id: Uuid::new_v4().to_string(),
642        r#type: "message".to_string(),
643        role: "assistant".to_string(),
644        model,
645        content: content_blocks,
646        stop_reason: Some(anthropic_stop_reason(response.finish_reason)),
647        stop_sequence: None,
648        usage: AnthropicUsage {
649            input_tokens: usage.prompt_tokens,
650            output_tokens: usage.completion_tokens,
651        },
652    }
653}
654
655pub(crate) fn anthropic_stop_reason(finish_reason: FinishReason) -> String {
656    match finish_reason {
657        FinishReason::Stop => "end_turn".to_string(),
658        FinishReason::Length => "max_tokens".to_string(),
659        FinishReason::ToolCalls => "tool_use".to_string(),
660        FinishReason::ContentFilter => "content_filter".to_string(),
661        FinishReason::Pause => "pause_turn".to_string(),
662        FinishReason::Refusal => "refusal".to_string(),
663        FinishReason::Error(message) => message,
664    }
665}
666
667fn parse_anthropic_tool_choice(tool_choice: Option<&Value>) -> (Option<ToolChoice>, Option<Box<ParallelToolConfig>>) {
668    let Some(choice) = tool_choice else {
669        return (None, None);
670    };
671    let Some(choice_obj) = choice.as_object() else {
672        return (None, None);
673    };
674
675    let disable_parallel_tool_use = choice_obj
676        .get("disable_parallel_tool_use")
677        .and_then(Value::as_bool)
678        .unwrap_or(false);
679
680    let parsed_tool_choice = match choice_obj.get("type").and_then(Value::as_str) {
681        Some("auto") => Some(ToolChoice::Auto),
682        Some("none") => Some(ToolChoice::None),
683        Some("any") => Some(ToolChoice::Any),
684        Some("tool") => choice_obj
685            .get("name")
686            .and_then(Value::as_str)
687            .map(|name| ToolChoice::function(name.to_string())),
688        _ => None,
689    };
690
691    let parallel_tool_config = disable_parallel_tool_use.then(|| {
692        Box::new(ParallelToolConfig {
693            disable_parallel_tool_use: true,
694            max_parallel_tools: Some(1),
695            encourage_parallel: false,
696        })
697    });
698
699    (parsed_tool_choice, parallel_tool_config)
700}
701
702fn anthropic_role_to_message_role(role: &str) -> MessageRole {
703    match role {
704        "assistant" => MessageRole::Assistant,
705        "system" => MessageRole::System,
706        "tool" => MessageRole::Tool,
707        _ => MessageRole::User,
708    }
709}
710
711fn extract_system_prompt_text(system_prompt: AnthropicSystemPrompt) -> String {
712    match system_prompt {
713        AnthropicSystemPrompt::Text(text) => text,
714        AnthropicSystemPrompt::Blocks(blocks) => blocks
715            .iter()
716            .map(anthropic_block_text)
717            .filter(|text| !text.is_empty())
718            .collect::<Vec<_>>()
719            .join("\n"),
720    }
721}
722
723fn convert_anthropic_blocks(blocks: &[AnthropicContentBlock]) -> ConvertedAnthropicBlocks {
724    let mut converted = ConvertedAnthropicBlocks::default();
725
726    for block in blocks {
727        match block {
728            AnthropicContentBlock::Text { text, .. } => {
729                converted.content_parts.push(ContentPart::text(text.clone()));
730            }
731            AnthropicContentBlock::Image { source } => {
732                converted
733                    .content_parts
734                    .push(ContentPart::image(source.data.clone(), source.media_type.clone()));
735            }
736            AnthropicContentBlock::ToolUse { id, name, input }
737            | AnthropicContentBlock::ServerToolUse { id, name, input } => {
738                converted
739                    .tool_calls
740                    .push(ToolCall::function(id.clone(), name.clone(), input.to_string()));
741            }
742            AnthropicContentBlock::ToolResult { tool_use_id, content, .. } => converted
743                .emitted_messages
744                .push(Message::tool_response(tool_use_id.clone(), anthropic_content_text(content))),
745            AnthropicContentBlock::Thinking { thinking, signature } => {
746                converted.reasoning_chunks.push(thinking.clone());
747                let mut detail = json!({
748                    "type": "thinking",
749                    "thinking": thinking,
750                });
751                if let Some(signature) = signature
752                    && let Some(obj) = detail.as_object_mut()
753                {
754                    obj.insert("signature".to_string(), Value::String(signature.clone()));
755                }
756                converted.reasoning_details.push(detail);
757            }
758            AnthropicContentBlock::RedactedThinking { data } => {
759                converted.reasoning_details.push(json!({
760                    "type": "redacted_thinking",
761                    "data": data,
762                }));
763            }
764            AnthropicContentBlock::ContainerUpload { file_id } => {
765                converted.content_parts.push(ContentPart::file_from_id(file_id.clone()));
766            }
767            AnthropicContentBlock::CodeExecutionToolResult { tool_use_id, content }
768            | AnthropicContentBlock::BashCodeExecutionToolResult { tool_use_id, content }
769            | AnthropicContentBlock::TextEditorCodeExecutionToolResult { tool_use_id, content }
770            | AnthropicContentBlock::WebSearchToolResult { tool_use_id, content }
771            | AnthropicContentBlock::AdvisorToolResult { tool_use_id, content } => converted
772                .emitted_messages
773                .push(Message::tool_response(tool_use_id.clone(), serialize_value(content))),
774            // Unknown content block types are silently skipped.
775            AnthropicContentBlock::Unknown => {}
776        }
777    }
778
779    converted
780}
781
782fn message_content_from_parts(parts: Vec<ContentPart>) -> MessageContent {
783    if parts.len() == 1
784        && let ContentPart::Text { text } = &parts[0]
785    {
786        return MessageContent::Text(text.clone());
787    }
788
789    MessageContent::Parts(parts)
790}
791
792fn anthropic_content_text(content: &AnthropicContent) -> String {
793    match content {
794        AnthropicContent::Text(text) => text.clone(),
795        AnthropicContent::Blocks(blocks) => blocks
796            .iter()
797            .map(anthropic_block_text)
798            .filter(|text| !text.is_empty())
799            .collect::<Vec<_>>()
800            .join("\n"),
801    }
802}
803
804fn anthropic_block_text(block: &AnthropicContentBlock) -> String {
805    match block {
806        AnthropicContentBlock::Text { text, .. } => text.clone(),
807        AnthropicContentBlock::Thinking { thinking, .. } => thinking.clone(),
808        AnthropicContentBlock::RedactedThinking { .. } => "[REDACTED THINKING]".to_string(),
809        AnthropicContentBlock::Image { .. } => "[Image]".to_string(),
810        AnthropicContentBlock::ContainerUpload { file_id } => format!("[File: {file_id}]"),
811        AnthropicContentBlock::ToolUse { name, input, .. }
812        | AnthropicContentBlock::ServerToolUse { name, input, .. } => {
813            format!("[Tool call: {name} with args: {input}]")
814        }
815        AnthropicContentBlock::ToolResult { tool_use_id, content, .. } => {
816            format!("[Tool result {}: {}]", tool_use_id, anthropic_content_text(content))
817        }
818        AnthropicContentBlock::CodeExecutionToolResult { tool_use_id, content }
819        | AnthropicContentBlock::BashCodeExecutionToolResult { tool_use_id, content }
820        | AnthropicContentBlock::TextEditorCodeExecutionToolResult { tool_use_id, content }
821        | AnthropicContentBlock::WebSearchToolResult { tool_use_id, content }
822        | AnthropicContentBlock::AdvisorToolResult { tool_use_id, content } => {
823            format!("[Tool result {}: {}]", tool_use_id, serialize_value(content))
824        }
825        AnthropicContentBlock::Unknown => "[Unknown Content Block]".to_string(),
826    }
827}
828
829fn compatibility_thinking_mode(_model: &str, thinking: Option<&ThinkingConfig>) -> AnthropicThinkingModeOverride {
830    match thinking {
831        Some(ThinkingConfig::Adaptive { .. }) => AnthropicThinkingModeOverride::Adaptive,
832        Some(ThinkingConfig::Enabled { budget_tokens, .. }) => {
833            AnthropicThinkingModeOverride::ManualBudget(*budget_tokens)
834        }
835        // `between_tools` is the "thinking off" spelling for the models that
836        // reject `disabled`; the builder rewrites it back for such a model.
837        Some(ThinkingConfig::Disabled) | Some(ThinkingConfig::BetweenTools) | Some(ThinkingConfig::Unknown) => {
838            AnthropicThinkingModeOverride::Disabled
839        }
840        None => AnthropicThinkingModeOverride::Disabled,
841    }
842}
843
844fn compatibility_thinking_display(thinking: Option<&ThinkingConfig>) -> AnthropicThinkingDisplayOverride {
845    let display = match thinking {
846        Some(ThinkingConfig::Adaptive { display }) | Some(ThinkingConfig::Enabled { display, .. }) => *display,
847        Some(ThinkingConfig::Disabled) | Some(ThinkingConfig::BetweenTools) | Some(ThinkingConfig::Unknown) | None => {
848            None
849        }
850    };
851
852    match display {
853        Some(ThinkingDisplay::Summarized) => AnthropicThinkingDisplayOverride::Summarized,
854        Some(ThinkingDisplay::Omitted) => AnthropicThinkingDisplayOverride::Omitted,
855        Some(ThinkingDisplay::Updates) => AnthropicThinkingDisplayOverride::Updates,
856        Some(ThinkingDisplay::Unknown) | None => AnthropicThinkingDisplayOverride::Inherit,
857    }
858}
859
860fn serialize_value(value: &Value) -> String {
861    serde_json::to_string(value).unwrap_or_else(|_| json!({ "value": value }).to_string())
862}