claude-api 0.5.0

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
//! Typed citations produced by Claude.
//!
//! [`Citation`] is the public, forward-compatible enum: it wraps a
//! [`KnownCitation`] for any citation type the SDK understands, or a raw
//! [`serde_json::Value`] for any type it doesn't. Same wrapper-enum +
//! strict-on-known pattern as [`crate::messages::content::ContentBlock`]
//! and [`crate::messages::stream::StreamEvent`].
//!
//! # Variants
//!
//! - **`CharLocation`** -- character range in a text document.
//! - **`PageLocation`** -- page range in a PDF document.
//! - **`ContentBlockLocation`** -- block range in a structured document.
//! - **`WebSearchResultLocation`** -- citation produced by the server-side
//!   web search tool.
//! - **`Other(Value)`** -- any future variant the SDK doesn't know about,
//!   preserved byte-for-byte for round-trip.

use serde::{Deserialize, Serialize};

use crate::forward_compat::dispatch_known_or_other;

/// A citation tying a span of generated text back to a source document or
/// web result.
///
/// Forward-compatible: unknown `type` tags deserialize into [`Citation::Other`]
/// with the raw JSON preserved.
#[derive(Debug, Clone, PartialEq)]
pub enum Citation {
    /// A citation whose `type` is recognized by this SDK version.
    Known(KnownCitation),
    /// A citation whose `type` is not recognized; the raw JSON is preserved.
    Other(serde_json::Value),
}

/// All citation variants known to this SDK version.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum KnownCitation {
    /// Citation tied to a character range in a text-source document.
    CharLocation {
        /// Index of the document in the request's content array.
        document_index: u32,
        /// Title of the document, if one was provided.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        document_title: Option<String>,
        /// The exact text span the model is citing.
        cited_text: String,
        /// Inclusive start character offset.
        start_char_index: u32,
        /// Exclusive end character offset.
        end_char_index: u32,
    },
    /// Citation tied to a page range in a PDF.
    PageLocation {
        /// Index of the document in the request's content array.
        document_index: u32,
        /// Title of the document, if one was provided.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        document_title: Option<String>,
        /// The exact text span the model is citing.
        cited_text: String,
        /// Inclusive start page number (1-indexed).
        start_page_number: u32,
        /// Exclusive end page number.
        end_page_number: u32,
    },
    /// Citation tied to a content-block range in a structured document.
    ContentBlockLocation {
        /// Index of the document in the request's content array.
        document_index: u32,
        /// Title of the document, if one was provided.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        document_title: Option<String>,
        /// The exact text span the model is citing.
        cited_text: String,
        /// Inclusive start block index.
        start_block_index: u32,
        /// Exclusive end block index.
        end_block_index: u32,
    },
    /// Citation produced by the server-side `web_search` built-in tool.
    WebSearchResultLocation {
        /// Source URL.
        url: String,
        /// Page title.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        title: Option<String>,
        /// The exact text span the model is citing.
        cited_text: String,
        /// Opaque encrypted index used by the server to resolve the search hit.
        encrypted_index: String,
    },
}

const KNOWN_CITATION_TAGS: &[&str] = &[
    "char_location",
    "page_location",
    "content_block_location",
    "web_search_result_location",
];

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

impl<'de> Deserialize<'de> for Citation {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let raw = serde_json::Value::deserialize(d)?;
        dispatch_known_or_other(raw, KNOWN_CITATION_TAGS, Citation::Known, Citation::Other)
            .map_err(serde::de::Error::custom)
    }
}

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

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

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

    /// Wire-level `type` tag for this citation regardless of variant.
    #[must_use]
    pub fn type_tag(&self) -> Option<&str> {
        match self {
            Self::Known(k) => Some(known_citation_tag(k)),
            Self::Other(v) => v.get("type").and_then(serde_json::Value::as_str),
        }
    }

    /// The text span the model cited. Available on every known variant
    /// and best-effort for [`Citation::Other`].
    #[must_use]
    pub fn cited_text(&self) -> Option<&str> {
        match self {
            Self::Known(k) => Some(match k {
                KnownCitation::CharLocation { cited_text, .. }
                | KnownCitation::PageLocation { cited_text, .. }
                | KnownCitation::ContentBlockLocation { cited_text, .. }
                | KnownCitation::WebSearchResultLocation { cited_text, .. } => cited_text,
            }),
            Self::Other(v) => v.get("cited_text").and_then(serde_json::Value::as_str),
        }
    }

    /// Title of the source (document title or web page title), when available.
    #[must_use]
    pub fn title(&self) -> Option<&str> {
        match self {
            Self::Known(
                KnownCitation::CharLocation { document_title, .. }
                | KnownCitation::PageLocation { document_title, .. }
                | KnownCitation::ContentBlockLocation { document_title, .. },
            ) => document_title.as_deref(),
            Self::Known(KnownCitation::WebSearchResultLocation { title, .. }) => title.as_deref(),
            Self::Other(v) => v
                .get("document_title")
                .or_else(|| v.get("title"))
                .and_then(serde_json::Value::as_str),
        }
    }
}

fn known_citation_tag(k: &KnownCitation) -> &'static str {
    match k {
        KnownCitation::CharLocation { .. } => "char_location",
        KnownCitation::PageLocation { .. } => "page_location",
        KnownCitation::ContentBlockLocation { .. } => "content_block_location",
        KnownCitation::WebSearchResultLocation { .. } => "web_search_result_location",
    }
}

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

    fn round_trip(citation: &Citation, expected: &serde_json::Value) {
        let v = serde_json::to_value(citation).expect("serialize");
        assert_eq!(&v, expected, "wire form mismatch");
        let parsed: Citation = serde_json::from_value(v).expect("deserialize");
        assert_eq!(&parsed, citation, "round-trip mismatch");
    }

    #[test]
    fn char_location_round_trips() {
        let c = Citation::Known(KnownCitation::CharLocation {
            document_index: 0,
            document_title: Some("Spec".into()),
            cited_text: "hello world".into(),
            start_char_index: 10,
            end_char_index: 21,
        });
        round_trip(
            &c,
            &json!({
                "type": "char_location",
                "document_index": 0,
                "document_title": "Spec",
                "cited_text": "hello world",
                "start_char_index": 10,
                "end_char_index": 21
            }),
        );
    }

    #[test]
    fn char_location_with_no_title_round_trips() {
        let c = Citation::Known(KnownCitation::CharLocation {
            document_index: 1,
            document_title: None,
            cited_text: "x".into(),
            start_char_index: 0,
            end_char_index: 1,
        });
        round_trip(
            &c,
            &json!({
                "type": "char_location",
                "document_index": 1,
                "cited_text": "x",
                "start_char_index": 0,
                "end_char_index": 1
            }),
        );
    }

    #[test]
    fn page_location_round_trips() {
        let c = Citation::Known(KnownCitation::PageLocation {
            document_index: 2,
            document_title: Some("Manual".into()),
            cited_text: "see page 5".into(),
            start_page_number: 5,
            end_page_number: 6,
        });
        round_trip(
            &c,
            &json!({
                "type": "page_location",
                "document_index": 2,
                "document_title": "Manual",
                "cited_text": "see page 5",
                "start_page_number": 5,
                "end_page_number": 6
            }),
        );
    }

    #[test]
    fn content_block_location_round_trips() {
        let c = Citation::Known(KnownCitation::ContentBlockLocation {
            document_index: 0,
            document_title: None,
            cited_text: "block excerpt".into(),
            start_block_index: 3,
            end_block_index: 5,
        });
        round_trip(
            &c,
            &json!({
                "type": "content_block_location",
                "document_index": 0,
                "cited_text": "block excerpt",
                "start_block_index": 3,
                "end_block_index": 5
            }),
        );
    }

    #[test]
    fn web_search_result_location_round_trips() {
        let c = Citation::Known(KnownCitation::WebSearchResultLocation {
            url: "https://example.com/post".into(),
            title: Some("Example Post".into()),
            cited_text: "the relevant snippet".into(),
            encrypted_index: "opaque-cursor-token".into(),
        });
        round_trip(
            &c,
            &json!({
                "type": "web_search_result_location",
                "url": "https://example.com/post",
                "title": "Example Post",
                "cited_text": "the relevant snippet",
                "encrypted_index": "opaque-cursor-token"
            }),
        );
    }

    #[test]
    fn unknown_citation_type_falls_back_to_other_preserving_json() {
        let raw = json!({
            "type": "future_location",
            "cited_text": "preserved",
            "extra_field": [1, 2, 3]
        });
        let c: Citation = serde_json::from_value(raw.clone()).expect("deserialize");
        match &c {
            Citation::Other(v) => assert_eq!(v, &raw),
            Citation::Known(_) => panic!("expected Other"),
        }
        let reserialized = serde_json::to_value(&c).expect("serialize");
        assert_eq!(reserialized, raw, "Other must round-trip byte-for-byte");
    }

    #[test]
    fn malformed_known_citation_is_an_error() {
        // type matches but start_char_index is wrong shape.
        let raw = json!({
            "type": "char_location",
            "document_index": 0,
            "cited_text": "x",
            "start_char_index": "nope",
            "end_char_index": 1
        });
        let result: Result<Citation, _> = serde_json::from_value(raw);
        assert!(
            result.is_err(),
            "malformed known citation must error, not silently fall through"
        );
    }

    #[test]
    fn cited_text_accessor_works_across_variants() {
        for (citation, expected) in [
            (
                Citation::Known(KnownCitation::CharLocation {
                    document_index: 0,
                    document_title: None,
                    cited_text: "char".into(),
                    start_char_index: 0,
                    end_char_index: 4,
                }),
                "char",
            ),
            (
                Citation::Known(KnownCitation::WebSearchResultLocation {
                    url: "https://x".into(),
                    title: None,
                    cited_text: "web".into(),
                    encrypted_index: "i".into(),
                }),
                "web",
            ),
        ] {
            assert_eq!(citation.cited_text(), Some(expected));
        }
    }

    #[test]
    fn cited_text_works_on_other_variant() {
        let c: Citation = serde_json::from_value(json!({
            "type": "future_xyz",
            "cited_text": "fallback works"
        }))
        .unwrap();
        assert_eq!(c.cited_text(), Some("fallback works"));
    }

    #[test]
    fn title_accessor_works_across_variants() {
        let doc = Citation::Known(KnownCitation::CharLocation {
            document_index: 0,
            document_title: Some("Doc".into()),
            cited_text: "x".into(),
            start_char_index: 0,
            end_char_index: 1,
        });
        assert_eq!(doc.title(), Some("Doc"));

        let web = Citation::Known(KnownCitation::WebSearchResultLocation {
            url: "https://x".into(),
            title: Some("Web Title".into()),
            cited_text: "x".into(),
            encrypted_index: "i".into(),
        });
        assert_eq!(web.title(), Some("Web Title"));
    }

    #[test]
    fn type_tag_works_for_known_and_other() {
        let known = Citation::Known(KnownCitation::CharLocation {
            document_index: 0,
            document_title: None,
            cited_text: "x".into(),
            start_char_index: 0,
            end_char_index: 1,
        });
        assert_eq!(known.type_tag(), Some("char_location"));

        let other: Citation = serde_json::from_value(json!({"type": "future"})).unwrap();
        assert_eq!(other.type_tag(), Some("future"));
    }
}