Skip to main content

strands/types/
citations.rs

1//! Citation content blocks.
2//!
3//! Models return citations when document citations are enabled. They are output-only blocks that
4//! appear in conversation history.
5
6use serde::{Deserialize, Serialize};
7
8/// Where a citation points (`CitationLocation`), tagged by `type` on the wire.
9#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
10#[serde(tag = "type", rename_all = "camelCase")]
11#[non_exhaustive]
12pub enum CitationLocation {
13    /// Character positions within a document, `"documentChar"`.
14    DocumentChar(DocumentCharLocation),
15    /// Page positions within a document, `"documentPage"`.
16    DocumentPage(DocumentPageLocation),
17    /// Chunk positions within a document, `"documentChunk"`.
18    DocumentChunk(DocumentChunkLocation),
19    /// Positions within a search result, `"searchResult"`.
20    SearchResult(SearchResultLocation),
21    /// A web page, `"web"`.
22    Web(WebLocation),
23}
24
25macro_rules! document_location {
26    ($(#[$doc:meta])* $name:ident, $variant:ident, $unit:literal) => {
27        $(#[$doc])*
28        #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
29        #[serde(rename_all = "camelCase")]
30        #[non_exhaustive]
31        pub struct $name {
32            /// Index of the source document.
33            pub document_index: u64,
34            #[doc = concat!("Start ", $unit, ".")]
35            pub start: u64,
36            #[doc = concat!("End ", $unit, ".")]
37            pub end: u64,
38        }
39
40        impl $name {
41            /// Creates the location.
42            pub fn new(document_index: u64, start: u64, end: u64) -> Self {
43                Self { document_index, start, end }
44            }
45        }
46
47        impl From<$name> for CitationLocation {
48            fn from(location: $name) -> Self {
49                Self::$variant(location)
50            }
51        }
52    };
53}
54
55document_location!(
56    /// Character positions within a document.
57    DocumentCharLocation,
58    DocumentChar,
59    "character position"
60);
61
62document_location!(
63    /// Page positions within a document.
64    DocumentPageLocation,
65    DocumentPage,
66    "page number"
67);
68
69document_location!(
70    /// Chunk positions within a document.
71    DocumentChunkLocation,
72    DocumentChunk,
73    "chunk index"
74);
75
76/// Positions within a search result.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(rename_all = "camelCase")]
79#[non_exhaustive]
80pub struct SearchResultLocation {
81    /// Index of the search result.
82    pub search_result_index: u64,
83    /// Start position within the search result.
84    pub start: u64,
85    /// End position within the search result.
86    pub end: u64,
87}
88
89impl SearchResultLocation {
90    /// Creates the location.
91    pub fn new(search_result_index: u64, start: u64, end: u64) -> Self {
92        Self {
93            search_result_index,
94            start,
95            end,
96        }
97    }
98}
99
100impl From<SearchResultLocation> for CitationLocation {
101    fn from(location: SearchResultLocation) -> Self {
102        Self::SearchResult(location)
103    }
104}
105
106/// A web page.
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
108#[non_exhaustive]
109pub struct WebLocation {
110    /// The URL of the web source.
111    pub url: String,
112    /// The domain of the web source.
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub domain: Option<String>,
115}
116
117impl WebLocation {
118    /// Creates the location from a URL.
119    pub fn new(url: impl Into<String>) -> Self {
120        Self {
121            url: url.into(),
122            domain: None,
123        }
124    }
125
126    /// Sets the domain.
127    #[must_use]
128    pub fn with_domain(mut self, domain: impl Into<String>) -> Self {
129        self.domain = Some(domain.into());
130        self
131    }
132}
133
134impl From<WebLocation> for CitationLocation {
135    fn from(location: WebLocation) -> Self {
136        Self::Web(location)
137    }
138}
139
140/// Source content referenced by a citation (`CitationSourceContent`).
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142#[non_exhaustive]
143pub struct CitationSourceContent {
144    /// The cited source text.
145    pub text: String,
146}
147
148impl CitationSourceContent {
149    /// Creates source content from text.
150    pub fn new(text: impl Into<String>) -> Self {
151        Self { text: text.into() }
152    }
153}
154
155/// Generated content associated with a citation (`CitationGeneratedContent`).
156#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
157#[non_exhaustive]
158pub struct CitationGeneratedContent {
159    /// The generated text.
160    pub text: String,
161}
162
163impl CitationGeneratedContent {
164    /// Creates generated content from text.
165    pub fn new(text: impl Into<String>) -> Self {
166        Self { text: text.into() }
167    }
168}
169
170/// A citation linking generated content to a source location (`Citation`).
171#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
172#[serde(rename_all = "camelCase")]
173#[non_exhaustive]
174pub struct Citation {
175    /// The location of the cited source.
176    pub location: CitationLocation,
177    /// The source identifier.
178    pub source: String,
179    /// The source content referenced by this citation.
180    pub source_content: Vec<CitationSourceContent>,
181    /// Title of the cited source.
182    pub title: String,
183}
184
185impl Citation {
186    /// Creates a citation.
187    pub fn new(
188        location: impl Into<CitationLocation>,
189        source: impl Into<String>,
190        source_content: Vec<CitationSourceContent>,
191        title: impl Into<String>,
192    ) -> Self {
193        Self {
194            location: location.into(),
195            source: source.into(),
196            source_content,
197            title: title.into(),
198        }
199    }
200}
201
202/// Citations content block (`CitationsBlock`), wrapped as `{"citations": {...}}` in a message.
203#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
204#[non_exhaustive]
205pub struct CitationsBlock {
206    /// Citations linking generated content to source locations.
207    pub citations: Vec<Citation>,
208    /// The generated content associated with these citations.
209    pub content: Vec<CitationGeneratedContent>,
210}
211
212impl CitationsBlock {
213    /// Creates a citations block.
214    pub fn new(citations: Vec<Citation>, content: Vec<CitationGeneratedContent>) -> Self {
215        Self { citations, content }
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use serde_json::json;
222
223    use super::*;
224    use crate::types::ContentBlock;
225
226    fn single_citation() -> CitationsBlock {
227        CitationsBlock::new(
228            vec![Citation::new(
229                DocumentCharLocation::new(0, 10, 50),
230                "doc-0",
231                vec![CitationSourceContent::new("source text from document")],
232                "Test Document",
233            )],
234            vec![CitationGeneratedContent::new("generated text with citation")],
235        )
236    }
237
238    fn all_variants() -> serde_json::Value {
239        json!({
240            "citations": {
241                "citations": [
242                    {"location": {"type": "documentChar", "documentIndex": 0, "start": 150, "end": 300}, "source": "doc-0", "sourceContent": [{"text": "char source"}], "title": "Text Document"},
243                    {"location": {"type": "documentPage", "documentIndex": 0, "start": 2, "end": 3}, "source": "doc-0", "sourceContent": [{"text": "page source"}], "title": "PDF Document"},
244                    {"location": {"type": "documentChunk", "documentIndex": 1, "start": 5, "end": 8}, "source": "doc-1", "sourceContent": [{"text": "chunk source"}], "title": "Chunked Document"},
245                    {"location": {"type": "searchResult", "searchResultIndex": 0, "start": 25, "end": 150}, "source": "search-0", "sourceContent": [{"text": "search source"}], "title": "Search Result"},
246                    {"location": {"type": "web", "url": "https://example.com/doc", "domain": "example.com"}, "source": "web-0", "sourceContent": [{"text": "web source"}, {"text": "additional source"}], "title": "Web Page"}
247                ],
248                "content": [{"text": "first generated"}, {"text": "second generated"}]
249            }
250        })
251    }
252
253    #[test]
254    fn creates_block_with_correct_type_discriminator() {
255        let block = ContentBlock::Citations(single_citation());
256        assert!(matches!(block, ContentBlock::Citations(_)));
257    }
258
259    #[test]
260    fn stores_citations_and_content() {
261        let block = single_citation();
262        assert_eq!(block.citations.len(), 1);
263        assert_eq!(block.citations[0].title, "Test Document");
264        assert_eq!(
265            block.content,
266            vec![CitationGeneratedContent::new("generated text with citation")]
267        );
268    }
269
270    #[test]
271    fn round_trips_all_citation_location_variants_multiple_citations_and_multiple_content_blocks() {
272        let original = all_variants();
273        let block: ContentBlock = serde_json::from_value(original.clone()).unwrap();
274        let ContentBlock::Citations(citations) = &block else {
275            panic!("expected a citations block");
276        };
277        assert_eq!(citations.citations.len(), 5);
278        assert_eq!(
279            citations.citations[4].location,
280            CitationLocation::Web(WebLocation::new("https://example.com/doc").with_domain("example.com"))
281        );
282        assert_eq!(serde_json::to_value(&block).unwrap(), original);
283    }
284
285    #[test]
286    fn handles_empty_arrays() {
287        let block = ContentBlock::Citations(CitationsBlock::default());
288        let json = serde_json::to_value(&block).unwrap();
289        assert_eq!(json, json!({"citations": {"citations": [], "content": []}}));
290        assert_eq!(serde_json::from_value::<ContentBlock>(json).unwrap(), block);
291    }
292
293    #[test]
294    fn to_json_returns_wrapped_format() {
295        assert_eq!(
296            serde_json::to_value(ContentBlock::Citations(single_citation())).unwrap(),
297            json!({
298                "citations": {
299                    "citations": [{
300                        "location": {"type": "documentChar", "documentIndex": 0, "start": 10, "end": 50},
301                        "source": "doc-0",
302                        "sourceContent": [{"text": "source text from document"}],
303                        "title": "Test Document"
304                    }],
305                    "content": [{"text": "generated text with citation"}]
306                }
307            })
308        );
309    }
310
311    #[test]
312    fn works_with_json_stringify() {
313        let text = serde_json::to_string(&all_variants()).unwrap();
314        let block: ContentBlock = serde_json::from_str(&text).unwrap();
315        assert_eq!(serde_json::to_string(&block).unwrap(), text);
316    }
317}