Skip to main content

dynamo_protocols/types/
anthropic.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Anthropic Messages API types.
5//!
6//! Pure protocol types for the `/v1/messages` endpoint -- request, response,
7//! streaming events, error shapes, and count-tokens types.
8
9use serde::{Deserialize, Serialize};
10
11/// Anthropic-style cache control hint for prefix pinning with TTL.
12#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
13pub struct CacheControl {
14    #[serde(rename = "type")]
15    pub control_type: CacheControlType,
16    /// TTL as seconds (integer) or shorthand ("5m" = 300s, "1h" = 3600s). Clamped to [300, 3600].
17    #[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    /// Parse TTL string to seconds, clamped to [300, 3600].
35    ///
36    /// Accepts integer seconds ("120", "600") or shorthand ("5m", "1h").
37    /// Values below 300 are clamped to 300; values above 3600 are clamped to 3600.
38    /// Unrecognized strings default to 300s.
39    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/// Parsed system prompt content, preserving cache_control from block arrays.
56#[derive(Debug, Clone, Serialize, Deserialize)]
57pub struct SystemContent {
58    /// The concatenated text from all system blocks (or the plain string).
59    pub text: String,
60    /// Cache control from the last system block that had one.
61    #[serde(skip_serializing_if = "Option::is_none")]
62    pub cache_control: Option<CacheControl>,
63}
64
65/// Deserialize `system` from either a plain string or an array of text blocks.
66/// The Anthropic API accepts both `"system": "text"` and
67/// `"system": [{"type": "text", "text": "...", "cache_control": {...}}]`.
68fn 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/// Top-level request body for `POST /v1/messages`.
107#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct AnthropicCreateMessageRequest {
109    /// The model to use (e.g. "claude-sonnet-4-20250514").
110    pub model: String,
111
112    /// The maximum number of tokens to generate.
113    pub max_tokens: u32,
114
115    /// The conversation messages.
116    pub messages: Vec<AnthropicMessage>,
117
118    /// Dynamo protocol extension envelope. Protocol parsing keeps this opaque;
119    /// LLM request handling owns extension validation and normalization.
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub nvext: Option<serde_json::Value>,
122
123    /// Optional system prompt (string or array of `{"type":"text","text":"..."}` blocks).
124    #[serde(
125        default,
126        skip_serializing_if = "Option::is_none",
127        deserialize_with = "deserialize_system_prompt"
128    )]
129    pub system: Option<SystemContent>,
130
131    /// Sampling temperature (0.0 - 1.0).
132    #[serde(skip_serializing_if = "Option::is_none")]
133    pub temperature: Option<f32>,
134
135    /// Nucleus sampling parameter.
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub top_p: Option<f32>,
138
139    /// Top-K sampling parameter.
140    #[serde(skip_serializing_if = "Option::is_none")]
141    pub top_k: Option<u32>,
142
143    /// Custom stop sequences.
144    #[serde(skip_serializing_if = "Option::is_none")]
145    pub stop_sequences: Option<Vec<String>>,
146
147    /// Whether to stream the response.
148    #[serde(default)]
149    pub stream: bool,
150
151    /// Optional metadata (e.g. user_id).
152    #[serde(skip_serializing_if = "Option::is_none")]
153    pub metadata: Option<serde_json::Value>,
154
155    /// Tools the model may call.
156    #[serde(skip_serializing_if = "Option::is_none")]
157    pub tools: Option<Vec<AnthropicTool>>,
158
159    /// How the model should choose which tool to call.
160    #[serde(skip_serializing_if = "Option::is_none")]
161    pub tool_choice: Option<AnthropicToolChoice>,
162
163    /// Top-level cache control for automatic prompt prefix caching.
164    /// When present, the system caches all content up to the last cacheable block.
165    /// Matches the Anthropic Messages API automatic caching mode.
166    /// See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching#automatic-caching
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub cache_control: Option<CacheControl>,
169
170    /// Extended thinking configuration. When enabled, the model produces
171    /// `thinking` content blocks containing its internal reasoning before
172    /// the final response. The `budget_tokens` field controls how many tokens
173    /// the model may use for thinking (must be >= 1024 and < max_tokens).
174    #[serde(default, skip_serializing_if = "Option::is_none")]
175    pub thinking: Option<ThinkingConfig>,
176
177    /// Service tier selection: `"auto"` or `"standard_only"`.
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    pub service_tier: Option<String>,
180
181    /// Container identifier for stateful sandbox sessions.
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub container: Option<String>,
184
185    /// Output configuration: effort level and optional JSON schema format.
186    /// `effort` can be `"low"`, `"medium"`, `"high"`, or `"max"`.
187    /// `format` specifies structured JSON output constraints.
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub output_config: Option<serde_json::Value>,
190}
191
192/// Extended thinking configuration for the request.
193///
194/// When `type` is `"enabled"`, the model will produce `thinking` content blocks
195/// with its internal reasoning. `budget_tokens` controls the maximum tokens
196/// available for thinking (minimum 1024, must be less than `max_tokens`).
197/// When `type` is `"disabled"`, no thinking blocks are produced.
198#[derive(Debug, Clone, Serialize, Deserialize)]
199pub struct ThinkingConfig {
200    /// Either `"enabled"` or `"disabled"`.
201    #[serde(rename = "type")]
202    pub thinking_type: String,
203    /// Maximum tokens for internal reasoning. Only relevant when type is "enabled".
204    #[serde(skip_serializing_if = "Option::is_none")]
205    pub budget_tokens: Option<u32>,
206    /// Select readable thinking or empty thinking blocks on the response path.
207    /// The server owns display semantics and validates combinations with `type`.
208    #[serde(default, skip_serializing_if = "Option::is_none")]
209    pub display: Option<ThinkingDisplay>,
210}
211
212#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
213#[serde(rename_all = "snake_case")]
214pub enum ThinkingDisplay {
215    Summarized,
216    Omitted,
217    /// Beta progress-update display; serving capability is validated downstream.
218    Updates,
219}
220
221/// A single message in the conversation.
222#[derive(Debug, Clone, Serialize, Deserialize)]
223pub struct AnthropicMessage {
224    pub role: AnthropicRole,
225    #[serde(flatten)]
226    pub content: AnthropicMessageContent,
227}
228
229/// The role of a message sender.
230#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
231#[serde(rename_all = "lowercase")]
232pub enum AnthropicRole {
233    User,
234    Assistant,
235    /// Compatibility for clients that place system instructions in `messages[]`
236    /// instead of the top-level `system` field.
237    System,
238}
239
240/// Message content -- either a plain string or an array of content blocks.
241#[derive(Debug, Clone, Serialize, Deserialize)]
242#[serde(untagged)]
243pub enum AnthropicMessageContent {
244    /// Plain text content.
245    Text { content: String },
246    /// Array of structured content blocks.
247    Blocks { content: Vec<AnthropicContentBlock> },
248}
249
250/// A single content block within a message.
251///
252/// Uses a custom deserializer so that unknown block types (e.g. `citations`,
253/// `server_tool_use`, `redacted_thinking`) are captured as `Other(Value)` instead
254/// of causing a hard deserialization failure. This is important because Claude
255/// Code may send block types that we don't yet handle.
256#[derive(Debug, Clone, Serialize)]
257#[serde(tag = "type")]
258pub enum AnthropicContentBlock {
259    /// Text content block. May optionally include `citations` -- references to
260    /// source documents that support the text content. Citations are generated
261    /// by the model when document/PDF content is provided and citation mode is enabled.
262    #[serde(rename = "text")]
263    Text {
264        text: String,
265        #[serde(default, skip_serializing_if = "Option::is_none")]
266        citations: Option<Vec<serde_json::Value>>,
267        #[serde(default, skip_serializing_if = "Option::is_none")]
268        cache_control: Option<CacheControl>,
269    },
270    /// Image content block.
271    #[serde(rename = "image")]
272    Image { source: AnthropicImageSource },
273    /// Tool use request from assistant.
274    #[serde(rename = "tool_use")]
275    ToolUse {
276        id: String,
277        name: String,
278        input: serde_json::Value,
279        #[serde(default, skip_serializing_if = "Option::is_none")]
280        cache_control: Option<CacheControl>,
281    },
282    /// Tool result from user.
283    #[serde(rename = "tool_result")]
284    ToolResult {
285        tool_use_id: String,
286        #[serde(default, skip_serializing_if = "Option::is_none")]
287        content: Option<ToolResultContent>,
288        #[serde(skip_serializing_if = "Option::is_none")]
289        is_error: Option<bool>,
290        #[serde(default, skip_serializing_if = "Option::is_none")]
291        cache_control: Option<CacheControl>,
292    },
293    /// Thinking content block from assistant (extended thinking / reasoning).
294    #[serde(rename = "thinking")]
295    Thinking {
296        thinking: String,
297        signature: String,
298        #[serde(default, skip_serializing_if = "Option::is_none")]
299        cache_control: Option<CacheControl>,
300    },
301    /// Redacted thinking block from assistant. Contains encrypted reasoning data
302    /// that is opaque to the client but must be passed back verbatim in multi-turn
303    /// conversations so the model can maintain its chain of thought.
304    #[serde(rename = "redacted_thinking")]
305    RedactedThinking { data: String },
306    /// Server-initiated tool use block. Represents a tool call that the API
307    /// executes server-side (e.g., web search). The client receives the result
308    /// via a corresponding `web_search_tool_result` or similar block.
309    #[serde(rename = "server_tool_use")]
310    ServerToolUse {
311        id: String,
312        name: String,
313        #[serde(default)]
314        input: serde_json::Value,
315    },
316    /// Result from a server-initiated tool (e.g., web search results).
317    /// Contains structured content returned by the server-side tool execution.
318    #[serde(rename = "web_search_tool_result")]
319    WebSearchToolResult {
320        tool_use_id: String,
321        #[serde(default)]
322        content: serde_json::Value,
323    },
324    /// Catch-all for unrecognized block types. Preserves the full JSON value
325    /// so that new Anthropic features don't break the endpoint and can be
326    /// round-tripped or inspected.
327    #[serde(untagged)]
328    Other(serde_json::Value),
329}
330
331/// Content of a `tool_result` block -- either a plain string or an array of
332/// content blocks (the Anthropic API accepts both).
333#[derive(Debug, Clone, Serialize, Deserialize)]
334#[serde(untagged)]
335pub enum ToolResultContent {
336    Text(String),
337    Blocks(Vec<ToolResultContentBlock>),
338}
339
340impl ToolResultContent {
341    /// Extract the text content, concatenating array blocks if needed.
342    pub fn into_text(self) -> String {
343        match self {
344            ToolResultContent::Text(s) => s,
345            ToolResultContent::Blocks(blocks) => blocks
346                .into_iter()
347                .filter_map(|b| match b {
348                    ToolResultContentBlock::Text { text } => Some(text),
349                    ToolResultContentBlock::Image { .. } | ToolResultContentBlock::Other(_) => None,
350                })
351                .collect::<Vec<_>>()
352                .join(""),
353        }
354    }
355}
356
357/// A content block within a `tool_result.content` array.
358#[derive(Debug, Clone)]
359pub enum ToolResultContentBlock {
360    Text {
361        text: String,
362    },
363    /// Image returned by a tool.
364    Image {
365        source: AnthropicImageSource,
366    },
367    /// Catch-all for other non-text blocks in tool results.
368    Other(serde_json::Value),
369}
370
371impl Serialize for ToolResultContentBlock {
372    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
373    where
374        S: serde::Serializer,
375    {
376        match self {
377            Self::Text { text } => serde_json::json!({
378                "type": "text",
379                "text": text,
380            })
381            .serialize(serializer),
382            Self::Image { source } => serde_json::json!({
383                "type": "image",
384                "source": source,
385            })
386            .serialize(serializer),
387            Self::Other(value) => value.serialize(serializer),
388        }
389    }
390}
391
392fn take_field(value: &mut serde_json::Value, field: &str) -> Option<serde_json::Value> {
393    value.as_object_mut()?.remove(field)
394}
395
396fn take_required_string<E: serde::de::Error>(
397    value: &mut serde_json::Value,
398    field: &'static str,
399) -> Result<String, E> {
400    match take_field(value, field) {
401        Some(serde_json::Value::String(text)) => Ok(text),
402        _ => Err(E::missing_field(field)),
403    }
404}
405
406impl<'de> Deserialize<'de> for ToolResultContentBlock {
407    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
408    where
409        D: serde::Deserializer<'de>,
410    {
411        let mut value = serde_json::Value::deserialize(deserializer)?;
412        match value.get("type").and_then(|value| value.as_str()) {
413            Some("text") => {
414                let text = take_required_string::<D::Error>(&mut value, "text")?;
415                Ok(Self::Text { text })
416            }
417            Some("image") => {
418                let source = take_field(&mut value, "source")
419                    .ok_or_else(|| serde::de::Error::missing_field("source"))
420                    .and_then(|value| {
421                        serde_json::from_value(value).map_err(serde::de::Error::custom)
422                    })?;
423                Ok(Self::Image { source })
424            }
425            None if value.get("text").is_some_and(serde_json::Value::is_string) => Ok(Self::Text {
426                text: take_required_string::<D::Error>(&mut value, "text")?,
427            }),
428            _ => Ok(Self::Other(value)),
429        }
430    }
431}
432
433/// Custom deserializer for `AnthropicContentBlock` that handles unknown types
434/// gracefully. Since serde's `#[serde(other)]` is not supported on internally
435/// tagged enums, we deserialize as `Value` first and dispatch manually.
436impl<'de> Deserialize<'de> for AnthropicContentBlock {
437    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
438    where
439        D: serde::Deserializer<'de>,
440    {
441        let mut value = serde_json::Value::deserialize(deserializer)?;
442        let block_type = value.get("type").and_then(|t| t.as_str()).unwrap_or("");
443
444        match block_type {
445            "text" => {
446                let text = take_required_string::<D::Error>(&mut value, "text")?;
447                let citations: Option<Vec<serde_json::Value>> = take_field(&mut value, "citations")
448                    .and_then(|v| serde_json::from_value(v).ok());
449                let cache_control: Option<CacheControl> = take_field(&mut value, "cache_control")
450                    .and_then(|v| serde_json::from_value(v).ok());
451                Ok(AnthropicContentBlock::Text {
452                    text,
453                    citations,
454                    cache_control,
455                })
456            }
457            "image" => {
458                let source: AnthropicImageSource =
459                    serde_json::from_value(take_field(&mut value, "source").unwrap_or_default())
460                        .map_err(serde::de::Error::custom)?;
461                Ok(AnthropicContentBlock::Image { source })
462            }
463            "tool_use" => {
464                let id = take_required_string::<D::Error>(&mut value, "id")?;
465                let name = take_required_string::<D::Error>(&mut value, "name")?;
466                let input =
467                    take_field(&mut value, "input").unwrap_or_else(|| serde_json::json!({}));
468                let cache_control: Option<CacheControl> = take_field(&mut value, "cache_control")
469                    .and_then(|v| serde_json::from_value(v).ok());
470                Ok(AnthropicContentBlock::ToolUse {
471                    id,
472                    name,
473                    input,
474                    cache_control,
475                })
476            }
477            "tool_result" => {
478                let tool_use_id = take_required_string::<D::Error>(&mut value, "tool_use_id")?;
479                let content = take_field(&mut value, "content")
480                    .map(serde_json::from_value::<Option<ToolResultContent>>)
481                    .transpose()
482                    .map_err(serde::de::Error::custom)?
483                    .flatten();
484                let is_error = take_field(&mut value, "is_error")
485                    .map(serde_json::from_value::<Option<bool>>)
486                    .transpose()
487                    .map_err(serde::de::Error::custom)?
488                    .flatten();
489                let cache_control: Option<CacheControl> = take_field(&mut value, "cache_control")
490                    .and_then(|v| serde_json::from_value(v).ok());
491                Ok(AnthropicContentBlock::ToolResult {
492                    tool_use_id,
493                    content,
494                    is_error,
495                    cache_control,
496                })
497            }
498            "thinking" => {
499                let thinking = take_required_string::<D::Error>(&mut value, "thinking")?;
500                let signature = take_required_string::<D::Error>(&mut value, "signature")?;
501                let cache_control: Option<CacheControl> = take_field(&mut value, "cache_control")
502                    .and_then(|v| serde_json::from_value(v).ok());
503                Ok(AnthropicContentBlock::Thinking {
504                    thinking,
505                    signature,
506                    cache_control,
507                })
508            }
509            "redacted_thinking" => {
510                let data = take_required_string::<D::Error>(&mut value, "data")?;
511                Ok(AnthropicContentBlock::RedactedThinking { data })
512            }
513            "server_tool_use" => {
514                let id = take_required_string::<D::Error>(&mut value, "id")?;
515                let name = take_required_string::<D::Error>(&mut value, "name")?;
516                let input =
517                    take_field(&mut value, "input").unwrap_or_else(|| serde_json::json!({}));
518                Ok(AnthropicContentBlock::ServerToolUse { id, name, input })
519            }
520            "web_search_tool_result" => {
521                let tool_use_id = take_required_string::<D::Error>(&mut value, "tool_use_id")?;
522                let content =
523                    take_field(&mut value, "content").unwrap_or_else(|| serde_json::json!([]));
524                Ok(AnthropicContentBlock::WebSearchToolResult {
525                    tool_use_id,
526                    content,
527                })
528            }
529            other => {
530                tracing::debug!(
531                    "Unrecognized Anthropic content block type '{}', preserving as Other",
532                    other
533                );
534                Ok(AnthropicContentBlock::Other(value))
535            }
536        }
537    }
538}
539
540/// Image source for image content blocks.
541#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
542#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
543pub enum AnthropicImageSource {
544    Base64 { media_type: String, data: String },
545    Url { url: String },
546}
547
548#[cfg(test)]
549mod source_and_display_tests {
550    use super::*;
551    use serde_json::json;
552
553    #[test]
554    fn image_sources_round_trip_in_messages_and_tool_results() {
555        for source in [
556            json!({"type": "base64", "media_type": "image/png", "data": "aGVsbG8="}),
557            json!({"type": "url", "url": "https://example.com/image.png"}),
558        ] {
559            let image = json!({"type": "image", "source": source});
560            let block: AnthropicContentBlock = serde_json::from_value(image.clone()).unwrap();
561            assert_eq!(serde_json::to_value(block).unwrap(), image);
562            let result: ToolResultContentBlock = serde_json::from_value(image.clone()).unwrap();
563            assert_eq!(serde_json::to_value(result).unwrap(), image);
564        }
565    }
566
567    #[test]
568    fn image_source_discriminators_require_the_matching_fields() {
569        for source in [
570            json!({"type": "url"}),
571            json!({"type": "url", "url": null}),
572            json!({"type": "url", "url": 42}),
573            json!({"type": "url", "url": "https://example.com/image.png", "data": "x"}),
574            json!({"type": "base64", "media_type": "image/png"}),
575            json!({"type": "base64", "data": "aGVsbG8="}),
576            json!({"type": "base64", "media_type": "image/png", "data": "x", "url": "https://example.com/image.png"}),
577            json!({"type": "file", "file_id": "file_123"}),
578            json!({"url": "https://example.com/image.png"}),
579        ] {
580            assert!(
581                serde_json::from_value::<AnthropicImageSource>(source.clone()).is_err(),
582                "{source}"
583            );
584            let image = json!({"type": "image", "source": source});
585            for block in [
586                image.clone(),
587                json!({"type": "tool_result", "tool_use_id": "toolu_image", "content": [image]}),
588            ] {
589                let request = json!({"model": "test-model", "max_tokens": 64,
590                    "messages": [{"role": "user", "content": [block]}]});
591                assert!(
592                    serde_json::from_value::<AnthropicCreateMessageRequest>(request).is_err(),
593                    "malformed nested image source must not be discarded: {source}"
594                );
595            }
596        }
597    }
598
599    #[test]
600    fn tool_result_content_keeps_absent_null_empty_and_text_semantics() {
601        for content in [
602            None,
603            Some(json!(null)),
604            Some(json!("")),
605            Some(json!([])),
606            Some(json!("result")),
607        ] {
608            let mut block = json!({"type": "tool_result", "tool_use_id": "toolu_image"});
609            if let Some(content) = &content {
610                block["content"] = content.clone();
611            }
612            let parsed: AnthropicContentBlock = serde_json::from_value(block).unwrap();
613            let value = serde_json::to_value(parsed).unwrap();
614            match content {
615                None | Some(serde_json::Value::Null) => assert!(value.get("content").is_none()),
616                Some(content) => assert_eq!(value["content"], content),
617            }
618        }
619    }
620
621    #[test]
622    fn tool_error_status_requires_a_boolean() {
623        for is_error in [json!("true"), json!(1), json!({}), json!([])] {
624            let request = json!({"model": "model", "max_tokens": 2048,
625                "messages": [{"role": "user", "content": [{"type": "tool_result",
626                    "tool_use_id": "tool_1", "content": "failed", "is_error": is_error}]}]});
627            assert!(serde_json::from_value::<AnthropicCreateMessageRequest>(request).is_err());
628        }
629        for is_error in [json!(true), json!(false), json!(null)] {
630            let block =
631                json!({"type": "tool_result", "tool_use_id": "tool_1", "is_error": is_error});
632            let parsed: AnthropicContentBlock = serde_json::from_value(block).unwrap();
633            assert_eq!(serde_json::to_value(parsed).unwrap()["is_error"], is_error);
634        }
635    }
636
637    #[test]
638    fn thinking_display_preserves_explicit_values_and_omission() {
639        for (display, expected) in [
640            ("summarized", ThinkingDisplay::Summarized),
641            ("omitted", ThinkingDisplay::Omitted),
642            ("updates", ThinkingDisplay::Updates),
643        ] {
644            let value = json!({"type": "adaptive", "display": display});
645            let config: ThinkingConfig = serde_json::from_value(value.clone()).unwrap();
646            assert_eq!(config.display, Some(expected));
647            assert_eq!(serde_json::to_value(config).unwrap(), value);
648        }
649        let value = json!({"type": "enabled", "budget_tokens": 1024});
650        let config: ThinkingConfig = serde_json::from_value(value.clone()).unwrap();
651        assert_eq!(config.display, None);
652        assert_eq!(serde_json::to_value(config).unwrap(), value);
653        for display in [json!("unknown"), json!(false), json!(1)] {
654            assert!(
655                serde_json::from_value::<ThinkingConfig>(
656                    json!({"type": "adaptive", "display": display})
657                )
658                .is_err()
659            );
660        }
661    }
662}
663
664/// A tool definition.
665///
666/// Client tools (custom) require `name` + `input_schema`. Server tools
667/// (web_search, bash, text_editor, code_execution, etc.) are discriminated
668/// by their `type` field (e.g. `"web_search_20260209"`) and may not have
669/// `input_schema`. We keep all fields optional beyond `name` so both
670/// kinds deserialize successfully and pass through to the backend.
671#[derive(Debug, Clone, Serialize, Deserialize)]
672pub struct AnthropicTool {
673    /// Tool name (required for client tools, present on server tools too).
674    pub name: String,
675    /// Tool type discriminator. Client tools use `"custom"` (or omit).
676    /// Server tools use versioned types like `"web_search_20260209"`.
677    #[serde(default, rename = "type", skip_serializing_if = "Option::is_none")]
678    pub tool_type: Option<String>,
679    #[serde(skip_serializing_if = "Option::is_none")]
680    pub description: Option<String>,
681    /// JSON Schema for the tool input. Required for client tools, absent on
682    /// server tools (which define their own input shape server-side).
683    #[serde(default, skip_serializing_if = "Option::is_none")]
684    pub input_schema: Option<serde_json::Value>,
685    /// Whether tool arguments must conform to the input schema.
686    #[serde(default, skip_serializing_if = "Option::is_none")]
687    pub strict: Option<bool>,
688    /// Cache control breakpoint on this tool definition.
689    #[serde(default, skip_serializing_if = "Option::is_none")]
690    pub cache_control: Option<CacheControl>,
691}
692
693/// Tool choice specification.
694#[derive(Debug, Clone, Serialize, Deserialize)]
695#[serde(untagged)]
696pub enum AnthropicToolChoice {
697    /// Named tool: `{type: "tool", name: "..."}`
698    /// Must be listed before Simple so serde tries the stricter shape first.
699    Named(AnthropicToolChoiceNamed),
700    /// Simple mode: "auto", "any", or "none".
701    Simple(AnthropicToolChoiceSimple),
702}
703
704/// Simple tool choice modes.
705#[derive(Debug, Clone, Serialize, Deserialize)]
706pub struct AnthropicToolChoiceSimple {
707    #[serde(rename = "type")]
708    pub choice_type: AnthropicToolChoiceMode,
709    /// When true, the model will call tools one at a time instead of
710    /// potentially issuing multiple tool calls in a single response.
711    #[serde(default, skip_serializing_if = "Option::is_none")]
712    pub disable_parallel_tool_use: Option<bool>,
713}
714
715#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
716#[serde(rename_all = "lowercase")]
717pub enum AnthropicToolChoiceMode {
718    Auto,
719    Any,
720    None,
721    Tool,
722}
723
724/// Named tool choice.
725#[derive(Debug, Clone, Serialize, Deserialize)]
726pub struct AnthropicToolChoiceNamed {
727    #[serde(rename = "type")]
728    pub choice_type: AnthropicToolChoiceMode,
729    pub name: String,
730    /// When true, the model will call tools one at a time instead of
731    /// potentially issuing multiple tool calls in a single response.
732    #[serde(default, skip_serializing_if = "Option::is_none")]
733    pub disable_parallel_tool_use: Option<bool>,
734}
735/// Response body for `POST /v1/messages` (non-streaming).
736#[derive(Debug, Clone, Serialize, Deserialize)]
737pub struct AnthropicMessageResponse {
738    pub id: String,
739    #[serde(rename = "type")]
740    pub object_type: String,
741    pub role: String,
742    pub content: Vec<AnthropicResponseContentBlock>,
743    pub model: String,
744    pub stop_reason: Option<AnthropicStopReason>,
745    pub stop_sequence: Option<String>,
746    pub usage: AnthropicUsage,
747}
748
749/// A content block in the response.
750///
751/// The Anthropic API returns up to 12 different block types. We model the
752/// common ones explicitly and catch the rest as `Other` so the proxy can
753/// forward them without losing data.
754#[derive(Debug, Clone, Serialize, Deserialize)]
755#[serde(tag = "type")]
756pub enum AnthropicResponseContentBlock {
757    #[serde(rename = "thinking")]
758    Thinking { thinking: String, signature: String },
759    #[serde(rename = "text")]
760    Text {
761        text: String,
762        #[serde(default, skip_serializing_if = "Option::is_none")]
763        citations: Option<Vec<serde_json::Value>>,
764    },
765    #[serde(rename = "tool_use")]
766    ToolUse {
767        id: String,
768        name: String,
769        input: serde_json::Value,
770    },
771    #[serde(rename = "redacted_thinking")]
772    RedactedThinking { data: String },
773    #[serde(rename = "server_tool_use")]
774    ServerToolUse {
775        id: String,
776        name: String,
777        #[serde(default)]
778        input: serde_json::Value,
779    },
780    #[serde(rename = "web_search_tool_result")]
781    WebSearchToolResult {
782        tool_use_id: String,
783        #[serde(default)]
784        content: serde_json::Value,
785    },
786    /// Catch-all for new/uncommon block types (web_fetch_tool_result,
787    /// code_execution_tool_result, container_upload, etc.) so the proxy
788    /// can serialize them back without data loss.
789    #[serde(untagged)]
790    Other(serde_json::Value),
791}
792
793/// Token usage information.
794#[derive(Debug, Clone, Serialize, Deserialize, Default)]
795pub struct AnthropicUsage {
796    pub input_tokens: u32,
797    pub output_tokens: u32,
798    /// Number of input tokens used to create a new cache entry.
799    #[serde(default, skip_serializing_if = "Option::is_none")]
800    pub cache_creation_input_tokens: Option<u32>,
801    /// Number of input tokens read from the prompt cache (prefix cache hits).
802    #[serde(default, skip_serializing_if = "Option::is_none")]
803    pub cache_read_input_tokens: Option<u32>,
804}
805
806/// Reason the model stopped generating.
807#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
808#[serde(rename_all = "snake_case")]
809pub enum AnthropicStopReason {
810    EndTurn,
811    MaxTokens,
812    StopSequence,
813    ToolUse,
814    /// The model paused to yield control in an agentic loop, intending to
815    /// continue in a subsequent turn. Used with extended thinking / tool use.
816    PauseTurn,
817    /// The model refused to generate content (safety refusal).
818    Refusal,
819}
820/// SSE event types for the Anthropic streaming API.
821#[derive(Debug, Clone, Serialize, Deserialize)]
822#[serde(tag = "type")]
823pub enum AnthropicStreamEvent {
824    #[serde(rename = "message_start")]
825    MessageStart { message: AnthropicMessageResponse },
826
827    #[serde(rename = "content_block_start")]
828    ContentBlockStart {
829        index: u32,
830        content_block: AnthropicResponseContentBlock,
831    },
832
833    #[serde(rename = "content_block_delta")]
834    ContentBlockDelta { index: u32, delta: AnthropicDelta },
835
836    #[serde(rename = "content_block_stop")]
837    ContentBlockStop { index: u32 },
838
839    #[serde(rename = "message_delta")]
840    MessageDelta {
841        delta: AnthropicMessageDeltaBody,
842        usage: AnthropicUsage,
843    },
844
845    #[serde(rename = "message_stop")]
846    MessageStop {},
847
848    #[serde(rename = "ping")]
849    Ping {},
850
851    #[serde(rename = "error")]
852    Error { error: AnthropicErrorBody },
853}
854
855/// Delta content in a streaming content_block_delta event.
856#[derive(Debug, Clone, Serialize, Deserialize)]
857#[serde(tag = "type")]
858pub enum AnthropicDelta {
859    #[serde(rename = "thinking_delta")]
860    ThinkingDelta { thinking: String },
861    #[serde(rename = "text_delta")]
862    TextDelta { text: String },
863    #[serde(rename = "input_json_delta")]
864    InputJsonDelta { partial_json: String },
865    /// Incremental signature for a thinking block (sent at the end).
866    #[serde(rename = "signature_delta")]
867    SignatureDelta { signature: String },
868    /// Incremental citation attached to a text block.
869    #[serde(rename = "citations_delta")]
870    CitationsDelta { citation: serde_json::Value },
871}
872
873/// The delta body in a message_delta event.
874#[derive(Debug, Clone, Serialize, Deserialize)]
875pub struct AnthropicMessageDeltaBody {
876    pub stop_reason: Option<AnthropicStopReason>,
877    #[serde(skip_serializing_if = "Option::is_none")]
878    pub stop_sequence: Option<String>,
879}
880/// Anthropic API error response wrapper.
881#[derive(Debug, Clone, Serialize, Deserialize)]
882pub struct AnthropicErrorResponse {
883    #[serde(rename = "type")]
884    pub object_type: String,
885    pub error: AnthropicErrorBody,
886}
887
888/// Error body within an error response.
889#[derive(Debug, Clone, Serialize, Deserialize)]
890pub struct AnthropicErrorBody {
891    #[serde(rename = "type")]
892    pub error_type: String,
893    pub message: String,
894}
895
896impl AnthropicErrorResponse {
897    /// Create an `invalid_request_error` response.
898    pub fn invalid_request(message: impl Into<String>) -> Self {
899        Self {
900            object_type: "error".to_string(),
901            error: AnthropicErrorBody {
902                error_type: "invalid_request_error".to_string(),
903                message: message.into(),
904            },
905        }
906    }
907
908    /// Create an `api_error` (internal server error) response.
909    pub fn api_error(message: impl Into<String>) -> Self {
910        Self {
911            object_type: "error".to_string(),
912            error: AnthropicErrorBody {
913                error_type: "api_error".to_string(),
914                message: message.into(),
915            },
916        }
917    }
918
919    /// Create a `not_found_error` response.
920    pub fn not_found(message: impl Into<String>) -> Self {
921        Self {
922            object_type: "error".to_string(),
923            error: AnthropicErrorBody {
924                error_type: "not_found_error".to_string(),
925                message: message.into(),
926            },
927        }
928    }
929}
930/// Request body for `POST /v1/messages/count_tokens`.
931#[derive(Debug, Clone, Deserialize)]
932pub struct AnthropicCountTokensRequest {
933    pub model: String,
934    pub messages: Vec<AnthropicMessage>,
935    #[serde(
936        default,
937        skip_serializing_if = "Option::is_none",
938        deserialize_with = "deserialize_system_prompt"
939    )]
940    pub system: Option<SystemContent>,
941    #[serde(default)]
942    pub tools: Option<Vec<AnthropicTool>>,
943}
944
945/// Response body for `POST /v1/messages/count_tokens`.
946#[derive(Debug, Clone, Serialize)]
947pub struct AnthropicCountTokensResponse {
948    pub input_tokens: u32,
949}
950
951impl AnthropicCountTokensRequest {
952    /// Estimate input token count using a `len/3` heuristic.
953    pub fn estimate_tokens(&self) -> u32 {
954        estimate_input_tokens(&self.messages, self.system.as_ref(), self.tools.as_deref())
955    }
956}
957
958impl AnthropicCreateMessageRequest {
959    /// Estimate input token count using the same `len/3` heuristic as `/count_tokens`.
960    pub fn estimate_tokens(&self) -> u32 {
961        estimate_input_tokens(&self.messages, self.system.as_ref(), self.tools.as_deref())
962    }
963}
964
965fn estimate_input_tokens(
966    messages: &[AnthropicMessage],
967    system: Option<&SystemContent>,
968    tools: Option<&[AnthropicTool]>,
969) -> u32 {
970    let mut total_len: usize = 0;
971
972    if let Some(system) = system {
973        total_len += system.text.len();
974    }
975
976    for msg in messages {
977        // Count role
978        total_len += match msg.role {
979            AnthropicRole::User => 4,
980            AnthropicRole::Assistant => 9,
981            AnthropicRole::System => 6,
982        };
983        // Count content
984        match &msg.content {
985            AnthropicMessageContent::Text { content } => total_len += content.len(),
986            AnthropicMessageContent::Blocks { content } => {
987                for block in content {
988                    total_len += estimate_block_len(block);
989                }
990            }
991        }
992    }
993
994    if let Some(tools) = tools {
995        for tool in tools {
996            total_len += tool.name.len();
997            if let Some(desc) = &tool.description {
998                total_len += desc.len();
999            }
1000            if let Some(schema) = &tool.input_schema {
1001                total_len += schema.to_string().len();
1002            }
1003        }
1004    }
1005
1006    let tokens = total_len / 3;
1007    if tokens == 0 && total_len > 0 {
1008        1
1009    } else {
1010        tokens as u32
1011    }
1012}
1013
1014fn estimate_block_len(block: &AnthropicContentBlock) -> usize {
1015    match block {
1016        AnthropicContentBlock::Text { text, .. } => text.len(),
1017        AnthropicContentBlock::ToolUse { name, input, .. } => name.len() + input.to_string().len(),
1018        AnthropicContentBlock::ToolResult { content, .. } => content
1019            .as_ref()
1020            .map(|c| match c {
1021                ToolResultContent::Text(s) => s.len(),
1022                ToolResultContent::Blocks(blocks) => blocks
1023                    .iter()
1024                    .map(|b| match b {
1025                        ToolResultContentBlock::Text { text } => text.len(),
1026                        ToolResultContentBlock::Image { .. } => 256,
1027                        ToolResultContentBlock::Other(v) => v.to_string().len(),
1028                    })
1029                    .sum(),
1030            })
1031            .unwrap_or(0),
1032        AnthropicContentBlock::Thinking { thinking, .. } => thinking.len(),
1033        AnthropicContentBlock::RedactedThinking { data, .. } => data.len(),
1034        AnthropicContentBlock::ServerToolUse { name, input, .. } => {
1035            name.len() + input.to_string().len()
1036        }
1037        AnthropicContentBlock::WebSearchToolResult { content, .. } => content.to_string().len(),
1038        AnthropicContentBlock::Image { .. } => 256, // rough estimate for image metadata
1039        AnthropicContentBlock::Other(v) => v.to_string().len(),
1040    }
1041}
1042
1043#[cfg(test)]
1044mod tests {
1045    use super::*;
1046
1047    #[test]
1048    fn tool_strict_round_trips() {
1049        for strict in [Some(true), Some(false), None] {
1050            let mut input = serde_json::json!({
1051                "name": "set_status",
1052                "input_schema": {"type": "object"}
1053            });
1054            if let Some(strict) = strict {
1055                input["strict"] = strict.into();
1056            }
1057            let tool: AnthropicTool = serde_json::from_value(input.clone()).unwrap();
1058            assert_eq!(serde_json::to_value(tool).unwrap(), input);
1059        }
1060    }
1061
1062    #[test]
1063    fn messages_request_keeps_nvext_opaque() {
1064        let request: AnthropicCreateMessageRequest = serde_json::from_value(serde_json::json!({
1065            "model": "test-model",
1066            "max_tokens": 16,
1067            "messages": [{"role": "user", "content": "hi"}],
1068            "nvext": {
1069                "unknown_future_extension": {"nested": true},
1070                "agent_context": {"trajectory_id": 7}
1071            }
1072        }))
1073        .unwrap();
1074
1075        let nvext = request.nvext.expect("opaque nvext value");
1076        assert_eq!(nvext["unknown_future_extension"]["nested"], true);
1077        assert_eq!(nvext["agent_context"]["trajectory_id"], 7);
1078    }
1079
1080    #[test]
1081    fn tool_result_blocks_preserve_image_and_reject_document() {
1082        let input = serde_json::json!([
1083            {"type": "text", "text": "Screenshot captured"},
1084            {
1085                "type": "image",
1086                "source": {
1087                    "type": "base64",
1088                    "media_type": "image/png",
1089                    "data": "aGVsbG8="
1090                }
1091            },
1092            {
1093                "type": "document",
1094                "source": {
1095                    "type": "base64",
1096                    "media_type": "application/pdf",
1097                    "data": "aGVsbG8="
1098                }
1099            },
1100            {"type": "", "text": "not legacy text"}
1101        ]);
1102        let content: ToolResultContent = serde_json::from_value(input.clone()).unwrap();
1103
1104        let ToolResultContent::Blocks(blocks) = &content else {
1105            panic!("expected content blocks");
1106        };
1107        assert!(matches!(blocks[1], ToolResultContentBlock::Image { .. }));
1108        assert!(matches!(blocks[2], ToolResultContentBlock::Other(_)));
1109        assert!(matches!(blocks[3], ToolResultContentBlock::Other(_)));
1110        assert_eq!(serde_json::to_value(content).unwrap(), input);
1111
1112        for input in [
1113            serde_json::json!({"text": "legacy"}),
1114            serde_json::json!({"type": null, "text": "legacy"}),
1115            serde_json::json!({"type": false, "text": "legacy"}),
1116        ] {
1117            let legacy: ToolResultContentBlock = serde_json::from_value(input).unwrap();
1118            assert!(matches!(legacy, ToolResultContentBlock::Text { .. }));
1119        }
1120    }
1121}