1use serde::{Deserialize, Serialize};
3use serde_json::{Map, Value};
4
5use crate::error::Error;
6use crate::response::{Citation, ContentBlock};
7
8pub(crate) const BETA_FALLBACK_DEFAULT: &str = "server-side-fallback-2026-07-01";
10pub(crate) const BETA_FALLBACK_LIST: &str = "server-side-fallback-2026-06-01";
12pub(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 #[serde(skip_serializing_if = "Option::is_none")]
34 pub cache_control: Option<CacheControl>,
35 #[serde(skip_serializing_if = "Option::is_none")]
38 pub fallbacks: Option<Fallbacks>,
39 #[serde(skip_serializing_if = "Option::is_none")]
41 pub stream: Option<bool>,
42 #[serde(skip)]
44 pub betas: Vec<String>,
45 #[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 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 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 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 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 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 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 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 System,
202}
203
204#[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 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 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 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 #[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 #[serde(skip_serializing_if = "Option::is_none")]
287 context: Option<String>,
288 #[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 Thinking {
309 thinking: String,
310 signature: String,
311 },
312 RedactedThinking {
313 data: String,
314 },
315 #[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 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 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 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 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 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 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 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 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 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
432impl 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
447fn 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 #[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#[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 Adaptive {
527 #[serde(skip_serializing_if = "Option::is_none")]
528 display: Option<ThinkingDisplay>,
529 },
530 Disabled,
532 Enabled { budget_tokens: u32 },
534 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 #[serde(skip_serializing_if = "Option::is_none")]
552 pub format: Option<Value>,
553 #[serde(skip_serializing_if = "Option::is_none")]
555 pub task_budget: Option<TaskBudget>,
556}
557
558#[derive(Debug, Clone, PartialEq, Serialize)]
560#[serde(tag = "type", rename = "tokens")]
561pub struct TaskBudget {
562 pub total: u32,
563 #[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 #[serde(skip_serializing_if = "Option::is_none")]
593 pub defer_loading: Option<bool>,
594 #[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 pub fn eager_input_streaming(mut self) -> Self {
619 self.eager_input_streaming = Some(true);
620 self
621 }
622
623 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#[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#[derive(Debug, Clone, PartialEq, Serialize)]
692pub struct WebSearchTool {
693 #[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 #[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 pub fn new() -> WebSearchTool {
714 WebSearchTool::version("web_search_20260209")
715 }
716
717 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#[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 #[serde(skip_serializing_if = "Option::is_none")]
771 pub country: Option<String>,
772 #[serde(skip_serializing_if = "Option::is_none")]
774 pub timezone: Option<String>,
775}
776
777#[derive(Debug, Clone, PartialEq, Serialize)]
780pub struct WebFetchTool {
781 #[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 #[serde(skip_serializing_if = "Option::is_none")]
793 pub citations: Option<CitationsConfig>,
794 #[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 pub fn new() -> WebFetchTool {
804 WebFetchTool::version("web_fetch_20260209")
805 }
806
807 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#[derive(Debug, Clone, PartialEq, Serialize)]
861pub struct CodeExecutionTool {
862 #[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 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#[derive(Debug, Clone, PartialEq, Serialize)]
890pub struct ToolSearchTool {
891 #[serde(rename = "type")]
893 pub kind: String,
894 pub name: String,
895}
896
897impl ToolSearchTool {
898 pub fn regex() -> ToolSearchTool {
900 ToolSearchTool { kind: "tool_search_tool_regex_20251119".into(), name: "tool_search_tool_regex".into() }
901 }
902
903 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 Any,
919 Tool {
921 name: String,
922 },
923}
924
925#[derive(Debug, Clone, PartialEq)]
927pub enum Fallbacks {
928 Default,
930 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}