1use serde::{Deserialize, Serialize};
3use serde_json::{Map, Value};
4
5#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
6pub struct Message {
7 pub id: String,
8 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 #[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 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 pub fn is_refusal(&self) -> bool {
37 self.stop_reason == Some(StopReason::Refusal)
38 }
39
40 pub fn refusal_category(&self) -> Option<&str> {
42 self.stop_details.as_ref()?.get("category")?.as_str()
43 }
44
45 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 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 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 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 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 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 CodeExecutionToolResult {
142 tool_use_id: String,
143 content: CodeExecutionContent,
144 #[serde(flatten)]
145 extra: Map<String, Value>,
146 },
147 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 Fallback {
162 from: ModelRef,
163 to: ModelRef,
164 },
165 #[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 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
205pub struct ServerToolError {
206 pub error_code: String,
207 #[serde(flatten)]
209 pub extra: Map<String, Value>,
210}
211
212#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
228 pub page_age: Option<String>,
229 #[serde(default)]
231 pub encrypted_content: String,
232 #[serde(flatten)]
234 pub extra: Map<String, Value>,
235}
236
237#[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 pub content: Value,
251 #[serde(default, skip_serializing_if = "Option::is_none")]
252 pub retrieved_at: Option<String>,
253 #[serde(flatten)]
255 pub extra: Map<String, Value>,
256}
257
258impl WebFetchResult {
259 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#[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 pub return_code: i64,
286 #[serde(default, skip_serializing_if = "Vec::is_empty")]
289 pub content: Vec<Value>,
290 #[serde(flatten)]
292 pub extra: Map<String, Value>,
293}
294
295impl CodeExecutionOutput {
296 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#[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 #[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 #[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
334#[serde(remote = "Self", tag = "type", rename_all = "snake_case")]
335pub enum Citation {
336 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 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 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 WebSearchResultLocation {
365 url: String,
366 #[serde(default)]
367 title: Option<String>,
368 #[serde(default)]
369 cited_text: String,
370 #[serde(default)]
372 encrypted_index: String,
373 },
374 #[serde(skip)]
376 Other(Value),
377}
378open_enum!(Citation, ["char_location", "page_location", "content_block_location", "web_search_result_location"]);
379
380impl Citation {
381 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 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 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 #[serde(default, skip_serializing_if = "Option::is_none")]
476 pub cache_creation_input_tokens: Option<u64>,
477 #[serde(default, skip_serializing_if = "Option::is_none")]
479 pub cache_read_input_tokens: Option<u64>,
480 #[serde(default, skip_serializing_if = "Option::is_none")]
482 pub server_tool_use: Option<ServerToolUsage>,
483 #[serde(flatten)]
485 pub extra: Map<String, Value>,
486}
487
488impl Usage {
489 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 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#[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 #[serde(flatten)]
538 pub extra: Map<String, Value>,
539}