claude-api 0.5.1

Type-safe Rust client for the Anthropic API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
//! Content blocks: the building blocks of message bodies and stream deltas.
//!
//! [`ContentBlock`] is the public, forward-compatible enum: it wraps a
//! [`KnownBlock`] for any block type the SDK understands, or a raw
//! [`serde_json::Value`] for any block type it doesn't. This means an SDK
//! older than the API will keep round-tripping payloads instead of panicking
//! on a new variant.
//!
//! # Forward-compat semantics
//!
//! - **Unknown `type` tag** → [`ContentBlock::Other`] preserving the JSON byte-for-byte.
//! - **Known `type` tag with malformed fields** → deserialization error
//!   (we do *not* silently fall through, so genuine bugs surface).
//!
//! ```
//! use claude_api::messages::content::ContentBlock;
//!
//! let json = serde_json::json!({"type": "text", "text": "hi"});
//! let block: ContentBlock = serde_json::from_value(json).unwrap();
//! assert_eq!(block.type_tag(), Some("text"));
//! ```

use serde::{Deserialize, Serialize};

use crate::messages::cache::CacheControl;
use crate::messages::citation::Citation;

/// One block of content within a message.
///
/// Forward-compatible: unknown `type` tags deserialize into [`ContentBlock::Other`]
/// with the raw JSON preserved.
#[derive(Debug, Clone, PartialEq)]
pub enum ContentBlock {
    /// A block whose `type` is recognized by this SDK version.
    Known(KnownBlock),
    /// A block whose `type` is not recognized; the raw JSON is preserved.
    Other(serde_json::Value),
}

/// All content block variants known to this SDK version.
///
/// `#[non_exhaustive]` so that adding a new variant in a future release
/// is not a breaking change for downstream `match` statements.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum KnownBlock {
    /// Plain text content.
    Text {
        /// The text payload.
        text: String,
        /// Optional cache breakpoint.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControl>,
        /// Citations the model attached to this text span, if any.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        citations: Option<Vec<Citation>>,
    },
    /// An image embedded in the message.
    Image {
        /// Where the image bytes come from.
        source: ImageSource,
        /// Optional cache breakpoint.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControl>,
    },
    /// A document (e.g. PDF) embedded in the message.
    Document {
        /// Where the document bytes come from.
        source: DocumentSource,
        /// Optional human-readable title used in citation rendering.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        title: Option<String>,
        /// Optional citation configuration for this document.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        citations: Option<CitationConfig>,
        /// Optional cache breakpoint.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControl>,
    },
    /// A model-emitted request to invoke a tool.
    ToolUse {
        /// Identifier the model assigns to this invocation.
        id: String,
        /// Name of the tool to invoke.
        name: String,
        /// Tool arguments as JSON.
        input: serde_json::Value,
    },
    /// The result of a tool invocation, supplied back to the model.
    ToolResult {
        /// The `id` of the [`KnownBlock::ToolUse`] this result corresponds to.
        tool_use_id: String,
        /// The tool's output.
        content: ToolResultContent,
        /// Whether the tool execution failed.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        is_error: Option<bool>,
        /// Optional cache breakpoint.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cache_control: Option<CacheControl>,
    },
    /// Extended-thinking trace from the model.
    Thinking {
        /// The model's chain-of-thought text.
        thinking: String,
        /// Cryptographic signature over the thinking text.
        signature: String,
    },
    /// A redacted thinking block; only the opaque blob is visible.
    RedactedThinking {
        /// Opaque server-side blob.
        data: String,
    },
    /// A server-side tool invocation initiated by the model.
    ServerToolUse {
        /// Identifier the model assigns to this invocation.
        id: String,
        /// Server tool name (e.g. `web_search`).
        name: String,
        /// Tool arguments as JSON.
        input: serde_json::Value,
    },
    /// The result of a server-side `web_search` invocation.
    WebSearchToolResult {
        /// The `id` of the [`KnownBlock::ServerToolUse`] this result corresponds to.
        tool_use_id: String,
        /// Result payload (search hits etc.); shape is server-defined.
        content: serde_json::Value,
    },
}

/// `type` tags recognized by this SDK version. Used by [`ContentBlock`]'s
/// `Deserialize` impl to decide between `Known` and `Other`.
const KNOWN_BLOCK_TAGS: &[&str] = &[
    "text",
    "image",
    "document",
    "tool_use",
    "tool_result",
    "thinking",
    "redacted_thinking",
    "server_tool_use",
    "web_search_tool_result",
];

impl Serialize for ContentBlock {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        match self {
            ContentBlock::Known(k) => k.serialize(s),
            ContentBlock::Other(v) => v.serialize(s),
        }
    }
}

impl<'de> Deserialize<'de> for ContentBlock {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let value = serde_json::Value::deserialize(d)?;
        let type_tag = value.get("type").and_then(serde_json::Value::as_str);
        match type_tag {
            Some(t) if KNOWN_BLOCK_TAGS.contains(&t) => {
                let known: KnownBlock =
                    serde_json::from_value(value).map_err(serde::de::Error::custom)?;
                Ok(ContentBlock::Known(known))
            }
            _ => Ok(ContentBlock::Other(value)),
        }
    }
}

impl From<KnownBlock> for ContentBlock {
    fn from(k: KnownBlock) -> Self {
        ContentBlock::Known(k)
    }
}

impl ContentBlock {
    /// If this is a known block, return the inner [`KnownBlock`].
    pub fn known(&self) -> Option<&KnownBlock> {
        match self {
            Self::Known(k) => Some(k),
            Self::Other(_) => None,
        }
    }

    /// If this is an unknown block, return the raw JSON.
    pub fn other(&self) -> Option<&serde_json::Value> {
        match self {
            Self::Other(v) => Some(v),
            Self::Known(_) => None,
        }
    }

    /// Returns the wire-level `type` tag for this block, regardless of variant.
    ///
    /// For known blocks this returns the `snake_case` discriminant; for unknown
    /// blocks it returns whatever string the server sent in the `type` field
    /// (or `None` if the field was missing or non-string).
    pub fn type_tag(&self) -> Option<&str> {
        match self {
            Self::Known(k) => Some(known_type_tag(k)),
            Self::Other(v) => v.get("type").and_then(serde_json::Value::as_str),
        }
    }

    /// Convenience constructor for a plain text block.
    pub fn text(s: impl Into<String>) -> Self {
        Self::Known(KnownBlock::Text {
            text: s.into(),
            cache_control: None,
            citations: None,
        })
    }

    /// Convenience constructor for a URL-sourced image block.
    ///
    /// ```
    /// use claude_api::messages::ContentBlock;
    /// let block = ContentBlock::image_url("https://example.com/cat.png");
    /// assert_eq!(block.type_tag(), Some("image"));
    /// ```
    pub fn image_url(url: impl Into<String>) -> Self {
        Self::Known(KnownBlock::Image {
            source: ImageSource::Url { url: url.into() },
            cache_control: None,
        })
    }

    /// Convenience constructor for a base64-encoded image block. `media_type`
    /// is the IANA MIME type (e.g. `"image/png"`); `data` is base64.
    pub fn image_base64(media_type: impl Into<String>, data: impl Into<String>) -> Self {
        Self::Known(KnownBlock::Image {
            source: ImageSource::Base64 {
                media_type: media_type.into(),
                data: data.into(),
            },
            cache_control: None,
        })
    }

    /// Convenience constructor for an inline-text document block. Cites the
    /// document by `title` if provided.
    ///
    /// ```
    /// use claude_api::messages::ContentBlock;
    /// let block = ContentBlock::document_text("Page contents.", Some("Spec"));
    /// assert_eq!(block.type_tag(), Some("document"));
    /// ```
    pub fn document_text(data: impl Into<String>, title: Option<&str>) -> Self {
        Self::Known(KnownBlock::Document {
            source: DocumentSource::Text {
                media_type: "text/plain".to_owned(),
                data: data.into(),
            },
            title: title.map(str::to_owned),
            citations: Some(CitationConfig { enabled: true }),
            cache_control: None,
        })
    }

    /// Convenience constructor for a URL-sourced document block.
    pub fn document_url(url: impl Into<String>) -> Self {
        Self::Known(KnownBlock::Document {
            source: DocumentSource::Url { url: url.into() },
            title: None,
            citations: Some(CitationConfig { enabled: true }),
            cache_control: None,
        })
    }

    /// Convenience constructor: a text block with an ephemeral cache
    /// breakpoint at the default (5-minute) TTL. Use this on the last
    /// block of a long-lived prefix you expect to reuse across requests.
    ///
    /// ```
    /// use claude_api::messages::ContentBlock;
    /// let block = ContentBlock::text_cached("Be concise.");
    /// assert_eq!(block.type_tag(), Some("text"));
    /// ```
    pub fn text_cached(text: impl Into<String>) -> Self {
        Self::Known(KnownBlock::Text {
            text: text.into(),
            cache_control: Some(CacheControl::ephemeral()),
            citations: None,
        })
    }
}

fn known_type_tag(k: &KnownBlock) -> &'static str {
    match k {
        KnownBlock::Text { .. } => "text",
        KnownBlock::Image { .. } => "image",
        KnownBlock::Document { .. } => "document",
        KnownBlock::ToolUse { .. } => "tool_use",
        KnownBlock::ToolResult { .. } => "tool_result",
        KnownBlock::Thinking { .. } => "thinking",
        KnownBlock::RedactedThinking { .. } => "redacted_thinking",
        KnownBlock::ServerToolUse { .. } => "server_tool_use",
        KnownBlock::WebSearchToolResult { .. } => "web_search_tool_result",
    }
}

/// Source of bytes for an [`KnownBlock::Image`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum ImageSource {
    /// Inline base64-encoded bytes.
    Base64 {
        /// MIME type (e.g. `image/png`).
        media_type: String,
        /// Base64-encoded image bytes.
        data: String,
    },
    /// Public URL the server should fetch.
    Url {
        /// Image URL.
        url: String,
    },
    /// Reference to an uploaded file.
    File {
        /// File ID returned by the Files API.
        file_id: String,
    },
}

/// Source of bytes for an [`KnownBlock::Document`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum DocumentSource {
    /// Inline base64-encoded bytes.
    Base64 {
        /// MIME type (e.g. `application/pdf`).
        media_type: String,
        /// Base64-encoded document bytes.
        data: String,
    },
    /// Public URL the server should fetch.
    Url {
        /// Document URL.
        url: String,
    },
    /// Reference to an uploaded file.
    File {
        /// File ID returned by the Files API.
        file_id: String,
    },
    /// Inline plain-text document. The API requires `media_type` for this
    /// variant (typically `"text/plain"`); use [`ContentBlock::document_text`]
    /// for the common-case constructor.
    Text {
        /// MIME type, e.g. `"text/plain"`. Required by the API.
        media_type: String,
        /// Document text.
        data: String,
    },
}

/// Content payload of a `tool_result` block.
///
/// May be a plain string or a list of further [`ContentBlock`]s (e.g. text + image).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ToolResultContent {
    /// Plain-text result.
    Text(String),
    /// Structured result composed of further content blocks.
    Blocks(Vec<ContentBlock>),
}

/// Per-document citation configuration on a [`KnownBlock::Document`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CitationConfig {
    /// Whether the model should cite this document in its response.
    pub enabled: bool,
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;
    use serde_json::json;

    fn round_trip_block(block: &ContentBlock, expected: &serde_json::Value) {
        let serialized = serde_json::to_value(block).expect("serialize");
        assert_eq!(&serialized, expected, "wire form mismatch");
        let parsed: ContentBlock = serde_json::from_value(serialized).expect("deserialize");
        assert_eq!(&parsed, block, "round-trip mismatch");
    }

    #[test]
    fn text_block_round_trips() {
        round_trip_block(
            &ContentBlock::text("hello"),
            &json!({"type": "text", "text": "hello"}),
        );
    }

    #[test]
    fn text_block_with_cache_control_round_trips() {
        let block = ContentBlock::Known(KnownBlock::Text {
            text: "cached".into(),
            cache_control: Some(CacheControl::ephemeral_ttl("1h")),
            citations: None,
        });
        round_trip_block(
            &block,
            &json!({
                "type": "text",
                "text": "cached",
                "cache_control": {"type": "ephemeral", "ttl": "1h"}
            }),
        );
    }

    #[test]
    fn image_block_url_source_round_trips() {
        let block = ContentBlock::Known(KnownBlock::Image {
            source: ImageSource::Url {
                url: "https://example.com/cat.png".into(),
            },
            cache_control: None,
        });
        round_trip_block(
            &block,
            &json!({
                "type": "image",
                "source": {"type": "url", "url": "https://example.com/cat.png"}
            }),
        );
    }

    #[test]
    fn document_block_with_text_source_round_trips() {
        let block = ContentBlock::Known(KnownBlock::Document {
            source: DocumentSource::Text {
                media_type: "text/plain".into(),
                data: "page contents".into(),
            },
            title: Some("Spec".into()),
            citations: Some(CitationConfig { enabled: true }),
            cache_control: None,
        });
        round_trip_block(
            &block,
            &json!({
                "type": "document",
                "source": {"type": "text", "media_type": "text/plain", "data": "page contents"},
                "title": "Spec",
                "citations": {"enabled": true}
            }),
        );
    }

    #[test]
    fn tool_use_round_trips() {
        let block = ContentBlock::Known(KnownBlock::ToolUse {
            id: "toolu_01".into(),
            name: "get_weather".into(),
            input: json!({"city": "Paris"}),
        });
        round_trip_block(
            &block,
            &json!({
                "type": "tool_use",
                "id": "toolu_01",
                "name": "get_weather",
                "input": {"city": "Paris"}
            }),
        );
    }

    #[test]
    fn tool_result_with_string_content_round_trips() {
        let block = ContentBlock::Known(KnownBlock::ToolResult {
            tool_use_id: "toolu_01".into(),
            content: ToolResultContent::Text("72F".into()),
            is_error: None,
            cache_control: None,
        });
        round_trip_block(
            &block,
            &json!({
                "type": "tool_result",
                "tool_use_id": "toolu_01",
                "content": "72F"
            }),
        );
    }

    #[test]
    fn tool_result_with_nested_blocks_round_trips() {
        let block = ContentBlock::Known(KnownBlock::ToolResult {
            tool_use_id: "toolu_01".into(),
            content: ToolResultContent::Blocks(vec![ContentBlock::text("see below")]),
            is_error: Some(false),
            cache_control: None,
        });
        round_trip_block(
            &block,
            &json!({
                "type": "tool_result",
                "tool_use_id": "toolu_01",
                "content": [{"type": "text", "text": "see below"}],
                "is_error": false
            }),
        );
    }

    #[test]
    fn thinking_block_round_trips() {
        let block = ContentBlock::Known(KnownBlock::Thinking {
            thinking: "let me think...".into(),
            signature: "sig".into(),
        });
        round_trip_block(
            &block,
            &json!({
                "type": "thinking",
                "thinking": "let me think...",
                "signature": "sig"
            }),
        );
    }

    #[test]
    fn redacted_thinking_block_round_trips() {
        let block = ContentBlock::Known(KnownBlock::RedactedThinking {
            data: "<opaque>".into(),
        });
        round_trip_block(
            &block,
            &json!({"type": "redacted_thinking", "data": "<opaque>"}),
        );
    }

    #[test]
    fn server_tool_use_round_trips() {
        let block = ContentBlock::Known(KnownBlock::ServerToolUse {
            id: "stu_01".into(),
            name: "web_search".into(),
            input: json!({"query": "rust"}),
        });
        round_trip_block(
            &block,
            &json!({
                "type": "server_tool_use",
                "id": "stu_01",
                "name": "web_search",
                "input": {"query": "rust"}
            }),
        );
    }

    #[test]
    fn web_search_tool_result_round_trips() {
        let block = ContentBlock::Known(KnownBlock::WebSearchToolResult {
            tool_use_id: "stu_01".into(),
            content: json!([{"url": "https://rust-lang.org"}]),
        });
        round_trip_block(
            &block,
            &json!({
                "type": "web_search_tool_result",
                "tool_use_id": "stu_01",
                "content": [{"url": "https://rust-lang.org"}]
            }),
        );
    }

    #[test]
    fn unknown_block_type_falls_back_to_other_preserving_json() {
        let raw = json!({
            "type": "future_block_type",
            "some_field": 42,
            "nested": {"a": "b"}
        });
        let block: ContentBlock = serde_json::from_value(raw.clone()).expect("deserialize");
        match &block {
            ContentBlock::Other(v) => assert_eq!(v, &raw),
            ContentBlock::Known(_) => panic!("expected Other, got Known"),
        }
        let reserialized = serde_json::to_value(&block).expect("serialize");
        assert_eq!(reserialized, raw, "Other must round-trip byte-for-byte");
    }

    #[test]
    fn missing_type_field_falls_back_to_other() {
        let raw = json!({"text": "hi"});
        let block: ContentBlock = serde_json::from_value(raw.clone()).expect("deserialize");
        match &block {
            ContentBlock::Other(v) => assert_eq!(v, &raw),
            ContentBlock::Known(_) => panic!("expected Other"),
        }
    }

    #[test]
    fn malformed_known_block_is_an_error_not_other() {
        // Known type tag but `text` field is the wrong shape.
        let raw = json!({"type": "text", "text": 42});
        let result: Result<ContentBlock, _> = serde_json::from_value(raw);
        assert!(
            result.is_err(),
            "malformed known type must error, not silently fall through to Other"
        );
    }

    #[test]
    fn type_tag_works_for_known_and_other() {
        assert_eq!(ContentBlock::text("x").type_tag(), Some("text"));

        let other_json = json!({"type": "future_thing", "x": 1});
        let other: ContentBlock = serde_json::from_value(other_json).unwrap();
        assert_eq!(other.type_tag(), Some("future_thing"));
    }

    #[test]
    fn known_and_other_accessors() {
        let known = ContentBlock::text("hi");
        assert!(known.known().is_some());
        assert!(known.other().is_none());

        let other: ContentBlock =
            serde_json::from_value(json!({"type": "future", "x": 1})).unwrap();
        assert!(other.known().is_none());
        assert!(other.other().is_some());
    }

    #[test]
    fn from_known_block_into_content_block() {
        let kb = KnownBlock::Text {
            text: "via from".into(),
            cache_control: None,
            citations: None,
        };
        let cb: ContentBlock = kb.into();
        assert_eq!(cb.type_tag(), Some("text"));
    }
}