1#![allow(clippy::needless_range_loop)] use crate::criteria::{ResponseMatchConfig, SimilarityAlgorithm, ToolTrajectoryConfig};
8use crate::schema::ToolUse;
9use std::collections::HashSet;
10
11fn unicode_tokenize(text: &str) -> impl Iterator<Item = &str> {
18 UnicodeTokenizer { text, pos: 0 }
19}
20
21struct UnicodeTokenizer<'a> {
22 text: &'a str,
23 pos: usize,
24}
25
26impl<'a> Iterator for UnicodeTokenizer<'a> {
27 type Item = &'a str;
28
29 fn next(&mut self) -> Option<Self::Item> {
30 while self.pos < self.text.len() {
32 if self.text[self.pos..].starts_with(char::is_whitespace) {
33 self.pos += self.text[self.pos..].chars().next().unwrap().len_utf8();
34 } else {
35 break;
36 }
37 }
38
39 if self.pos >= self.text.len() {
40 return None;
41 }
42
43 let start = self.pos;
44 let c = self.text[start..].chars().next().unwrap();
45
46 if is_cjk_char(c) {
48 self.pos += c.len_utf8();
49 return Some(&self.text[start..self.pos]);
50 }
51
52 while self.pos < self.text.len() {
54 let ch = self.text[self.pos..].chars().next().unwrap();
55 if ch.is_whitespace() || is_cjk_char(ch) {
56 break;
57 }
58 self.pos += ch.len_utf8();
59 }
60
61 Some(&self.text[start..self.pos])
62 }
63}
64
65fn is_cjk_char(c: char) -> bool {
67 matches!(c,
68 '\u{4e00}'..='\u{9fff}' | '\u{3400}'..='\u{4dbf}' | '\u{f900}'..='\u{faff}' | '\u{3040}'..='\u{309f}' | '\u{30a0}'..='\u{30ff}' | '\u{ac00}'..='\u{d7af}' )
75}
76
77pub struct ToolTrajectoryScorer {
79 config: ToolTrajectoryConfig,
80}
81
82impl ToolTrajectoryScorer {
83 pub fn new() -> Self {
85 Self { config: ToolTrajectoryConfig::default() }
86 }
87
88 pub fn with_config(config: ToolTrajectoryConfig) -> Self {
90 Self { config }
91 }
92
93 pub fn score(&self, expected: &[ToolUse], actual: &[ToolUse]) -> f64 {
98 if expected.is_empty() && actual.is_empty() {
99 return 1.0;
100 }
101 let matches = self.match_pairs(expected, actual).len();
102 matches as f64 / expected.len().max(actual.len()) as f64
103 }
104
105 fn match_pairs(&self, expected: &[ToolUse], actual: &[ToolUse]) -> Vec<(usize, usize)> {
110 let strict_args = self.config.strict_args;
111 let mut pairs = Vec::new();
112
113 if self.config.strict_order {
114 let mut next_actual = 0;
115 for (exp_idx, exp) in expected.iter().enumerate() {
116 if let Some(offset) =
117 actual[next_actual..].iter().position(|act| exp.matches(act, strict_args))
118 {
119 pairs.push((exp_idx, next_actual + offset));
120 next_actual += offset + 1;
121 }
122 }
123 } else {
124 let mut used = vec![false; actual.len()];
125 for (exp_idx, exp) in expected.iter().enumerate() {
126 if let Some(act_idx) =
127 (0..actual.len()).find(|&i| !used[i] && exp.matches(&actual[i], strict_args))
128 {
129 used[act_idx] = true;
130 pairs.push((exp_idx, act_idx));
131 }
132 }
133 }
134
135 pairs
136 }
137
138 pub fn compare(&self, expected: &[ToolUse], actual: &[ToolUse]) -> ToolTrajectoryComparison {
143 let pairs = self.match_pairs(expected, actual);
144 let mut expected_matched = vec![false; expected.len()];
145 let mut actual_matched = vec![false; actual.len()];
146 let mut matched = Vec::with_capacity(pairs.len());
147 for (exp_idx, act_idx) in pairs {
148 expected_matched[exp_idx] = true;
149 actual_matched[act_idx] = true;
150 matched.push((expected[exp_idx].clone(), actual[act_idx].clone()));
151 }
152
153 let missing = expected
154 .iter()
155 .zip(&expected_matched)
156 .filter(|(_, is_matched)| !**is_matched)
157 .map(|(tool, _)| tool.clone())
158 .collect();
159 let extra = actual
160 .iter()
161 .zip(&actual_matched)
162 .filter(|(_, is_matched)| !**is_matched)
163 .map(|(tool, _)| tool.clone())
164 .collect();
165
166 ToolTrajectoryComparison { matched, missing, extra, score: self.score(expected, actual) }
167 }
168}
169
170impl Default for ToolTrajectoryScorer {
171 fn default() -> Self {
172 Self::new()
173 }
174}
175
176#[derive(Debug, Clone)]
178pub struct ToolTrajectoryComparison {
179 pub matched: Vec<(ToolUse, ToolUse)>,
181 pub missing: Vec<ToolUse>,
183 pub extra: Vec<ToolUse>,
185 pub score: f64,
187}
188
189pub struct ResponseScorer {
191 config: ResponseMatchConfig,
192}
193
194impl ResponseScorer {
195 pub fn new() -> Self {
197 Self { config: ResponseMatchConfig::default() }
198 }
199
200 pub fn with_config(config: ResponseMatchConfig) -> Self {
202 Self { config }
203 }
204
205 pub fn score(&self, expected: &str, actual: &str) -> f64 {
207 let (expected, actual) = if self.config.normalize {
208 (self.normalize(expected), self.normalize(actual))
209 } else {
210 (expected.to_string(), actual.to_string())
211 };
212
213 match self.config.algorithm {
214 SimilarityAlgorithm::Exact => {
215 if expected == actual {
216 1.0
217 } else {
218 0.0
219 }
220 }
221 SimilarityAlgorithm::Contains => {
222 if actual.contains(&expected) || expected.contains(&actual) { 1.0 } else { 0.0 }
223 }
224 SimilarityAlgorithm::Levenshtein => self.levenshtein_similarity(&expected, &actual),
225 SimilarityAlgorithm::Jaccard => self.jaccard_similarity(&expected, &actual),
226 SimilarityAlgorithm::Rouge1 => self.rouge_n(&expected, &actual, 1),
227 SimilarityAlgorithm::Rouge2 => self.rouge_n(&expected, &actual, 2),
228 SimilarityAlgorithm::RougeL => self.rouge_l(&expected, &actual),
229 }
230 }
231
232 fn normalize(&self, text: &str) -> String {
234 let mut result = text.to_string();
235
236 if self.config.ignore_case {
237 result = result.to_lowercase();
238 }
239
240 if self.config.ignore_punctuation {
241 result = result.chars().filter(|c| c.is_alphanumeric() || c.is_whitespace()).collect();
242 }
243
244 result.split_whitespace().collect::<Vec<_>>().join(" ")
246 }
247
248 fn levenshtein_similarity(&self, a: &str, b: &str) -> f64 {
250 let distance = self.levenshtein_distance(a, b);
251 let max_len = a.chars().count().max(b.chars().count());
252 if max_len == 0 { 1.0 } else { 1.0 - (distance as f64 / max_len as f64) }
253 }
254
255 fn levenshtein_distance(&self, a: &str, b: &str) -> usize {
257 let a_chars: Vec<char> = a.chars().collect();
258 let b_chars: Vec<char> = b.chars().collect();
259 let m = a_chars.len();
260 let n = b_chars.len();
261
262 if m == 0 {
263 return n;
264 }
265 if n == 0 {
266 return m;
267 }
268
269 let mut dp = vec![vec![0; n + 1]; m + 1];
270
271 for i in 0..=m {
272 dp[i][0] = i;
273 }
274 for j in 0..=n {
275 dp[0][j] = j;
276 }
277
278 for i in 1..=m {
279 for j in 1..=n {
280 let cost = if a_chars[i - 1] == b_chars[j - 1] { 0 } else { 1 };
281 dp[i][j] = (dp[i - 1][j] + 1).min(dp[i][j - 1] + 1).min(dp[i - 1][j - 1] + cost);
282 }
283 }
284
285 dp[m][n]
286 }
287
288 fn jaccard_similarity(&self, a: &str, b: &str) -> f64 {
290 let a_words: HashSet<&str> = unicode_tokenize(a).collect();
291 let b_words: HashSet<&str> = unicode_tokenize(b).collect();
292
293 if a_words.is_empty() && b_words.is_empty() {
294 return 1.0;
295 }
296
297 let intersection = a_words.intersection(&b_words).count();
298 let union = a_words.union(&b_words).count();
299
300 if union == 0 { 0.0 } else { intersection as f64 / union as f64 }
301 }
302
303 fn rouge_n(&self, reference: &str, candidate: &str, n: usize) -> f64 {
305 let ref_ngrams = self.get_ngrams(reference, n);
306 let cand_ngrams = self.get_ngrams(candidate, n);
307
308 if ref_ngrams.is_empty() {
309 return if cand_ngrams.is_empty() { 1.0 } else { 0.0 };
310 }
311
312 let overlap = ref_ngrams.intersection(&cand_ngrams).count();
313 overlap as f64 / ref_ngrams.len() as f64
314 }
315
316 fn get_ngrams(&self, text: &str, n: usize) -> HashSet<Vec<String>> {
318 let words: Vec<String> = unicode_tokenize(text).map(|s| s.to_string()).collect();
319 if words.len() < n {
320 return HashSet::new();
321 }
322
323 words.windows(n).map(|w| w.to_vec()).collect()
324 }
325
326 fn rouge_l(&self, reference: &str, candidate: &str) -> f64 {
328 let ref_words: Vec<&str> = unicode_tokenize(reference).collect();
329 let cand_words: Vec<&str> = unicode_tokenize(candidate).collect();
330
331 if ref_words.is_empty() {
332 return if cand_words.is_empty() { 1.0 } else { 0.0 };
333 }
334
335 let lcs_len = self.lcs_length(&ref_words, &cand_words);
336
337 let precision =
339 if cand_words.is_empty() { 0.0 } else { lcs_len as f64 / cand_words.len() as f64 };
340 let recall = lcs_len as f64 / ref_words.len() as f64;
341
342 if precision + recall == 0.0 {
343 0.0
344 } else {
345 2.0 * precision * recall / (precision + recall)
346 }
347 }
348
349 fn lcs_length(&self, a: &[&str], b: &[&str]) -> usize {
351 let m = a.len();
352 let n = b.len();
353
354 if m == 0 || n == 0 {
355 return 0;
356 }
357
358 let mut dp = vec![vec![0; n + 1]; m + 1];
359
360 for i in 1..=m {
361 for j in 1..=n {
362 if a[i - 1] == b[j - 1] {
363 dp[i][j] = dp[i - 1][j - 1] + 1;
364 } else {
365 dp[i][j] = dp[i - 1][j].max(dp[i][j - 1]);
366 }
367 }
368 }
369
370 dp[m][n]
371 }
372}
373
374impl Default for ResponseScorer {
375 fn default() -> Self {
376 Self::new()
377 }
378}
379
380#[cfg(test)]
381mod tests {
382 use super::*;
383 use serde_json::json;
384
385 #[test]
386 fn test_tool_trajectory_exact_match() {
387 let scorer = ToolTrajectoryScorer::new();
388
389 let expected = vec![
390 ToolUse::new("get_weather").with_args(json!({"location": "NYC"})),
391 ToolUse::new("get_forecast").with_args(json!({"days": 3})),
392 ];
393
394 let actual = vec![
395 ToolUse::new("get_weather").with_args(json!({"location": "NYC"})),
396 ToolUse::new("get_forecast").with_args(json!({"days": 3})),
397 ];
398
399 assert_eq!(scorer.score(&expected, &actual), 1.0);
400 }
401
402 #[test]
403 fn test_tool_trajectory_partial_match() {
404 let scorer = ToolTrajectoryScorer::new();
405
406 let expected = vec![ToolUse::new("tool_a"), ToolUse::new("tool_b")];
407
408 let actual = vec![ToolUse::new("tool_a"), ToolUse::new("tool_c")];
409
410 let score = scorer.score(&expected, &actual);
411 assert!(score > 0.0 && score < 1.0);
412 }
413
414 #[test]
415 fn test_tool_trajectory_unordered() {
416 let scorer = ToolTrajectoryScorer::with_config(ToolTrajectoryConfig {
417 strict_order: false,
418 strict_args: false,
419 });
420
421 let expected = vec![ToolUse::new("tool_a"), ToolUse::new("tool_b")];
422
423 let actual = vec![ToolUse::new("tool_b"), ToolUse::new("tool_a")];
424
425 assert_eq!(scorer.score(&expected, &actual), 1.0);
426 }
427
428 #[test]
429 fn compare_honours_strict_order() {
430 let expected = vec![ToolUse::new("tool_a"), ToolUse::new("tool_b")];
431 let actual = vec![ToolUse::new("tool_b"), ToolUse::new("tool_a")];
432
433 let ordered = ToolTrajectoryScorer::new().compare(&expected, &actual);
434 assert_eq!(ordered.matched.len(), 1);
435 assert_eq!(ordered.matched[0].0.name, "tool_a");
436 assert_eq!(
437 ordered.missing.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(),
438 vec!["tool_b"]
439 );
440 assert_eq!(
441 ordered.extra.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(),
442 vec!["tool_b"]
443 );
444 assert_eq!(ordered.score, 0.5);
445
446 let unordered = ToolTrajectoryScorer::with_config(ToolTrajectoryConfig {
447 strict_order: false,
448 strict_args: false,
449 })
450 .compare(&expected, &actual);
451 assert_eq!(unordered.matched.len(), 2);
452 assert!(unordered.missing.is_empty());
453 assert!(unordered.extra.is_empty());
454 assert_eq!(unordered.score, 1.0);
455 }
456
457 #[test]
458 fn test_response_exact_match() {
459 let scorer = ResponseScorer::with_config(ResponseMatchConfig {
460 algorithm: SimilarityAlgorithm::Exact,
461 normalize: true,
462 ignore_case: true,
463 ignore_punctuation: false,
464 });
465
466 assert_eq!(scorer.score("Hello World", "hello world"), 1.0);
467 assert_eq!(scorer.score("Hello", "World"), 0.0);
468 }
469
470 #[test]
471 fn test_response_jaccard() {
472 let scorer = ResponseScorer::new();
473
474 let score = scorer.score("the quick brown fox", "the quick brown dog");
475 assert!(score > 0.5 && score < 1.0);
476 }
477
478 #[test]
479 fn test_response_levenshtein() {
480 let scorer = ResponseScorer::with_config(ResponseMatchConfig {
481 algorithm: SimilarityAlgorithm::Levenshtein,
482 ..Default::default()
483 });
484
485 let score = scorer.score("hello", "hallo");
486 assert!(score > 0.7);
487
488 let score = scorer.score("abc", "xyz");
489 assert!(score < 0.5);
490 }
491
492 #[test]
493 fn test_rouge_l() {
494 let scorer = ResponseScorer::with_config(ResponseMatchConfig {
495 algorithm: SimilarityAlgorithm::RougeL,
496 ..Default::default()
497 });
498
499 let score = scorer.score("the cat sat on the mat", "the cat was on the mat");
500 assert!(score > 0.7);
501 }
502}