Skip to main content

vtcode_llm/providers/
anthropic_types.rs

1use std::borrow::Cow;
2
3use serde::{Deserialize, Deserializer, Serialize};
4use serde_json::{Map, Value};
5
6use crate::provider::MessageClearAt;
7
8mod tool_blocks;
9pub use tool_blocks::{AnthropicToolResultBlock, AnthropicToolUseBlock};
10
11#[derive(Debug, Serialize, Deserialize, Clone)]
12#[serde(tag = "type", rename_all = "lowercase")]
13pub enum AnthropicFallback {
14    #[serde(rename = "fallback")]
15    Fallback {
16        from: AnthropicFallbackModel,
17        to: AnthropicFallbackModel,
18    },
19}
20
21#[derive(Debug, Serialize, Deserialize, Clone)]
22pub struct AnthropicFallbackModel {
23    model: String,
24}
25
26#[derive(Debug, Serialize, Deserialize)]
27pub struct AnthropicRequest {
28    pub(crate) model: String,
29    pub(crate) messages: Vec<AnthropicMessage>,
30    pub(crate) max_tokens: u32,
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub(crate) cache_control: Option<CacheControl>,
33    #[serde(skip_serializing_if = "Option::is_none")]
34    pub(crate) system: Option<Value>, // Can be string or array of blocks
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub(crate) tools: Option<Vec<AnthropicTool>>,
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub(crate) tool_choice: Option<Value>,
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub(crate) thinking: Option<ThinkingConfig>,
41    #[serde(skip_serializing_if = "Option::is_none")]
42    pub(crate) reasoning: Option<Value>, // Deprecated in favor of thinking, but kept for backward compat or direct effort passing
43    #[serde(
44        default,
45        deserialize_with = "deserialize_boxed_output_config_opt",
46        skip_serializing_if = "Option::is_none"
47    )]
48    pub(crate) output_config: Option<Box<AnthropicOutputConfig>>,
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub(crate) context_management: Option<Value>,
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub(crate) fallbacks: Option<AnthropicFallbacksParam>,
53    /// Opaque credit token returned by a refused request's `stop_details.fallback_credit_token`.
54    /// Echoed on the retry to avoid paying the prompt-cache cost twice.
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub(crate) fallback_credit_token: Option<String>,
57    pub(crate) stream: bool,
58}
59
60/// The `fallbacks` request parameter: the `"default"` keyword (Anthropic picks
61/// the fallback by refusal category) or an explicit list of entries. Each form
62/// needs its own beta header; see `headers::ServerSideFallbackForm`.
63#[derive(Debug, Serialize, Deserialize, Clone)]
64#[serde(untagged)]
65pub enum AnthropicFallbacksParam {
66    Mode(AnthropicFallbacksKeyword),
67    Models(Vec<AnthropicFallbackParam>),
68}
69
70#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
71#[serde(rename_all = "lowercase")]
72pub enum AnthropicFallbacksKeyword {
73    Default,
74}
75
76impl AnthropicFallbacksParam {
77    /// Explicit entries, or an empty slice for the `"default"` form.
78    pub(crate) fn models(&self) -> &[AnthropicFallbackParam] {
79        match self {
80            Self::Mode(_) => &[],
81            Self::Models(models) => models,
82        }
83    }
84}
85
86#[derive(Debug, Serialize, Deserialize, Clone)]
87pub struct AnthropicFallbackParam {
88    pub(crate) model: String,
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub(crate) max_tokens: Option<u32>,
91    #[serde(skip_serializing_if = "Option::is_none")]
92    pub(crate) thinking: Option<ThinkingConfig>,
93}
94
95#[derive(Debug, Serialize, Deserialize, Clone)]
96#[serde(tag = "type", rename_all = "lowercase")]
97pub enum ThinkingConfig {
98    Enabled {
99        budget_tokens: u32,
100        #[serde(skip_serializing_if = "Option::is_none")]
101        display: Option<ThinkingDisplay>,
102    },
103    Adaptive {
104        #[serde(skip_serializing_if = "Option::is_none")]
105        display: Option<ThinkingDisplay>,
106    },
107    Disabled,
108    /// Claude Sonnet 5.5's lowest thinking setting: up-front thinking is off
109    /// while the short progress notes written between tool calls still come
110    /// back as `thinking` blocks. `disabled` is rejected with a 400 on that
111    /// model, and `between_tools` is itself rejected at `xhigh`/`max` effort.
112    /// Takes no other field.
113    #[serde(rename = "between_tools")]
114    BetweenTools,
115    /// Catch-all for unknown thinking config types added by the Anthropic API.
116    #[serde(other)]
117    Unknown,
118}
119
120/// Controls how thinking content is returned in API responses.
121#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
122#[serde(rename_all = "lowercase")]
123pub enum ThinkingDisplay {
124    /// Thinking blocks contain summarized thinking text (default on Claude 4 models).
125    Summarized,
126    /// Thinking blocks are returned with an empty `thinking` field; the `signature`
127    /// still carries encrypted full thinking for multi-turn continuity
128    /// (default on Claude Opus 4.7).
129    Omitted,
130    /// Progress-update thinking blocks (the short notes written between tool
131    /// calls) carry their text; reasoning blocks stay empty. Requires the
132    /// `thinking-display-updates-2026-08-18` beta; supported on Claude Sonnet
133    /// 5.5, Claude Opus 5.5 and Claude Fable 5.x.
134    Updates,
135    /// Catch-all for unknown display modes added by the Anthropic API.
136    #[serde(other)]
137    Unknown,
138}
139
140#[derive(Debug, Serialize, Deserialize)]
141pub struct AnthropicMessage {
142    pub(crate) role: String,
143    pub(crate) content: Vec<AnthropicContentBlock>,
144    /// Anthropic's turn-scoped system-message lifecycle field.
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub(crate) clear_at: Option<MessageClearAt>,
147}
148
149#[derive(Debug, Serialize, Deserialize, Clone)]
150#[serde(tag = "type")]
151pub enum AnthropicContentBlock {
152    #[serde(rename = "text")]
153    Text {
154        text: String,
155        #[serde(skip_serializing_if = "Option::is_none")]
156        citations: Option<Vec<TextCitation>>,
157        #[serde(skip_serializing_if = "Option::is_none")]
158        cache_control: Option<CacheControl>,
159    },
160    #[serde(rename = "image")]
161    Image {
162        source: ImageSource,
163        #[serde(skip_serializing_if = "Option::is_none")]
164        cache_control: Option<CacheControl>,
165    },
166    #[serde(rename = "tool_use")]
167    ToolUse(Box<AnthropicToolUseBlock>),
168    #[serde(rename = "tool_result")]
169    ToolResult(Box<AnthropicToolResultBlock>),
170    #[serde(rename = "thinking")]
171    Thinking {
172        thinking: String,
173        #[serde(skip_serializing_if = "Option::is_none")]
174        signature: Option<String>,
175        #[serde(skip_serializing_if = "Option::is_none")]
176        cache_control: Option<CacheControl>,
177    },
178    #[serde(rename = "redacted_thinking")]
179    RedactedThinking {
180        data: String,
181        #[serde(skip_serializing_if = "Option::is_none")]
182        cache_control: Option<CacheControl>,
183    },
184    #[serde(rename = "compaction")]
185    Compaction {
186        /// Threshold compaction streams may start with `null` and provide the
187        /// summary in a single delta. On-demand compaction returns the full
188        /// signed block in the start event.
189        content: Option<String>,
190        #[serde(skip_serializing_if = "Option::is_none")]
191        signature: Option<String>,
192        #[serde(skip_serializing_if = "Option::is_none")]
193        cache_control: Option<CacheControl>,
194        /// Preserve provider fields that are not yet modeled so an opaque
195        /// compaction block can be replayed without alteration.
196        #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
197        extra: Map<String, Value>,
198    },
199    /// Server-side tool use (e.g., tool search execution) - advanced-tool-use beta
200    #[serde(rename = "server_tool_use")]
201    ServerToolUse { id: String, name: String, input: Value },
202    /// Tool search result containing discovered tool references - advanced-tool-use beta
203    #[serde(rename = "tool_search_tool_result")]
204    ToolSearchToolResult {
205        tool_use_id: String,
206        content: ToolSearchResultContent,
207    },
208    /// Files API upload reference used by Anthropic code execution.
209    #[serde(rename = "container_upload")]
210    ContainerUpload { file_id: String },
211    /// Generic code execution result block used in some Anthropic responses.
212    #[serde(rename = "code_execution_tool_result")]
213    CodeExecutionToolResult { tool_use_id: String, content: Value },
214    /// Bash code execution result block returned by Anthropic code execution.
215    #[serde(rename = "bash_code_execution_tool_result")]
216    BashCodeExecutionToolResult { tool_use_id: String, content: Value },
217    /// Text editor code execution result block returned by Anthropic code execution.
218    #[serde(rename = "text_editor_code_execution_tool_result")]
219    TextEditorCodeExecutionToolResult { tool_use_id: String, content: Value },
220    /// Native web search result blocks returned by Anthropic web search tools.
221    #[serde(rename = "web_search_tool_result")]
222    WebSearchToolResult { tool_use_id: String, content: Value },
223    /// Advisor tool result block returned by the server-side advisor sub-inference.
224    /// `content` is the verbatim result union (`advisor_result`,
225    /// `advisor_redacted_result`, or `advisor_tool_result_error`).
226    #[serde(rename = "advisor_tool_result")]
227    AdvisorToolResult { tool_use_id: String, content: Value },
228    /// Fallback content block marking model boundary in server-side fallback
229    #[serde(rename = "fallback")]
230    Fallback {
231        from: AnthropicFallbackModel,
232        to: AnthropicFallbackModel,
233    },
234    /// Catch-all for unknown content block types added by the Anthropic API.
235    #[serde(other)]
236    Unknown,
237}
238
239/// Content of a tool search result
240#[derive(Debug, Serialize, Deserialize, Clone)]
241#[serde(tag = "type")]
242pub enum ToolSearchResultContent {
243    #[serde(rename = "tool_search_tool_search_result")]
244    SearchResult { tool_references: Vec<ToolReference> },
245    #[serde(rename = "tool_search_tool_result_error")]
246    Error { error_code: String },
247    /// Catch-all for unknown tool search result types.
248    #[serde(other)]
249    Unknown,
250}
251
252/// A reference to a discovered tool from tool search
253#[derive(Debug, Serialize, Deserialize, Clone)]
254pub struct ToolReference {
255    #[serde(rename = "type")]
256    ref_type: Option<String>, // "tool_reference"
257    tool_name: String,
258}
259
260#[derive(Debug, Serialize, Deserialize, Clone)]
261#[serde(tag = "type")]
262pub enum TextCitation {
263    #[serde(rename = "char_location")]
264    CharLocation {
265        cited_text: String,
266        document_index: usize,
267        document_title: Option<String>,
268        start_char_index: usize,
269        end_char_index: usize,
270    },
271    #[serde(rename = "page_location")]
272    PageLocation {
273        cited_text: String,
274        document_index: usize,
275        document_title: Option<String>,
276        start_page_number: usize,
277        end_page_number: usize,
278    },
279    #[serde(rename = "content_block_location")]
280    ContentBlockLocation {
281        cited_text: String,
282        document_index: usize,
283        document_title: Option<String>,
284        start_block_index: usize,
285        end_block_index: usize,
286    },
287    #[serde(rename = "web_search_result_location")]
288    WebSearchResultLocation {
289        url: Option<String>,
290        title: Option<String>,
291        encrypted_index: Option<String>,
292        cited_text: Option<String>,
293    },
294    /// Catch-all for unknown citation types.
295    #[serde(other)]
296    Unknown,
297}
298
299#[derive(Debug, Serialize, Deserialize, Clone)]
300pub struct ImageSource {
301    #[serde(rename = "type")]
302    pub(crate) source_type: String, // "base64"
303    pub(crate) media_type: String,
304    pub(crate) data: String,
305}
306
307#[derive(Debug, Serialize, Deserialize, Clone)]
308pub struct CacheControl {
309    #[serde(rename = "type")]
310    pub(crate) control_type: Cow<'static, str>, // "ephemeral"
311    #[serde(skip_serializing_if = "Option::is_none")]
312    pub(crate) ttl: Option<Cow<'static, str>>, // "5m" or "1h"
313}
314
315/// Anthropic tool definition
316/// Supports both regular function tools and tool search tools (advanced-tool-use beta)
317#[derive(Debug, Serialize, Deserialize, Clone)]
318#[serde(untagged)]
319pub enum AnthropicTool {
320    /// Tool search tool (regex or bm25)
321    ToolSearch(AnthropicToolSearchTool),
322    /// Native Anthropic code execution tool revision
323    CodeExecution(AnthropicCodeExecutionTool),
324    /// Native Anthropic memory tool revision
325    Memory(AnthropicMemoryTool),
326    /// Native Anthropic web search tool revision
327    WebSearch(AnthropicWebSearchTool),
328    /// Anthropic server-side advisor tool (beta `advisor-tool-2026-03-01`).
329    Advisor(AnthropicAdvisorTool),
330    /// Regular function tool
331    Function(AnthropicFunctionTool),
332}
333
334/// Regular function tool definition for Anthropic API
335#[derive(Debug, Serialize, Deserialize, Clone)]
336pub struct AnthropicFunctionTool {
337    pub(crate) name: String,
338    pub(crate) description: String,
339    pub(crate) input_schema: Value,
340    #[serde(skip_serializing_if = "Option::is_none")]
341    pub(crate) input_examples: Option<Vec<Value>>,
342    #[serde(skip_serializing_if = "Option::is_none")]
343    pub(crate) strict: Option<bool>,
344    #[serde(skip_serializing_if = "Option::is_none")]
345    pub(crate) allowed_callers: Option<Vec<String>>,
346    #[serde(skip_serializing_if = "Option::is_none")]
347    pub(crate) cache_control: Option<CacheControl>,
348    /// When true, the tool is deferred and only loaded when discovered via tool search
349    #[serde(skip_serializing_if = "Option::is_none")]
350    pub(crate) defer_loading: Option<bool>,
351}
352
353/// Native code execution tool definition for Anthropic API.
354#[derive(Debug, Serialize, Deserialize, Clone)]
355pub struct AnthropicCodeExecutionTool {
356    /// Versioned code execution type (e.g. "code_execution_20250825")
357    #[serde(rename = "type")]
358    pub(crate) tool_type: String,
359    /// Tool name (typically "code_execution")
360    pub(crate) name: String,
361}
362
363/// Native memory tool definition for Anthropic API.
364#[derive(Debug, Serialize, Deserialize, Clone)]
365pub struct AnthropicMemoryTool {
366    /// Versioned memory type (e.g. "memory_20250818")
367    #[serde(rename = "type")]
368    pub(crate) tool_type: String,
369    /// Tool name (typically "memory")
370    pub(crate) name: String,
371}
372
373/// Tool search tool definition for Anthropic's advanced-tool-use beta
374#[derive(Debug, Serialize, Deserialize, Clone)]
375pub struct AnthropicToolSearchTool {
376    /// The type of tool search: "tool_search_tool_regex_20251119" or "tool_search_tool_bm25_20251119"
377    #[serde(rename = "type")]
378    pub(crate) tool_type: String,
379    /// Tool name (e.g., "tool_search_tool_regex" or "tool_search_tool_bm25")
380    pub(crate) name: String,
381}
382
383/// Native web search tool definition for Anthropic API (PTC-enabled search revisions)
384#[derive(Debug, Serialize, Deserialize, Clone)]
385pub struct AnthropicWebSearchTool {
386    /// Versioned web search type (e.g., "web_search_20260209")
387    #[serde(rename = "type")]
388    pub(crate) tool_type: String,
389    /// Tool name (typically "web_search")
390    pub(crate) name: String,
391    /// Optional Anthropic-native web search configuration.
392    #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
393    pub(crate) options: Map<String, Value>,
394}
395
396/// Anthropic server-side advisor tool definition (beta `advisor-tool-2026-03-01`).
397///
398/// The executor model consults the advisor model for strategic guidance
399/// mid-generation. The tool takes no client-supplied input; the server builds
400/// the advisor's view from the full transcript.
401#[derive(Debug, Serialize, Deserialize, Clone)]
402pub struct AnthropicAdvisorTool {
403    /// Fixed advisor tool type.
404    #[serde(rename = "type")]
405    pub(crate) tool_type: String, // "advisor_20260301"
406    /// Fixed advisor tool name.
407    pub(crate) name: String, // "advisor"
408    /// Advisor model id (e.g. "claude-opus-5").
409    pub(crate) model: String,
410    /// Maximum number of advisor invocations per request.
411    #[serde(skip_serializing_if = "Option::is_none")]
412    pub(crate) max_uses: Option<u32>,
413    /// Caps the advisor's total output (thinking plus text) per call (min 1024).
414    #[serde(skip_serializing_if = "Option::is_none")]
415    pub(crate) max_tokens: Option<u32>,
416    /// Enables prompt caching for the advisor's own transcript across calls.
417    #[serde(skip_serializing_if = "Option::is_none")]
418    pub(crate) caching: Option<AnthropicAdvisorCaching>,
419}
420
421/// Prompt-caching configuration for the advisor tool.
422#[derive(Debug, Serialize, Deserialize, Clone)]
423pub struct AnthropicAdvisorCaching {
424    /// Fixed cache type.
425    #[serde(rename = "type")]
426    pub(crate) cache_type: String, // "ephemeral"
427    /// Cache lifetime ("5m" or "1h").
428    pub(crate) ttl: String,
429}
430
431#[derive(Debug, Deserialize)]
432#[serde(tag = "type")]
433pub enum AnthropicStreamEvent {
434    #[serde(rename = "message_start")]
435    MessageStart { message: AnthropicMessageResponse },
436    #[serde(rename = "content_block_start")]
437    ContentBlockStart {
438        index: usize,
439        content_block: AnthropicContentBlock,
440    },
441    #[serde(rename = "ping")]
442    Ping,
443    #[serde(rename = "content_block_delta")]
444    ContentBlockDelta { index: usize, delta: AnthropicStreamDelta },
445    #[serde(rename = "content_block_stop")]
446    ContentBlockStop { index: usize },
447    #[serde(rename = "message_delta")]
448    MessageDelta {
449        delta: AnthropicMessageDelta,
450        usage: Option<AnthropicUsage>,
451    },
452    #[serde(rename = "message_stop")]
453    MessageStop,
454    #[serde(rename = "error")]
455    Error { error: AnthropicErrorBody },
456    /// Catch-all for unknown streaming event types added by the Anthropic API.
457    #[serde(other)]
458    Unknown,
459}
460
461#[derive(Debug, Deserialize)]
462#[serde(tag = "type")]
463pub enum AnthropicStreamDelta {
464    #[serde(rename = "text_delta")]
465    TextDelta { text: String },
466    #[serde(rename = "input_json_delta")]
467    InputJsonDelta { partial_json: String },
468    #[serde(rename = "thinking_delta")]
469    ThinkingDelta { thinking: String },
470    #[serde(rename = "signature_delta")]
471    SignatureDelta { signature: String },
472    #[serde(rename = "compaction_delta")]
473    CompactionDelta {
474        content: Option<String>,
475        /// Preserve opaque fields such as `encrypted_content` from a delta.
476        #[serde(flatten, default)]
477        extra: Map<String, Value>,
478    },
479    /// Catch-all for unknown delta types added by the Anthropic API.
480    #[serde(other)]
481    Unknown,
482}
483
484#[derive(Debug, Deserialize)]
485pub struct AnthropicMessageDelta {
486    pub(crate) stop_reason: Option<String>,
487    stop_sequence: Option<String>,
488    /// Refusal category, explanation and fallback-credit fields. Streaming
489    /// responses deliver `stop_details` here rather than on `message_start`.
490    #[serde(default)]
491    pub(crate) stop_details: Option<Value>,
492}
493
494#[derive(Debug, Deserialize, Clone)]
495pub struct AnthropicStopDetails {
496    #[serde(rename = "type")]
497    stop_details_type: Option<String>,
498    category: Option<String>,
499    explanation: Option<String>,
500    /// Opaque token that represents fallback credit when retrying on another model.
501    /// Present when the refusal qualifies for fallback credit.
502    fallback_credit_token: Option<String>,
503    /// Whether the retry can append an assistant message continuing the refused model's
504    /// partial output (`true`) or must use the unchanged request body (`false`).
505    fallback_has_prefill_claim: Option<bool>,
506}
507
508#[derive(Debug, Deserialize)]
509pub struct AnthropicMessageResponse {
510    id: String,
511    role: String,
512    content: Vec<AnthropicContentBlock>,
513    model: String,
514    stop_reason: Option<String>,
515    stop_sequence: Option<String>,
516    stop_details: Option<AnthropicStopDetails>,
517    pub(crate) usage: AnthropicUsage,
518}
519
520#[derive(Debug, Serialize, Deserialize)]
521pub struct AnthropicUsage {
522    #[serde(default, skip_serializing_if = "Option::is_none")]
523    pub(crate) speed: Option<String>,
524    #[serde(default, deserialize_with = "deserialize_nullable_u32")]
525    pub(crate) input_tokens: u32,
526    #[serde(default, deserialize_with = "deserialize_nullable_u32")]
527    pub(crate) output_tokens: u32,
528    pub(crate) cache_creation_input_tokens: Option<u32>,
529    pub(crate) cache_read_input_tokens: Option<u32>,
530    /// Per-iteration token usage, populated when compaction, advisor, or
531    /// server-side fallback runs. Each entry represents one sampling pass.
532    #[serde(default, skip_serializing_if = "Option::is_none")]
533    iterations: Option<Vec<AnthropicUsageIteration>>,
534}
535
536#[derive(Debug, Serialize, Deserialize)]
537#[serde(tag = "type", rename_all = "snake_case")]
538pub enum AnthropicUsageIteration {
539    Message {
540        model: Option<String>,
541        #[serde(default, deserialize_with = "deserialize_nullable_u32")]
542        input_tokens: u32,
543        #[serde(default, deserialize_with = "deserialize_nullable_u32")]
544        output_tokens: u32,
545        cache_creation_input_tokens: Option<u32>,
546        cache_read_input_tokens: Option<u32>,
547    },
548    FallbackMessage {
549        model: Option<String>,
550        #[serde(default, deserialize_with = "deserialize_nullable_u32")]
551        input_tokens: u32,
552        #[serde(default, deserialize_with = "deserialize_nullable_u32")]
553        output_tokens: u32,
554        cache_creation_input_tokens: Option<u32>,
555        cache_read_input_tokens: Option<u32>,
556    },
557    AdvisorMessage {
558        model: Option<String>,
559        #[serde(default, deserialize_with = "deserialize_nullable_u32")]
560        input_tokens: u32,
561        #[serde(default, deserialize_with = "deserialize_nullable_u32")]
562        output_tokens: u32,
563        cache_creation_input_tokens: Option<u32>,
564        cache_read_input_tokens: Option<u32>,
565    },
566    Compaction {
567        #[serde(default, deserialize_with = "deserialize_nullable_u32")]
568        input_tokens: u32,
569        #[serde(default, deserialize_with = "deserialize_nullable_u32")]
570        output_tokens: u32,
571        cache_creation_input_tokens: Option<u32>,
572        cache_read_input_tokens: Option<u32>,
573    },
574    /// Catch-all for unknown iteration types added by the Anthropic API.
575    #[serde(other)]
576    Unknown,
577}
578
579fn deserialize_nullable_u32<'de, D>(deserializer: D) -> Result<u32, D::Error>
580where
581    D: Deserializer<'de>,
582{
583    Option::<u32>::deserialize(deserializer).map(Option::unwrap_or_default)
584}
585
586#[derive(Debug, Deserialize)]
587pub struct AnthropicErrorBody {
588    #[serde(rename = "type")]
589    error_type: String,
590    pub(crate) message: String,
591}
592
593/// Output configuration for Anthropic API (e.g., effort parameter)
594#[derive(Debug, Serialize, Deserialize, Clone)]
595pub struct AnthropicOutputConfig {
596    #[serde(skip_serializing_if = "Option::is_none")]
597    pub(crate) effort: Option<String>,
598    #[serde(skip_serializing_if = "Option::is_none")]
599    pub(crate) task_budget: Option<AnthropicTaskBudget>,
600    #[serde(skip_serializing_if = "Option::is_none")]
601    pub(crate) format: Option<AnthropicOutputFormat>,
602}
603
604impl AnthropicOutputConfig {
605    fn is_empty(&self) -> bool {
606        self.effort.is_none() && self.task_budget.is_none() && self.format.is_none()
607    }
608
609    fn into_boxed_if_non_empty(self) -> Option<Box<Self>> {
610        (!self.is_empty()).then_some(Box::new(self))
611    }
612}
613
614#[derive(Debug, Serialize, Deserialize, Clone)]
615pub struct AnthropicTaskBudget {
616    #[serde(rename = "type")]
617    pub(crate) budget_type: String,
618    pub(crate) total: u32,
619}
620
621/// Native structured output format for Anthropic responses.
622#[derive(Debug, Serialize, Deserialize, Clone)]
623#[serde(tag = "type", rename_all = "snake_case")]
624pub enum AnthropicOutputFormat {
625    JsonSchema {
626        schema: Value,
627    },
628    /// Catch-all for unknown output format types added by the Anthropic API.
629    #[serde(other)]
630    Unknown,
631}
632
633/// Request body for Anthropic's count_tokens endpoint
634/// <https://docs.anthropic.com/en/api/messages-count-tokens>
635#[derive(Debug, Serialize, Deserialize)]
636pub struct CountTokensRequest {
637    model: String,
638    #[serde(skip_serializing_if = "Option::is_none")]
639    system: Option<Value>,
640    messages: Vec<AnthropicMessage>,
641    #[serde(skip_serializing_if = "Option::is_none")]
642    tools: Option<Vec<AnthropicTool>>,
643    #[serde(skip_serializing_if = "Option::is_none")]
644    thinking: Option<ThinkingConfig>,
645}
646
647fn deserialize_boxed_output_config_opt<'de, D>(deserializer: D) -> Result<Option<Box<AnthropicOutputConfig>>, D::Error>
648where
649    D: Deserializer<'de>,
650{
651    Option::<AnthropicOutputConfig>::deserialize(deserializer)
652        .map(|value| value.and_then(AnthropicOutputConfig::into_boxed_if_non_empty))
653}
654
655/// Response from Anthropic's count_tokens endpoint
656#[derive(Debug, Deserialize)]
657pub struct CountTokensResponse {
658    input_tokens: u32,
659}
660
661#[cfg(test)]
662mod tests {
663    use super::{AnthropicContentBlock, AnthropicOutputConfig, AnthropicRequest, AnthropicStreamEvent, TextCitation};
664
665    #[test]
666    fn stream_content_block_start_thinking_allows_missing_signature() {
667        let payload = r#"{
668            "type": "content_block_start",
669            "index": 0,
670            "content_block": {
671                "type": "thinking",
672                "thinking": "Drafting plan"
673            }
674        }"#;
675
676        let event: AnthropicStreamEvent = serde_json::from_str(payload).expect("should deserialize thinking block");
677        match event {
678            AnthropicStreamEvent::ContentBlockStart {
679                content_block: AnthropicContentBlock::Thinking { thinking, signature, .. },
680                ..
681            } => {
682                assert_eq!(thinking, "Drafting plan");
683                assert!(signature.is_none());
684            }
685            other => panic!("expected thinking content_block_start, got {other:?}"),
686        }
687    }
688
689    #[test]
690    fn stream_content_block_start_accepts_web_search_tool_result() {
691        let payload = r#"{
692            "type": "content_block_start",
693            "index": 1,
694            "content_block": {
695                "type": "web_search_tool_result",
696                "tool_use_id": "srvtoolu_123",
697                "content": [{
698                    "type": "web_search_result",
699                    "title": "Rust Releases",
700                    "url": "https://blog.rust-lang.org"
701                }]
702            }
703        }"#;
704
705        let event: AnthropicStreamEvent =
706            serde_json::from_str(payload).expect("should deserialize web search tool result");
707        match event {
708            AnthropicStreamEvent::ContentBlockStart {
709                content_block: AnthropicContentBlock::WebSearchToolResult { tool_use_id, .. },
710                ..
711            } => assert_eq!(tool_use_id, "srvtoolu_123"),
712            other => panic!("expected web_search_tool_result content_block_start, got {other:?}"),
713        }
714    }
715
716    #[test]
717    fn stream_content_block_start_accepts_bash_code_execution_result() {
718        let payload = r#"{
719            "type": "content_block_start",
720            "index": 1,
721            "content_block": {
722                "type": "bash_code_execution_tool_result",
723                "tool_use_id": "srvtoolu_456",
724                "content": {
725                    "type": "bash_code_execution_result",
726                    "stdout": "Python 3.11.12",
727                    "stderr": "",
728                    "return_code": 0
729                }
730            }
731        }"#;
732
733        let event: AnthropicStreamEvent =
734            serde_json::from_str(payload).expect("should deserialize bash code execution result");
735        match event {
736            AnthropicStreamEvent::ContentBlockStart {
737                content_block: AnthropicContentBlock::BashCodeExecutionToolResult { tool_use_id, .. },
738                ..
739            } => assert_eq!(tool_use_id, "srvtoolu_456"),
740            other => panic!("expected bash_code_execution_tool_result content_block_start, got {other:?}"),
741        }
742    }
743
744    #[test]
745    fn stream_content_block_start_accepts_text_editor_code_execution_result() {
746        let payload = r#"{
747            "type": "content_block_start",
748            "index": 2,
749            "content_block": {
750                "type": "text_editor_code_execution_tool_result",
751                "tool_use_id": "srvtoolu_789",
752                "content": {
753                    "type": "text_editor_code_execution_result",
754                    "is_file_update": false
755                }
756            }
757        }"#;
758
759        let event: AnthropicStreamEvent =
760            serde_json::from_str(payload).expect("should deserialize text editor code execution result");
761        match event {
762            AnthropicStreamEvent::ContentBlockStart {
763                content_block: AnthropicContentBlock::TextEditorCodeExecutionToolResult { tool_use_id, .. },
764                ..
765            } => assert_eq!(tool_use_id, "srvtoolu_789"),
766            other => panic!("expected text_editor_code_execution_tool_result content_block_start, got {other:?}"),
767        }
768    }
769
770    #[test]
771    fn text_block_accepts_web_search_result_citation() {
772        let payload = r#"{
773            "type": "text",
774            "text": "Rust 1.82 shipped",
775            "citations": [{
776                "type": "web_search_result_location",
777                "url": "https://blog.rust-lang.org",
778                "title": "Rust Blog",
779                "encrypted_index": "enc_123",
780                "cited_text": "Rust 1.82 shipped"
781            }]
782        }"#;
783
784        let block: AnthropicContentBlock = serde_json::from_str(payload).expect("should deserialize cited text block");
785        match block {
786            AnthropicContentBlock::Text { citations: Some(citations), .. } => {
787                assert!(matches!(
788                    &citations[0],
789                    TextCitation::WebSearchResultLocation {
790                        url: Some(url),
791                        title: Some(title),
792                        encrypted_index: Some(index),
793                        cited_text: Some(cited_text),
794                    } if url == "https://blog.rust-lang.org"
795                        && title == "Rust Blog"
796                        && index == "enc_123"
797                        && cited_text == "Rust 1.82 shipped"
798                ));
799            }
800            other => panic!("expected text block with citations, got {other:?}"),
801        }
802    }
803
804    #[test]
805    fn empty_output_config_deserializes_to_none() {
806        let request: AnthropicRequest = serde_json::from_str(
807            r#"{
808                "model": "claude-sonnet",
809                "messages": [],
810                "max_tokens": 128,
811                "output_config": {},
812                "stream": false
813            }"#,
814        )
815        .expect("should deserialize request");
816
817        assert!(request.output_config.is_none());
818    }
819
820    #[test]
821    fn boxed_output_config_is_smaller_than_inline_option() {
822        use std::mem::size_of;
823
824        assert!(size_of::<Option<Box<AnthropicOutputConfig>>>() < size_of::<Option<AnthropicOutputConfig>>());
825    }
826}