агенты: добавить поиск инструментов по каталогу
This commit is contained in:
1 parent
63f8ee333f
commit
99bd05c145
35 files changed
+2088
-155
No files matched your search
@@ -0,0 +1,237 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SearchableTool {
|
||||
pub name: String,
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub input_schema: Value,
|
||||
#[serde(default)]
|
||||
pub group_ids: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub group_context: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ToolSearchMatch {
|
||||
pub tool: SearchableTool,
|
||||
pub score: f64,
|
||||
}
|
||||
|
||||
pub fn search_tool_catalog(
|
||||
tools: &[SearchableTool],
|
||||
query: &str,
|
||||
group_ids: &[String],
|
||||
max_results: usize,
|
||||
) -> Vec<ToolSearchMatch> {
|
||||
let query_tokens = tokenize(query);
|
||||
if query_tokens.is_empty() || max_results == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let requested_groups = group_ids
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect::<BTreeSet<_>>();
|
||||
let candidates = tools
|
||||
.iter()
|
||||
.filter(|tool| {
|
||||
requested_groups.is_empty()
|
||||
|| tool
|
||||
.group_ids
|
||||
.iter()
|
||||
.any(|group_id| requested_groups.contains(group_id.as_str()))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if candidates.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let documents = candidates
|
||||
.iter()
|
||||
.map(|tool| weighted_tokens(tool))
|
||||
.collect::<Vec<_>>();
|
||||
let average_length =
|
||||
documents.iter().map(Vec::len).sum::<usize>() as f64 / documents.len() as f64;
|
||||
let candidate_count = documents.len();
|
||||
let document_frequency = document_frequency(&documents, &query_tokens);
|
||||
let normalized_query = query.trim().to_lowercase();
|
||||
|
||||
let mut matches = candidates
|
||||
.into_iter()
|
||||
.zip(documents)
|
||||
.filter_map(|(tool, document)| {
|
||||
let score = bm25_score(
|
||||
&document,
|
||||
&query_tokens,
|
||||
&document_frequency,
|
||||
candidate_count,
|
||||
average_length,
|
||||
) + exact_match_bonus(tool, &normalized_query);
|
||||
(score > 0.0).then(|| ToolSearchMatch {
|
||||
tool: tool.clone(),
|
||||
score,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
matches.sort_by(|left, right| {
|
||||
right
|
||||
.score
|
||||
.total_cmp(&left.score)
|
||||
.then_with(|| left.tool.name.cmp(&right.tool.name))
|
||||
});
|
||||
matches.truncate(max_results);
|
||||
matches
|
||||
}
|
||||
|
||||
fn weighted_tokens(tool: &SearchableTool) -> Vec<String> {
|
||||
let mut tokens = Vec::new();
|
||||
for _ in 0..3 {
|
||||
tokens.extend(tokenize(&tool.name));
|
||||
tokens.extend(tokenize(&tool.title));
|
||||
}
|
||||
tokens.extend(tokenize(&tool.description));
|
||||
for _ in 0..2 {
|
||||
tokens.extend(tokenize(&tool.group_context));
|
||||
}
|
||||
tokens
|
||||
}
|
||||
|
||||
fn document_frequency(
|
||||
documents: &[Vec<String>],
|
||||
query_tokens: &[String],
|
||||
) -> BTreeMap<String, usize> {
|
||||
let mut frequencies = BTreeMap::new();
|
||||
for query_token in query_tokens {
|
||||
let count = documents
|
||||
.iter()
|
||||
.filter(|document| document.iter().any(|token| token == query_token))
|
||||
.count();
|
||||
frequencies.insert(query_token.clone(), count);
|
||||
}
|
||||
frequencies
|
||||
}
|
||||
|
||||
fn bm25_score(
|
||||
document: &[String],
|
||||
query_tokens: &[String],
|
||||
document_frequency: &BTreeMap<String, usize>,
|
||||
document_count: usize,
|
||||
average_length: f64,
|
||||
) -> f64 {
|
||||
const K1: f64 = 1.2;
|
||||
const B: f64 = 0.75;
|
||||
|
||||
query_tokens.iter().fold(0.0, |score, token| {
|
||||
let term_frequency = document.iter().filter(|term| *term == token).count() as f64;
|
||||
if term_frequency == 0.0 {
|
||||
return score;
|
||||
}
|
||||
let frequency = document_frequency.get(token).copied().unwrap_or_default() as f64;
|
||||
let inverse_document_frequency =
|
||||
((document_count as f64 - frequency + 0.5) / (frequency + 0.5) + 1.0).ln();
|
||||
let length_ratio = if average_length > 0.0 {
|
||||
document.len() as f64 / average_length
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
let normalized_frequency =
|
||||
term_frequency * (K1 + 1.0) / (term_frequency + K1 * (1.0 - B + B * length_ratio));
|
||||
score + inverse_document_frequency * normalized_frequency
|
||||
})
|
||||
}
|
||||
|
||||
fn exact_match_bonus(tool: &SearchableTool, query: &str) -> f64 {
|
||||
if query.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let name = tool.name.to_lowercase();
|
||||
let title = tool.title.to_lowercase();
|
||||
if name == query || title == query {
|
||||
8.0
|
||||
} else if name.contains(query) || title.contains(query) {
|
||||
3.0
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
fn tokenize(value: &str) -> Vec<String> {
|
||||
value
|
||||
.to_lowercase()
|
||||
.split(|character: char| !character.is_alphanumeric())
|
||||
.filter(|token| token.chars().count() >= 2)
|
||||
.map(ToOwned::to_owned)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::{SearchableTool, search_tool_catalog};
|
||||
|
||||
fn tool(name: &str, title: &str, description: &str, group_ids: &[&str]) -> SearchableTool {
|
||||
SearchableTool {
|
||||
name: name.to_owned(),
|
||||
title: title.to_owned(),
|
||||
description: description.to_owned(),
|
||||
input_schema: json!({"type": "object"}),
|
||||
group_ids: group_ids.iter().map(|value| (*value).to_owned()).collect(),
|
||||
group_context: if group_ids.contains(&"finance") {
|
||||
"Finance invoices and payments".to_owned()
|
||||
} else {
|
||||
"Customer support tickets".to_owned()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranks_title_and_name_matches_above_description_matches() {
|
||||
let tools = vec![
|
||||
tool(
|
||||
"create_invoice",
|
||||
"Create invoice",
|
||||
"Issue a bill",
|
||||
&["finance"],
|
||||
),
|
||||
tool(
|
||||
"list_customers",
|
||||
"List customers",
|
||||
"Customers with invoices",
|
||||
&["support"],
|
||||
),
|
||||
];
|
||||
|
||||
let matches = search_tool_catalog(&tools, "create invoice", &[], 8);
|
||||
|
||||
assert_eq!(matches[0].tool.name, "create_invoice");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_candidates_by_group() {
|
||||
let tools = vec![
|
||||
tool(
|
||||
"create_invoice",
|
||||
"Create invoice",
|
||||
"Issue a bill",
|
||||
&["finance"],
|
||||
),
|
||||
tool(
|
||||
"create_ticket",
|
||||
"Create ticket",
|
||||
"Open a support case",
|
||||
&["support"],
|
||||
),
|
||||
];
|
||||
|
||||
let matches = search_tool_catalog(&tools, "create", &["support".to_owned()], 8);
|
||||
|
||||
assert_eq!(matches.len(), 1);
|
||||
assert_eq!(matches[0].tool.name, "create_ticket");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user