aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,243 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::CheapSkillSelection;
|
||||
use super::CheapSkillSelector;
|
||||
use super::SkillSelectionDocument;
|
||||
|
||||
const MAX_QUERY_BYTES: usize = 4 * 1024;
|
||||
const MAX_QUERY_TERMS: usize = 64;
|
||||
const MAX_QUERY_GRAMS: usize = 512;
|
||||
const MAX_DOCUMENT_BYTES: usize = 4 * 1024;
|
||||
const MAX_DOCUMENT_TERMS: usize = 256;
|
||||
const MAX_DOCUMENT_GRAMS: usize = 512;
|
||||
const MAX_CANDIDATES: usize = 1_000;
|
||||
const MAX_RESULTS: usize = 50;
|
||||
const MIN_GRAM_CHARS: usize = 2;
|
||||
const MAX_GRAM_CHARS: usize = 5;
|
||||
const FIELD_WEIGHTS: [f64; 3] = [8.0, 4.0, 1.0];
|
||||
|
||||
const STOP_WORDS: &[&str] = &[
|
||||
"a", "an", "and", "are", "as", "at", "be", "by", "do", "for", "from", "how", "i", "in", "is",
|
||||
"it", "me", "my", "of", "on", "or", "please", "that", "the", "this", "to", "use", "we", "what",
|
||||
"when", "where", "which", "with", "you", "your",
|
||||
];
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(crate) struct CharacterNgramSkillSelector;
|
||||
|
||||
impl CheapSkillSelector for CharacterNgramSkillSelector {
|
||||
fn method(&self) -> &'static str {
|
||||
"character_ngram_v1"
|
||||
}
|
||||
|
||||
fn select(
|
||||
&self,
|
||||
query: &str,
|
||||
documents: &[SkillSelectionDocument<'_>],
|
||||
limit: usize,
|
||||
) -> CheapSkillSelection {
|
||||
let (query, query_bytes_truncated) = bounded(query, MAX_QUERY_BYTES);
|
||||
let (query_terms, query_terms_truncated) = query_terms(query);
|
||||
let (query_grams, query_grams_truncated) = grams(&query_terms, MAX_QUERY_GRAMS);
|
||||
let query_truncated =
|
||||
query_bytes_truncated || query_terms_truncated || query_grams_truncated;
|
||||
let candidate_set_truncated = documents.len() > MAX_CANDIDATES;
|
||||
if query_grams.is_empty() || limit == 0 {
|
||||
return CheapSkillSelection {
|
||||
query_term_count: query_terms.len(),
|
||||
query_truncated,
|
||||
candidate_set_truncated,
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
|
||||
let prepared = documents
|
||||
.iter()
|
||||
.take(MAX_CANDIDATES)
|
||||
.map(PreparedDocument::new)
|
||||
.collect::<Vec<_>>();
|
||||
let document_frequencies = document_frequencies(&prepared);
|
||||
let document_count = prepared.len() as f64;
|
||||
let minimum_matches = query_grams.len().min(3);
|
||||
let mut scored = prepared
|
||||
.iter()
|
||||
.filter_map(|document| {
|
||||
let (score, matched_grams) = score_document(
|
||||
document,
|
||||
&query_grams,
|
||||
&document_frequencies,
|
||||
document_count,
|
||||
);
|
||||
(matched_grams >= minimum_matches).then_some((score, document.id, document.name))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
scored.sort_by(|left, right| {
|
||||
right
|
||||
.0
|
||||
.total_cmp(&left.0)
|
||||
.then_with(|| left.2.cmp(right.2))
|
||||
.then_with(|| left.1.cmp(&right.1))
|
||||
});
|
||||
|
||||
CheapSkillSelection {
|
||||
candidate_ids: scored
|
||||
.into_iter()
|
||||
.take(limit.min(MAX_RESULTS))
|
||||
.map(|(_, id, _)| id)
|
||||
.collect(),
|
||||
query_term_count: query_terms.len(),
|
||||
query_truncated,
|
||||
candidate_set_truncated,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PreparedDocument<'a> {
|
||||
id: usize,
|
||||
name: &'a str,
|
||||
fields: [HashSet<String>; 3],
|
||||
}
|
||||
|
||||
impl<'a> PreparedDocument<'a> {
|
||||
fn new(document: &'a SkillSelectionDocument<'a>) -> Self {
|
||||
Self {
|
||||
id: document.id,
|
||||
name: document.name,
|
||||
fields: [
|
||||
document_grams(document.name),
|
||||
document_grams(document.short_description.unwrap_or_default()),
|
||||
document_grams(document.description),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn score_document(
|
||||
document: &PreparedDocument<'_>,
|
||||
query_grams: &[String],
|
||||
document_frequencies: &HashMap<String, usize>,
|
||||
document_count: f64,
|
||||
) -> (f64, usize) {
|
||||
query_grams.iter().fold((0.0, 0), |(score, matched), gram| {
|
||||
let frequency = document_frequencies.get(gram).copied().unwrap_or_default() as f64;
|
||||
if frequency == 0.0 {
|
||||
return (score, matched);
|
||||
}
|
||||
let inverse_document_frequency =
|
||||
(1.0 + (document_count - frequency + 0.5) / (frequency + 0.5)).ln();
|
||||
let field_weight = document
|
||||
.fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, field)| field.contains(gram))
|
||||
.map(|(index, _)| FIELD_WEIGHTS[index])
|
||||
.sum::<f64>();
|
||||
if field_weight == 0.0 {
|
||||
(score, matched)
|
||||
} else {
|
||||
(
|
||||
score + inverse_document_frequency * field_weight,
|
||||
matched + 1,
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn document_frequencies(documents: &[PreparedDocument<'_>]) -> HashMap<String, usize> {
|
||||
let mut frequencies = HashMap::new();
|
||||
for document in documents {
|
||||
let grams = document
|
||||
.fields
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(String::as_str)
|
||||
.collect::<HashSet<_>>();
|
||||
for gram in grams {
|
||||
*frequencies.entry(gram.to_string()).or_default() += 1;
|
||||
}
|
||||
}
|
||||
frequencies
|
||||
}
|
||||
|
||||
fn query_terms(query: &str) -> (Vec<String>, bool) {
|
||||
let mut seen = HashSet::new();
|
||||
let mut terms = Vec::new();
|
||||
for term in normalized_terms(query)
|
||||
.into_iter()
|
||||
.filter(|term| term.chars().count() >= 2 && !STOP_WORDS.contains(&term.as_str()))
|
||||
{
|
||||
if !seen.insert(term.clone()) {
|
||||
continue;
|
||||
}
|
||||
if terms.len() == MAX_QUERY_TERMS {
|
||||
return (terms, true);
|
||||
}
|
||||
terms.push(term);
|
||||
}
|
||||
(terms, false)
|
||||
}
|
||||
|
||||
fn document_grams(value: &str) -> HashSet<String> {
|
||||
let (value, _) = bounded(value, MAX_DOCUMENT_BYTES);
|
||||
let terms = normalized_terms(value)
|
||||
.into_iter()
|
||||
.take(MAX_DOCUMENT_TERMS)
|
||||
.collect::<Vec<_>>();
|
||||
grams(&terms, MAX_DOCUMENT_GRAMS).0.into_iter().collect()
|
||||
}
|
||||
|
||||
fn grams(terms: &[String], limit: usize) -> (Vec<String>, bool) {
|
||||
let mut seen = HashSet::new();
|
||||
let mut grams = Vec::new();
|
||||
for term in terms {
|
||||
let characters = term.chars().collect::<Vec<_>>();
|
||||
let minimum_gram_chars = if term.is_ascii() && characters.len() > MIN_GRAM_CHARS {
|
||||
MIN_GRAM_CHARS + 1
|
||||
} else {
|
||||
MIN_GRAM_CHARS
|
||||
};
|
||||
for gram_size in minimum_gram_chars..=MAX_GRAM_CHARS.min(characters.len()) {
|
||||
for start in 0..=characters.len() - gram_size {
|
||||
let gram = characters[start..start + gram_size]
|
||||
.iter()
|
||||
.collect::<String>();
|
||||
if !seen.insert(gram.clone()) {
|
||||
continue;
|
||||
}
|
||||
if grams.len() == limit {
|
||||
return (grams, true);
|
||||
}
|
||||
grams.push(gram);
|
||||
}
|
||||
}
|
||||
}
|
||||
(grams, false)
|
||||
}
|
||||
|
||||
fn normalized_terms(value: &str) -> Vec<String> {
|
||||
let mut normalized = String::with_capacity(value.len());
|
||||
for character in value.chars() {
|
||||
if character.is_alphanumeric() {
|
||||
normalized.extend(character.to_lowercase());
|
||||
} else {
|
||||
normalized.push(' ');
|
||||
}
|
||||
}
|
||||
normalized.split_whitespace().map(str::to_string).collect()
|
||||
}
|
||||
|
||||
fn bounded(value: &str, max_bytes: usize) -> (&str, bool) {
|
||||
if value.len() <= max_bytes {
|
||||
return (value, false);
|
||||
}
|
||||
let mut end = max_bytes;
|
||||
while !value.is_char_boundary(end) {
|
||||
end = end.saturating_sub(1);
|
||||
}
|
||||
(&value[..end], true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "character_ngram_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,79 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn ngrams_match_related_word_forms() {
|
||||
let documents = [
|
||||
document(/*id*/ 1, "presentations", "Create visual decks."),
|
||||
document(/*id*/ 2, "spreadsheets", "Analyze tabular data."),
|
||||
];
|
||||
|
||||
let selection =
|
||||
CharacterNgramSkillSelector.select("create a presentation", &documents, /*limit*/ 20);
|
||||
|
||||
assert_eq!(vec![1], selection.candidate_ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ngrams_tolerate_a_typo() {
|
||||
let documents = [
|
||||
document(/*id*/ 1, "postgresql", "Manage a relational database."),
|
||||
document(/*id*/ 2, "postscript", "Render printable documents."),
|
||||
];
|
||||
|
||||
let selection = CharacterNgramSkillSelector.select(
|
||||
"repair my postgrez database",
|
||||
&documents,
|
||||
/*limit*/ 20,
|
||||
);
|
||||
|
||||
assert_eq!(vec![1, 2], selection.candidate_ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ngrams_match_cjk_without_word_boundaries() {
|
||||
let documents = [
|
||||
document(/*id*/ 1, "演示文稿", "创建幻灯片。"),
|
||||
document(/*id*/ 2, "电子表格", "分析表格数据。"),
|
||||
];
|
||||
|
||||
let selection =
|
||||
CharacterNgramSkillSelector.select("帮我制作演示文稿", &documents, /*limit*/ 20);
|
||||
|
||||
assert_eq!(vec![1], selection.candidate_ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ngrams_report_bounded_inputs() {
|
||||
let long_query = "match ".repeat(MAX_QUERY_BYTES);
|
||||
let names = (0..=MAX_CANDIDATES)
|
||||
.map(|index| format!("candidate-{index}"))
|
||||
.collect::<Vec<_>>();
|
||||
let documents = names
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(id, name)| SkillSelectionDocument {
|
||||
id,
|
||||
name,
|
||||
short_description: None,
|
||||
description: "match",
|
||||
dependencies: None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let selection = CharacterNgramSkillSelector.select(&long_query, &documents, /*limit*/ 20);
|
||||
|
||||
assert!(selection.query_truncated);
|
||||
assert!(selection.candidate_set_truncated);
|
||||
assert_eq!(20, selection.candidate_ids.len());
|
||||
}
|
||||
|
||||
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
|
||||
SkillSelectionDocument {
|
||||
id,
|
||||
name,
|
||||
short_description: None,
|
||||
description,
|
||||
dependencies: None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use akode_utils_path_uri::LegacyAppPathString;
|
||||
|
||||
use crate::HostSkillsSnapshot;
|
||||
|
||||
use crate::catalog::SkillCatalog;
|
||||
use crate::catalog::SkillSourceKind;
|
||||
|
||||
use super::CharacterNgramSkillSelector;
|
||||
use super::CheapSkillSelection;
|
||||
use super::CheapSkillSelector;
|
||||
use super::SkillSelectionDocument;
|
||||
|
||||
const MAX_ROUTING_FIELD_BYTES: usize = 4 * 1024;
|
||||
const MAX_DEPENDENCY_RECORDS: usize = 32;
|
||||
const MAX_CANDIDATES: usize = 1_000;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct CharacterRoutingCardSkillSelector {
|
||||
routing_fields: HashMap<usize, String>,
|
||||
}
|
||||
|
||||
impl CharacterRoutingCardSkillSelector {
|
||||
pub(crate) fn new(catalog: &SkillCatalog, host_snapshot: Option<&HostSkillsSnapshot>) -> Self {
|
||||
let host_skill_ids = catalog
|
||||
.entries
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, entry)| {
|
||||
entry.authority.kind == SkillSourceKind::Host && entry.is_model_visible()
|
||||
})
|
||||
.take(MAX_CANDIDATES)
|
||||
.filter_map(|(id, entry)| {
|
||||
let path = LegacyAppPathString::from_string(entry.main_prompt.as_str())
|
||||
.to_inferred_path_uri()?;
|
||||
Some((path, id))
|
||||
})
|
||||
.collect::<HashMap<_, _>>();
|
||||
let routing_fields = host_snapshot
|
||||
.into_iter()
|
||||
.flat_map(|snapshot| snapshot.outcome().skills.iter())
|
||||
.filter_map(|skill| {
|
||||
let id = host_skill_ids.get(&skill.path_to_skills_md)?;
|
||||
let interface = skill.interface.as_ref()?;
|
||||
let mut field = String::new();
|
||||
for value in [
|
||||
interface.display_name.as_deref(),
|
||||
interface.short_description.as_deref(),
|
||||
interface.default_prompt.as_deref(),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
push_bounded(&mut field, value);
|
||||
}
|
||||
(!field.is_empty()).then_some((*id, field))
|
||||
})
|
||||
.take(MAX_CANDIDATES)
|
||||
.collect();
|
||||
Self { routing_fields }
|
||||
}
|
||||
}
|
||||
|
||||
impl CheapSkillSelector for CharacterRoutingCardSkillSelector {
|
||||
fn method(&self) -> &'static str {
|
||||
"character_routing_card_v1"
|
||||
}
|
||||
|
||||
fn select(
|
||||
&self,
|
||||
query: &str,
|
||||
documents: &[SkillSelectionDocument<'_>],
|
||||
limit: usize,
|
||||
) -> CheapSkillSelection {
|
||||
if limit == 0 {
|
||||
return CharacterNgramSkillSelector.select(query, documents, /*limit*/ 0);
|
||||
}
|
||||
|
||||
let routing_fields = documents
|
||||
.iter()
|
||||
.take(MAX_CANDIDATES)
|
||||
.map(|document| {
|
||||
let mut field = String::new();
|
||||
if let Some(description) = document.short_description {
|
||||
push_bounded(&mut field, description);
|
||||
}
|
||||
if let Some(routing_field) = self.routing_fields.get(&document.id) {
|
||||
push_bounded(&mut field, routing_field);
|
||||
}
|
||||
if let Some(dependencies) = document.dependencies {
|
||||
for dependency in dependencies.tools.iter().take(MAX_DEPENDENCY_RECORDS) {
|
||||
push_bounded(&mut field, dependency.value.as_str());
|
||||
if let Some(description) = dependency.description.as_deref() {
|
||||
push_bounded(&mut field, description);
|
||||
}
|
||||
}
|
||||
}
|
||||
field
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let routing_documents = documents
|
||||
.iter()
|
||||
.zip(&routing_fields)
|
||||
.map(|(document, field)| SkillSelectionDocument {
|
||||
short_description: (!field.is_empty()).then_some(field.as_str()),
|
||||
..*document
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let selection = CharacterNgramSkillSelector.select(query, &routing_documents, limit);
|
||||
CheapSkillSelection {
|
||||
candidate_set_truncated: documents.len() > MAX_CANDIDATES
|
||||
|| selection.candidate_set_truncated,
|
||||
..selection
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn push_bounded(destination: &mut String, value: &str) {
|
||||
if value.is_empty() || destination.len() == MAX_ROUTING_FIELD_BYTES {
|
||||
return;
|
||||
}
|
||||
if !destination.is_empty() {
|
||||
destination.push(' ');
|
||||
}
|
||||
let remaining = MAX_ROUTING_FIELD_BYTES.saturating_sub(destination.len());
|
||||
let mut end = value.len().min(remaining);
|
||||
while !value.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
destination.push_str(&value[..end]);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "character_routing_card_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,154 @@
|
||||
use crate::SkillLoadOutcome;
|
||||
use akode_protocol::protocol::SkillScope;
|
||||
use akode_skills::SkillDependencies;
|
||||
use akode_skills::SkillInterface;
|
||||
use akode_skills::SkillMetadata;
|
||||
use akode_skills::SkillToolDependency;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use crate::catalog::SkillAuthority;
|
||||
use crate::catalog::SkillCatalogEntry;
|
||||
use crate::catalog::SkillPackageId;
|
||||
use crate::catalog::SkillResourceId;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn host_interface_metadata_makes_unlisted_workflow_discoverable() {
|
||||
let path = AbsolutePathBuf::try_from(std::env::temp_dir().join("routing-card/SKILL.md"))
|
||||
.expect("temporary directory should be absolute");
|
||||
let resource = path.to_string_lossy().to_string();
|
||||
let mut outcome = SkillLoadOutcome::default();
|
||||
outcome.skills.push(SkillMetadata {
|
||||
name: "content-tools".to_string(),
|
||||
description: "Prepare visual content.".to_string(),
|
||||
short_description: None,
|
||||
interface: Some(SkillInterface {
|
||||
display_name: Some("Visual Assets".to_string()),
|
||||
short_description: Some("Create illustrated assets.".to_string()),
|
||||
icon_small: None,
|
||||
icon_large: None,
|
||||
brand_color: None,
|
||||
default_prompt: Some("Create an animated pet spritesheet.".to_string()),
|
||||
}),
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
path_to_skills_md: PathUri::from_abs_path(&path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: None,
|
||||
});
|
||||
let snapshot = HostSkillsSnapshot::new(std::sync::Arc::new(outcome));
|
||||
let catalog = SkillCatalog {
|
||||
is_partial: false,
|
||||
entries: vec![SkillCatalogEntry::new(
|
||||
SkillPackageId(resource.clone()),
|
||||
SkillAuthority::new(SkillSourceKind::Host, "host"),
|
||||
"content-tools",
|
||||
"Prepare visual content.",
|
||||
SkillResourceId::new(resource),
|
||||
)],
|
||||
..Default::default()
|
||||
};
|
||||
let selector = CharacterRoutingCardSkillSelector::new(&catalog, Some(&snapshot));
|
||||
let documents = [document(
|
||||
/*id*/ 0,
|
||||
"content-tools",
|
||||
"Prepare visual content.",
|
||||
)];
|
||||
|
||||
let selection = selector.select(
|
||||
"make an animated pet spritesheet",
|
||||
&documents,
|
||||
/*limit*/ 20,
|
||||
);
|
||||
|
||||
assert_eq!(vec![0], selection.candidate_ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connector_dependencies_make_generic_skills_discoverable() {
|
||||
let dependencies = SkillDependencies {
|
||||
tools: vec![SkillToolDependency {
|
||||
r#type: "app".to_string(),
|
||||
value: "slack".to_string(),
|
||||
description: Some("Post messages to team channels.".to_string()),
|
||||
transport: None,
|
||||
command: None,
|
||||
url: None,
|
||||
oauth_callback_port: None,
|
||||
}],
|
||||
};
|
||||
let documents = [
|
||||
SkillSelectionDocument {
|
||||
dependencies: Some(&dependencies),
|
||||
..document(
|
||||
/*id*/ 3,
|
||||
"team-communication",
|
||||
"Share updates with the team.",
|
||||
)
|
||||
},
|
||||
document(/*id*/ 4, "documents", "Write project updates."),
|
||||
];
|
||||
let selector = CharacterRoutingCardSkillSelector::new(
|
||||
&SkillCatalog::default(),
|
||||
/*host_snapshot*/ None,
|
||||
);
|
||||
|
||||
let selection = selector.select("post this update in Slack", &documents, /*limit*/ 20);
|
||||
|
||||
assert_eq!(Some(3), selection.candidate_ids.first().copied());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strong_baseline_match_is_preserved_alongside_routing_match() {
|
||||
let documents = [
|
||||
document(/*id*/ 1, "presentation-tools", "Build meeting decks."),
|
||||
document(/*id*/ 2, "content-tools", "Prepare visual content."),
|
||||
];
|
||||
let selector = CharacterRoutingCardSkillSelector {
|
||||
routing_fields: HashMap::from([(
|
||||
2,
|
||||
"Create a presentation with PowerPoint slides".to_string(),
|
||||
)]),
|
||||
};
|
||||
|
||||
let selection = selector.select(
|
||||
"create a PowerPoint presentation",
|
||||
&documents,
|
||||
/*limit*/ 2,
|
||||
);
|
||||
|
||||
assert_eq!(vec![2, 1], selection.candidate_ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_routing_metadata_preserves_original_short_description_matches() {
|
||||
let metadata = (0_u64..60)
|
||||
.map(|index| format!("{:016x}", index.wrapping_mul(/*rhs*/ 0x9e37_79b9_7f4a_7c15)))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let short_description = "zebra xylophone quasar";
|
||||
let documents = [SkillSelectionDocument {
|
||||
short_description: Some(short_description),
|
||||
..document(/*id*/ 0, "content-tools", "Prepare visual content.")
|
||||
}];
|
||||
let selector = CharacterRoutingCardSkillSelector {
|
||||
routing_fields: HashMap::from([(/*id*/ 0, metadata)]),
|
||||
};
|
||||
|
||||
let selection = selector.select(short_description, &documents, /*limit*/ 20);
|
||||
|
||||
assert_eq!(vec![0], selection.candidate_ids);
|
||||
}
|
||||
|
||||
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
|
||||
SkillSelectionDocument {
|
||||
id,
|
||||
name,
|
||||
short_description: None,
|
||||
description,
|
||||
dependencies: None,
|
||||
}
|
||||
}
|
||||
239
akode-rs/ext/skills/src/dynamic_skill_selector/fielded_bm25.rs
Normal file
239
akode-rs/ext/skills/src/dynamic_skill_selector/fielded_bm25.rs
Normal file
@@ -0,0 +1,239 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::CheapSkillSelection;
|
||||
use super::CheapSkillSelector;
|
||||
use super::SkillSelectionDocument;
|
||||
|
||||
const MAX_QUERY_BYTES: usize = 4 * 1024;
|
||||
const MAX_QUERY_TERMS: usize = 64;
|
||||
const MAX_DOCUMENT_BYTES: usize = 4 * 1024;
|
||||
const MAX_DOCUMENT_TERMS: usize = 256;
|
||||
const MAX_CANDIDATES: usize = 1_000;
|
||||
const MAX_RESULTS: usize = 50;
|
||||
const FIELD_WEIGHTS: [f64; 3] = [8.0, 4.0, 1.0];
|
||||
const K1: f64 = 1.2;
|
||||
const B: f64 = 0.75;
|
||||
|
||||
const STOP_WORDS: &[&str] = &[
|
||||
"a", "an", "and", "are", "as", "at", "be", "by", "do", "for", "from", "how", "i", "in", "is",
|
||||
"it", "me", "my", "of", "on", "or", "please", "that", "the", "this", "to", "use", "we", "what",
|
||||
"when", "where", "which", "with", "you", "your",
|
||||
];
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(crate) struct FieldedBm25SkillSelector;
|
||||
|
||||
impl CheapSkillSelector for FieldedBm25SkillSelector {
|
||||
fn method(&self) -> &'static str {
|
||||
"fielded_bm25_v1"
|
||||
}
|
||||
|
||||
fn select(
|
||||
&self,
|
||||
query: &str,
|
||||
documents: &[SkillSelectionDocument<'_>],
|
||||
limit: usize,
|
||||
) -> CheapSkillSelection {
|
||||
let (query, query_bytes_truncated) = bounded(query, MAX_QUERY_BYTES);
|
||||
let (query_terms, query_terms_truncated) = query_terms(query);
|
||||
let query_truncated = query_bytes_truncated || query_terms_truncated;
|
||||
let candidate_set_truncated = documents.len() > MAX_CANDIDATES;
|
||||
if query_terms.is_empty() || limit == 0 {
|
||||
return CheapSkillSelection {
|
||||
query_term_count: query_terms.len(),
|
||||
query_truncated,
|
||||
candidate_set_truncated,
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
|
||||
let prepared = documents
|
||||
.iter()
|
||||
.take(MAX_CANDIDATES)
|
||||
.map(PreparedDocument::new)
|
||||
.collect::<Vec<_>>();
|
||||
let averages = average_field_lengths(&prepared);
|
||||
let document_frequencies = document_frequencies(&prepared);
|
||||
let document_count = prepared.len() as f64;
|
||||
let mut scored = prepared
|
||||
.iter()
|
||||
.filter_map(|document| {
|
||||
let score = score_document(
|
||||
document,
|
||||
&query_terms,
|
||||
&document_frequencies,
|
||||
document_count,
|
||||
averages,
|
||||
);
|
||||
(score > 0.0).then_some((score, document.id, document.name))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
scored.sort_by(|left, right| {
|
||||
right
|
||||
.0
|
||||
.total_cmp(&left.0)
|
||||
.then_with(|| left.2.cmp(right.2))
|
||||
.then_with(|| left.1.cmp(&right.1))
|
||||
});
|
||||
|
||||
CheapSkillSelection {
|
||||
candidate_ids: scored
|
||||
.into_iter()
|
||||
.take(limit.min(MAX_RESULTS))
|
||||
.map(|(_, id, _)| id)
|
||||
.collect(),
|
||||
query_term_count: query_terms.len(),
|
||||
query_truncated,
|
||||
candidate_set_truncated,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PreparedDocument<'a> {
|
||||
id: usize,
|
||||
name: &'a str,
|
||||
fields: [Vec<String>; 3],
|
||||
}
|
||||
|
||||
impl<'a> PreparedDocument<'a> {
|
||||
fn new(document: &'a SkillSelectionDocument<'a>) -> Self {
|
||||
Self {
|
||||
id: document.id,
|
||||
name: document.name,
|
||||
fields: [
|
||||
document_terms(document.name),
|
||||
document_terms(document.short_description.unwrap_or_default()),
|
||||
document_terms(document.description),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn score_document(
|
||||
document: &PreparedDocument<'_>,
|
||||
query_terms: &[String],
|
||||
document_frequencies: &HashMap<String, usize>,
|
||||
document_count: f64,
|
||||
average_field_lengths: [f64; 3],
|
||||
) -> f64 {
|
||||
query_terms.iter().fold(0.0, |score, query_term| {
|
||||
let frequency = document_frequencies
|
||||
.get(query_term)
|
||||
.copied()
|
||||
.unwrap_or_default() as f64;
|
||||
if frequency == 0.0 {
|
||||
return score;
|
||||
}
|
||||
let weighted_term_frequency =
|
||||
document
|
||||
.fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.fold(0.0, |weighted, (field_index, terms)| {
|
||||
let term_frequency =
|
||||
terms.iter().filter(|term| *term == query_term).count() as f64;
|
||||
if term_frequency == 0.0 {
|
||||
return weighted;
|
||||
}
|
||||
let average_length = average_field_lengths[field_index];
|
||||
let length_ratio = if average_length == 0.0 {
|
||||
1.0
|
||||
} else {
|
||||
terms.len() as f64 / average_length
|
||||
};
|
||||
weighted
|
||||
+ FIELD_WEIGHTS[field_index] * term_frequency / (1.0 - B + B * length_ratio)
|
||||
});
|
||||
if weighted_term_frequency == 0.0 {
|
||||
return score;
|
||||
}
|
||||
let inverse_document_frequency =
|
||||
(1.0 + (document_count - frequency + 0.5) / (frequency + 0.5)).ln();
|
||||
score
|
||||
+ inverse_document_frequency * weighted_term_frequency * (K1 + 1.0)
|
||||
/ (weighted_term_frequency + K1)
|
||||
})
|
||||
}
|
||||
|
||||
fn average_field_lengths(documents: &[PreparedDocument<'_>]) -> [f64; 3] {
|
||||
if documents.is_empty() {
|
||||
return [0.0; 3];
|
||||
}
|
||||
let totals = documents.iter().fold([0usize; 3], |mut totals, document| {
|
||||
for (index, field) in document.fields.iter().enumerate() {
|
||||
totals[index] = totals[index].saturating_add(field.len());
|
||||
}
|
||||
totals
|
||||
});
|
||||
totals.map(|total| total as f64 / documents.len() as f64)
|
||||
}
|
||||
|
||||
fn document_frequencies(documents: &[PreparedDocument<'_>]) -> HashMap<String, usize> {
|
||||
let mut frequencies = HashMap::new();
|
||||
for document in documents {
|
||||
let terms = document
|
||||
.fields
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(String::as_str)
|
||||
.collect::<HashSet<_>>();
|
||||
for term in terms {
|
||||
*frequencies.entry(term.to_string()).or_default() += 1;
|
||||
}
|
||||
}
|
||||
frequencies
|
||||
}
|
||||
|
||||
fn query_terms(query: &str) -> (Vec<String>, bool) {
|
||||
let mut seen = HashSet::new();
|
||||
let mut terms = Vec::new();
|
||||
for term in normalized_terms(query)
|
||||
.into_iter()
|
||||
.filter(|term| term.chars().count() >= 2 && !STOP_WORDS.contains(&term.as_str()))
|
||||
{
|
||||
if !seen.insert(term.clone()) {
|
||||
continue;
|
||||
}
|
||||
if terms.len() == MAX_QUERY_TERMS {
|
||||
return (terms, true);
|
||||
}
|
||||
terms.push(term);
|
||||
}
|
||||
(terms, false)
|
||||
}
|
||||
|
||||
fn document_terms(value: &str) -> Vec<String> {
|
||||
let (value, _) = bounded(value, MAX_DOCUMENT_BYTES);
|
||||
normalized_terms(value)
|
||||
.into_iter()
|
||||
.take(MAX_DOCUMENT_TERMS)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn normalized_terms(value: &str) -> Vec<String> {
|
||||
let mut normalized = String::with_capacity(value.len());
|
||||
for character in value.chars() {
|
||||
if character.is_alphanumeric() {
|
||||
normalized.extend(character.to_lowercase());
|
||||
} else {
|
||||
normalized.push(' ');
|
||||
}
|
||||
}
|
||||
normalized.split_whitespace().map(str::to_string).collect()
|
||||
}
|
||||
|
||||
fn bounded(value: &str, max_bytes: usize) -> (&str, bool) {
|
||||
if value.len() <= max_bytes {
|
||||
return (value, false);
|
||||
}
|
||||
let mut end = max_bytes;
|
||||
while !value.is_char_boundary(end) {
|
||||
end = end.saturating_sub(1);
|
||||
}
|
||||
(&value[..end], true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "fielded_bm25_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,81 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn bm25_prioritizes_rare_terms() {
|
||||
let documents = [
|
||||
document(/*id*/ 1, "review-helper", "Review code and prose."),
|
||||
document(
|
||||
/*id*/ 2,
|
||||
"terraform-review",
|
||||
"Review Terraform infrastructure.",
|
||||
),
|
||||
document(/*id*/ 3, "document-review", "Review Word documents."),
|
||||
];
|
||||
|
||||
let selection =
|
||||
FieldedBm25SkillSelector.select("review terraform", &documents, /*limit*/ 20);
|
||||
|
||||
assert_eq!(vec![2, 3, 1], selection.candidate_ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bm25_weights_names_above_descriptions() {
|
||||
let documents = [
|
||||
document(/*id*/ 1, "slides", "Create presentations."),
|
||||
document(/*id*/ 2, "presentations", "Create and edit slides."),
|
||||
];
|
||||
|
||||
let selection = FieldedBm25SkillSelector.select("slides", &documents, /*limit*/ 20);
|
||||
|
||||
assert_eq!(vec![1, 2], selection.candidate_ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bm25_drops_candidates_without_matching_terms() {
|
||||
let documents = [document(
|
||||
/*id*/ 1,
|
||||
"spreadsheets",
|
||||
"Analyze tabular data.",
|
||||
)];
|
||||
|
||||
let selection =
|
||||
FieldedBm25SkillSelector.select("render a video", &documents, /*limit*/ 20);
|
||||
|
||||
assert!(selection.candidate_ids.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bm25_reports_bounded_inputs() {
|
||||
let long_query = "match ".repeat(MAX_QUERY_BYTES);
|
||||
let names = (0..=MAX_CANDIDATES)
|
||||
.map(|index| format!("candidate-{index}"))
|
||||
.collect::<Vec<_>>();
|
||||
let documents = names
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(id, name)| SkillSelectionDocument {
|
||||
id,
|
||||
name,
|
||||
short_description: None,
|
||||
description: "match",
|
||||
dependencies: None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let selection = FieldedBm25SkillSelector.select(&long_query, &documents, /*limit*/ 20);
|
||||
|
||||
assert!(selection.query_truncated);
|
||||
assert!(selection.candidate_set_truncated);
|
||||
assert_eq!(20, selection.candidate_ids.len());
|
||||
}
|
||||
|
||||
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
|
||||
SkillSelectionDocument {
|
||||
id,
|
||||
name,
|
||||
short_description: None,
|
||||
description,
|
||||
dependencies: None,
|
||||
}
|
||||
}
|
||||
61
akode-rs/ext/skills/src/dynamic_skill_selector/lru.rs
Normal file
61
akode-rs/ext/skills/src/dynamic_skill_selector/lru.rs
Normal file
@@ -0,0 +1,61 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::CheapSkillSelection;
|
||||
use super::CheapSkillSelector;
|
||||
use super::SkillSelectionDocument;
|
||||
|
||||
const MAX_CANDIDATES: usize = 1_000;
|
||||
const MAX_QUERY_TERMS: usize = 64;
|
||||
const MAX_RESULTS: usize = 50;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct LruSkillSelector {
|
||||
recent_skill_ids: Vec<usize>,
|
||||
}
|
||||
|
||||
impl LruSkillSelector {
|
||||
pub(crate) fn new(recent_skill_ids: Vec<usize>) -> Self {
|
||||
Self { recent_skill_ids }
|
||||
}
|
||||
}
|
||||
|
||||
impl CheapSkillSelector for LruSkillSelector {
|
||||
fn method(&self) -> &'static str {
|
||||
"lru_v1"
|
||||
}
|
||||
|
||||
fn select(
|
||||
&self,
|
||||
query: &str,
|
||||
documents: &[SkillSelectionDocument<'_>],
|
||||
limit: usize,
|
||||
) -> CheapSkillSelection {
|
||||
let mut query_terms = query.split_whitespace();
|
||||
let query_term_count = query_terms.by_ref().take(MAX_QUERY_TERMS).count();
|
||||
let query_truncated = query_terms.next().is_some();
|
||||
let candidate_set_truncated = documents.len() > MAX_CANDIDATES;
|
||||
let eligible_ids = documents
|
||||
.iter()
|
||||
.take(MAX_CANDIDATES)
|
||||
.map(|document| document.id)
|
||||
.collect::<HashSet<_>>();
|
||||
let mut seen_ids = HashSet::new();
|
||||
|
||||
CheapSkillSelection {
|
||||
candidate_ids: self
|
||||
.recent_skill_ids
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| eligible_ids.contains(id) && seen_ids.insert(*id))
|
||||
.take(limit.min(MAX_RESULTS))
|
||||
.collect(),
|
||||
query_term_count,
|
||||
query_truncated,
|
||||
candidate_set_truncated,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lru_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,136 @@
|
||||
use super::CharacterRoutingCardSkillSelector;
|
||||
use super::CheapSkillSelection;
|
||||
use super::CheapSkillSelector;
|
||||
use super::LruSkillSelector;
|
||||
use super::SkillSelectionDocument;
|
||||
use super::WeightedLexicalSkillSelector;
|
||||
use super::rrf_lexical_char::fuse_rankings_with_constant;
|
||||
|
||||
const MAX_RESULTS: usize = 50;
|
||||
const RRF_K: usize = 10;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct LruPlusCharacterRoutingSkillSelector {
|
||||
lru_selector: LruSkillSelector,
|
||||
character_selector: CharacterRoutingCardSkillSelector,
|
||||
}
|
||||
|
||||
impl LruPlusCharacterRoutingSkillSelector {
|
||||
pub(crate) fn new(
|
||||
lru_selector: LruSkillSelector,
|
||||
character_selector: CharacterRoutingCardSkillSelector,
|
||||
) -> Self {
|
||||
Self {
|
||||
lru_selector,
|
||||
character_selector,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CheapSkillSelector for LruPlusCharacterRoutingSkillSelector {
|
||||
fn method(&self) -> &'static str {
|
||||
"lru_plus_character_routing_v1"
|
||||
}
|
||||
|
||||
fn select(
|
||||
&self,
|
||||
query: &str,
|
||||
documents: &[SkillSelectionDocument<'_>],
|
||||
limit: usize,
|
||||
) -> CheapSkillSelection {
|
||||
if limit == 0 {
|
||||
return CheapSkillSelection::default();
|
||||
}
|
||||
|
||||
let recent = self
|
||||
.lru_selector
|
||||
.select(query, documents, /*limit*/ MAX_RESULTS);
|
||||
let character =
|
||||
self.character_selector
|
||||
.select(query, documents, /*limit*/ MAX_RESULTS);
|
||||
let candidate_ids = fuse_rankings_with_constant(
|
||||
[&recent.candidate_ids, &character.candidate_ids],
|
||||
limit.min(MAX_RESULTS),
|
||||
/*rank_constant*/ RRF_K,
|
||||
);
|
||||
|
||||
CheapSkillSelection {
|
||||
candidate_ids,
|
||||
query_term_count: recent.query_term_count.max(character.query_term_count),
|
||||
query_truncated: recent.query_truncated || character.query_truncated,
|
||||
candidate_set_truncated: recent.candidate_set_truncated
|
||||
|| character.candidate_set_truncated,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct LruPlusLexicalCharacterRoutingSkillSelector {
|
||||
lru_selector: LruSkillSelector,
|
||||
character_selector: CharacterRoutingCardSkillSelector,
|
||||
}
|
||||
|
||||
impl LruPlusLexicalCharacterRoutingSkillSelector {
|
||||
pub(crate) fn new(
|
||||
lru_selector: LruSkillSelector,
|
||||
character_selector: CharacterRoutingCardSkillSelector,
|
||||
) -> Self {
|
||||
Self {
|
||||
lru_selector,
|
||||
character_selector,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CheapSkillSelector for LruPlusLexicalCharacterRoutingSkillSelector {
|
||||
fn method(&self) -> &'static str {
|
||||
"lru_plus_lexical_character_routing_v1"
|
||||
}
|
||||
|
||||
fn select(
|
||||
&self,
|
||||
query: &str,
|
||||
documents: &[SkillSelectionDocument<'_>],
|
||||
limit: usize,
|
||||
) -> CheapSkillSelection {
|
||||
if limit == 0 {
|
||||
return CheapSkillSelection::default();
|
||||
}
|
||||
|
||||
let recent = self
|
||||
.lru_selector
|
||||
.select(query, documents, /*limit*/ MAX_RESULTS);
|
||||
let lexical =
|
||||
WeightedLexicalSkillSelector.select(query, documents, /*limit*/ MAX_RESULTS);
|
||||
let character =
|
||||
self.character_selector
|
||||
.select(query, documents, /*limit*/ MAX_RESULTS);
|
||||
let candidate_ids = fuse_rankings_with_constant(
|
||||
[
|
||||
&recent.candidate_ids,
|
||||
&lexical.candidate_ids,
|
||||
&character.candidate_ids,
|
||||
],
|
||||
limit.min(MAX_RESULTS),
|
||||
/*rank_constant*/ RRF_K,
|
||||
);
|
||||
|
||||
CheapSkillSelection {
|
||||
candidate_ids,
|
||||
query_term_count: recent
|
||||
.query_term_count
|
||||
.max(lexical.query_term_count)
|
||||
.max(character.query_term_count),
|
||||
query_truncated: recent.query_truncated
|
||||
|| lexical.query_truncated
|
||||
|| character.query_truncated,
|
||||
candidate_set_truncated: recent.candidate_set_truncated
|
||||
|| lexical.candidate_set_truncated
|
||||
|| character.candidate_set_truncated,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lru_plus_character_routing_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,179 @@
|
||||
use akode_skills::SkillDependencies;
|
||||
use akode_skills::SkillToolDependency;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cold_start_uses_character_routing_metadata() {
|
||||
let dependencies = SkillDependencies {
|
||||
tools: vec![SkillToolDependency {
|
||||
r#type: "app".to_string(),
|
||||
value: "slack".to_string(),
|
||||
description: None,
|
||||
transport: None,
|
||||
command: None,
|
||||
url: None,
|
||||
oauth_callback_port: None,
|
||||
}],
|
||||
};
|
||||
let documents = [
|
||||
document(/*id*/ 10, "compilation", "Compile Rust crates."),
|
||||
SkillSelectionDocument {
|
||||
dependencies: Some(&dependencies),
|
||||
..document(/*id*/ 20, "team-communication", "Share team updates.")
|
||||
},
|
||||
];
|
||||
let expected = CheapSkillSelection {
|
||||
candidate_ids: vec![20],
|
||||
query_term_count: 1,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
for selector in selectors(Vec::new(), CharacterRoutingCardSkillSelector::default()) {
|
||||
let method = selector.method();
|
||||
assert_eq!(
|
||||
expected,
|
||||
selector.select("slack", &documents, /*limit*/ 50),
|
||||
"{method}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_and_text_matches_are_merged_without_duplicates() {
|
||||
let documents = [
|
||||
document(/*id*/ 10, "rust-build", "Inspect compiler errors."),
|
||||
document(
|
||||
/*id*/ 20,
|
||||
"python-tools",
|
||||
"Manage Python environments.",
|
||||
),
|
||||
document(/*id*/ 30, "monorepo", "Repository conventions."),
|
||||
];
|
||||
let expected = CheapSkillSelection {
|
||||
candidate_ids: vec![20, 30, 10],
|
||||
query_term_count: 1,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
for selector in selectors(
|
||||
vec![30, 10, 20, 20, 999],
|
||||
CharacterRoutingCardSkillSelector::default(),
|
||||
) {
|
||||
let method = selector.method();
|
||||
assert_eq!(
|
||||
expected,
|
||||
selector.select("python", &documents, /*limit*/ 50),
|
||||
"{method}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_way_fusion_retains_short_exact_matches() {
|
||||
let documents = [
|
||||
document(/*id*/ 10, "ci", ""),
|
||||
document(/*id*/ 20, "python", ""),
|
||||
document(/*id*/ 30, "rust", ""),
|
||||
];
|
||||
let expected_rankings = [vec![20, 30], vec![20, 10, 30]];
|
||||
|
||||
for (selector, candidate_ids) in
|
||||
selectors(vec![30], CharacterRoutingCardSkillSelector::default())
|
||||
.into_iter()
|
||||
.zip(expected_rankings)
|
||||
{
|
||||
let method = selector.method();
|
||||
assert_eq!(
|
||||
CheapSkillSelection {
|
||||
candidate_ids,
|
||||
query_term_count: 2,
|
||||
..Default::default()
|
||||
},
|
||||
selector.select("ci python", &documents, /*limit*/ 50),
|
||||
"{method}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fusion_is_deterministic_capped_and_reports_input_bounds() {
|
||||
let documents = (0..1_001)
|
||||
.map(|id| document(id, "python", ""))
|
||||
.collect::<Vec<_>>();
|
||||
let query = "python ".repeat(4 * 1024);
|
||||
let expected_rankings = [
|
||||
[0, 999].into_iter().chain(1..49).collect::<Vec<_>>(),
|
||||
(0..11)
|
||||
.chain(std::iter::once(999))
|
||||
.chain(11..49)
|
||||
.collect::<Vec<_>>(),
|
||||
];
|
||||
|
||||
for (selector, candidate_ids) in selectors(
|
||||
vec![1_000, 999, 999, 1_002],
|
||||
CharacterRoutingCardSkillSelector::default(),
|
||||
)
|
||||
.into_iter()
|
||||
.zip(expected_rankings)
|
||||
{
|
||||
let method = selector.method();
|
||||
let expected = CheapSkillSelection {
|
||||
candidate_ids,
|
||||
query_term_count: 64,
|
||||
query_truncated: true,
|
||||
candidate_set_truncated: true,
|
||||
};
|
||||
assert_eq!(
|
||||
expected,
|
||||
selector.select(&query, &documents, /*limit*/ 50),
|
||||
"{method}"
|
||||
);
|
||||
assert_eq!(
|
||||
expected,
|
||||
selector.select(&query, &documents, usize::MAX),
|
||||
"{method}"
|
||||
);
|
||||
assert_eq!(
|
||||
CheapSkillSelection {
|
||||
candidate_ids: expected.candidate_ids[..7].to_vec(),
|
||||
..expected
|
||||
},
|
||||
selector.select(&query, &documents, /*limit*/ 7),
|
||||
"{method}"
|
||||
);
|
||||
assert_eq!(
|
||||
CheapSkillSelection::default(),
|
||||
selector.select(&query, &documents, /*limit*/ 0),
|
||||
"{method}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn selectors(
|
||||
recent_skill_ids: Vec<usize>,
|
||||
character_selector: CharacterRoutingCardSkillSelector,
|
||||
) -> [Box<dyn CheapSkillSelector>; 2] {
|
||||
let lru_selector = LruSkillSelector::new(recent_skill_ids);
|
||||
[
|
||||
Box::new(LruPlusCharacterRoutingSkillSelector::new(
|
||||
lru_selector.clone(),
|
||||
character_selector.clone(),
|
||||
)),
|
||||
Box::new(LruPlusLexicalCharacterRoutingSkillSelector::new(
|
||||
lru_selector,
|
||||
character_selector,
|
||||
)),
|
||||
]
|
||||
}
|
||||
|
||||
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
|
||||
SkillSelectionDocument {
|
||||
id,
|
||||
name,
|
||||
short_description: None,
|
||||
description,
|
||||
dependencies: None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
use super::CheapSkillSelection;
|
||||
use super::CheapSkillSelector;
|
||||
use super::LruSkillSelector;
|
||||
use super::SkillSelectionDocument;
|
||||
use super::WeightedLexicalSkillSelector;
|
||||
use super::rrf_lexical_char::fuse_rankings_with_constant;
|
||||
|
||||
const MAX_RESULTS: usize = 50;
|
||||
const RRF_K: usize = 10;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct LruPlusLexicalSkillSelector {
|
||||
lru_selector: LruSkillSelector,
|
||||
}
|
||||
|
||||
impl LruPlusLexicalSkillSelector {
|
||||
pub(crate) fn new(lru_selector: LruSkillSelector) -> Self {
|
||||
Self { lru_selector }
|
||||
}
|
||||
}
|
||||
|
||||
impl CheapSkillSelector for LruPlusLexicalSkillSelector {
|
||||
fn method(&self) -> &'static str {
|
||||
"lru_plus_lexical_v1"
|
||||
}
|
||||
|
||||
fn select(
|
||||
&self,
|
||||
query: &str,
|
||||
documents: &[SkillSelectionDocument<'_>],
|
||||
limit: usize,
|
||||
) -> CheapSkillSelection {
|
||||
if limit == 0 {
|
||||
return CheapSkillSelection::default();
|
||||
}
|
||||
|
||||
let recent = self
|
||||
.lru_selector
|
||||
.select(query, documents, /*limit*/ MAX_RESULTS);
|
||||
let lexical =
|
||||
WeightedLexicalSkillSelector.select(query, documents, /*limit*/ MAX_RESULTS);
|
||||
let candidate_ids = fuse_rankings_with_constant(
|
||||
[&recent.candidate_ids, &lexical.candidate_ids],
|
||||
limit.min(MAX_RESULTS),
|
||||
/*rank_constant*/ RRF_K,
|
||||
);
|
||||
|
||||
CheapSkillSelection {
|
||||
candidate_ids,
|
||||
query_term_count: recent.query_term_count.max(lexical.query_term_count),
|
||||
query_truncated: recent.query_truncated || lexical.query_truncated,
|
||||
candidate_set_truncated: recent.candidate_set_truncated
|
||||
|| lexical.candidate_set_truncated,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lru_plus_lexical_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,119 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn combined_selector_uses_lexical_results_before_invocation_history_exists() {
|
||||
let documents = [
|
||||
SkillSelectionDocument {
|
||||
id: 10,
|
||||
name: "ci",
|
||||
short_description: None,
|
||||
description: "Investigate failing checks.",
|
||||
dependencies: None,
|
||||
},
|
||||
SkillSelectionDocument {
|
||||
id: 20,
|
||||
name: "python-tools",
|
||||
short_description: None,
|
||||
description: "Manage Python environments.",
|
||||
dependencies: None,
|
||||
},
|
||||
];
|
||||
|
||||
let selection = LruPlusLexicalSkillSelector::new(LruSkillSelector::default()).select(
|
||||
"manage python environments",
|
||||
&documents,
|
||||
/*limit*/ 50,
|
||||
);
|
||||
|
||||
assert_eq!(vec![20], selection.candidate_ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combined_selector_merges_recent_and_newly_matching_skills() {
|
||||
let documents = [
|
||||
SkillSelectionDocument {
|
||||
id: 10,
|
||||
name: "ci",
|
||||
short_description: None,
|
||||
description: "Investigate failing checks.",
|
||||
dependencies: None,
|
||||
},
|
||||
SkillSelectionDocument {
|
||||
id: 20,
|
||||
name: "python-tools",
|
||||
short_description: None,
|
||||
description: "Manage Python environments.",
|
||||
dependencies: None,
|
||||
},
|
||||
SkillSelectionDocument {
|
||||
id: 30,
|
||||
name: "monorepo",
|
||||
short_description: None,
|
||||
description: "Follow repository conventions.",
|
||||
dependencies: None,
|
||||
},
|
||||
];
|
||||
|
||||
let selection = LruPlusLexicalSkillSelector::new(LruSkillSelector::new(vec![30, 10])).select(
|
||||
"manage python environments",
|
||||
&documents,
|
||||
/*limit*/ 50,
|
||||
);
|
||||
|
||||
assert_eq!(vec![20, 30, 10], selection.candidate_ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combined_selector_promotes_skills_supported_by_both_signals() {
|
||||
let documents = [
|
||||
SkillSelectionDocument {
|
||||
id: 10,
|
||||
name: "ci",
|
||||
short_description: None,
|
||||
description: "Investigate failing checks.",
|
||||
dependencies: None,
|
||||
},
|
||||
SkillSelectionDocument {
|
||||
id: 30,
|
||||
name: "monorepo",
|
||||
short_description: None,
|
||||
description: "Follow repository conventions.",
|
||||
dependencies: None,
|
||||
},
|
||||
];
|
||||
|
||||
let selection = LruPlusLexicalSkillSelector::new(LruSkillSelector::new(vec![30, 10])).select(
|
||||
"investigate failing ci checks",
|
||||
&documents,
|
||||
/*limit*/ 50,
|
||||
);
|
||||
|
||||
assert_eq!(vec![10, 30], selection.candidate_ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combined_fusion_keeps_a_top_ranked_skill_ahead_of_a_weak_overlap() {
|
||||
let recent = std::iter::once(1)
|
||||
.chain(100..148)
|
||||
.chain(std::iter::once(2))
|
||||
.collect::<Vec<_>>();
|
||||
let lexical = (200..249).chain(std::iter::once(2)).collect::<Vec<_>>();
|
||||
|
||||
let fused = fuse_rankings_with_constant(
|
||||
[&recent, &lexical],
|
||||
/*limit*/ MAX_RESULTS,
|
||||
/*rank_constant*/ RRF_K,
|
||||
);
|
||||
let top_ranked = fused
|
||||
.iter()
|
||||
.position(|candidate| *candidate == 1)
|
||||
.expect("top-ranked skill should be selected");
|
||||
let weak_overlap = fused
|
||||
.iter()
|
||||
.position(|candidate| *candidate == 2)
|
||||
.expect("weak overlapping skill should be selected");
|
||||
|
||||
assert!(top_ranked < weak_overlap);
|
||||
}
|
||||
60
akode-rs/ext/skills/src/dynamic_skill_selector/lru_tests.rs
Normal file
60
akode-rs/ext/skills/src/dynamic_skill_selector/lru_tests.rs
Normal file
@@ -0,0 +1,60 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lru_selector_preserves_recent_invocation_order() {
|
||||
let documents = [
|
||||
SkillSelectionDocument {
|
||||
id: 10,
|
||||
name: "ci",
|
||||
short_description: None,
|
||||
description: "Investigate failing checks.",
|
||||
dependencies: None,
|
||||
},
|
||||
SkillSelectionDocument {
|
||||
id: 20,
|
||||
name: "python-tools",
|
||||
short_description: None,
|
||||
description: "Manage Python environments.",
|
||||
dependencies: None,
|
||||
},
|
||||
SkillSelectionDocument {
|
||||
id: 30,
|
||||
name: "monorepo",
|
||||
short_description: None,
|
||||
description: "Follow repository conventions.",
|
||||
dependencies: None,
|
||||
},
|
||||
];
|
||||
|
||||
let selection =
|
||||
LruSkillSelector::new(vec![30, 10]).select("continue", &documents, /*limit*/ 50);
|
||||
|
||||
assert_eq!(vec![30, 10], selection.candidate_ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lru_selector_filters_stale_or_duplicate_skills_and_respects_the_limit() {
|
||||
let documents = [
|
||||
SkillSelectionDocument {
|
||||
id: 10,
|
||||
name: "ci",
|
||||
short_description: None,
|
||||
description: "Investigate failing checks.",
|
||||
dependencies: None,
|
||||
},
|
||||
SkillSelectionDocument {
|
||||
id: 20,
|
||||
name: "python-tools",
|
||||
short_description: None,
|
||||
description: "Manage Python environments.",
|
||||
dependencies: None,
|
||||
},
|
||||
];
|
||||
|
||||
let selection =
|
||||
LruSkillSelector::new(vec![99, 10, 10, 20]).select("yes", &documents, /*limit*/ 1);
|
||||
|
||||
assert_eq!(vec![10], selection.candidate_ids);
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::CheapSkillSelection;
|
||||
use super::CheapSkillSelector;
|
||||
use super::SkillSelectionDocument;
|
||||
use super::WeightedLexicalSkillSelector;
|
||||
|
||||
const MAX_QUERY_VIEWS: usize = 8;
|
||||
const MAX_DECOMPOSITION_BYTES: usize = 4 * 1024;
|
||||
const MAX_RESULTS: usize = 50;
|
||||
const CONNECTORS: &[&str] = &[" and then ", " and ", " then ", " also "];
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(crate) struct MultiQueryLexicalSkillSelector;
|
||||
|
||||
impl CheapSkillSelector for MultiQueryLexicalSkillSelector {
|
||||
fn method(&self) -> &'static str {
|
||||
"multi_query_lexical_v1"
|
||||
}
|
||||
|
||||
fn select(
|
||||
&self,
|
||||
query: &str,
|
||||
documents: &[SkillSelectionDocument<'_>],
|
||||
limit: usize,
|
||||
) -> CheapSkillSelection {
|
||||
let full_selection =
|
||||
WeightedLexicalSkillSelector.select(query, documents, limit.min(MAX_RESULTS));
|
||||
let views = query_views(query);
|
||||
if views.len() <= 1 || limit == 0 {
|
||||
return full_selection;
|
||||
}
|
||||
|
||||
let mut candidates = HashMap::new();
|
||||
record_candidates(&mut candidates, &full_selection, /*view_index*/ 0);
|
||||
let mut query_truncated = full_selection.query_truncated;
|
||||
let mut candidate_set_truncated = full_selection.candidate_set_truncated;
|
||||
for (view_index, view) in views.into_iter().enumerate().skip(1) {
|
||||
let selection =
|
||||
WeightedLexicalSkillSelector.select(view, documents, limit.min(MAX_RESULTS));
|
||||
query_truncated |= selection.query_truncated;
|
||||
candidate_set_truncated |= selection.candidate_set_truncated;
|
||||
record_candidates(&mut candidates, &selection, view_index);
|
||||
}
|
||||
|
||||
let mut candidates = candidates.into_values().collect::<Vec<_>>();
|
||||
candidates.sort_by(|left, right| {
|
||||
left.best_rank
|
||||
.cmp(&right.best_rank)
|
||||
.then_with(|| {
|
||||
left.full_query_rank
|
||||
.unwrap_or(usize::MAX)
|
||||
.cmp(&right.full_query_rank.unwrap_or(usize::MAX))
|
||||
})
|
||||
.then_with(|| right.view_count.cmp(&left.view_count))
|
||||
.then_with(|| left.first_view.cmp(&right.first_view))
|
||||
.then_with(|| left.id.cmp(&right.id))
|
||||
});
|
||||
|
||||
CheapSkillSelection {
|
||||
candidate_ids: candidates
|
||||
.into_iter()
|
||||
.take(limit.min(MAX_RESULTS))
|
||||
.map(|candidate| candidate.id)
|
||||
.collect(),
|
||||
query_term_count: full_selection.query_term_count,
|
||||
query_truncated,
|
||||
candidate_set_truncated,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct RankedCandidate {
|
||||
id: usize,
|
||||
best_rank: usize,
|
||||
full_query_rank: Option<usize>,
|
||||
view_count: usize,
|
||||
first_view: usize,
|
||||
}
|
||||
|
||||
fn record_candidates(
|
||||
candidates: &mut HashMap<usize, RankedCandidate>,
|
||||
selection: &CheapSkillSelection,
|
||||
view_index: usize,
|
||||
) {
|
||||
for (rank, id) in selection.candidate_ids.iter().copied().enumerate() {
|
||||
let rank = rank + 1;
|
||||
candidates
|
||||
.entry(id)
|
||||
.and_modify(|candidate| {
|
||||
candidate.best_rank = candidate.best_rank.min(rank);
|
||||
candidate.view_count = candidate.view_count.saturating_add(1);
|
||||
if view_index == 0 {
|
||||
candidate.full_query_rank = Some(rank);
|
||||
}
|
||||
})
|
||||
.or_insert(RankedCandidate {
|
||||
id,
|
||||
best_rank: rank,
|
||||
full_query_rank: (view_index == 0).then_some(rank),
|
||||
view_count: 1,
|
||||
first_view: view_index,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn query_views(query: &str) -> Vec<&str> {
|
||||
let full_query = bounded(query, MAX_DECOMPOSITION_BYTES).trim();
|
||||
if full_query.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut views = vec![full_query];
|
||||
let mut seen = HashSet::from([full_query]);
|
||||
for sentence in full_query.split(['\n', '\r', '.', '!', '?', ';']) {
|
||||
for clause in split_connectors(sentence) {
|
||||
let clause = clause.trim();
|
||||
if clause.chars().count() >= 2 && seen.insert(clause) {
|
||||
views.push(clause);
|
||||
if views.len() == MAX_QUERY_VIEWS {
|
||||
return views;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
views
|
||||
}
|
||||
|
||||
fn bounded(value: &str, max_bytes: usize) -> &str {
|
||||
if value.len() <= max_bytes {
|
||||
return value;
|
||||
}
|
||||
let mut end = max_bytes;
|
||||
while !value.is_char_boundary(end) {
|
||||
end = end.saturating_sub(1);
|
||||
}
|
||||
&value[..end]
|
||||
}
|
||||
|
||||
fn split_connectors(value: &str) -> Vec<&str> {
|
||||
let lowercase = value.to_ascii_lowercase();
|
||||
let mut segments = Vec::new();
|
||||
let mut start = 0;
|
||||
while start < value.len() {
|
||||
let next = CONNECTORS
|
||||
.iter()
|
||||
.filter_map(|connector| {
|
||||
lowercase[start..]
|
||||
.find(connector)
|
||||
.map(|offset| (start + offset, connector.len()))
|
||||
})
|
||||
.min_by_key(|(position, _)| *position);
|
||||
let Some((position, connector_length)) = next else {
|
||||
break;
|
||||
};
|
||||
segments.push(&value[start..position]);
|
||||
start = position + connector_length;
|
||||
}
|
||||
segments.push(&value[start..]);
|
||||
segments
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "multi_query_lexical_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,92 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn multi_query_promotes_each_clause_leader() {
|
||||
let documents = [
|
||||
document(/*id*/ 1, "rust-format", "Format Rust source code."),
|
||||
document(/*id*/ 2, "rust-lint", "Fix Rust source lint errors."),
|
||||
document(/*id*/ 3, "rust-review", "Review Rust source code."),
|
||||
document(
|
||||
/*id*/ 4,
|
||||
"ci-fix",
|
||||
"Diagnose failing GitHub Actions checks.",
|
||||
),
|
||||
];
|
||||
|
||||
let selection = MultiQueryLexicalSkillSelector.select(
|
||||
"format and review Rust source code, and then diagnose failing GitHub Actions checks",
|
||||
&documents,
|
||||
/*limit*/ 4,
|
||||
);
|
||||
|
||||
assert!(selection.candidate_ids[..3].contains(&1));
|
||||
assert!(selection.candidate_ids[..3].contains(&4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_query_matches_the_underlying_selector() {
|
||||
let documents = [
|
||||
document(/*id*/ 1, "presentations", "Create visual decks."),
|
||||
document(/*id*/ 2, "spreadsheets", "Analyze tabular data."),
|
||||
];
|
||||
|
||||
let expected =
|
||||
WeightedLexicalSkillSelector.select("create presentations", &documents, /*limit*/ 20);
|
||||
let actual = MultiQueryLexicalSkillSelector.select(
|
||||
"create presentations",
|
||||
&documents,
|
||||
/*limit*/ 20,
|
||||
);
|
||||
|
||||
assert_eq!(expected, actual);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_views_split_sentences_and_connectors() {
|
||||
assert_eq!(
|
||||
vec![
|
||||
"format code and then fix tests; write a summary",
|
||||
"format code",
|
||||
"fix tests",
|
||||
"write a summary",
|
||||
],
|
||||
query_views("format code and then fix tests; write a summary"),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_query_preserves_bounded_input_signals() {
|
||||
let long_query = format!("{}\nand inspect logs", "match ".repeat(4 * 1024));
|
||||
let names = (0..=1_000)
|
||||
.map(|index| format!("candidate-{index}"))
|
||||
.collect::<Vec<_>>();
|
||||
let documents = names
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(id, name)| SkillSelectionDocument {
|
||||
id,
|
||||
name,
|
||||
short_description: None,
|
||||
description: "match logs",
|
||||
dependencies: None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let selection =
|
||||
MultiQueryLexicalSkillSelector.select(&long_query, &documents, /*limit*/ 20);
|
||||
|
||||
assert!(selection.query_truncated);
|
||||
assert!(selection.candidate_set_truncated);
|
||||
assert_eq!(20, selection.candidate_ids.len());
|
||||
}
|
||||
|
||||
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
|
||||
SkillSelectionDocument {
|
||||
id,
|
||||
name,
|
||||
short_description: None,
|
||||
description,
|
||||
dependencies: None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::CheapSkillSelection;
|
||||
use super::CheapSkillSelector;
|
||||
use super::SkillSelectionDocument;
|
||||
|
||||
const MAX_QUERY_BYTES: usize = 4 * 1024;
|
||||
const MAX_QUERY_TERMS: usize = 64;
|
||||
const MAX_DOCUMENT_BYTES: usize = 4 * 1024;
|
||||
const MAX_FIELD_TERMS: usize = 256;
|
||||
const MAX_DEPENDENCY_RECORDS: usize = 32;
|
||||
const MAX_CANDIDATES: usize = 1_000;
|
||||
const MAX_RESULTS: usize = 50;
|
||||
|
||||
const STOP_WORDS: &[&str] = &[
|
||||
"a", "an", "and", "are", "as", "at", "be", "by", "do", "for", "from", "how", "i", "in", "is",
|
||||
"it", "me", "my", "of", "on", "or", "please", "that", "the", "this", "to", "use", "we", "what",
|
||||
"when", "where", "which", "with", "you", "your",
|
||||
];
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(crate) struct RoutingCardLexicalSkillSelector;
|
||||
|
||||
impl CheapSkillSelector for RoutingCardLexicalSkillSelector {
|
||||
fn method(&self) -> &'static str {
|
||||
"routing_card_exact_v1"
|
||||
}
|
||||
|
||||
fn select(
|
||||
&self,
|
||||
query: &str,
|
||||
documents: &[SkillSelectionDocument<'_>],
|
||||
limit: usize,
|
||||
) -> CheapSkillSelection {
|
||||
let (query, query_bytes_truncated) = bounded(query, MAX_QUERY_BYTES);
|
||||
let query_phrase = normalize(query);
|
||||
let (query_terms, query_terms_truncated) = query_terms(&query_phrase);
|
||||
let query_truncated = query_bytes_truncated || query_terms_truncated;
|
||||
let candidate_set_truncated = documents.len() > MAX_CANDIDATES;
|
||||
if query_phrase.is_empty() || limit == 0 {
|
||||
return CheapSkillSelection {
|
||||
query_term_count: query_terms.len(),
|
||||
query_truncated,
|
||||
candidate_set_truncated,
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
|
||||
let mut scored = documents
|
||||
.iter()
|
||||
.take(MAX_CANDIDATES)
|
||||
.filter_map(|document| {
|
||||
let prepared = PreparedRoutingCard::new(document);
|
||||
let score = prepared.score(&query_phrase, &query_terms);
|
||||
(score > 0).then_some((score, document.id, document.name))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
scored.sort_by(|left, right| {
|
||||
right
|
||||
.0
|
||||
.cmp(&left.0)
|
||||
.then_with(|| left.2.cmp(right.2))
|
||||
.then_with(|| left.1.cmp(&right.1))
|
||||
});
|
||||
|
||||
CheapSkillSelection {
|
||||
candidate_ids: scored
|
||||
.into_iter()
|
||||
.take(limit.min(MAX_RESULTS))
|
||||
.map(|(_, id, _)| id)
|
||||
.collect(),
|
||||
query_term_count: query_terms.len(),
|
||||
query_truncated,
|
||||
candidate_set_truncated,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PreparedRoutingCard {
|
||||
name: String,
|
||||
name_has_searchable_term: bool,
|
||||
fields: RoutingFields,
|
||||
}
|
||||
|
||||
struct RoutingFields {
|
||||
name: HashSet<String>,
|
||||
dependencies: HashSet<String>,
|
||||
short_description: HashSet<String>,
|
||||
description: HashSet<String>,
|
||||
}
|
||||
|
||||
impl PreparedRoutingCard {
|
||||
fn new(document: &SkillSelectionDocument<'_>) -> Self {
|
||||
let name = normalize_bounded(document.name);
|
||||
Self {
|
||||
name_has_searchable_term: name.split_whitespace().any(is_searchable_query_term),
|
||||
name,
|
||||
fields: RoutingFields {
|
||||
name: field_terms(document.name),
|
||||
dependencies: dependency_terms(document),
|
||||
short_description: field_terms(document.short_description.unwrap_or_default()),
|
||||
description: field_terms(document.description),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn score(&self, query_phrase: &str, query_terms: &[&str]) -> u32 {
|
||||
let mut score = 0u32;
|
||||
let name_phrase_matches = contains_phrase(query_phrase, &self.name);
|
||||
if !self.name.is_empty()
|
||||
&& ((self.name_has_searchable_term && name_phrase_matches) || query_phrase == self.name)
|
||||
{
|
||||
score = score.saturating_add(256);
|
||||
}
|
||||
|
||||
let mut matched_query_terms = 0u32;
|
||||
for query_term in query_terms {
|
||||
let mut matched = false;
|
||||
score = score.saturating_add(score_field(
|
||||
&self.fields.name,
|
||||
query_term,
|
||||
/*weight*/ 80,
|
||||
&mut matched,
|
||||
));
|
||||
score = score.saturating_add(score_field(
|
||||
&self.fields.dependencies,
|
||||
query_term,
|
||||
/*weight*/ 24,
|
||||
&mut matched,
|
||||
));
|
||||
score = score.saturating_add(score_field(
|
||||
&self.fields.short_description,
|
||||
query_term,
|
||||
/*weight*/ 12,
|
||||
&mut matched,
|
||||
));
|
||||
score = score.saturating_add(score_field(
|
||||
&self.fields.description,
|
||||
query_term,
|
||||
/*weight*/ 3,
|
||||
&mut matched,
|
||||
));
|
||||
if matched {
|
||||
matched_query_terms = matched_query_terms.saturating_add(1);
|
||||
}
|
||||
}
|
||||
score.saturating_add(matched_query_terms.saturating_mul(matched_query_terms))
|
||||
}
|
||||
}
|
||||
|
||||
fn score_field(terms: &HashSet<String>, query_term: &str, weight: u32, matched: &mut bool) -> u32 {
|
||||
if terms.contains(query_term) {
|
||||
*matched = true;
|
||||
weight
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
fn dependency_terms(document: &SkillSelectionDocument<'_>) -> HashSet<String> {
|
||||
let mut terms = HashSet::new();
|
||||
let Some(dependencies) = document.dependencies else {
|
||||
return terms;
|
||||
};
|
||||
let mut remaining_bytes = MAX_DOCUMENT_BYTES;
|
||||
for tool in dependencies.tools.iter().take(MAX_DEPENDENCY_RECORDS) {
|
||||
extend_terms(&mut terms, &tool.value, &mut remaining_bytes);
|
||||
if let Some(description) = tool.description.as_deref() {
|
||||
extend_terms(&mut terms, description, &mut remaining_bytes);
|
||||
}
|
||||
if remaining_bytes == 0 || terms.len() >= MAX_FIELD_TERMS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
terms
|
||||
}
|
||||
|
||||
fn field_terms(value: &str) -> HashSet<String> {
|
||||
normalized_terms(bounded(value, MAX_DOCUMENT_BYTES).0)
|
||||
.into_iter()
|
||||
.take(MAX_FIELD_TERMS)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn extend_terms(terms: &mut HashSet<String>, value: &str, remaining_bytes: &mut usize) {
|
||||
let value = bounded(value, *remaining_bytes).0;
|
||||
*remaining_bytes = remaining_bytes.saturating_sub(value.len());
|
||||
for term in normalized_terms(value) {
|
||||
if terms.len() == MAX_FIELD_TERMS {
|
||||
return;
|
||||
}
|
||||
terms.insert(term);
|
||||
}
|
||||
}
|
||||
|
||||
fn query_terms(query_phrase: &str) -> (Vec<&str>, bool) {
|
||||
let mut seen = HashSet::new();
|
||||
let mut terms = Vec::new();
|
||||
for term in query_phrase
|
||||
.split_whitespace()
|
||||
.filter(|term| is_searchable_query_term(term))
|
||||
{
|
||||
if !seen.insert(term) {
|
||||
continue;
|
||||
}
|
||||
if terms.len() == MAX_QUERY_TERMS {
|
||||
return (terms, true);
|
||||
}
|
||||
terms.push(term);
|
||||
}
|
||||
(terms, false)
|
||||
}
|
||||
|
||||
fn is_searchable_query_term(term: &str) -> bool {
|
||||
term.chars().count() >= 2 && !STOP_WORDS.contains(&term)
|
||||
}
|
||||
|
||||
fn normalize_bounded(value: &str) -> String {
|
||||
normalize(bounded(value, MAX_DOCUMENT_BYTES).0)
|
||||
}
|
||||
|
||||
fn normalize(value: &str) -> String {
|
||||
normalized_terms(value).join(" ")
|
||||
}
|
||||
|
||||
fn normalized_terms(value: &str) -> Vec<String> {
|
||||
let mut normalized = String::with_capacity(value.len());
|
||||
for character in value.chars() {
|
||||
if character.is_alphanumeric() {
|
||||
normalized.extend(character.to_lowercase());
|
||||
} else {
|
||||
normalized.push(' ');
|
||||
}
|
||||
}
|
||||
normalized.split_whitespace().map(str::to_string).collect()
|
||||
}
|
||||
|
||||
fn contains_phrase(haystack: &str, needle: &str) -> bool {
|
||||
haystack == needle
|
||||
|| haystack.starts_with(&format!("{needle} "))
|
||||
|| haystack.ends_with(&format!(" {needle}"))
|
||||
|| haystack.contains(&format!(" {needle} "))
|
||||
}
|
||||
|
||||
fn bounded(value: &str, max_bytes: usize) -> (&str, bool) {
|
||||
if value.len() <= max_bytes {
|
||||
return (value, false);
|
||||
}
|
||||
let mut end = max_bytes;
|
||||
while !value.is_char_boundary(end) {
|
||||
end = end.saturating_sub(1);
|
||||
}
|
||||
(&value[..end], true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "routing_card_lexical_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,134 @@
|
||||
use akode_skills::SkillDependencies;
|
||||
use akode_skills::SkillToolDependency;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn dependency_names_outrank_description_only_matches() {
|
||||
let dependencies = SkillDependencies {
|
||||
tools: vec![SkillToolDependency {
|
||||
r#type: "app".to_string(),
|
||||
value: "slack".to_string(),
|
||||
description: Some("Send messages to Slack channels.".to_string()),
|
||||
transport: None,
|
||||
command: None,
|
||||
url: None,
|
||||
oauth_callback_port: None,
|
||||
}],
|
||||
};
|
||||
let documents = [
|
||||
SkillSelectionDocument {
|
||||
id: 1,
|
||||
name: "team-messaging",
|
||||
short_description: None,
|
||||
description: "Work with team communication.",
|
||||
dependencies: Some(&dependencies),
|
||||
},
|
||||
document(
|
||||
/*id*/ 2,
|
||||
"documents",
|
||||
"Send messages to Slack channels.",
|
||||
),
|
||||
];
|
||||
|
||||
let selection = RoutingCardLexicalSkillSelector.select(
|
||||
"send this update to Slack",
|
||||
&documents,
|
||||
/*limit*/ 20,
|
||||
);
|
||||
|
||||
assert_eq!(vec![1, 2], selection.candidate_ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stop_word_name_requires_an_exact_query() {
|
||||
let documents = [document(/*id*/ 1, "do", "Run a task.")];
|
||||
|
||||
let selection = RoutingCardLexicalSkillSelector.select("do", &documents, /*limit*/ 20);
|
||||
assert_eq!(vec![1], selection.candidate_ids);
|
||||
assert_eq!(0, selection.query_term_count);
|
||||
|
||||
let selection = RoutingCardLexicalSkillSelector.select(
|
||||
"how do I format Rust",
|
||||
&documents,
|
||||
/*limit*/ 20,
|
||||
);
|
||||
assert_eq!(Vec::<usize>::new(), selection.candidate_ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefixes_do_not_match_field_terms() {
|
||||
let documents = [document(
|
||||
/*id*/ 1,
|
||||
"presentations",
|
||||
"Create presentations.",
|
||||
)];
|
||||
|
||||
let selection =
|
||||
RoutingCardLexicalSkillSelector.select("present", &documents, /*limit*/ 20);
|
||||
|
||||
assert_eq!(Vec::<usize>::new(), selection.candidate_ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dependency_records_are_bounded() {
|
||||
let mut tools = (0..MAX_DEPENDENCY_RECORDS)
|
||||
.map(|_| SkillToolDependency {
|
||||
r#type: "app".to_string(),
|
||||
value: "shared".to_string(),
|
||||
description: None,
|
||||
transport: None,
|
||||
command: None,
|
||||
url: None,
|
||||
oauth_callback_port: None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
tools.push(SkillToolDependency {
|
||||
r#type: "app".to_string(),
|
||||
value: "unbounded".to_string(),
|
||||
description: None,
|
||||
transport: None,
|
||||
command: None,
|
||||
url: None,
|
||||
oauth_callback_port: None,
|
||||
});
|
||||
let dependencies = SkillDependencies { tools };
|
||||
let document = SkillSelectionDocument {
|
||||
id: 1,
|
||||
name: "dependency-test",
|
||||
short_description: None,
|
||||
description: "Test dependencies.",
|
||||
dependencies: Some(&dependencies),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
HashSet::from(["shared".to_string()]),
|
||||
dependency_terms(&document)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selector_reports_bounded_inputs() {
|
||||
let documents = [document(
|
||||
/*id*/ 1,
|
||||
"presentations",
|
||||
"Create visual decks.",
|
||||
)];
|
||||
let query = "presentations ".repeat(MAX_QUERY_BYTES);
|
||||
|
||||
let selection = RoutingCardLexicalSkillSelector.select(&query, &documents, /*limit*/ 20);
|
||||
|
||||
assert_eq!(vec![1], selection.candidate_ids);
|
||||
assert!(selection.query_truncated);
|
||||
}
|
||||
|
||||
fn document<'a>(id: usize, name: &'a str, description: &'a str) -> SkillSelectionDocument<'a> {
|
||||
SkillSelectionDocument {
|
||||
id,
|
||||
name,
|
||||
short_description: None,
|
||||
description,
|
||||
dependencies: None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::CharacterNgramSkillSelector;
|
||||
use super::CheapSkillSelection;
|
||||
use super::CheapSkillSelector;
|
||||
use super::SkillSelectionDocument;
|
||||
use super::WeightedLexicalSkillSelector;
|
||||
|
||||
const MAX_FUSION_CANDIDATES: usize = 50;
|
||||
const RRF_K: usize = 60;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(crate) struct RrfLexicalCharSkillSelector;
|
||||
|
||||
impl CheapSkillSelector for RrfLexicalCharSkillSelector {
|
||||
fn method(&self) -> &'static str {
|
||||
"rrf_lexical_char_v1"
|
||||
}
|
||||
|
||||
fn select(
|
||||
&self,
|
||||
query: &str,
|
||||
documents: &[SkillSelectionDocument<'_>],
|
||||
limit: usize,
|
||||
) -> CheapSkillSelection {
|
||||
if limit == 0 {
|
||||
return CheapSkillSelection::default();
|
||||
}
|
||||
|
||||
let lexical = WeightedLexicalSkillSelector.select(
|
||||
query,
|
||||
documents,
|
||||
/*limit*/ MAX_FUSION_CANDIDATES,
|
||||
);
|
||||
let character = CharacterNgramSkillSelector.select(
|
||||
query,
|
||||
documents,
|
||||
/*limit*/ MAX_FUSION_CANDIDATES,
|
||||
);
|
||||
let candidate_ids = fuse_rankings(
|
||||
[&lexical.candidate_ids, &character.candidate_ids],
|
||||
limit.min(MAX_FUSION_CANDIDATES),
|
||||
);
|
||||
|
||||
CheapSkillSelection {
|
||||
candidate_ids,
|
||||
query_term_count: lexical.query_term_count.max(character.query_term_count),
|
||||
query_truncated: lexical.query_truncated || character.query_truncated,
|
||||
candidate_set_truncated: lexical.candidate_set_truncated
|
||||
|| character.candidate_set_truncated,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fuse_rankings<const N: usize>(rankings: [&[usize]; N], limit: usize) -> Vec<usize> {
|
||||
fuse_rankings_with_constant(rankings, limit, RRF_K)
|
||||
}
|
||||
|
||||
pub(super) fn fuse_rankings_with_constant<const N: usize>(
|
||||
rankings: [&[usize]; N],
|
||||
limit: usize,
|
||||
rank_constant: usize,
|
||||
) -> Vec<usize> {
|
||||
let mut scores = HashMap::<usize, f64>::new();
|
||||
let mut best_ranks = HashMap::<usize, usize>::new();
|
||||
for ranking in rankings {
|
||||
for (index, id) in ranking.iter().copied().enumerate() {
|
||||
let rank = index + 1;
|
||||
*scores.entry(id).or_default() += 1.0 / (rank_constant + rank) as f64;
|
||||
best_ranks
|
||||
.entry(id)
|
||||
.and_modify(|best_rank| *best_rank = (*best_rank).min(rank))
|
||||
.or_insert(rank);
|
||||
}
|
||||
}
|
||||
|
||||
let mut candidates = scores.into_iter().collect::<Vec<_>>();
|
||||
candidates.sort_by(|(left_id, left_score), (right_id, right_score)| {
|
||||
right_score
|
||||
.total_cmp(left_score)
|
||||
.then_with(|| best_ranks[left_id].cmp(&best_ranks[right_id]))
|
||||
.then_with(|| left_id.cmp(right_id))
|
||||
});
|
||||
candidates
|
||||
.into_iter()
|
||||
.take(limit)
|
||||
.map(|(id, _)| id)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "rrf_lexical_char_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,35 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn fusion_prefers_candidates_supported_by_both_rankings() {
|
||||
let fused = fuse_rankings([&[1, 2, 3], &[2, 3, 4]], /*limit*/ 4);
|
||||
|
||||
assert_eq!(vec![2, 3, 1, 4], fused);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fusion_uses_rank_and_id_to_break_ties() {
|
||||
let fused = fuse_rankings([&[20, 10], &[30]], /*limit*/ 3);
|
||||
|
||||
assert_eq!(vec![20, 30, 10], fused);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selector_reports_the_combined_input_bounds() {
|
||||
let documents = [SkillSelectionDocument {
|
||||
id: 7,
|
||||
name: "presentations",
|
||||
short_description: None,
|
||||
description: "Create visual decks.",
|
||||
dependencies: None,
|
||||
}];
|
||||
let query = "presentation ".repeat(4 * 1024);
|
||||
|
||||
let selection = RrfLexicalCharSkillSelector.select(&query, &documents, /*limit*/ 20);
|
||||
|
||||
assert_eq!(vec![7], selection.candidate_ids);
|
||||
assert!(selection.query_truncated);
|
||||
assert!(!selection.candidate_set_truncated);
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::CheapSkillSelection;
|
||||
use super::CheapSkillSelector;
|
||||
use super::SkillSelectionDocument;
|
||||
|
||||
const MAX_QUERY_BYTES: usize = 4 * 1024;
|
||||
const MAX_QUERY_TERMS: usize = 64;
|
||||
const MAX_DOCUMENT_BYTES: usize = 4 * 1024;
|
||||
const MAX_DOCUMENT_TERMS: usize = 256;
|
||||
const MAX_CANDIDATES: usize = 1_000;
|
||||
const MAX_RESULTS: usize = 50;
|
||||
|
||||
const STOP_WORDS: &[&str] = &[
|
||||
"a", "an", "and", "are", "as", "at", "be", "by", "do", "for", "from", "how", "i", "in", "is",
|
||||
"it", "me", "my", "of", "on", "or", "please", "that", "the", "this", "to", "use", "we", "what",
|
||||
"when", "where", "which", "with", "you", "your",
|
||||
];
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(crate) struct WeightedLexicalSkillSelector;
|
||||
|
||||
impl CheapSkillSelector for WeightedLexicalSkillSelector {
|
||||
fn method(&self) -> &'static str {
|
||||
"weighted_lexical_v1"
|
||||
}
|
||||
|
||||
fn select(
|
||||
&self,
|
||||
query: &str,
|
||||
documents: &[SkillSelectionDocument<'_>],
|
||||
limit: usize,
|
||||
) -> CheapSkillSelection {
|
||||
let (query, query_bytes_truncated) = bounded(query, MAX_QUERY_BYTES);
|
||||
let query_phrase = normalize_phrase(query);
|
||||
let (query_terms, query_terms_truncated) = query_terms(&query_phrase);
|
||||
let query_truncated = query_bytes_truncated || query_terms_truncated;
|
||||
let candidate_set_truncated = documents.len() > MAX_CANDIDATES;
|
||||
if query_terms.is_empty() || limit == 0 {
|
||||
return CheapSkillSelection {
|
||||
query_term_count: query_terms.len(),
|
||||
query_truncated,
|
||||
candidate_set_truncated,
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
|
||||
let mut scored = documents
|
||||
.iter()
|
||||
.take(MAX_CANDIDATES)
|
||||
.filter_map(|document| {
|
||||
let score = score_document(&query_phrase, &query_terms, document);
|
||||
(score > 0).then_some((score, document.id, document.name))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
scored.sort_by(|left, right| {
|
||||
right
|
||||
.0
|
||||
.cmp(&left.0)
|
||||
.then_with(|| left.2.cmp(right.2))
|
||||
.then_with(|| left.1.cmp(&right.1))
|
||||
});
|
||||
|
||||
CheapSkillSelection {
|
||||
candidate_ids: scored
|
||||
.into_iter()
|
||||
.take(limit.min(MAX_RESULTS))
|
||||
.map(|(_, id, _)| id)
|
||||
.collect(),
|
||||
query_term_count: query_terms.len(),
|
||||
query_truncated,
|
||||
candidate_set_truncated,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn score_document(
|
||||
query_phrase: &str,
|
||||
query_terms: &[&str],
|
||||
document: &SkillSelectionDocument<'_>,
|
||||
) -> u32 {
|
||||
let name = normalize_bounded(document.name);
|
||||
let short_description = document
|
||||
.short_description
|
||||
.map(normalize_bounded)
|
||||
.unwrap_or_default();
|
||||
let description = normalize_bounded(document.description);
|
||||
let name_terms = phrase_terms(&name);
|
||||
let short_description_terms = phrase_terms(&short_description);
|
||||
let description_terms = phrase_terms(&description);
|
||||
|
||||
let mut score = 0u32;
|
||||
if !name.is_empty() && contains_phrase(query_phrase, &name) {
|
||||
score = score.saturating_add(256);
|
||||
}
|
||||
|
||||
let mut matched_query_terms = 0u32;
|
||||
for query_term in query_terms {
|
||||
let mut matched = false;
|
||||
if name == *query_term {
|
||||
score = score.saturating_add(128);
|
||||
matched = true;
|
||||
} else if name_terms.contains(query_term) {
|
||||
score = score.saturating_add(64);
|
||||
matched = true;
|
||||
} else if contains_related_term(&name_terms, query_term) {
|
||||
score = score.saturating_add(24);
|
||||
matched = true;
|
||||
}
|
||||
|
||||
if short_description_terms.contains(query_term) {
|
||||
score = score.saturating_add(16);
|
||||
matched = true;
|
||||
} else if contains_related_term(&short_description_terms, query_term) {
|
||||
score = score.saturating_add(6);
|
||||
matched = true;
|
||||
}
|
||||
|
||||
if description_terms.contains(query_term) {
|
||||
score = score.saturating_add(4);
|
||||
matched = true;
|
||||
} else if contains_related_term(&description_terms, query_term) {
|
||||
score = score.saturating_add(1);
|
||||
matched = true;
|
||||
}
|
||||
|
||||
if matched {
|
||||
matched_query_terms = matched_query_terms.saturating_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
score.saturating_add(matched_query_terms.saturating_mul(matched_query_terms))
|
||||
}
|
||||
|
||||
fn normalize_bounded(value: &str) -> String {
|
||||
normalize_phrase(bounded(value, MAX_DOCUMENT_BYTES).0)
|
||||
}
|
||||
|
||||
fn normalize_phrase(value: &str) -> String {
|
||||
let mut normalized = String::with_capacity(value.len());
|
||||
let mut previous_was_separator = true;
|
||||
for character in value.chars() {
|
||||
if character.is_alphanumeric() {
|
||||
normalized.extend(character.to_lowercase());
|
||||
previous_was_separator = false;
|
||||
} else if !previous_was_separator {
|
||||
normalized.push(' ');
|
||||
previous_was_separator = true;
|
||||
}
|
||||
}
|
||||
if previous_was_separator {
|
||||
normalized.pop();
|
||||
}
|
||||
normalized
|
||||
}
|
||||
|
||||
fn query_terms(query_phrase: &str) -> (Vec<&str>, bool) {
|
||||
let mut seen = HashSet::new();
|
||||
let mut terms = Vec::new();
|
||||
for term in query_phrase
|
||||
.split_whitespace()
|
||||
.filter(|term| term.chars().count() >= 2 && !STOP_WORDS.contains(term))
|
||||
{
|
||||
if !seen.insert(term) {
|
||||
continue;
|
||||
}
|
||||
if terms.len() == MAX_QUERY_TERMS {
|
||||
return (terms, true);
|
||||
}
|
||||
terms.push(term);
|
||||
}
|
||||
(terms, false)
|
||||
}
|
||||
|
||||
fn phrase_terms(phrase: &str) -> HashSet<&str> {
|
||||
phrase.split_whitespace().take(MAX_DOCUMENT_TERMS).collect()
|
||||
}
|
||||
|
||||
fn contains_phrase(haystack: &str, needle: &str) -> bool {
|
||||
haystack == needle
|
||||
|| haystack.starts_with(&format!("{needle} "))
|
||||
|| haystack.ends_with(&format!(" {needle}"))
|
||||
|| haystack.contains(&format!(" {needle} "))
|
||||
}
|
||||
|
||||
fn contains_related_term(terms: &HashSet<&str>, query_term: &str) -> bool {
|
||||
if query_term.chars().count() < 4 {
|
||||
return false;
|
||||
}
|
||||
terms.iter().any(|term| {
|
||||
term.chars().count() >= 4 && (term.starts_with(query_term) || query_term.starts_with(*term))
|
||||
})
|
||||
}
|
||||
|
||||
fn bounded(value: &str, max_bytes: usize) -> (&str, bool) {
|
||||
if value.len() <= max_bytes {
|
||||
return (value, false);
|
||||
}
|
||||
let mut end = max_bytes;
|
||||
while !value.is_char_boundary(end) {
|
||||
end = end.saturating_sub(1);
|
||||
}
|
||||
(&value[..end], true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "weighted_lexical_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,176 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn lexical_selector_prioritizes_an_exact_skill_name() {
|
||||
let documents = [
|
||||
SkillSelectionDocument {
|
||||
id: 10,
|
||||
name: "slides-helper",
|
||||
short_description: None,
|
||||
description: "Create presentations and visual decks.",
|
||||
dependencies: None,
|
||||
},
|
||||
SkillSelectionDocument {
|
||||
id: 20,
|
||||
name: "presentations",
|
||||
short_description: None,
|
||||
description: "Create or edit PowerPoint presentations.",
|
||||
dependencies: None,
|
||||
},
|
||||
SkillSelectionDocument {
|
||||
id: 30,
|
||||
name: "spreadsheets",
|
||||
short_description: None,
|
||||
description: "Analyze tabular data.",
|
||||
dependencies: None,
|
||||
},
|
||||
];
|
||||
|
||||
let selection = WeightedLexicalSkillSelector.select(
|
||||
"Use presentations to create a deck",
|
||||
&documents,
|
||||
/*limit*/ 20,
|
||||
);
|
||||
|
||||
assert_eq!(vec![20, 10], selection.candidate_ids);
|
||||
assert!(!selection.query_truncated);
|
||||
assert!(!selection.candidate_set_truncated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lexical_selector_uses_descriptions_and_drops_zero_score_candidates() {
|
||||
let documents = [
|
||||
SkillSelectionDocument {
|
||||
id: 1,
|
||||
name: "ci-helper",
|
||||
short_description: Some("Diagnose continuous integration failures."),
|
||||
description: "Inspect failing GitHub Actions checks and logs.",
|
||||
dependencies: None,
|
||||
},
|
||||
SkillSelectionDocument {
|
||||
id: 2,
|
||||
name: "document-editor",
|
||||
short_description: None,
|
||||
description: "Edit Word documents.",
|
||||
dependencies: None,
|
||||
},
|
||||
];
|
||||
|
||||
let selection = WeightedLexicalSkillSelector.select(
|
||||
"Please diagnose the failing GitHub Actions check",
|
||||
&documents,
|
||||
/*limit*/ 20,
|
||||
);
|
||||
|
||||
assert_eq!(vec![1], selection.candidate_ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lexical_selector_respects_requested_limit() {
|
||||
let names = (0..10)
|
||||
.map(|index| format!("lint-{index}"))
|
||||
.collect::<Vec<_>>();
|
||||
let documents = names
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(id, name)| SkillSelectionDocument {
|
||||
id,
|
||||
name,
|
||||
short_description: None,
|
||||
description: "Fix lint errors.",
|
||||
dependencies: None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let selection =
|
||||
WeightedLexicalSkillSelector.select("fix lint errors", &documents, /*limit*/ 3);
|
||||
|
||||
assert_eq!(3, selection.candidate_ids.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lexical_selector_reports_bounded_inputs() {
|
||||
let long_query = "match ".repeat(MAX_QUERY_BYTES);
|
||||
let names = (0..=MAX_CANDIDATES)
|
||||
.map(|index| format!("candidate-{index}"))
|
||||
.collect::<Vec<_>>();
|
||||
let documents = names
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(id, name)| SkillSelectionDocument {
|
||||
id,
|
||||
name,
|
||||
short_description: None,
|
||||
description: "match",
|
||||
dependencies: None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let selection = WeightedLexicalSkillSelector.select(&long_query, &documents, /*limit*/ 20);
|
||||
|
||||
assert!(selection.query_truncated);
|
||||
assert!(selection.candidate_set_truncated);
|
||||
assert_eq!(20, selection.candidate_ids.len());
|
||||
assert!(
|
||||
selection
|
||||
.candidate_ids
|
||||
.iter()
|
||||
.all(|id| *id < MAX_CANDIDATES)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lexical_selector_caps_query_terms() {
|
||||
let query = (0..=MAX_QUERY_TERMS)
|
||||
.map(|index| format!("term{index}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let documents = [SkillSelectionDocument {
|
||||
id: 1,
|
||||
name: "term0",
|
||||
short_description: None,
|
||||
description: "term0",
|
||||
dependencies: None,
|
||||
}];
|
||||
|
||||
let selection = WeightedLexicalSkillSelector.select(&query, &documents, /*limit*/ 20);
|
||||
|
||||
assert_eq!(MAX_QUERY_TERMS, selection.query_term_count);
|
||||
assert!(selection.query_truncated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lexical_selector_returns_nothing_for_stop_words_only() {
|
||||
let documents = [SkillSelectionDocument {
|
||||
id: 1,
|
||||
name: "anything",
|
||||
short_description: None,
|
||||
description: "Do anything.",
|
||||
dependencies: None,
|
||||
}];
|
||||
|
||||
let selection =
|
||||
WeightedLexicalSkillSelector.select("please use the", &documents, /*limit*/ 20);
|
||||
|
||||
assert_eq!(CheapSkillSelection::default(), selection);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selector_can_be_used_behind_the_shared_trait() {
|
||||
fn run(selector: &dyn CheapSkillSelector) -> CheapSkillSelection {
|
||||
selector.select(
|
||||
"review code",
|
||||
&[SkillSelectionDocument {
|
||||
id: 7,
|
||||
name: "code-review",
|
||||
short_description: None,
|
||||
description: "Review code.",
|
||||
dependencies: None,
|
||||
}],
|
||||
/*limit*/ 20,
|
||||
)
|
||||
}
|
||||
|
||||
assert_eq!(vec![7], run(&WeightedLexicalSkillSelector).candidate_ids);
|
||||
}
|
||||
Reference in New Issue
Block a user