Skip to main content

adk_memory/
text.rs

1//! Shared text extraction utilities for memory backends.
2//!
3//! A memory's searchable text is its text parts alone ([`extract_text`]). The artifacts it
4//! refers to — an image a caption describes, a document a note cites — are kept beside the
5//! text as [`ArtifactReference`]s ([`artifact_references`]): a URI and a media type, never
6//! the bytes.
7
8use adk_core::Part;
9use serde::{Deserialize, Serialize};
10use std::collections::HashSet;
11
12/// An artifact a memory refers to: its URI and media type, never its bytes.
13///
14/// A memory carries one as a `Part::FileData` beside its text
15/// ([`MemoryEntry::with_artifact`](crate::MemoryEntry::with_artifact)). Every backend that
16/// stores the entry's content keeps the part; a backend that stores text alone, such as
17/// the knowledge graph's episodic log, keeps the references in a column of their own and
18/// returns them as `Part::FileData` again.
19///
20/// # Example
21///
22/// ```rust
23/// use adk_core::Content;
24/// use adk_memory::text::{ArtifactReference, artifact_references, extract_text};
25///
26/// let reference = ArtifactReference::new("artifact://inspector/u1/s1/frame.png#0", "image/png");
27/// let mut content = Content::new("model").with_text("torn seal on carton 117");
28/// content.parts.push(reference.to_part());
29///
30/// assert_eq!(extract_text(&content), "torn seal on carton 117");
31/// assert_eq!(artifact_references(&content), vec![reference]);
32/// ```
33#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
34#[serde(rename_all = "camelCase")]
35pub struct ArtifactReference {
36    /// Where the artifact is: an `artifact://` locator, a URL, or a cloud storage path.
37    pub uri: String,
38    /// Its media type, such as `image/png`.
39    pub mime_type: String,
40}
41
42impl ArtifactReference {
43    /// A reference to the artifact at `uri` of media type `mime_type`.
44    pub fn new(uri: impl Into<String>, mime_type: impl Into<String>) -> Self {
45        Self { uri: uri.into(), mime_type: mime_type.into() }
46    }
47
48    /// The `Part::FileData` that carries this reference in a [`Content`](adk_core::Content).
49    pub fn to_part(&self) -> Part {
50        Part::FileData {
51            mime_type: self.mime_type.clone(),
52            file_uri: self.uri.clone(),
53            annotations: None,
54        }
55    }
56}
57
58/// The artifacts a [`Content`](adk_core::Content) refers to, in part order: every
59/// `Part::FileData`, and every `Part::InlineData` or `Part::EmbeddedResource` that names its
60/// source URI. Inline bytes are never part of a reference; inline data without a `uri`
61/// refers to nothing.
62pub fn artifact_references(content: &adk_core::Content) -> Vec<ArtifactReference> {
63    content
64        .parts
65        .iter()
66        .filter_map(|part| match part {
67            Part::FileData { mime_type, file_uri, .. } => {
68                Some(ArtifactReference::new(file_uri, mime_type))
69            }
70            Part::InlineData { mime_type, uri: Some(uri), .. } => {
71                Some(ArtifactReference::new(uri, mime_type))
72            }
73            Part::EmbeddedResource { resource } => Some(ArtifactReference::new(
74                resource.uri(),
75                resource.mime_type().unwrap_or("application/octet-stream"),
76            )),
77            Part::InlineData { uri: None, .. }
78            | Part::Thinking { .. }
79            | Part::Text { .. }
80            | Part::FunctionCall { .. }
81            | Part::FunctionResponse { .. }
82            | Part::ServerToolCall { .. }
83            | Part::ServerToolResponse { .. } => None,
84        })
85        .collect()
86}
87
88/// Extract all text parts from a [`Content`](adk_core::Content) into a single string.
89///
90/// Parts are joined with a single space. Non-text parts (images, function calls,
91/// etc.) are skipped; [`artifact_references`] returns the artifacts among them.
92pub fn extract_text(content: &adk_core::Content) -> String {
93    content
94        .parts
95        .iter()
96        .filter_map(|part| match part {
97            Part::Text { text } => Some(text.as_str()),
98            _ => None,
99        })
100        .collect::<Vec<_>>()
101        .join(" ")
102}
103
104/// Returns `true` if the character is in a CJK Unified Ideographs block.
105fn is_cjk_char(c: char) -> bool {
106    matches!(c,
107        '\u{4e00}'..='\u{9fff}'   // CJK Unified Ideographs
108        | '\u{3400}'..='\u{4dbf}' // CJK Unified Ideographs Extension A
109        | '\u{f900}'..='\u{faff}' // CJK Compatibility Ideographs
110        | '\u{2e80}'..='\u{2eff}' // CJK Radicals Supplement
111        | '\u{3000}'..='\u{303f}' // CJK Symbols and Punctuation
112        | '\u{3040}'..='\u{309f}' // Hiragana
113        | '\u{30a0}'..='\u{30ff}' // Katakana
114        | '\u{ac00}'..='\u{d7af}' // Hangul Syllables
115    )
116}
117
118/// Tokenize text into a set of lowercase words for keyword matching.
119///
120/// A word is a maximal run of Unicode letters and digits ([`char::is_alphanumeric`]), so
121/// punctuation never sticks to a word: `"Nairobi."`, `"(Nairobi)"` and `"Nairobi"` all
122/// yield `nairobi`, in every script.
123///
124/// CJK text (Chinese, Japanese, Korean) has no spaces between words, so each word that
125/// contains CJK characters also yields its character unigrams and bigrams, which lets a
126/// query match part of a longer run of CJK text.
127pub fn extract_words(text: &str) -> HashSet<String> {
128    let mut words = HashSet::new();
129    let lower = text.to_lowercase();
130
131    for word in lower.split(|c: char| !c.is_alphanumeric()).filter(|word| !word.is_empty()) {
132        if word.chars().any(is_cjk_char) {
133            // "编程" matches within "用户喜欢用rust编程".
134            let chars: Vec<char> = word.chars().collect();
135            for c in &chars {
136                if is_cjk_char(*c) {
137                    words.insert(c.to_string());
138                }
139            }
140            for window in chars.windows(2) {
141                if window.iter().any(|c| is_cjk_char(*c)) {
142                    words.insert(window.iter().collect());
143                }
144            }
145        }
146        words.insert(word.to_string());
147    }
148
149    words
150}
151
152/// The share of `query_words` that `entry_words` contains, from 0.0 (none) to 1.0 (all).
153pub(crate) fn match_score(query_words: &HashSet<String>, entry_words: &HashSet<String>) -> f32 {
154    if query_words.is_empty() {
155        return 0.0;
156    }
157    let matched = query_words.iter().filter(|word| entry_words.contains(*word)).count();
158    matched as f32 / query_words.len() as f32
159}
160
161/// Orders keyword matches best first: the higher score, then the newer entry.
162pub(crate) fn rank_matches(
163    mut matches: Vec<(f32, crate::service::MemoryEntry)>,
164    limit: usize,
165) -> Vec<crate::service::MemoryEntry> {
166    matches.sort_by(|(left_score, left), (right_score, right)| {
167        right_score.total_cmp(left_score).then_with(|| right.timestamp.cmp(&left.timestamp))
168    });
169    matches.into_iter().take(limit).map(|(_, entry)| entry).collect()
170}
171
172/// Extract and tokenize all text from a [`Content`](adk_core::Content) into word set.
173pub fn extract_words_from_content(content: &adk_core::Content) -> HashSet<String> {
174    let mut words = HashSet::new();
175    for part in &content.parts {
176        if let Part::Text { text } = part {
177            words.extend(extract_words(text));
178        }
179    }
180    words
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    #[test]
188    fn artifact_references_keep_uris_and_never_bytes() {
189        let content = adk_core::Content {
190            role: "model".into(),
191            parts: vec![
192                Part::Text { text: "torn seal".into() },
193                Part::FileData {
194                    mime_type: "image/png".into(),
195                    file_uri: "artifact://a/u/s/f.png#0".into(),
196                    annotations: None,
197                },
198                Part::InlineData {
199                    mime_type: "image/jpeg".into(),
200                    data: vec![0xff, 0xd8],
201                    uri: Some("artifact://a/u/s/g.jpg#1".into()),
202                    annotations: None,
203                },
204                Part::InlineData {
205                    mime_type: "image/jpeg".into(),
206                    data: vec![0xff, 0xd8],
207                    uri: None,
208                    annotations: None,
209                },
210            ],
211        };
212        assert_eq!(extract_text(&content), "torn seal");
213        assert_eq!(
214            artifact_references(&content),
215            vec![
216                ArtifactReference::new("artifact://a/u/s/f.png#0", "image/png"),
217                ArtifactReference::new("artifact://a/u/s/g.jpg#1", "image/jpeg"),
218            ]
219        );
220        let reference = ArtifactReference::new("artifact://a/u/s/f.png#0", "image/png");
221        assert_eq!(
222            serde_json::to_value(&reference).unwrap(),
223            serde_json::json!({ "uri": "artifact://a/u/s/f.png#0", "mimeType": "image/png" })
224        );
225    }
226
227    #[test]
228    fn test_extract_words_english() {
229        let words = extract_words("Hello World foo bar");
230        assert!(words.contains("hello"));
231        assert!(words.contains("world"));
232        assert!(words.contains("foo"));
233        assert!(words.contains("bar"));
234    }
235
236    #[test]
237    fn test_extract_words_cjk_bigram_matching() {
238        // "用户喜欢用Rust编程" should produce bigrams that include "编程"
239        let stored = extract_words("用户喜欢用Rust编程");
240        let query = extract_words("编程");
241
242        // The query "编程" should match because it's a bigram in the stored text
243        let matches: HashSet<_> = stored.intersection(&query).collect();
244        assert!(
245            !matches.is_empty(),
246            "CJK search should find matches. Stored: {stored:?}, Query: {query:?}"
247        );
248    }
249
250    #[test]
251    fn test_extract_words_cjk_single_char() {
252        let stored = extract_words("今天天气很好");
253        let query = extract_words("天气");
254
255        let matches: HashSet<_> = stored.intersection(&query).collect();
256        assert!(
257            !matches.is_empty(),
258            "CJK bigram '天气' should match. Stored: {stored:?}, Query: {query:?}"
259        );
260    }
261
262    #[test]
263    fn test_extract_words_mixed_cjk_english() {
264        let words = extract_words("Hello 你好 World");
265        assert!(words.contains("hello"));
266        assert!(words.contains("world"));
267        assert!(words.contains("你"));
268        assert!(words.contains("好"));
269        assert!(words.contains("你好"));
270    }
271
272    #[test]
273    fn test_extract_words_ignore_punctuation() {
274        let words = extract_words("Hometown: Nairobi. (Kenya!) state-of-the-art, \"quoted\"");
275        for word in ["hometown", "nairobi", "kenya", "state", "art", "quoted"] {
276            assert!(words.contains(word), "{word} missing from {words:?}");
277        }
278        assert!(!words.iter().any(|word| word.contains(|c: char| !c.is_alphanumeric())));
279        assert!(extract_words("Ünïcödé: café, naïve!").contains("café"));
280        assert!(extract_words("Привет, мир!").contains("мир"));
281        assert!(extract_words("!!! ... ---").is_empty());
282    }
283
284    #[test]
285    fn test_extract_words_cjk_punctuation_is_not_a_gram() {
286        let words = extract_words("你好,世界。");
287        assert!(words.contains("你好") && words.contains("世界"));
288        assert!(!words.iter().any(|word| word.contains([',', '。'])));
289    }
290
291    #[test]
292    fn test_match_score_counts_matched_query_words() {
293        let query = extract_words("rust ownership borrowing");
294        assert_eq!(match_score(&query, &extract_words("Rust ownership and borrowing.")), 1.0);
295        assert!((match_score(&query, &extract_words("Rust note.")) - 1.0 / 3.0).abs() < 1e-6);
296        assert_eq!(match_score(&query, &extract_words("unrelated")), 0.0);
297        assert_eq!(match_score(&HashSet::new(), &extract_words("rust")), 0.0);
298    }
299
300    #[test]
301    fn test_extract_words_japanese() {
302        let stored = extract_words("東京タワー");
303        let query = extract_words("東京");
304
305        let matches: HashSet<_> = stored.intersection(&query).collect();
306        assert!(!matches.is_empty(), "Japanese bigram should match");
307    }
308}