Skip to main content

rust_claude_sdk/
request.rs

1//! The body of `POST /v1/messages`.
2use serde::{Deserialize, Serialize};
3use serde_json::{Map, Value};
4
5use crate::error::Error;
6use crate::response::{Citation, ContentBlock};
7
8/// Beta header for `fallbacks: "default"`.
9pub(crate) const BETA_FALLBACK_DEFAULT: &str = "server-side-fallback-2026-07-01";
10/// Beta header for the array form `fallbacks: [{"model": ...}]`.
11pub(crate) const BETA_FALLBACK_LIST: &str = "server-side-fallback-2026-06-01";
12/// Beta header for `output_config.task_budget`.
13pub(crate) const BETA_TASK_BUDGET: &str = "task-budgets-2026-03-13";
14
15#[derive(Debug, Clone, PartialEq, Serialize)]
16pub struct MessagesRequest {
17    pub model: String,
18    pub max_tokens: u32,
19    pub messages: Vec<MessageParam>,
20    #[serde(skip_serializing_if = "Option::is_none")]
21    pub system: Option<System>,
22    #[serde(skip_serializing_if = "Option::is_none")]
23    pub thinking: Option<ThinkingConfig>,
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub output_config: Option<OutputConfig>,
26    #[serde(skip_serializing_if = "Vec::is_empty")]
27    pub tools: Vec<ToolDefinition>,
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub tool_choice: Option<ToolChoice>,
30    #[serde(skip_serializing_if = "Vec::is_empty")]
31    pub stop_sequences: Vec<String>,
32    /// Top-level automatic caching: the API places the breakpoint on the last cacheable block.
33    #[serde(skip_serializing_if = "Option::is_none")]
34    pub cache_control: Option<CacheControl>,
35    /// Server-side retry of a refused request on another model. The client adds the beta
36    /// header this form needs.
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub fallbacks: Option<Fallbacks>,
39    /// Set by `Client::stream`; leave it `None`.
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub stream: Option<bool>,
42    /// Further `anthropic-beta` values for this request.
43    #[serde(skip)]
44    pub betas: Vec<String>,
45    /// Any other top-level parameter, sent as is (e.g. `inference_geo`, `metadata`).
46    #[serde(flatten)]
47    pub extra: Map<String, Value>,
48}
49
50impl MessagesRequest {
51    pub fn new(model: impl Into<String>, max_tokens: u32) -> MessagesRequest {
52        MessagesRequest {
53            model: model.into(),
54            max_tokens,
55            messages: Vec::new(),
56            system: None,
57            thinking: None,
58            output_config: None,
59            tools: Vec::new(),
60            tool_choice: None,
61            stop_sequences: Vec::new(),
62            cache_control: None,
63            fallbacks: None,
64            stream: None,
65            betas: Vec::new(),
66            extra: Map::new(),
67        }
68    }
69
70    pub fn system(mut self, text: impl Into<String>) -> Self {
71        self.system = Some(System::Text(text.into()));
72        self
73    }
74
75    /// A system prompt marked as a cache breakpoint: keep it byte-identical across requests
76    /// (no dates or ids in it) so later requests read it from the cache.
77    pub fn system_cached(mut self, text: impl Into<String>) -> Self {
78        self.system = Some(System::Blocks(vec![SystemBlock { text: text.into(), cache_control: Some(CacheControl::ephemeral()) }]));
79        self
80    }
81
82    pub fn message(mut self, message: MessageParam) -> Self {
83        self.messages.push(message);
84        self
85    }
86
87    pub fn user(self, text: impl Into<String>) -> Self {
88        self.message(MessageParam::user_text(text))
89    }
90
91    pub fn thinking(mut self, thinking: ThinkingConfig) -> Self {
92        self.thinking = Some(thinking);
93        self
94    }
95
96    /// Sets `output_config.effort`. Not every model accepts it: Claude Haiku 4.5 and
97    /// Claude Sonnet 4.5 reject the parameter (use `ThinkingConfig::Enabled` there),
98    /// Claude Opus 4.5 takes only `Low`/`Medium`/`High`, and Claude Opus 4.6 / Sonnet 4.6
99    /// do not take `Xhigh`. The SDK does not check this; the API returns an error.
100    pub fn effort(mut self, effort: Effort) -> Self {
101        self.output_config.get_or_insert_with(OutputConfig::default).effort = Some(effort);
102        self
103    }
104
105    /// Sets `output_config.task_budget`: a token budget for the whole agentic loop that the
106    /// model sees and paces itself against (unlike `max_tokens`, which cuts it off). At least
107    /// 20,000. The client adds the beta header it needs. Leave `remaining` unset unless you
108    /// rewrite history between requests.
109    pub fn task_budget(mut self, total: u32) -> Self {
110        self.output_config.get_or_insert_with(OutputConfig::default).task_budget = Some(TaskBudget::tokens(total));
111        self
112    }
113
114    /// Structured outputs: the reply's text is JSON valid against `schema` (which needs
115    /// `additionalProperties: false` on its objects). Read it with `Message::json`. Cannot be
116    /// combined with citations. On models that reject forced `tool_choice` this replaces a
117    /// forced tool call made only to get JSON back.
118    pub fn json_schema(mut self, schema: Value) -> Self {
119        self.output_config.get_or_insert_with(OutputConfig::default).format = Some(serde_json::json!({"type": "json_schema", "schema": schema}));
120        self
121    }
122
123    pub fn tool(mut self, tool: impl Into<ToolDefinition>) -> Self {
124        self.tools.push(tool.into());
125        self
126    }
127
128    pub fn tool_choice(mut self, choice: ToolChoice) -> Self {
129        self.tool_choice = Some(choice);
130        self
131    }
132
133    pub fn fallbacks(mut self, fallbacks: Fallbacks) -> Self {
134        self.fallbacks = Some(fallbacks);
135        self
136    }
137
138    pub fn beta(mut self, beta: impl Into<String>) -> Self {
139        self.betas.push(beta.into());
140        self
141    }
142
143    /// Any other top-level parameter.
144    pub fn param(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
145        self.extra.insert(key.into(), value.into());
146        self
147    }
148
149    /// Checks the rules API version `2026-10-21` added, which the client applies before
150    /// sending on that version: no `temperature`, `top_p` or `top_k` (they were removed),
151    /// no `document` block directly in an assistant message (send documents in user
152    /// messages), and no `citations` on text in a user message, `search_result` blocks
153    /// included (citations stay accepted on echoed assistant text).
154    pub fn validate(&self) -> Result<(), Error> {
155        if let Some(p) = ["temperature", "top_p", "top_k"].into_iter().find(|p| self.extra.contains_key(*p)) {
156            return Err(Error::InvalidRequest(format!("`{p}` was removed in API version 2026-10-21")));
157        }
158        for (i, message) in self.messages.iter().enumerate() {
159            let blocks = match message {
160                MessageParam::User { content: Content::Blocks(b) } | MessageParam::Assistant { content: Content::Blocks(b) } => b,
161                _ => continue,
162            };
163            let role = message.role();
164            for block in blocks {
165                if role == Role::Assistant && block.kind() == Some("document") {
166                    return Err(Error::InvalidRequest(format!("messages[{i}]: send `document` blocks in user messages, not assistant ones")));
167                }
168                if role == Role::User && block.has_citations() {
169                    return Err(Error::InvalidRequest(format!("messages[{i}]: a user message cannot carry `citations` on its text")));
170                }
171            }
172        }
173        Ok(())
174    }
175
176    /// The `anthropic-beta` values this request needs: its own, then the ones its
177    /// `fallbacks` form and task budget require (unless already present), without duplicates.
178    pub fn beta_header_values(&self) -> Vec<String> {
179        let mut out: Vec<String> = Vec::new();
180        let fallback = match &self.fallbacks {
181            Some(Fallbacks::Default) => Some(BETA_FALLBACK_DEFAULT),
182            Some(Fallbacks::Models(_)) => Some(BETA_FALLBACK_LIST),
183            None => None,
184        };
185        let budget = self.output_config.as_ref().and_then(|c| c.task_budget.as_ref()).map(|_| BETA_TASK_BUDGET);
186        for b in self.betas.iter().map(String::as_str).chain(fallback).chain(budget) {
187            if !out.iter().any(|o| o == b) {
188                out.push(b.to_string());
189            }
190        }
191        out
192    }
193}
194
195#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
196#[serde(rename_all = "lowercase")]
197pub enum Role {
198    User,
199    Assistant,
200    /// A mid-conversation operator instruction (see `MessageParam::system`).
201    System,
202}
203
204/// One message of the conversation, typed by its role (serialised with its `role`).
205#[derive(Debug, Clone, PartialEq, Serialize)]
206#[serde(tag = "role", rename_all = "lowercase")]
207pub enum MessageParam {
208    User {
209        content: Content,
210    },
211    Assistant {
212        content: Content,
213    },
214    /// A mid-conversation operator instruction: text only (see `MessageParam::system`).
215    System {
216        content: System,
217    },
218}
219
220impl MessageParam {
221    pub fn user_text(text: impl Into<String>) -> MessageParam {
222        MessageParam::User { content: Content::Text(text.into()) }
223    }
224
225    pub fn user(blocks: Vec<ContentBlockParam>) -> MessageParam {
226        MessageParam::User { content: Content::Blocks(blocks) }
227    }
228
229    pub fn assistant(blocks: Vec<ContentBlockParam>) -> MessageParam {
230        MessageParam::Assistant { content: Content::Blocks(blocks) }
231    }
232
233    /// An operator instruction added mid-conversation, instead of editing the top-level
234    /// `system` (which would invalidate the cached history). It must follow a user turn and
235    /// be the last message or be followed by an assistant turn; never `messages[0]`. Not every
236    /// model accepts it (Claude Sonnet 5 does not).
237    pub fn system(text: impl Into<String>) -> MessageParam {
238        MessageParam::System { content: System::Text(text.into()) }
239    }
240
241    pub fn role(&self) -> Role {
242        match self {
243            MessageParam::User { .. } => Role::User,
244            MessageParam::Assistant { .. } => Role::Assistant,
245            MessageParam::System { .. } => Role::System,
246        }
247    }
248
249    /// The content of a user or assistant message; `None` for a system message.
250    pub fn content(&self) -> Option<&Content> {
251        match self {
252            MessageParam::User { content } | MessageParam::Assistant { content } => Some(content),
253            MessageParam::System { .. } => None,
254        }
255    }
256}
257
258#[derive(Debug, Clone, PartialEq, Serialize)]
259#[serde(untagged)]
260pub enum Content {
261    Text(String),
262    Blocks(Vec<ContentBlockParam>),
263}
264
265#[derive(Debug, Clone, PartialEq, Serialize)]
266#[serde(tag = "type", rename_all = "snake_case")]
267pub enum ContentBlockParam {
268    Text {
269        text: String,
270        /// Only on echoed assistant text that carried citations.
271        #[serde(skip_serializing_if = "Option::is_none")]
272        citations: Option<Vec<Citation>>,
273        #[serde(skip_serializing_if = "Option::is_none")]
274        cache_control: Option<CacheControl>,
275    },
276    Image {
277        source: ImageSource,
278        #[serde(skip_serializing_if = "Option::is_none")]
279        cache_control: Option<CacheControl>,
280    },
281    Document {
282        source: DocumentSource,
283        #[serde(skip_serializing_if = "Option::is_none")]
284        title: Option<String>,
285        /// Shown to the model but never cited from.
286        #[serde(skip_serializing_if = "Option::is_none")]
287        context: Option<String>,
288        /// Citations must be enabled on all documents of a request or on none.
289        #[serde(skip_serializing_if = "Option::is_none")]
290        citations: Option<CitationsConfig>,
291        #[serde(skip_serializing_if = "Option::is_none")]
292        cache_control: Option<CacheControl>,
293    },
294    ToolUse {
295        id: String,
296        name: String,
297        input: Value,
298    },
299    ToolResult {
300        tool_use_id: String,
301        content: ToolResultContent,
302        #[serde(skip_serializing_if = "Option::is_none")]
303        is_error: Option<bool>,
304        #[serde(skip_serializing_if = "Option::is_none")]
305        cache_control: Option<CacheControl>,
306    },
307    /// Echoed back unchanged on the same model.
308    Thinking {
309        thinking: String,
310        signature: String,
311    },
312    RedactedThinking {
313        data: String,
314    },
315    /// Any other block, sent verbatim (e.g. an echoed block type this crate does not model).
316    #[serde(untagged)]
317    Raw(Value),
318}
319
320impl ContentBlockParam {
321    pub fn text(text: impl Into<String>) -> ContentBlockParam {
322        ContentBlockParam::Text { text: text.into(), citations: None, cache_control: None }
323    }
324
325    /// A plain-text document; the API splits it into sentences for citations.
326    pub fn text_document(data: impl Into<String>, title: impl Into<String>) -> ContentBlockParam {
327        ContentBlockParam::Document {
328            source: DocumentSource::Text { media_type: "text/plain".into(), data: data.into() },
329            title: Some(title.into()),
330            context: None,
331            citations: None,
332            cache_control: None,
333        }
334    }
335
336    /// A document made of chunks you choose; citations point at chunk indices.
337    pub fn chunked_document(chunks: impl IntoIterator<Item = impl Into<String>>, title: impl Into<String>) -> ContentBlockParam {
338        let content = chunks.into_iter().map(|c| ContentBlockParam::text(c)).collect();
339        ContentBlockParam::Document {
340            source: DocumentSource::Content { content },
341            title: Some(title.into()),
342            context: None,
343            citations: None,
344            cache_control: None,
345        }
346    }
347
348    pub fn base64_pdf(data: impl Into<String>) -> ContentBlockParam {
349        ContentBlockParam::Document {
350            source: DocumentSource::Base64 { media_type: "application/pdf".into(), data: data.into() },
351            title: None,
352            context: None,
353            citations: None,
354            cache_control: None,
355        }
356    }
357
358    /// A document uploaded with the Files API (PDF or plain text).
359    pub fn file_document(file_id: impl Into<String>) -> ContentBlockParam {
360        ContentBlockParam::Document {
361            source: DocumentSource::File { file_id: file_id.into() },
362            title: None,
363            context: None,
364            citations: None,
365            cache_control: None,
366        }
367    }
368
369    /// An image uploaded with the Files API.
370    pub fn file_image(file_id: impl Into<String>) -> ContentBlockParam {
371        ContentBlockParam::Image { source: ImageSource::File { file_id: file_id.into() }, cache_control: None }
372    }
373
374    pub fn tool_result(tool_use_id: impl Into<String>, content: impl Into<String>, is_error: bool) -> ContentBlockParam {
375        ContentBlockParam::ToolResult {
376            tool_use_id: tool_use_id.into(),
377            content: ToolResultContent::Text(content.into()),
378            is_error: is_error.then_some(true),
379            cache_control: None,
380        }
381    }
382
383    /// The block's `type`.
384    fn kind(&self) -> Option<&str> {
385        match self {
386            ContentBlockParam::Document { .. } => Some("document"),
387            ContentBlockParam::Raw(v) => v.get("type").and_then(Value::as_str),
388            _ => None,
389        }
390    }
391
392    /// Whether this block, or a text block inside it (a tool result's content, a search
393    /// result's content), carries a non-empty `citations` array.
394    fn has_citations(&self) -> bool {
395        match self {
396            ContentBlockParam::Text { citations, .. } => citations.as_ref().is_some_and(|c| !c.is_empty()),
397            ContentBlockParam::ToolResult { content: ToolResultContent::Blocks(blocks), .. } => blocks.iter().any(ContentBlockParam::has_citations),
398            ContentBlockParam::Raw(v) => raw_has_citations(v),
399            _ => false,
400        }
401    }
402
403    /// Enables citations on a document; no effect on other blocks.
404    pub fn with_citations(mut self) -> Self {
405        if let ContentBlockParam::Document { citations, .. } = &mut self {
406            *citations = Some(CitationsConfig { enabled: true });
407        }
408        self
409    }
410
411    /// Sets the document's non-citable context; no effect on other blocks.
412    pub fn with_context(mut self, text: impl Into<String>) -> Self {
413        if let ContentBlockParam::Document { context, .. } = &mut self {
414            *context = Some(text.into());
415        }
416        self
417    }
418
419    /// Marks this block as a cache breakpoint; no effect on blocks that take none.
420    pub fn with_cache_control(mut self, cc: CacheControl) -> Self {
421        match &mut self {
422            ContentBlockParam::Text { cache_control, .. }
423            | ContentBlockParam::Image { cache_control, .. }
424            | ContentBlockParam::Document { cache_control, .. }
425            | ContentBlockParam::ToolResult { cache_control, .. } => *cache_control = Some(cc),
426            _ => {}
427        }
428        self
429    }
430}
431
432/// Echoing an assistant turn: every block goes back as received.
433impl From<ContentBlock> for ContentBlockParam {
434    fn from(block: ContentBlock) -> ContentBlockParam {
435        match block {
436            ContentBlock::Text { text, citations } => {
437                ContentBlockParam::Text { text, citations: (!citations.is_empty()).then_some(citations), cache_control: None }
438            }
439            ContentBlock::Thinking { thinking, signature } => ContentBlockParam::Thinking { thinking, signature },
440            ContentBlock::RedactedThinking { data } => ContentBlockParam::RedactedThinking { data },
441            ContentBlock::ToolUse { id, name, input } => ContentBlockParam::ToolUse { id, name, input },
442            other => ContentBlockParam::Raw(serde_json::to_value(&other).unwrap_or(Value::Null)),
443        }
444    }
445}
446
447/// A raw `text` block with non-empty `citations`, or a `search_result` or `tool_result`
448/// whose content holds one.
449fn raw_has_citations(v: &Value) -> bool {
450    match v.get("type").and_then(Value::as_str) {
451        Some("text") => v.get("citations").and_then(Value::as_array).is_some_and(|c| !c.is_empty()),
452        Some("search_result" | "tool_result") => v.get("content").and_then(Value::as_array).is_some_and(|c| c.iter().any(raw_has_citations)),
453        _ => false,
454    }
455}
456
457#[derive(Debug, Clone, PartialEq, Serialize)]
458#[serde(tag = "type", rename_all = "snake_case")]
459pub enum DocumentSource {
460    Text { media_type: String, data: String },
461    Base64 { media_type: String, data: String },
462    Content { content: Vec<ContentBlockParam> },
463    Url { url: String },
464    File { file_id: String },
465}
466
467#[derive(Debug, Clone, PartialEq, Serialize)]
468#[serde(tag = "type", rename_all = "snake_case")]
469pub enum ImageSource {
470    Base64 { media_type: String, data: String },
471    Url { url: String },
472    File { file_id: String },
473}
474
475#[derive(Debug, Clone, PartialEq, Serialize)]
476#[serde(untagged)]
477pub enum ToolResultContent {
478    Text(String),
479    Blocks(Vec<ContentBlockParam>),
480}
481
482#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
483pub struct CitationsConfig {
484    pub enabled: bool,
485}
486
487#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
488pub struct CacheControl {
489    #[serde(rename = "type")]
490    pub kind: String,
491    /// `"5m"` (default) or `"1h"`.
492    #[serde(skip_serializing_if = "Option::is_none")]
493    pub ttl: Option<String>,
494}
495
496impl CacheControl {
497    pub fn ephemeral() -> CacheControl {
498        CacheControl { kind: "ephemeral".into(), ttl: None }
499    }
500
501    pub fn one_hour() -> CacheControl {
502        CacheControl { kind: "ephemeral".into(), ttl: Some("1h".into()) }
503    }
504}
505
506#[derive(Debug, Clone, PartialEq, Serialize)]
507#[serde(untagged)]
508pub enum System {
509    Text(String),
510    Blocks(Vec<SystemBlock>),
511}
512
513/// A system prompt block; serialised with `"type": "text"`.
514#[derive(Debug, Clone, PartialEq, Serialize)]
515#[serde(tag = "type", rename = "text")]
516pub struct SystemBlock {
517    pub text: String,
518    #[serde(skip_serializing_if = "Option::is_none")]
519    pub cache_control: Option<CacheControl>,
520}
521
522#[derive(Debug, Clone, PartialEq, Serialize)]
523#[serde(tag = "type", rename_all = "snake_case")]
524pub enum ThinkingConfig {
525    /// The model decides when and how much to think; `effort` sets the depth.
526    Adaptive {
527        #[serde(skip_serializing_if = "Option::is_none")]
528        display: Option<ThinkingDisplay>,
529    },
530    /// Rejected by several current models (see the model's documentation).
531    Disabled,
532    /// Older models only.
533    Enabled { budget_tokens: u32 },
534    /// Claude Sonnet 5.5's way to turn thinking off.
535    BetweenTools,
536}
537
538#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
539#[serde(rename_all = "lowercase")]
540pub enum ThinkingDisplay {
541    Summarized,
542    Omitted,
543    Updates,
544}
545
546#[derive(Debug, Clone, Default, PartialEq, Serialize)]
547pub struct OutputConfig {
548    #[serde(skip_serializing_if = "Option::is_none")]
549    pub effort: Option<Effort>,
550    /// Structured output format (cannot be combined with citations).
551    #[serde(skip_serializing_if = "Option::is_none")]
552    pub format: Option<Value>,
553    /// Token budget for an agentic loop (beta; see `MessagesRequest::task_budget`).
554    #[serde(skip_serializing_if = "Option::is_none")]
555    pub task_budget: Option<TaskBudget>,
556}
557
558/// `output_config.task_budget`.
559#[derive(Debug, Clone, PartialEq, Serialize)]
560#[serde(tag = "type", rename = "tokens")]
561pub struct TaskBudget {
562    pub total: u32,
563    /// What is left of `total`; the server tracks it unless history was rewritten.
564    #[serde(skip_serializing_if = "Option::is_none")]
565    pub remaining: Option<u32>,
566}
567
568impl TaskBudget {
569    pub fn tokens(total: u32) -> TaskBudget {
570        TaskBudget { total, remaining: None }
571    }
572}
573
574#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
575#[serde(rename_all = "lowercase")]
576pub enum Effort {
577    Low,
578    Medium,
579    High,
580    Xhigh,
581    Max,
582}
583
584#[derive(Debug, Clone, PartialEq, Serialize)]
585pub struct Tool {
586    pub name: String,
587    pub description: String,
588    pub input_schema: Value,
589    #[serde(skip_serializing_if = "Option::is_none")]
590    pub strict: Option<bool>,
591    /// Loaded only when a tool search finds it (see `ToolSearchTool`).
592    #[serde(skip_serializing_if = "Option::is_none")]
593    pub defer_loading: Option<bool>,
594    /// Stream the input as it is generated (see `Tool::eager_input_streaming`).
595    #[serde(skip_serializing_if = "Option::is_none")]
596    pub eager_input_streaming: Option<bool>,
597    #[serde(skip_serializing_if = "Option::is_none")]
598    pub cache_control: Option<CacheControl>,
599}
600
601impl Tool {
602    pub fn new(name: impl Into<String>, description: impl Into<String>, input_schema: Value) -> Tool {
603        Tool {
604            name: name.into(),
605            description: description.into(),
606            input_schema,
607            strict: None,
608            defer_loading: None,
609            eager_input_streaming: None,
610            cache_control: None,
611        }
612    }
613
614    /// When streaming, large inputs arrive as they are generated instead of in one burst at
615    /// the end. The API then no longer validates the input: it may be cut short
616    /// (`max_tokens`) or invalid JSON, so check it before running the tool. Leave it off for
617    /// requests that are not streamed.
618    pub fn eager_input_streaming(mut self) -> Self {
619        self.eager_input_streaming = Some(true);
620        self
621    }
622
623    /// Inputs always validate against the schema (which needs `additionalProperties: false`).
624    pub fn strict(mut self) -> Self {
625        self.strict = Some(true);
626        self
627    }
628
629    pub fn deferred(mut self) -> Self {
630        self.defer_loading = Some(true);
631        self
632    }
633
634    pub fn with_cache_control(mut self, cc: CacheControl) -> Self {
635        self.cache_control = Some(cc);
636        self
637    }
638}
639
640/// A tool definition: a custom tool, a server tool Anthropic runs, or anything else as raw JSON.
641#[derive(Debug, Clone, PartialEq, Serialize)]
642#[serde(untagged)]
643pub enum ToolDefinition {
644    Custom(Tool),
645    WebSearch(WebSearchTool),
646    WebFetch(WebFetchTool),
647    CodeExecution(CodeExecutionTool),
648    ToolSearch(ToolSearchTool),
649    Raw(Value),
650}
651
652impl From<Tool> for ToolDefinition {
653    fn from(t: Tool) -> ToolDefinition {
654        ToolDefinition::Custom(t)
655    }
656}
657
658impl From<WebSearchTool> for ToolDefinition {
659    fn from(t: WebSearchTool) -> ToolDefinition {
660        ToolDefinition::WebSearch(t)
661    }
662}
663
664impl From<WebFetchTool> for ToolDefinition {
665    fn from(t: WebFetchTool) -> ToolDefinition {
666        ToolDefinition::WebFetch(t)
667    }
668}
669
670impl From<CodeExecutionTool> for ToolDefinition {
671    fn from(t: CodeExecutionTool) -> ToolDefinition {
672        ToolDefinition::CodeExecution(t)
673    }
674}
675
676impl From<ToolSearchTool> for ToolDefinition {
677    fn from(t: ToolSearchTool) -> ToolDefinition {
678        ToolDefinition::ToolSearch(t)
679    }
680}
681
682impl From<Value> for ToolDefinition {
683    fn from(v: Value) -> ToolDefinition {
684        ToolDefinition::Raw(v)
685    }
686}
687
688/// Server-side web search. Results come back as `ContentBlock::WebSearchToolResult` blocks
689/// and cited text carries `Citation::WebSearchResultLocation`. A failed search is an error
690/// object inside the result block, not an API error.
691#[derive(Debug, Clone, PartialEq, Serialize)]
692pub struct WebSearchTool {
693    /// The tool version, e.g. `web_search_20260209`.
694    #[serde(rename = "type")]
695    pub kind: String,
696    pub name: String,
697    #[serde(skip_serializing_if = "Option::is_none")]
698    pub max_uses: Option<u32>,
699    /// Use `allowed_domains` or `blocked_domains`, not both.
700    #[serde(skip_serializing_if = "Option::is_none")]
701    pub allowed_domains: Option<Vec<String>>,
702    #[serde(skip_serializing_if = "Option::is_none")]
703    pub blocked_domains: Option<Vec<String>>,
704    #[serde(skip_serializing_if = "Option::is_none")]
705    pub user_location: Option<UserLocation>,
706    #[serde(skip_serializing_if = "Option::is_none")]
707    pub cache_control: Option<CacheControl>,
708}
709
710impl WebSearchTool {
711    /// The version with dynamic filtering (Claude Opus 4.6, Claude Sonnet 4.6 and later).
712    /// Do not also declare `CodeExecutionTool`: it runs code on its own.
713    pub fn new() -> WebSearchTool {
714        WebSearchTool::version("web_search_20260209")
715    }
716
717    /// The basic version, for older models and Vertex AI.
718    pub fn basic() -> WebSearchTool {
719        WebSearchTool::version("web_search_20250305")
720    }
721
722    pub fn version(kind: impl Into<String>) -> WebSearchTool {
723        WebSearchTool {
724            kind: kind.into(),
725            name: "web_search".into(),
726            max_uses: None,
727            allowed_domains: None,
728            blocked_domains: None,
729            user_location: None,
730            cache_control: None,
731        }
732    }
733
734    pub fn max_uses(mut self, n: u32) -> Self {
735        self.max_uses = Some(n);
736        self
737    }
738
739    pub fn allowed_domains(mut self, domains: impl IntoIterator<Item = impl Into<String>>) -> Self {
740        self.allowed_domains = Some(domains.into_iter().map(Into::into).collect());
741        self
742    }
743
744    pub fn blocked_domains(mut self, domains: impl IntoIterator<Item = impl Into<String>>) -> Self {
745        self.blocked_domains = Some(domains.into_iter().map(Into::into).collect());
746        self
747    }
748
749    pub fn user_location(mut self, location: UserLocation) -> Self {
750        self.user_location = Some(location);
751        self
752    }
753}
754
755impl Default for WebSearchTool {
756    fn default() -> Self {
757        WebSearchTool::new()
758    }
759}
760
761/// Where the user roughly is, to localise search results; serialised with `"type": "approximate"`.
762#[derive(Debug, Clone, Default, PartialEq, Serialize)]
763#[serde(tag = "type", rename = "approximate")]
764pub struct UserLocation {
765    #[serde(skip_serializing_if = "Option::is_none")]
766    pub city: Option<String>,
767    #[serde(skip_serializing_if = "Option::is_none")]
768    pub region: Option<String>,
769    /// ISO 3166-1 alpha-2, e.g. `RO`.
770    #[serde(skip_serializing_if = "Option::is_none")]
771    pub country: Option<String>,
772    /// IANA time zone, e.g. `Europe/Bucharest`.
773    #[serde(skip_serializing_if = "Option::is_none")]
774    pub timezone: Option<String>,
775}
776
777/// Server-side fetch of a URL already present in the conversation. The page comes back as
778/// a `ContentBlock::WebFetchToolResult` block.
779#[derive(Debug, Clone, PartialEq, Serialize)]
780pub struct WebFetchTool {
781    /// The tool version, e.g. `web_fetch_20260209`.
782    #[serde(rename = "type")]
783    pub kind: String,
784    pub name: String,
785    #[serde(skip_serializing_if = "Option::is_none")]
786    pub max_uses: Option<u32>,
787    #[serde(skip_serializing_if = "Option::is_none")]
788    pub allowed_domains: Option<Vec<String>>,
789    #[serde(skip_serializing_if = "Option::is_none")]
790    pub blocked_domains: Option<Vec<String>>,
791    /// Lets the answer cite the fetched pages.
792    #[serde(skip_serializing_if = "Option::is_none")]
793    pub citations: Option<CitationsConfig>,
794    /// Truncates long pages to about this many tokens.
795    #[serde(skip_serializing_if = "Option::is_none")]
796    pub max_content_tokens: Option<u32>,
797    #[serde(skip_serializing_if = "Option::is_none")]
798    pub cache_control: Option<CacheControl>,
799}
800
801impl WebFetchTool {
802    /// The version with dynamic filtering (Claude Opus 4.6, Claude Sonnet 4.6 and later).
803    pub fn new() -> WebFetchTool {
804        WebFetchTool::version("web_fetch_20260209")
805    }
806
807    /// The basic version, for older models.
808    pub fn basic() -> WebFetchTool {
809        WebFetchTool::version("web_fetch_20250910")
810    }
811
812    pub fn version(kind: impl Into<String>) -> WebFetchTool {
813        WebFetchTool {
814            kind: kind.into(),
815            name: "web_fetch".into(),
816            max_uses: None,
817            allowed_domains: None,
818            blocked_domains: None,
819            citations: None,
820            max_content_tokens: None,
821            cache_control: None,
822        }
823    }
824
825    pub fn max_uses(mut self, n: u32) -> Self {
826        self.max_uses = Some(n);
827        self
828    }
829
830    pub fn allowed_domains(mut self, domains: impl IntoIterator<Item = impl Into<String>>) -> Self {
831        self.allowed_domains = Some(domains.into_iter().map(Into::into).collect());
832        self
833    }
834
835    pub fn blocked_domains(mut self, domains: impl IntoIterator<Item = impl Into<String>>) -> Self {
836        self.blocked_domains = Some(domains.into_iter().map(Into::into).collect());
837        self
838    }
839
840    pub fn with_citations(mut self) -> Self {
841        self.citations = Some(CitationsConfig { enabled: true });
842        self
843    }
844
845    pub fn max_content_tokens(mut self, n: u32) -> Self {
846        self.max_content_tokens = Some(n);
847        self
848    }
849}
850
851impl Default for WebFetchTool {
852    fn default() -> Self {
853        WebFetchTool::new()
854    }
855}
856
857/// Server-side code execution in a sandbox. Output comes back as
858/// `ContentBlock::BashCodeExecutionToolResult` and `TextEditorCodeExecutionToolResult` blocks;
859/// files it writes can be downloaded with `Client::download_file`.
860#[derive(Debug, Clone, PartialEq, Serialize)]
861pub struct CodeExecutionTool {
862    /// The tool version, e.g. `code_execution_20260521`.
863    #[serde(rename = "type")]
864    pub kind: String,
865    pub name: String,
866    #[serde(skip_serializing_if = "Option::is_none")]
867    pub cache_control: Option<CacheControl>,
868}
869
870impl CodeExecutionTool {
871    pub fn new() -> CodeExecutionTool {
872        CodeExecutionTool::version("code_execution_20260521")
873    }
874
875    /// Another version, e.g. `code_execution_20260120` for programmatic tool calling.
876    pub fn version(kind: impl Into<String>) -> CodeExecutionTool {
877        CodeExecutionTool { kind: kind.into(), name: "code_execution".into(), cache_control: None }
878    }
879}
880
881impl Default for CodeExecutionTool {
882    fn default() -> Self {
883        CodeExecutionTool::new()
884    }
885}
886
887/// Server-side search over the request's deferred tools (`Tool::deferred`): only the tools
888/// it finds are loaded. Keep at least one tool, this one included, not deferred.
889#[derive(Debug, Clone, PartialEq, Serialize)]
890pub struct ToolSearchTool {
891    /// `tool_search_tool_regex_20251119` or `tool_search_tool_bm25_20251119`.
892    #[serde(rename = "type")]
893    pub kind: String,
894    pub name: String,
895}
896
897impl ToolSearchTool {
898    /// The model searches with regular expressions.
899    pub fn regex() -> ToolSearchTool {
900        ToolSearchTool { kind: "tool_search_tool_regex_20251119".into(), name: "tool_search_tool_regex".into() }
901    }
902
903    /// The model searches with natural-language queries.
904    pub fn bm25() -> ToolSearchTool {
905        ToolSearchTool { kind: "tool_search_tool_bm25_20251119".into(), name: "tool_search_tool_bm25".into() }
906    }
907}
908
909#[derive(Debug, Clone, PartialEq, Serialize)]
910#[serde(tag = "type", rename_all = "snake_case")]
911pub enum ToolChoice {
912    Auto {
913        #[serde(skip_serializing_if = "Option::is_none")]
914        disable_parallel_tool_use: Option<bool>,
915    },
916    None,
917    /// Rejected by several current models; prefer `Auto` and say which tool to use.
918    Any,
919    /// Rejected by several current models; prefer `Auto` and say which tool to use.
920    Tool {
921        name: String,
922    },
923}
924
925/// Which model the API retries a refused request on.
926#[derive(Debug, Clone, PartialEq)]
927pub enum Fallbacks {
928    /// `"default"`: the API picks the fallback by refusal category.
929    Default,
930    /// Named models, tried in order.
931    Models(Vec<FallbackModel>),
932}
933
934#[derive(Debug, Clone, PartialEq, Serialize)]
935pub struct FallbackModel {
936    pub model: String,
937    #[serde(skip_serializing_if = "Option::is_none")]
938    pub max_tokens: Option<u32>,
939}
940
941impl Serialize for Fallbacks {
942    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
943        match self {
944            Fallbacks::Default => s.serialize_str("default"),
945            Fallbacks::Models(models) => models.serialize(s),
946        }
947    }
948}