1use adk_core::Part;
9use serde::{Deserialize, Serialize};
10use std::collections::HashSet;
11
12#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
34#[serde(rename_all = "camelCase")]
35pub struct ArtifactReference {
36 pub uri: String,
38 pub mime_type: String,
40}
41
42impl ArtifactReference {
43 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 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
58pub 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
88pub 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
104fn is_cjk_char(c: char) -> bool {
106 matches!(c,
107 '\u{4e00}'..='\u{9fff}' | '\u{3400}'..='\u{4dbf}' | '\u{f900}'..='\u{faff}' | '\u{2e80}'..='\u{2eff}' | '\u{3000}'..='\u{303f}' | '\u{3040}'..='\u{309f}' | '\u{30a0}'..='\u{30ff}' | '\u{ac00}'..='\u{d7af}' )
116}
117
118pub 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 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
152pub(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
161pub(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
172pub 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 let stored = extract_words("用户喜欢用Rust编程");
240 let query = extract_words("编程");
241
242 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}