1use serde::{Deserialize, Serialize};
10
11#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
13pub struct CacheControl {
14 #[serde(rename = "type")]
15 pub control_type: CacheControlType,
16 #[serde(default, skip_serializing_if = "Option::is_none")]
18 pub ttl: Option<String>,
19}
20
21#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
22#[serde(rename_all = "lowercase")]
23pub enum CacheControlType {
24 #[default]
25 Ephemeral,
26 #[serde(other)]
27 Unknown,
28}
29
30const MIN_TTL_SECONDS: u64 = 300;
31const MAX_TTL_SECONDS: u64 = 3600;
32
33impl CacheControl {
34 pub fn ttl_seconds(&self) -> u64 {
40 let raw = match self.ttl.as_deref() {
41 None => return MIN_TTL_SECONDS,
42 Some("5m") => 300,
43 Some("1h") => 3600,
44 Some(other) => match other.parse::<u64>() {
45 Ok(secs) => secs,
46 Err(_) => {
47 tracing::warn!("Unrecognized TTL '{}', defaulting to 300s", other);
48 return MIN_TTL_SECONDS;
49 }
50 },
51 };
52 raw.clamp(MIN_TTL_SECONDS, MAX_TTL_SECONDS)
53 }
54}
55#[derive(Debug, Clone, Serialize, Deserialize)]
57pub struct SystemContent {
58 pub text: String,
60 #[serde(skip_serializing_if = "Option::is_none")]
62 pub cache_control: Option<CacheControl>,
63}
64
65fn deserialize_system_prompt<'de, D>(deserializer: D) -> Result<Option<SystemContent>, D::Error>
69where
70 D: serde::Deserializer<'de>,
71{
72 #[derive(Deserialize)]
73 #[serde(untagged)]
74 enum SystemPrompt {
75 Text(String),
76 Blocks(Vec<SystemBlock>),
77 }
78
79 #[derive(Deserialize)]
80 struct SystemBlock {
81 text: String,
82 #[serde(default)]
83 cache_control: Option<CacheControl>,
84 }
85
86 let maybe: Option<SystemPrompt> = Option::deserialize(deserializer)?;
87 Ok(maybe.map(|sp| match sp {
88 SystemPrompt::Text(s) => SystemContent {
89 text: s,
90 cache_control: None,
91 },
92 SystemPrompt::Blocks(blocks) => {
93 let cache_control = blocks.iter().rev().find_map(|b| b.cache_control.clone());
94 let text = blocks
95 .into_iter()
96 .map(|b| b.text)
97 .collect::<Vec<_>>()
98 .join("\n");
99 SystemContent {
100 text,
101 cache_control,
102 }
103 }
104 }))
105}
106#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct AnthropicCreateMessageRequest {
109 pub model: String,
111
112 pub max_tokens: u32,
114
115 pub messages: Vec<AnthropicMessage>,
117
118 #[serde(default, skip_serializing_if = "Option::is_none")]
121 pub nvext: Option<serde_json::Value>,
122
123 #[serde(
125 default,
126 skip_serializing_if = "Option::is_none",
127 deserialize_with = "deserialize_system_prompt"
128 )]
129 pub system: Option<SystemContent>,
130
131 #[serde(skip_serializing_if = "Option::is_none")]
133 pub temperature: Option<f32>,
134
135 #[serde(skip_serializing_if = "Option::is_none")]
137 pub top_p: Option<f32>,
138
139 #[serde(skip_serializing_if = "Option::is_none")]
141 pub top_k: Option<u32>,
142
143 #[serde(skip_serializing_if = "Option::is_none")]
145 pub stop_sequences: Option<Vec<String>>,
146
147 #[serde(default)]
149 pub stream: bool,
150
151 #[serde(skip_serializing_if = "Option::is_none")]
153 pub metadata: Option<serde_json::Value>,
154
155 #[serde(skip_serializing_if = "Option::is_none")]
157 pub tools: Option<Vec<AnthropicTool>>,
158
159 #[serde(skip_serializing_if = "Option::is_none")]
161 pub tool_choice: Option<AnthropicToolChoice>,
162
163 #[serde(default, skip_serializing_if = "Option::is_none")]
168 pub cache_control: Option<CacheControl>,
169
170 #[serde(default, skip_serializing_if = "Option::is_none")]
175 pub thinking: Option<ThinkingConfig>,
176
177 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub service_tier: Option<String>,
180
181 #[serde(default, skip_serializing_if = "Option::is_none")]
183 pub container: Option<String>,
184
185 #[serde(default, skip_serializing_if = "Option::is_none")]
189 pub output_config: Option<serde_json::Value>,
190}
191
192#[derive(Debug, Clone, Serialize, Deserialize)]
199pub struct ThinkingConfig {
200 #[serde(rename = "type")]
202 pub thinking_type: String,
203 #[serde(skip_serializing_if = "Option::is_none")]
205 pub budget_tokens: Option<u32>,
206}
207
208#[derive(Debug, Clone, Serialize, Deserialize)]
210pub struct AnthropicMessage {
211 pub role: AnthropicRole,
212 #[serde(flatten)]
213 pub content: AnthropicMessageContent,
214}
215
216#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
218#[serde(rename_all = "lowercase")]
219pub enum AnthropicRole {
220 User,
221 Assistant,
222 System,
225}
226
227#[derive(Debug, Clone, Serialize, Deserialize)]
229#[serde(untagged)]
230pub enum AnthropicMessageContent {
231 Text { content: String },
233 Blocks { content: Vec<AnthropicContentBlock> },
235}
236
237#[derive(Debug, Clone, Serialize)]
244#[serde(tag = "type")]
245pub enum AnthropicContentBlock {
246 #[serde(rename = "text")]
250 Text {
251 text: String,
252 #[serde(default, skip_serializing_if = "Option::is_none")]
253 citations: Option<Vec<serde_json::Value>>,
254 #[serde(default, skip_serializing_if = "Option::is_none")]
255 cache_control: Option<CacheControl>,
256 },
257 #[serde(rename = "image")]
259 Image { source: AnthropicImageSource },
260 #[serde(rename = "tool_use")]
262 ToolUse {
263 id: String,
264 name: String,
265 input: serde_json::Value,
266 #[serde(default, skip_serializing_if = "Option::is_none")]
267 cache_control: Option<CacheControl>,
268 },
269 #[serde(rename = "tool_result")]
271 ToolResult {
272 tool_use_id: String,
273 #[serde(default, skip_serializing_if = "Option::is_none")]
274 content: Option<ToolResultContent>,
275 #[serde(skip_serializing_if = "Option::is_none")]
276 is_error: Option<bool>,
277 #[serde(default, skip_serializing_if = "Option::is_none")]
278 cache_control: Option<CacheControl>,
279 },
280 #[serde(rename = "thinking")]
282 Thinking {
283 thinking: String,
284 signature: String,
285 #[serde(default, skip_serializing_if = "Option::is_none")]
286 cache_control: Option<CacheControl>,
287 },
288 #[serde(rename = "redacted_thinking")]
292 RedactedThinking { data: String },
293 #[serde(rename = "server_tool_use")]
297 ServerToolUse {
298 id: String,
299 name: String,
300 #[serde(default)]
301 input: serde_json::Value,
302 },
303 #[serde(rename = "web_search_tool_result")]
306 WebSearchToolResult {
307 tool_use_id: String,
308 #[serde(default)]
309 content: serde_json::Value,
310 },
311 #[serde(untagged)]
315 Other(serde_json::Value),
316}
317
318#[derive(Debug, Clone, Serialize, Deserialize)]
321#[serde(untagged)]
322pub enum ToolResultContent {
323 Text(String),
324 Blocks(Vec<ToolResultContentBlock>),
325}
326
327impl ToolResultContent {
328 pub fn into_text(self) -> String {
330 match self {
331 ToolResultContent::Text(s) => s,
332 ToolResultContent::Blocks(blocks) => blocks
333 .into_iter()
334 .filter_map(|b| match b {
335 ToolResultContentBlock::Text { text } => Some(text),
336 ToolResultContentBlock::Image { .. } | ToolResultContentBlock::Other(_) => None,
337 })
338 .collect::<Vec<_>>()
339 .join(""),
340 }
341 }
342}
343
344#[derive(Debug, Clone)]
346pub enum ToolResultContentBlock {
347 Text {
348 text: String,
349 },
350 Image {
352 source: AnthropicImageSource,
353 },
354 Other(serde_json::Value),
356}
357
358impl Serialize for ToolResultContentBlock {
359 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
360 where
361 S: serde::Serializer,
362 {
363 match self {
364 Self::Text { text } => serde_json::json!({
365 "type": "text",
366 "text": text,
367 })
368 .serialize(serializer),
369 Self::Image { source } => serde_json::json!({
370 "type": "image",
371 "source": source,
372 })
373 .serialize(serializer),
374 Self::Other(value) => value.serialize(serializer),
375 }
376 }
377}
378
379fn take_field(value: &mut serde_json::Value, field: &str) -> Option<serde_json::Value> {
380 value.as_object_mut()?.remove(field)
381}
382
383fn take_required_string<E: serde::de::Error>(
384 value: &mut serde_json::Value,
385 field: &'static str,
386) -> Result<String, E> {
387 match take_field(value, field) {
388 Some(serde_json::Value::String(text)) => Ok(text),
389 _ => Err(E::missing_field(field)),
390 }
391}
392
393impl<'de> Deserialize<'de> for ToolResultContentBlock {
394 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
395 where
396 D: serde::Deserializer<'de>,
397 {
398 let mut value = serde_json::Value::deserialize(deserializer)?;
399 match value.get("type").and_then(|value| value.as_str()) {
400 Some("text") => {
401 let text = take_required_string::<D::Error>(&mut value, "text")?;
402 Ok(Self::Text { text })
403 }
404 Some("image") => {
405 let source = take_field(&mut value, "source")
406 .ok_or_else(|| serde::de::Error::missing_field("source"))
407 .and_then(|value| {
408 serde_json::from_value(value).map_err(serde::de::Error::custom)
409 })?;
410 Ok(Self::Image { source })
411 }
412 None if value.get("text").is_some_and(serde_json::Value::is_string) => Ok(Self::Text {
413 text: take_required_string::<D::Error>(&mut value, "text")?,
414 }),
415 _ => Ok(Self::Other(value)),
416 }
417 }
418}
419
420impl<'de> Deserialize<'de> for AnthropicContentBlock {
424 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
425 where
426 D: serde::Deserializer<'de>,
427 {
428 let mut value = serde_json::Value::deserialize(deserializer)?;
429 let block_type = value.get("type").and_then(|t| t.as_str()).unwrap_or("");
430
431 match block_type {
432 "text" => {
433 let text = take_required_string::<D::Error>(&mut value, "text")?;
434 let citations: Option<Vec<serde_json::Value>> = take_field(&mut value, "citations")
435 .and_then(|v| serde_json::from_value(v).ok());
436 let cache_control: Option<CacheControl> = take_field(&mut value, "cache_control")
437 .and_then(|v| serde_json::from_value(v).ok());
438 Ok(AnthropicContentBlock::Text {
439 text,
440 citations,
441 cache_control,
442 })
443 }
444 "image" => {
445 let source: AnthropicImageSource =
446 serde_json::from_value(take_field(&mut value, "source").unwrap_or_default())
447 .map_err(serde::de::Error::custom)?;
448 Ok(AnthropicContentBlock::Image { source })
449 }
450 "tool_use" => {
451 let id = take_required_string::<D::Error>(&mut value, "id")?;
452 let name = take_required_string::<D::Error>(&mut value, "name")?;
453 let input =
454 take_field(&mut value, "input").unwrap_or_else(|| serde_json::json!({}));
455 let cache_control: Option<CacheControl> = take_field(&mut value, "cache_control")
456 .and_then(|v| serde_json::from_value(v).ok());
457 Ok(AnthropicContentBlock::ToolUse {
458 id,
459 name,
460 input,
461 cache_control,
462 })
463 }
464 "tool_result" => {
465 let tool_use_id = take_required_string::<D::Error>(&mut value, "tool_use_id")?;
466 let content: Option<ToolResultContent> =
467 take_field(&mut value, "content").and_then(|v| serde_json::from_value(v).ok());
468 let is_error = value.get("is_error").and_then(|v| v.as_bool());
469 let cache_control: Option<CacheControl> = take_field(&mut value, "cache_control")
470 .and_then(|v| serde_json::from_value(v).ok());
471 Ok(AnthropicContentBlock::ToolResult {
472 tool_use_id,
473 content,
474 is_error,
475 cache_control,
476 })
477 }
478 "thinking" => {
479 let thinking = take_required_string::<D::Error>(&mut value, "thinking")?;
480 let signature = take_required_string::<D::Error>(&mut value, "signature")?;
481 let cache_control: Option<CacheControl> = take_field(&mut value, "cache_control")
482 .and_then(|v| serde_json::from_value(v).ok());
483 Ok(AnthropicContentBlock::Thinking {
484 thinking,
485 signature,
486 cache_control,
487 })
488 }
489 "redacted_thinking" => {
490 let data = take_required_string::<D::Error>(&mut value, "data")?;
491 Ok(AnthropicContentBlock::RedactedThinking { data })
492 }
493 "server_tool_use" => {
494 let id = take_required_string::<D::Error>(&mut value, "id")?;
495 let name = take_required_string::<D::Error>(&mut value, "name")?;
496 let input =
497 take_field(&mut value, "input").unwrap_or_else(|| serde_json::json!({}));
498 Ok(AnthropicContentBlock::ServerToolUse { id, name, input })
499 }
500 "web_search_tool_result" => {
501 let tool_use_id = take_required_string::<D::Error>(&mut value, "tool_use_id")?;
502 let content =
503 take_field(&mut value, "content").unwrap_or_else(|| serde_json::json!([]));
504 Ok(AnthropicContentBlock::WebSearchToolResult {
505 tool_use_id,
506 content,
507 })
508 }
509 other => {
510 tracing::debug!(
511 "Unrecognized Anthropic content block type '{}', preserving as Other",
512 other
513 );
514 Ok(AnthropicContentBlock::Other(value))
515 }
516 }
517 }
518}
519
520#[derive(Debug, Clone, Serialize, Deserialize)]
522pub struct AnthropicImageSource {
523 #[serde(rename = "type")]
524 pub source_type: String,
525 pub media_type: String,
526 pub data: String,
527}
528
529#[derive(Debug, Clone, Serialize, Deserialize)]
537pub struct AnthropicTool {
538 pub name: String,
540 #[serde(default, rename = "type", skip_serializing_if = "Option::is_none")]
543 pub tool_type: Option<String>,
544 #[serde(skip_serializing_if = "Option::is_none")]
545 pub description: Option<String>,
546 #[serde(default, skip_serializing_if = "Option::is_none")]
549 pub input_schema: Option<serde_json::Value>,
550 #[serde(default, skip_serializing_if = "Option::is_none")]
552 pub cache_control: Option<CacheControl>,
553}
554
555#[derive(Debug, Clone, Serialize, Deserialize)]
557#[serde(untagged)]
558pub enum AnthropicToolChoice {
559 Named(AnthropicToolChoiceNamed),
562 Simple(AnthropicToolChoiceSimple),
564}
565
566#[derive(Debug, Clone, Serialize, Deserialize)]
568pub struct AnthropicToolChoiceSimple {
569 #[serde(rename = "type")]
570 pub choice_type: AnthropicToolChoiceMode,
571 #[serde(default, skip_serializing_if = "Option::is_none")]
574 pub disable_parallel_tool_use: Option<bool>,
575}
576
577#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
578#[serde(rename_all = "lowercase")]
579pub enum AnthropicToolChoiceMode {
580 Auto,
581 Any,
582 None,
583 Tool,
584}
585
586#[derive(Debug, Clone, Serialize, Deserialize)]
588pub struct AnthropicToolChoiceNamed {
589 #[serde(rename = "type")]
590 pub choice_type: AnthropicToolChoiceMode,
591 pub name: String,
592 #[serde(default, skip_serializing_if = "Option::is_none")]
595 pub disable_parallel_tool_use: Option<bool>,
596}
597#[derive(Debug, Clone, Serialize, Deserialize)]
599pub struct AnthropicMessageResponse {
600 pub id: String,
601 #[serde(rename = "type")]
602 pub object_type: String,
603 pub role: String,
604 pub content: Vec<AnthropicResponseContentBlock>,
605 pub model: String,
606 pub stop_reason: Option<AnthropicStopReason>,
607 pub stop_sequence: Option<String>,
608 pub usage: AnthropicUsage,
609}
610
611#[derive(Debug, Clone, Serialize, Deserialize)]
617#[serde(tag = "type")]
618pub enum AnthropicResponseContentBlock {
619 #[serde(rename = "thinking")]
620 Thinking { thinking: String, signature: String },
621 #[serde(rename = "text")]
622 Text {
623 text: String,
624 #[serde(default, skip_serializing_if = "Option::is_none")]
625 citations: Option<Vec<serde_json::Value>>,
626 },
627 #[serde(rename = "tool_use")]
628 ToolUse {
629 id: String,
630 name: String,
631 input: serde_json::Value,
632 },
633 #[serde(rename = "redacted_thinking")]
634 RedactedThinking { data: String },
635 #[serde(rename = "server_tool_use")]
636 ServerToolUse {
637 id: String,
638 name: String,
639 #[serde(default)]
640 input: serde_json::Value,
641 },
642 #[serde(rename = "web_search_tool_result")]
643 WebSearchToolResult {
644 tool_use_id: String,
645 #[serde(default)]
646 content: serde_json::Value,
647 },
648 #[serde(untagged)]
652 Other(serde_json::Value),
653}
654
655#[derive(Debug, Clone, Serialize, Deserialize, Default)]
657pub struct AnthropicUsage {
658 pub input_tokens: u32,
659 pub output_tokens: u32,
660 #[serde(default, skip_serializing_if = "Option::is_none")]
662 pub cache_creation_input_tokens: Option<u32>,
663 #[serde(default, skip_serializing_if = "Option::is_none")]
665 pub cache_read_input_tokens: Option<u32>,
666}
667
668#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
670#[serde(rename_all = "snake_case")]
671pub enum AnthropicStopReason {
672 EndTurn,
673 MaxTokens,
674 StopSequence,
675 ToolUse,
676 PauseTurn,
679 Refusal,
681}
682#[derive(Debug, Clone, Serialize, Deserialize)]
684#[serde(tag = "type")]
685pub enum AnthropicStreamEvent {
686 #[serde(rename = "message_start")]
687 MessageStart { message: AnthropicMessageResponse },
688
689 #[serde(rename = "content_block_start")]
690 ContentBlockStart {
691 index: u32,
692 content_block: AnthropicResponseContentBlock,
693 },
694
695 #[serde(rename = "content_block_delta")]
696 ContentBlockDelta { index: u32, delta: AnthropicDelta },
697
698 #[serde(rename = "content_block_stop")]
699 ContentBlockStop { index: u32 },
700
701 #[serde(rename = "message_delta")]
702 MessageDelta {
703 delta: AnthropicMessageDeltaBody,
704 usage: AnthropicUsage,
705 },
706
707 #[serde(rename = "message_stop")]
708 MessageStop {},
709
710 #[serde(rename = "ping")]
711 Ping {},
712
713 #[serde(rename = "error")]
714 Error { error: AnthropicErrorBody },
715}
716
717#[derive(Debug, Clone, Serialize, Deserialize)]
719#[serde(tag = "type")]
720pub enum AnthropicDelta {
721 #[serde(rename = "thinking_delta")]
722 ThinkingDelta { thinking: String },
723 #[serde(rename = "text_delta")]
724 TextDelta { text: String },
725 #[serde(rename = "input_json_delta")]
726 InputJsonDelta { partial_json: String },
727 #[serde(rename = "signature_delta")]
729 SignatureDelta { signature: String },
730 #[serde(rename = "citations_delta")]
732 CitationsDelta { citation: serde_json::Value },
733}
734
735#[derive(Debug, Clone, Serialize, Deserialize)]
737pub struct AnthropicMessageDeltaBody {
738 pub stop_reason: Option<AnthropicStopReason>,
739 #[serde(skip_serializing_if = "Option::is_none")]
740 pub stop_sequence: Option<String>,
741}
742#[derive(Debug, Clone, Serialize, Deserialize)]
744pub struct AnthropicErrorResponse {
745 #[serde(rename = "type")]
746 pub object_type: String,
747 pub error: AnthropicErrorBody,
748}
749
750#[derive(Debug, Clone, Serialize, Deserialize)]
752pub struct AnthropicErrorBody {
753 #[serde(rename = "type")]
754 pub error_type: String,
755 pub message: String,
756}
757
758impl AnthropicErrorResponse {
759 pub fn invalid_request(message: impl Into<String>) -> Self {
761 Self {
762 object_type: "error".to_string(),
763 error: AnthropicErrorBody {
764 error_type: "invalid_request_error".to_string(),
765 message: message.into(),
766 },
767 }
768 }
769
770 pub fn api_error(message: impl Into<String>) -> Self {
772 Self {
773 object_type: "error".to_string(),
774 error: AnthropicErrorBody {
775 error_type: "api_error".to_string(),
776 message: message.into(),
777 },
778 }
779 }
780
781 pub fn not_found(message: impl Into<String>) -> Self {
783 Self {
784 object_type: "error".to_string(),
785 error: AnthropicErrorBody {
786 error_type: "not_found_error".to_string(),
787 message: message.into(),
788 },
789 }
790 }
791}
792#[derive(Debug, Clone, Deserialize)]
794pub struct AnthropicCountTokensRequest {
795 pub model: String,
796 pub messages: Vec<AnthropicMessage>,
797 #[serde(
798 default,
799 skip_serializing_if = "Option::is_none",
800 deserialize_with = "deserialize_system_prompt"
801 )]
802 pub system: Option<SystemContent>,
803 #[serde(default)]
804 pub tools: Option<Vec<AnthropicTool>>,
805}
806
807#[derive(Debug, Clone, Serialize)]
809pub struct AnthropicCountTokensResponse {
810 pub input_tokens: u32,
811}
812
813impl AnthropicCountTokensRequest {
814 pub fn estimate_tokens(&self) -> u32 {
816 estimate_input_tokens(&self.messages, self.system.as_ref(), self.tools.as_deref())
817 }
818}
819
820impl AnthropicCreateMessageRequest {
821 pub fn estimate_tokens(&self) -> u32 {
823 estimate_input_tokens(&self.messages, self.system.as_ref(), self.tools.as_deref())
824 }
825}
826
827fn estimate_input_tokens(
828 messages: &[AnthropicMessage],
829 system: Option<&SystemContent>,
830 tools: Option<&[AnthropicTool]>,
831) -> u32 {
832 let mut total_len: usize = 0;
833
834 if let Some(system) = system {
835 total_len += system.text.len();
836 }
837
838 for msg in messages {
839 total_len += match msg.role {
841 AnthropicRole::User => 4,
842 AnthropicRole::Assistant => 9,
843 AnthropicRole::System => 6,
844 };
845 match &msg.content {
847 AnthropicMessageContent::Text { content } => total_len += content.len(),
848 AnthropicMessageContent::Blocks { content } => {
849 for block in content {
850 total_len += estimate_block_len(block);
851 }
852 }
853 }
854 }
855
856 if let Some(tools) = tools {
857 for tool in tools {
858 total_len += tool.name.len();
859 if let Some(desc) = &tool.description {
860 total_len += desc.len();
861 }
862 if let Some(schema) = &tool.input_schema {
863 total_len += schema.to_string().len();
864 }
865 }
866 }
867
868 let tokens = total_len / 3;
869 if tokens == 0 && total_len > 0 {
870 1
871 } else {
872 tokens as u32
873 }
874}
875
876fn estimate_block_len(block: &AnthropicContentBlock) -> usize {
877 match block {
878 AnthropicContentBlock::Text { text, .. } => text.len(),
879 AnthropicContentBlock::ToolUse { name, input, .. } => name.len() + input.to_string().len(),
880 AnthropicContentBlock::ToolResult { content, .. } => content
881 .as_ref()
882 .map(|c| match c {
883 ToolResultContent::Text(s) => s.len(),
884 ToolResultContent::Blocks(blocks) => blocks
885 .iter()
886 .map(|b| match b {
887 ToolResultContentBlock::Text { text } => text.len(),
888 ToolResultContentBlock::Image { .. } => 256,
889 ToolResultContentBlock::Other(v) => v.to_string().len(),
890 })
891 .sum(),
892 })
893 .unwrap_or(0),
894 AnthropicContentBlock::Thinking { thinking, .. } => thinking.len(),
895 AnthropicContentBlock::RedactedThinking { data, .. } => data.len(),
896 AnthropicContentBlock::ServerToolUse { name, input, .. } => {
897 name.len() + input.to_string().len()
898 }
899 AnthropicContentBlock::WebSearchToolResult { content, .. } => content.to_string().len(),
900 AnthropicContentBlock::Image { .. } => 256, AnthropicContentBlock::Other(v) => v.to_string().len(),
902 }
903}
904
905#[cfg(test)]
906mod tests {
907 use super::*;
908
909 #[test]
910 fn messages_request_keeps_nvext_opaque() {
911 let request: AnthropicCreateMessageRequest = serde_json::from_value(serde_json::json!({
912 "model": "test-model",
913 "max_tokens": 16,
914 "messages": [{"role": "user", "content": "hi"}],
915 "nvext": {
916 "unknown_future_extension": {"nested": true},
917 "agent_context": {"trajectory_id": 7}
918 }
919 }))
920 .unwrap();
921
922 let nvext = request.nvext.expect("opaque nvext value");
923 assert_eq!(nvext["unknown_future_extension"]["nested"], true);
924 assert_eq!(nvext["agent_context"]["trajectory_id"], 7);
925 }
926
927 #[test]
928 fn tool_result_blocks_preserve_image_and_reject_document() {
929 let input = serde_json::json!([
930 {"type": "text", "text": "Screenshot captured"},
931 {
932 "type": "image",
933 "source": {
934 "type": "base64",
935 "media_type": "image/png",
936 "data": "aGVsbG8="
937 }
938 },
939 {
940 "type": "document",
941 "source": {
942 "type": "base64",
943 "media_type": "application/pdf",
944 "data": "aGVsbG8="
945 }
946 },
947 {"type": "", "text": "not legacy text"}
948 ]);
949 let content: ToolResultContent = serde_json::from_value(input.clone()).unwrap();
950
951 let ToolResultContent::Blocks(blocks) = &content else {
952 panic!("expected content blocks");
953 };
954 assert!(matches!(blocks[1], ToolResultContentBlock::Image { .. }));
955 assert!(matches!(blocks[2], ToolResultContentBlock::Other(_)));
956 assert!(matches!(blocks[3], ToolResultContentBlock::Other(_)));
957 assert_eq!(serde_json::to_value(content).unwrap(), input);
958
959 for input in [
960 serde_json::json!({"text": "legacy"}),
961 serde_json::json!({"type": null, "text": "legacy"}),
962 serde_json::json!({"type": false, "text": "legacy"}),
963 ] {
964 let legacy: ToolResultContentBlock = serde_json::from_value(input).unwrap();
965 assert!(matches!(legacy, ToolResultContentBlock::Text { .. }));
966 }
967 }
968}