Skip to main content

rust_claude_sdk/
response.rs

1//! The message returned by `POST /v1/messages` (or accumulated from a stream).
2use serde::{Deserialize, Serialize};
3use serde_json::{Map, Value};
4
5#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
6pub struct Message {
7    pub id: String,
8    /// The model that produced the message (the fallback model after a refusal fallback).
9    pub model: String,
10    #[serde(default)]
11    pub content: Vec<ContentBlock>,
12    pub stop_reason: Option<StopReason>,
13    #[serde(default)]
14    pub stop_sequence: Option<String>,
15    /// Set when `stop_reason` is `refusal`: category, explanation, fallback credit...
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    pub stop_details: Option<Value>,
18    #[serde(default)]
19    pub usage: Usage,
20}
21
22impl Message {
23    /// All text blocks, concatenated.
24    pub fn text(&self) -> String {
25        self.content
26            .iter()
27            .filter_map(|b| match b {
28                ContentBlock::Text { text, .. } => Some(text.as_str()),
29                _ => None,
30            })
31            .collect()
32    }
33
34    /// A safety classifier declined the request (and any fallback declined too). Check this
35    /// before using `content`.
36    pub fn is_refusal(&self) -> bool {
37        self.stop_reason == Some(StopReason::Refusal)
38    }
39
40    /// The classifier category of a refusal (`"cyber"`, `"bio"`...), when it gives one.
41    pub fn refusal_category(&self) -> Option<&str> {
42        self.stop_details.as_ref()?.get("category")?.as_str()
43    }
44
45    /// The text decoded as JSON, for a request made with `MessagesRequest::json_schema`.
46    pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T, crate::Error> {
47        serde_json::from_str(&self.text()).map_err(|e| crate::Error::Decode(format!("structured output: {e}")))
48    }
49
50    /// Each cited text span with one of its citations, in order.
51    pub fn citations(&self) -> impl Iterator<Item = (&str, &Citation)> {
52        self.content.iter().flat_map(|b| match b {
53            ContentBlock::Text { text, citations } => citations.iter().map(move |c| (text.as_str(), c)).collect::<Vec<_>>(),
54            _ => Vec::new(),
55        })
56    }
57
58    /// The web search results in this message, across all searches.
59    pub fn web_search_results(&self) -> impl Iterator<Item = &WebSearchResult> {
60        self.content.iter().flat_map(|b| match b {
61            ContentBlock::WebSearchToolResult { content: WebSearchContent::Results(r), .. } => r.iter().collect::<Vec<_>>(),
62            _ => Vec::new(),
63        })
64    }
65
66    /// Server tool calls that failed, with the id of the call: `(tool_use_id, error)`.
67    pub fn server_tool_errors(&self) -> impl Iterator<Item = (&str, &ServerToolError)> {
68        self.content.iter().filter_map(|b| {
69            let err = match b {
70                ContentBlock::WebSearchToolResult { content: WebSearchContent::Error(e), .. }
71                | ContentBlock::WebFetchToolResult { content: WebFetchContent::Error(e), .. }
72                | ContentBlock::BashCodeExecutionToolResult { content: CodeExecutionContent::Error(e), .. }
73                | ContentBlock::CodeExecutionToolResult { content: CodeExecutionContent::Error(e), .. }
74                | ContentBlock::ToolSearchToolResult { content: ToolSearchContent::Error(e), .. } => e,
75                _ => return None,
76            };
77            Some((b.server_tool_result_id()?, err))
78        })
79    }
80
81    /// The tool calls the model asked for: `(id, name, input)`.
82    pub fn tool_uses(&self) -> impl Iterator<Item = (&str, &str, &Value)> {
83        self.content.iter().filter_map(|b| match b {
84            ContentBlock::ToolUse { id, name, input } => Some((id.as_str(), name.as_str(), input)),
85            _ => None,
86        })
87    }
88}
89
90#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
91#[serde(remote = "Self", tag = "type", rename_all = "snake_case")]
92pub enum ContentBlock {
93    Text {
94        text: String,
95        #[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "null_as_empty")]
96        citations: Vec<Citation>,
97    },
98    Thinking {
99        #[serde(default)]
100        thinking: String,
101        #[serde(default)]
102        signature: String,
103    },
104    RedactedThinking {
105        data: String,
106    },
107    ToolUse {
108        id: String,
109        name: String,
110        #[serde(default)]
111        input: Value,
112    },
113    /// A call of a server tool (web search, web fetch, code execution...), run by the API.
114    ServerToolUse {
115        id: String,
116        name: String,
117        #[serde(default)]
118        input: Value,
119        #[serde(flatten)]
120        extra: Map<String, Value>,
121    },
122    WebSearchToolResult {
123        tool_use_id: String,
124        content: WebSearchContent,
125        #[serde(flatten)]
126        extra: Map<String, Value>,
127    },
128    WebFetchToolResult {
129        tool_use_id: String,
130        content: WebFetchContent,
131        #[serde(flatten)]
132        extra: Map<String, Value>,
133    },
134    BashCodeExecutionToolResult {
135        tool_use_id: String,
136        content: CodeExecutionContent,
137        #[serde(flatten)]
138        extra: Map<String, Value>,
139    },
140    /// The result of an older code execution version.
141    CodeExecutionToolResult {
142        tool_use_id: String,
143        content: CodeExecutionContent,
144        #[serde(flatten)]
145        extra: Map<String, Value>,
146    },
147    /// A file the sandbox viewed, created or edited; `content` kept as sent.
148    TextEditorCodeExecutionToolResult {
149        tool_use_id: String,
150        content: Value,
151        #[serde(flatten)]
152        extra: Map<String, Value>,
153    },
154    ToolSearchToolResult {
155        tool_use_id: String,
156        content: ToolSearchContent,
157        #[serde(flatten)]
158        extra: Map<String, Value>,
159    },
160    /// Marks where a refused attempt handed over to a fallback model.
161    Fallback {
162        from: ModelRef,
163        to: ModelRef,
164    },
165    /// Any other block type, kept verbatim.
166    #[serde(skip)]
167    Other(Value),
168}
169open_enum!(
170    ContentBlock,
171    [
172        "text",
173        "thinking",
174        "redacted_thinking",
175        "tool_use",
176        "server_tool_use",
177        "web_search_tool_result",
178        "web_fetch_tool_result",
179        "bash_code_execution_tool_result",
180        "code_execution_tool_result",
181        "text_editor_code_execution_tool_result",
182        "tool_search_tool_result",
183        "fallback",
184    ]
185);
186
187impl ContentBlock {
188    /// The `tool_use_id` of a server tool's result block.
189    pub fn server_tool_result_id(&self) -> Option<&str> {
190        match self {
191            ContentBlock::WebSearchToolResult { tool_use_id, .. }
192            | ContentBlock::WebFetchToolResult { tool_use_id, .. }
193            | ContentBlock::BashCodeExecutionToolResult { tool_use_id, .. }
194            | ContentBlock::CodeExecutionToolResult { tool_use_id, .. }
195            | ContentBlock::TextEditorCodeExecutionToolResult { tool_use_id, .. }
196            | ContentBlock::ToolSearchToolResult { tool_use_id, .. } => Some(tool_use_id),
197            _ => None,
198        }
199    }
200}
201
202/// A server tool that ran but failed (`max_uses_exceeded`, `too_many_requests`,
203/// `unavailable`, `url_not_accessible`...). The response itself still succeeds.
204#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
205pub struct ServerToolError {
206    pub error_code: String,
207    /// `type` and anything else.
208    #[serde(flatten)]
209    pub extra: Map<String, Value>,
210}
211
212/// What a web search returned: a list of results, or an error object.
213#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
214#[serde(untagged)]
215pub enum WebSearchContent {
216    Results(Vec<WebSearchResult>),
217    Error(ServerToolError),
218    Other(Value),
219}
220
221#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
222pub struct WebSearchResult {
223    pub url: String,
224    #[serde(default)]
225    pub title: String,
226    /// How old the page is, when known (e.g. `"2 days ago"`).
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub page_age: Option<String>,
229    /// Opaque page content; must be echoed back for later turns to cite it.
230    #[serde(default)]
231    pub encrypted_content: String,
232    /// `type` and anything else.
233    #[serde(flatten)]
234    pub extra: Map<String, Value>,
235}
236
237/// What a web fetch returned: the page, or an error object.
238#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
239#[serde(untagged)]
240pub enum WebFetchContent {
241    Page(WebFetchResult),
242    Error(ServerToolError),
243    Other(Value),
244}
245
246#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
247pub struct WebFetchResult {
248    pub url: String,
249    /// A `document` block holding the page (`source.data` is its text for text pages).
250    pub content: Value,
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    pub retrieved_at: Option<String>,
253    /// `type` and anything else.
254    #[serde(flatten)]
255    pub extra: Map<String, Value>,
256}
257
258impl WebFetchResult {
259    /// The fetched text, when the page came back as a text document.
260    pub fn text(&self) -> Option<&str> {
261        self.content.get("source").and_then(|s| s.get("data")).and_then(Value::as_str)
262    }
263
264    pub fn title(&self) -> Option<&str> {
265        self.content.get("title").and_then(Value::as_str)
266    }
267}
268
269/// What a code execution returned: its output, or an error object.
270#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
271#[serde(untagged)]
272pub enum CodeExecutionContent {
273    Output(CodeExecutionOutput),
274    Error(ServerToolError),
275    Other(Value),
276}
277
278#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
279pub struct CodeExecutionOutput {
280    #[serde(default)]
281    pub stdout: String,
282    #[serde(default)]
283    pub stderr: String,
284    /// `0` on success.
285    pub return_code: i64,
286    /// Files the code wrote: `{"type": ..., "file_id": ...}`, downloadable with
287    /// `Client::download_file`.
288    #[serde(default, skip_serializing_if = "Vec::is_empty")]
289    pub content: Vec<Value>,
290    /// `type` and anything else.
291    #[serde(flatten)]
292    pub extra: Map<String, Value>,
293}
294
295impl CodeExecutionOutput {
296    /// Ids of the files the code wrote.
297    pub fn file_ids(&self) -> impl Iterator<Item = &str> {
298        self.content.iter().filter_map(|f| f.get("file_id").and_then(Value::as_str))
299    }
300}
301
302/// What a tool search found: references to the tools now loaded, or an error object.
303#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
304#[serde(untagged)]
305pub enum ToolSearchContent {
306    Found(ToolSearchFound),
307    Error(ServerToolError),
308    Other(Value),
309}
310
311#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
312pub struct ToolSearchFound {
313    pub tool_references: Vec<ToolReference>,
314    /// `type` and anything else.
315    #[serde(flatten)]
316    pub extra: Map<String, Value>,
317}
318
319#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
320pub struct ToolReference {
321    pub tool_name: String,
322    /// `type` and anything else.
323    #[serde(flatten)]
324    pub extra: Map<String, Value>,
325}
326
327#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
328pub struct ModelRef {
329    pub model: String,
330}
331
332/// Where a cited span comes from.
333#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
334#[serde(remote = "Self", tag = "type", rename_all = "snake_case")]
335pub enum Citation {
336    /// Plain-text document: character range, end exclusive.
337    CharLocation {
338        cited_text: String,
339        document_index: usize,
340        #[serde(default)]
341        document_title: Option<String>,
342        start_char_index: usize,
343        end_char_index: usize,
344    },
345    /// PDF: page range, 1-indexed, end exclusive.
346    PageLocation {
347        cited_text: String,
348        document_index: usize,
349        #[serde(default)]
350        document_title: Option<String>,
351        start_page_number: usize,
352        end_page_number: usize,
353    },
354    /// Custom-content document: chunk range, end exclusive.
355    ContentBlockLocation {
356        cited_text: String,
357        document_index: usize,
358        #[serde(default)]
359        document_title: Option<String>,
360        start_block_index: usize,
361        end_block_index: usize,
362    },
363    /// A web search result.
364    WebSearchResultLocation {
365        url: String,
366        #[serde(default)]
367        title: Option<String>,
368        #[serde(default)]
369        cited_text: String,
370        /// Opaque; must be echoed back unchanged.
371        #[serde(default)]
372        encrypted_index: String,
373    },
374    /// Any other citation type (search results...), kept verbatim.
375    #[serde(skip)]
376    Other(Value),
377}
378open_enum!(Citation, ["char_location", "page_location", "content_block_location", "web_search_result_location"]);
379
380impl Citation {
381    /// The quoted source text, when the citation type has one.
382    pub fn cited_text(&self) -> Option<&str> {
383        match self {
384            Citation::CharLocation { cited_text, .. }
385            | Citation::PageLocation { cited_text, .. }
386            | Citation::ContentBlockLocation { cited_text, .. }
387            | Citation::WebSearchResultLocation { cited_text, .. } => Some(cited_text),
388            Citation::Other(v) => v.get("cited_text").and_then(Value::as_str),
389        }
390    }
391
392    /// Index of the cited document among the request's documents.
393    pub fn document_index(&self) -> Option<usize> {
394        match self {
395            Citation::CharLocation { document_index, .. }
396            | Citation::PageLocation { document_index, .. }
397            | Citation::ContentBlockLocation { document_index, .. } => Some(*document_index),
398            Citation::WebSearchResultLocation { .. } => None,
399            Citation::Other(v) => v.get("document_index").and_then(Value::as_u64).map(|i| i as usize),
400        }
401    }
402
403    /// The cited page of a web search result.
404    pub fn url(&self) -> Option<&str> {
405        match self {
406            Citation::WebSearchResultLocation { url, .. } => Some(url),
407            Citation::Other(v) => v.get("url").and_then(Value::as_str),
408            _ => None,
409        }
410    }
411}
412
413fn null_as_empty<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<Citation>, D::Error> {
414    Ok(Option::<Vec<Citation>>::deserialize(d)?.unwrap_or_default())
415}
416
417#[derive(Debug, Clone, PartialEq, Eq)]
418pub enum StopReason {
419    EndTurn,
420    MaxTokens,
421    StopSequence,
422    ToolUse,
423    PauseTurn,
424    Refusal,
425    Other(String),
426}
427
428impl StopReason {
429    pub fn as_str(&self) -> &str {
430        match self {
431            StopReason::EndTurn => "end_turn",
432            StopReason::MaxTokens => "max_tokens",
433            StopReason::StopSequence => "stop_sequence",
434            StopReason::ToolUse => "tool_use",
435            StopReason::PauseTurn => "pause_turn",
436            StopReason::Refusal => "refusal",
437            StopReason::Other(s) => s,
438        }
439    }
440}
441
442impl From<String> for StopReason {
443    fn from(s: String) -> StopReason {
444        match s.as_str() {
445            "end_turn" => StopReason::EndTurn,
446            "max_tokens" => StopReason::MaxTokens,
447            "stop_sequence" => StopReason::StopSequence,
448            "tool_use" => StopReason::ToolUse,
449            "pause_turn" => StopReason::PauseTurn,
450            "refusal" => StopReason::Refusal,
451            _ => StopReason::Other(s),
452        }
453    }
454}
455
456impl Serialize for StopReason {
457    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
458        s.serialize_str(self.as_str())
459    }
460}
461
462impl<'de> Deserialize<'de> for StopReason {
463    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
464        String::deserialize(d).map(StopReason::from)
465    }
466}
467
468#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
469pub struct Usage {
470    #[serde(default)]
471    pub input_tokens: u64,
472    #[serde(default)]
473    pub output_tokens: u64,
474    /// Tokens written to the prompt cache by this request.
475    #[serde(default, skip_serializing_if = "Option::is_none")]
476    pub cache_creation_input_tokens: Option<u64>,
477    /// Tokens read from the prompt cache; zero on every request means the prefix changes.
478    #[serde(default, skip_serializing_if = "Option::is_none")]
479    pub cache_read_input_tokens: Option<u64>,
480    /// How many times each server tool ran.
481    #[serde(default, skip_serializing_if = "Option::is_none")]
482    pub server_tool_use: Option<ServerToolUsage>,
483    /// Anything else (`iterations`, `service_tier`, `inference_geo`...).
484    #[serde(flatten)]
485    pub extra: Map<String, Value>,
486}
487
488impl Usage {
489    /// Adds another request's token and server tool counts; `extra` is left as is.
490    pub(crate) fn add(&mut self, other: &Usage) {
491        fn sum(a: Option<u64>, b: Option<u64>) -> Option<u64> {
492            if a.is_none() && b.is_none() {
493                None
494            } else {
495                Some(a.unwrap_or(0) + b.unwrap_or(0))
496            }
497        }
498        self.input_tokens += other.input_tokens;
499        self.output_tokens += other.output_tokens;
500        self.cache_creation_input_tokens = sum(self.cache_creation_input_tokens, other.cache_creation_input_tokens);
501        self.cache_read_input_tokens = sum(self.cache_read_input_tokens, other.cache_read_input_tokens);
502        if let Some(o) = &other.server_tool_use {
503            let s = self.server_tool_use.get_or_insert_with(ServerToolUsage::default);
504            s.web_search_requests += o.web_search_requests;
505            s.web_fetch_requests += o.web_fetch_requests;
506        }
507    }
508
509    /// Applies the cumulative counts of a `message_delta` event.
510    pub(crate) fn merge(&mut self, delta: &Map<String, Value>) {
511        for (k, v) in delta {
512            if v.is_null() {
513                continue;
514            }
515            match k.as_str() {
516                "input_tokens" => self.input_tokens = v.as_u64().unwrap_or(self.input_tokens),
517                "output_tokens" => self.output_tokens = v.as_u64().unwrap_or(self.output_tokens),
518                "cache_creation_input_tokens" => self.cache_creation_input_tokens = v.as_u64(),
519                "cache_read_input_tokens" => self.cache_read_input_tokens = v.as_u64(),
520                "server_tool_use" => self.server_tool_use = serde_json::from_value(v.clone()).ok(),
521                _ => {
522                    self.extra.insert(k.clone(), v.clone());
523                }
524            }
525        }
526    }
527}
528
529/// `usage.server_tool_use`: billable server tool calls.
530#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
531pub struct ServerToolUsage {
532    #[serde(default)]
533    pub web_search_requests: u64,
534    #[serde(default)]
535    pub web_fetch_requests: u64,
536    /// Anything else.
537    #[serde(flatten)]
538    pub extra: Map<String, Value>,
539}