adk_rag/document.rs
1//! Data types for documents, chunks, and search results.
2
3use std::collections::HashMap;
4
5use serde::{Deserialize, Serialize};
6
7/// A source document containing text content, metadata, and provenance.
8///
9/// `source_uri` and `title` say where the text came from. Every chunker copies them onto
10/// each [`Chunk`], every vector store returns them with search results, and
11/// [`RagTool`](crate::RagTool) gives them to the model, so an answer can cite the
12/// document. `metadata` is stored verbatim; no key is reserved.
13///
14/// # Example
15///
16/// ```rust
17/// use adk_rag::Document;
18///
19/// let document = Document::new("refunds", "Refunds are issued within 30 days.")
20/// .with_source_uri("https://example.com/policies/refunds")
21/// .with_title("Refund policy")
22/// .with_metadata("section", "billing");
23///
24/// assert_eq!(document.source_uri.as_deref(), Some("https://example.com/policies/refunds"));
25/// assert_eq!(document.metadata["section"], "billing");
26/// ```
27#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
28#[non_exhaustive]
29pub struct Document {
30 /// Unique identifier for the document.
31 pub id: String,
32 /// The text content of the document.
33 pub text: String,
34 /// Key-value metadata associated with the document.
35 pub metadata: HashMap<String, String>,
36 /// URI of the original source, such as a web page or file path.
37 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub source_uri: Option<String>,
39 /// Human-readable title of the original source.
40 #[serde(default, skip_serializing_if = "Option::is_none")]
41 pub title: Option<String>,
42}
43
44impl Document {
45 /// Creates a document with no metadata and no provenance.
46 ///
47 /// # Example
48 ///
49 /// ```rust
50 /// use adk_rag::Document;
51 ///
52 /// let document = Document::new("intro", "Rust is a systems programming language.");
53 /// assert!(document.metadata.is_empty());
54 /// assert_eq!(document.source_uri, None);
55 /// ```
56 pub fn new(id: impl Into<String>, text: impl Into<String>) -> Self {
57 Self {
58 id: id.into(),
59 text: text.into(),
60 metadata: HashMap::new(),
61 source_uri: None,
62 title: None,
63 }
64 }
65
66 /// Adds one metadata entry, replacing any earlier value for `key`.
67 #[must_use]
68 pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
69 self.metadata.insert(key.into(), value.into());
70 self
71 }
72
73 /// Sets the URI of the original source.
74 #[must_use]
75 pub fn with_source_uri(mut self, source_uri: impl Into<String>) -> Self {
76 self.source_uri = Some(source_uri.into());
77 self
78 }
79
80 /// Sets the title of the original source.
81 #[must_use]
82 pub fn with_title(mut self, title: impl Into<String>) -> Self {
83 self.title = Some(title.into());
84 self
85 }
86}
87
88/// A segment of a [`Document`] with its vector embedding.
89///
90/// A chunk carries its document's `source_uri` and `title`, which every vector store
91/// persists and returns as fields of their own.
92///
93/// # Example
94///
95/// ```rust
96/// use adk_rag::{Chunk, Document};
97///
98/// let document = Document::new("refunds", "Refunds are issued within 30 days.")
99/// .with_source_uri("https://example.com/policies/refunds");
100/// let chunk = Chunk::from_document(&document, "refunds_0", "Refunds are issued")
101/// .with_embedding(vec![0.1, 0.2]);
102///
103/// assert_eq!(chunk.document_id, "refunds");
104/// assert_eq!(chunk.source_uri, document.source_uri);
105/// ```
106#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
107#[non_exhaustive]
108pub struct Chunk {
109 /// Unique identifier for the chunk.
110 pub id: String,
111 /// The text content of the chunk.
112 pub text: String,
113 /// The vector embedding for this chunk's text.
114 pub embedding: Vec<f32>,
115 /// Key-value metadata inherited from the parent document plus chunk-specific fields.
116 pub metadata: HashMap<String, String>,
117 /// The ID of the parent [`Document`].
118 pub document_id: String,
119 /// URI of the parent document's original source.
120 #[serde(default, skip_serializing_if = "Option::is_none")]
121 pub source_uri: Option<String>,
122 /// Title of the parent document's original source.
123 #[serde(default, skip_serializing_if = "Option::is_none")]
124 pub title: Option<String>,
125}
126
127impl Chunk {
128 /// Creates a chunk with no embedding, metadata, or provenance.
129 ///
130 /// # Example
131 ///
132 /// ```rust
133 /// use adk_rag::Chunk;
134 ///
135 /// let chunk = Chunk::new("doc_0", "doc", "first chunk").with_embedding(vec![1.0, 0.0]);
136 /// assert_eq!(chunk.embedding, [1.0, 0.0]);
137 /// ```
138 pub fn new(
139 id: impl Into<String>,
140 document_id: impl Into<String>,
141 text: impl Into<String>,
142 ) -> Self {
143 Self {
144 id: id.into(),
145 text: text.into(),
146 embedding: Vec::new(),
147 metadata: HashMap::new(),
148 document_id: document_id.into(),
149 source_uri: None,
150 title: None,
151 }
152 }
153
154 /// Creates a chunk of `document` that inherits its ID, metadata, source URI, and title.
155 ///
156 /// A [`Chunker`](crate::Chunker) builds its chunks with this constructor, so provenance
157 /// reaches the vector store.
158 pub fn from_document(
159 document: &Document,
160 id: impl Into<String>,
161 text: impl Into<String>,
162 ) -> Self {
163 Self {
164 id: id.into(),
165 text: text.into(),
166 embedding: Vec::new(),
167 metadata: document.metadata.clone(),
168 document_id: document.id.clone(),
169 source_uri: document.source_uri.clone(),
170 title: document.title.clone(),
171 }
172 }
173
174 /// Sets the embedding vector.
175 #[must_use]
176 pub fn with_embedding(mut self, embedding: Vec<f32>) -> Self {
177 self.embedding = embedding;
178 self
179 }
180
181 /// Adds one metadata entry, replacing any earlier value for `key`.
182 #[must_use]
183 pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
184 self.metadata.insert(key.into(), value.into());
185 self
186 }
187
188 /// Sets the URI of the original source.
189 #[must_use]
190 pub fn with_source_uri(mut self, source_uri: impl Into<String>) -> Self {
191 self.source_uri = Some(source_uri.into());
192 self
193 }
194
195 /// Sets the title of the original source.
196 #[must_use]
197 pub fn with_title(mut self, title: impl Into<String>) -> Self {
198 self.title = Some(title.into());
199 self
200 }
201}
202
203/// A retrieved [`Chunk`] paired with a relevance score.
204#[derive(Debug, Clone, Serialize, Deserialize)]
205pub struct SearchResult {
206 /// The retrieved chunk.
207 pub chunk: Chunk,
208 /// The similarity score (higher is more relevant).
209 pub score: f32,
210}