use adk_core::Part;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ArtifactReference {
pub uri: String,
pub mime_type: String,
}
impl ArtifactReference {
pub fn new(uri: impl Into<String>, mime_type: impl Into<String>) -> Self {
Self { uri: uri.into(), mime_type: mime_type.into() }
}
pub fn to_part(&self) -> Part {
Part::FileData {
mime_type: self.mime_type.clone(),
file_uri: self.uri.clone(),
annotations: None,
}
}
}
pub fn artifact_references(content: &adk_core::Content) -> Vec<ArtifactReference> {
content
.parts
.iter()
.filter_map(|part| match part {
Part::FileData { mime_type, file_uri, .. } => {
Some(ArtifactReference::new(file_uri, mime_type))
}
Part::InlineData { mime_type, uri: Some(uri), .. } => {
Some(ArtifactReference::new(uri, mime_type))
}
Part::EmbeddedResource { resource } => Some(ArtifactReference::new(
resource.uri(),
resource.mime_type().unwrap_or("application/octet-stream"),
)),
Part::InlineData { uri: None, .. }
| Part::Thinking { .. }
| Part::Text { .. }
| Part::FunctionCall { .. }
| Part::FunctionResponse { .. }
| Part::ServerToolCall { .. }
| Part::ServerToolResponse { .. } => None,
})
.collect()
}
pub fn extract_text(content: &adk_core::Content) -> String {
content
.parts
.iter()
.filter_map(|part| match part {
Part::Text { text } => Some(text.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join(" ")
}
fn is_cjk_char(c: char) -> bool {
matches!(c,
'\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}' )
}
pub fn extract_words(text: &str) -> HashSet<String> {
let mut words = HashSet::new();
let lower = text.to_lowercase();
for word in lower.split(|c: char| !c.is_alphanumeric()).filter(|word| !word.is_empty()) {
if word.chars().any(is_cjk_char) {
let chars: Vec<char> = word.chars().collect();
for c in &chars {
if is_cjk_char(*c) {
words.insert(c.to_string());
}
}
for window in chars.windows(2) {
if window.iter().any(|c| is_cjk_char(*c)) {
words.insert(window.iter().collect());
}
}
}
words.insert(word.to_string());
}
words
}
pub(crate) fn match_score(query_words: &HashSet<String>, entry_words: &HashSet<String>) -> f32 {
if query_words.is_empty() {
return 0.0;
}
let matched = query_words.iter().filter(|word| entry_words.contains(*word)).count();
matched as f32 / query_words.len() as f32
}
pub(crate) fn rank_matches(
mut matches: Vec<(f32, crate::service::MemoryEntry)>,
limit: usize,
) -> Vec<crate::service::MemoryEntry> {
matches.sort_by(|(left_score, left), (right_score, right)| {
right_score.total_cmp(left_score).then_with(|| right.timestamp.cmp(&left.timestamp))
});
matches.into_iter().take(limit).map(|(_, entry)| entry).collect()
}
pub fn extract_words_from_content(content: &adk_core::Content) -> HashSet<String> {
let mut words = HashSet::new();
for part in &content.parts {
if let Part::Text { text } = part {
words.extend(extract_words(text));
}
}
words
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn artifact_references_keep_uris_and_never_bytes() {
let content = adk_core::Content {
role: "model".into(),
parts: vec![
Part::Text { text: "torn seal".into() },
Part::FileData {
mime_type: "image/png".into(),
file_uri: "artifact://a/u/s/f.png#0".into(),
annotations: None,
},
Part::InlineData {
mime_type: "image/jpeg".into(),
data: vec![0xff, 0xd8],
uri: Some("artifact://a/u/s/g.jpg#1".into()),
annotations: None,
},
Part::InlineData {
mime_type: "image/jpeg".into(),
data: vec![0xff, 0xd8],
uri: None,
annotations: None,
},
],
};
assert_eq!(extract_text(&content), "torn seal");
assert_eq!(
artifact_references(&content),
vec![
ArtifactReference::new("artifact://a/u/s/f.png#0", "image/png"),
ArtifactReference::new("artifact://a/u/s/g.jpg#1", "image/jpeg"),
]
);
let reference = ArtifactReference::new("artifact://a/u/s/f.png#0", "image/png");
assert_eq!(
serde_json::to_value(&reference).unwrap(),
serde_json::json!({ "uri": "artifact://a/u/s/f.png#0", "mimeType": "image/png" })
);
}
#[test]
fn test_extract_words_english() {
let words = extract_words("Hello World foo bar");
assert!(words.contains("hello"));
assert!(words.contains("world"));
assert!(words.contains("foo"));
assert!(words.contains("bar"));
}
#[test]
fn test_extract_words_cjk_bigram_matching() {
let stored = extract_words("用户喜欢用Rust编程");
let query = extract_words("编程");
let matches: HashSet<_> = stored.intersection(&query).collect();
assert!(
!matches.is_empty(),
"CJK search should find matches. Stored: {stored:?}, Query: {query:?}"
);
}
#[test]
fn test_extract_words_cjk_single_char() {
let stored = extract_words("今天天气很好");
let query = extract_words("天气");
let matches: HashSet<_> = stored.intersection(&query).collect();
assert!(
!matches.is_empty(),
"CJK bigram '天气' should match. Stored: {stored:?}, Query: {query:?}"
);
}
#[test]
fn test_extract_words_mixed_cjk_english() {
let words = extract_words("Hello 你好 World");
assert!(words.contains("hello"));
assert!(words.contains("world"));
assert!(words.contains("你"));
assert!(words.contains("好"));
assert!(words.contains("你好"));
}
#[test]
fn test_extract_words_ignore_punctuation() {
let words = extract_words("Hometown: Nairobi. (Kenya!) state-of-the-art, \"quoted\"");
for word in ["hometown", "nairobi", "kenya", "state", "art", "quoted"] {
assert!(words.contains(word), "{word} missing from {words:?}");
}
assert!(!words.iter().any(|word| word.contains(|c: char| !c.is_alphanumeric())));
assert!(extract_words("Ünïcödé: café, naïve!").contains("café"));
assert!(extract_words("Привет, мир!").contains("мир"));
assert!(extract_words("!!! ... ---").is_empty());
}
#[test]
fn test_extract_words_cjk_punctuation_is_not_a_gram() {
let words = extract_words("你好,世界。");
assert!(words.contains("你好") && words.contains("世界"));
assert!(!words.iter().any(|word| word.contains([',', '。'])));
}
#[test]
fn test_match_score_counts_matched_query_words() {
let query = extract_words("rust ownership borrowing");
assert_eq!(match_score(&query, &extract_words("Rust ownership and borrowing.")), 1.0);
assert!((match_score(&query, &extract_words("Rust note.")) - 1.0 / 3.0).abs() < 1e-6);
assert_eq!(match_score(&query, &extract_words("unrelated")), 0.0);
assert_eq!(match_score(&HashSet::new(), &extract_words("rust")), 0.0);
}
#[test]
fn test_extract_words_japanese() {
let stored = extract_words("東京タワー");
let query = extract_words("東京");
let matches: HashSet<_> = stored.intersection(&query).collect();
assert!(!matches.is_empty(), "Japanese bigram should match");
}
}