kkachi 0.1.8

High-performance, zero-copy library for optimizing language model prompts and programs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
// Copyright © 2025 lituus-io <spicyzhug@gmail.com>
// All Rights Reserved.
// Licensed under PolyForm Noncommercial 1.0.0

//! Metric trait and built-in implementations for evaluating LLM outputs.
//!
//! This module provides the [`Metric`] trait, which defines a standard interface
//! for scoring prediction quality against expected output. Built-in metrics cover
//! common evaluation patterns:
//!
//! - [`ExactMatch`]: Exact string equality (trimmed)
//! - [`Contains`]: Substring containment check
//! - [`F1Token`]: Word-level precision/recall/F1 score
//! - [`FnMetric`]: Closure wrapper for ad-hoc metrics
//!
//! All metrics return scores in the range `[0.0, 1.0]`.
//!
//! # Examples
//!
//! ```
//! use kkachi::metric::{Metric, ExactMatch, Contains, F1Token, FnMetric};
//!
//! // Exact match
//! let m = ExactMatch;
//! assert_eq!(m.evaluate("hello", "hello"), 1.0);
//! assert_eq!(m.evaluate("hello", "world"), 0.0);
//!
//! // Contains
//! let m = Contains;
//! assert_eq!(m.evaluate("the answer is 42", "42"), 1.0);
//! assert_eq!(m.evaluate("the answer is 41", "42"), 0.0);
//!
//! // F1 token overlap
//! let m = F1Token;
//! let score = m.evaluate("the quick brown fox", "the slow brown fox");
//! assert!(score > 0.5);
//!
//! // Custom closure metric
//! let m = FnMetric::new("length_ratio", |pred, expected| {
//!     let ratio = pred.len() as f64 / expected.len().max(1) as f64;
//!     ratio.min(1.0)
//! });
//! assert!(m.evaluate("abc", "abcd") > 0.5);
//! ```

use std::collections::HashMap;

/// Trait for evaluating prediction quality against expected output.
///
/// Implementations must be `Send + Sync` so they can be shared across threads
/// in async evaluation harnesses.
///
/// # Contract
///
/// - `evaluate` must return a value in `[0.0, 1.0]`.
/// - `1.0` indicates a perfect match.
/// - `0.0` indicates no match.
pub trait Metric: Send + Sync {
    /// Evaluate the prediction against the expected output.
    /// Returns a score between 0.0 and 1.0.
    fn evaluate(&self, prediction: &str, expected: &str) -> f64;

    /// Get the metric name.
    fn name(&self) -> &'static str;
}

// ---------------------------------------------------------------------------
// Blanket implementations
// ---------------------------------------------------------------------------

impl Metric for Box<dyn Metric> {
    #[inline]
    fn evaluate(&self, prediction: &str, expected: &str) -> f64 {
        (**self).evaluate(prediction, expected)
    }

    #[inline]
    fn name(&self) -> &'static str {
        (**self).name()
    }
}

impl<M: Metric> Metric for &M {
    #[inline]
    fn evaluate(&self, prediction: &str, expected: &str) -> f64 {
        (**self).evaluate(prediction, expected)
    }

    #[inline]
    fn name(&self) -> &'static str {
        (**self).name()
    }
}

// ---------------------------------------------------------------------------
// ExactMatch
// ---------------------------------------------------------------------------

/// Exact string match metric (trimmed).
///
/// Scores 1.0 when `prediction.trim() == expected.trim()`, 0.0 otherwise.
///
/// # Examples
///
/// ```
/// use kkachi::metric::{Metric, ExactMatch};
///
/// let m = ExactMatch;
/// assert_eq!(m.evaluate("  hello  ", "hello"), 1.0);
/// assert_eq!(m.evaluate("hello", "world"), 0.0);
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct ExactMatch;

impl Metric for ExactMatch {
    #[inline]
    fn evaluate(&self, prediction: &str, expected: &str) -> f64 {
        if prediction.trim() == expected.trim() {
            1.0
        } else {
            0.0
        }
    }

    #[inline]
    fn name(&self) -> &'static str {
        "exact_match"
    }
}

// ---------------------------------------------------------------------------
// Contains
// ---------------------------------------------------------------------------

/// Substring containment metric.
///
/// Scores 1.0 when `prediction.contains(expected)`, 0.0 otherwise.
/// Both sides are trimmed before the check.
///
/// # Examples
///
/// ```
/// use kkachi::metric::{Metric, Contains};
///
/// let m = Contains;
/// assert_eq!(m.evaluate("the answer is 42", "42"), 1.0);
/// assert_eq!(m.evaluate("the answer is 41", "42"), 0.0);
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct Contains;

impl Metric for Contains {
    #[inline]
    fn evaluate(&self, prediction: &str, expected: &str) -> f64 {
        if prediction.trim().contains(expected.trim()) {
            1.0
        } else {
            0.0
        }
    }

    #[inline]
    fn name(&self) -> &'static str {
        "contains"
    }
}

// ---------------------------------------------------------------------------
// F1Token
// ---------------------------------------------------------------------------

/// Word-level F1 score metric.
///
/// Tokenizes both strings by whitespace, computes precision and recall
/// over the token multisets, and returns their harmonic mean (F1 score).
///
/// This is commonly used in QA evaluation (e.g., SQuAD).
///
/// # Examples
///
/// ```
/// use kkachi::metric::{Metric, F1Token};
///
/// let m = F1Token;
///
/// // Identical strings
/// assert_eq!(m.evaluate("the quick brown fox", "the quick brown fox"), 1.0);
///
/// // Partial overlap
/// let score = m.evaluate("the quick brown fox", "the slow brown fox");
/// assert!(score > 0.5 && score < 1.0);
///
/// // No overlap
/// assert_eq!(m.evaluate("hello world", "foo bar"), 0.0);
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct F1Token;

impl F1Token {
    /// Tokenize a string into lowercased words.
    fn tokenize(s: &str) -> Vec<&str> {
        s.split_whitespace().collect()
    }

    /// Build a word frequency map.
    fn word_counts<'a>(tokens: &[&'a str]) -> HashMap<&'a str, u32> {
        let mut counts = HashMap::new();
        for &token in tokens {
            *counts.entry(token).or_insert(0) += 1;
        }
        counts
    }
}

impl Metric for F1Token {
    fn evaluate(&self, prediction: &str, expected: &str) -> f64 {
        let pred_tokens = Self::tokenize(prediction.trim());
        let exp_tokens = Self::tokenize(expected.trim());

        if pred_tokens.is_empty() && exp_tokens.is_empty() {
            return 1.0;
        }
        if pred_tokens.is_empty() || exp_tokens.is_empty() {
            return 0.0;
        }

        let pred_counts = Self::word_counts(&pred_tokens);
        let exp_counts = Self::word_counts(&exp_tokens);

        // Count shared tokens (intersection of multisets)
        let mut shared = 0u32;
        for (token, &pred_count) in &pred_counts {
            if let Some(&exp_count) = exp_counts.get(token) {
                shared += pred_count.min(exp_count);
            }
        }

        if shared == 0 {
            return 0.0;
        }

        let precision = shared as f64 / pred_tokens.len() as f64;
        let recall = shared as f64 / exp_tokens.len() as f64;

        // Harmonic mean (F1)
        2.0 * precision * recall / (precision + recall)
    }

    #[inline]
    fn name(&self) -> &'static str {
        "f1_token"
    }
}

// ---------------------------------------------------------------------------
// FnMetric
// ---------------------------------------------------------------------------

/// Closure-based metric for ad-hoc evaluation functions.
///
/// Wraps any `Fn(&str, &str) -> f64` closure as a [`Metric`] implementation.
/// Useful for one-off metrics or rapid prototyping.
///
/// # Examples
///
/// ```
/// use kkachi::metric::{Metric, FnMetric};
///
/// let m = FnMetric::new("starts_with", |pred, expected| {
///     if pred.starts_with(expected) { 1.0 } else { 0.0 }
/// });
///
/// assert_eq!(m.evaluate("hello world", "hello"), 1.0);
/// assert_eq!(m.evaluate("world hello", "hello"), 0.0);
/// ```
pub struct FnMetric<F>
where
    F: Fn(&str, &str) -> f64 + Send + Sync,
{
    name: &'static str,
    func: F,
}

impl<F> FnMetric<F>
where
    F: Fn(&str, &str) -> f64 + Send + Sync,
{
    /// Create a new closure-based metric with the given name.
    pub fn new(name: &'static str, func: F) -> Self {
        Self { name, func }
    }
}

impl<F> Metric for FnMetric<F>
where
    F: Fn(&str, &str) -> f64 + Send + Sync,
{
    #[inline]
    fn evaluate(&self, prediction: &str, expected: &str) -> f64 {
        (self.func)(prediction, expected)
    }

    #[inline]
    fn name(&self) -> &'static str {
        self.name
    }
}

impl<F> std::fmt::Debug for FnMetric<F>
where
    F: Fn(&str, &str) -> f64 + Send + Sync,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FnMetric")
            .field("name", &self.name)
            .finish()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // ---- ExactMatch ----

    #[test]
    fn test_exact_match_identical() {
        let m = ExactMatch;
        assert_eq!(m.evaluate("hello", "hello"), 1.0);
    }

    #[test]
    fn test_exact_match_with_whitespace() {
        let m = ExactMatch;
        assert_eq!(m.evaluate("  hello  ", "hello"), 1.0);
        assert_eq!(m.evaluate("hello", "  hello  "), 1.0);
        assert_eq!(m.evaluate("\thello\n", "hello"), 1.0);
    }

    #[test]
    fn test_exact_match_different() {
        let m = ExactMatch;
        assert_eq!(m.evaluate("hello", "world"), 0.0);
        assert_eq!(m.evaluate("Hello", "hello"), 0.0); // case-sensitive
    }

    #[test]
    fn test_exact_match_empty() {
        let m = ExactMatch;
        assert_eq!(m.evaluate("", ""), 1.0);
        assert_eq!(m.evaluate("  ", ""), 1.0);
        assert_eq!(m.evaluate("", "hello"), 0.0);
    }

    #[test]
    fn test_exact_match_name() {
        assert_eq!(ExactMatch.name(), "exact_match");
    }

    // ---- Contains ----

    #[test]
    fn test_contains_substring() {
        let m = Contains;
        assert_eq!(m.evaluate("the answer is 42", "42"), 1.0);
        assert_eq!(m.evaluate("42", "42"), 1.0);
    }

    #[test]
    fn test_contains_no_match() {
        let m = Contains;
        assert_eq!(m.evaluate("the answer is 41", "42"), 0.0);
    }

    #[test]
    fn test_contains_with_whitespace() {
        let m = Contains;
        assert_eq!(m.evaluate("  the answer is 42  ", "42"), 1.0);
        assert_eq!(m.evaluate("the answer is 42", "  42  "), 1.0);
    }

    #[test]
    fn test_contains_empty_expected() {
        let m = Contains;
        assert_eq!(m.evaluate("anything", ""), 1.0);
    }

    #[test]
    fn test_contains_name() {
        assert_eq!(Contains.name(), "contains");
    }

    // ---- F1Token ----

    #[test]
    fn test_f1_identical() {
        let m = F1Token;
        assert_eq!(
            m.evaluate("the quick brown fox", "the quick brown fox"),
            1.0
        );
    }

    #[test]
    fn test_f1_partial_overlap() {
        let m = F1Token;
        // 3 out of 4 tokens match: "the", "brown", "fox"
        // precision = 3/4, recall = 3/4, F1 = 3/4
        let score = m.evaluate("the quick brown fox", "the slow brown fox");
        assert!((score - 0.75).abs() < 1e-9, "score = {}", score);
    }

    #[test]
    fn test_f1_no_overlap() {
        let m = F1Token;
        assert_eq!(m.evaluate("hello world", "foo bar"), 0.0);
    }

    #[test]
    fn test_f1_empty_both() {
        let m = F1Token;
        assert_eq!(m.evaluate("", ""), 1.0);
    }

    #[test]
    fn test_f1_one_empty() {
        let m = F1Token;
        assert_eq!(m.evaluate("hello", ""), 0.0);
        assert_eq!(m.evaluate("", "hello"), 0.0);
    }

    #[test]
    fn test_f1_different_lengths() {
        let m = F1Token;
        // pred: "a b c d", exp: "a b"
        // shared = 2, precision = 2/4 = 0.5, recall = 2/2 = 1.0
        // F1 = 2 * 0.5 * 1.0 / (0.5 + 1.0) = 2/3
        let score = m.evaluate("a b c d", "a b");
        assert!((score - 2.0 / 3.0).abs() < 1e-9, "score = {}", score);
    }

    #[test]
    fn test_f1_repeated_tokens() {
        let m = F1Token;
        // pred: "a a b", exp: "a b b"
        // pred_counts: a=2, b=1; exp_counts: a=1, b=2
        // shared: min(2,1) + min(1,2) = 1 + 1 = 2
        // precision = 2/3, recall = 2/3, F1 = 2/3
        let score = m.evaluate("a a b", "a b b");
        assert!((score - 2.0 / 3.0).abs() < 1e-9, "score = {}", score);
    }

    #[test]
    fn test_f1_name() {
        assert_eq!(F1Token.name(), "f1_token");
    }

    // ---- FnMetric ----

    #[test]
    fn test_fn_metric_basic() {
        let m = FnMetric::new("custom", |pred, exp| if pred == exp { 1.0 } else { 0.0 });
        assert_eq!(m.evaluate("hello", "hello"), 1.0);
        assert_eq!(m.evaluate("hello", "world"), 0.0);
    }

    #[test]
    fn test_fn_metric_continuous() {
        let m = FnMetric::new("length_ratio", |pred, expected| {
            let ratio = pred.len() as f64 / expected.len().max(1) as f64;
            ratio.min(1.0)
        });
        assert_eq!(m.evaluate("abcd", "abcd"), 1.0);
        assert!((m.evaluate("ab", "abcd") - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_fn_metric_name() {
        let m = FnMetric::new("my_metric", |_, _| 0.5);
        assert_eq!(m.name(), "my_metric");
    }

    #[test]
    fn test_fn_metric_debug() {
        let m = FnMetric::new("test", |_, _| 0.0);
        let debug = format!("{:?}", m);
        assert!(debug.contains("FnMetric"));
        assert!(debug.contains("test"));
    }

    // ---- Blanket impls ----

    #[test]
    fn test_box_dyn_metric() {
        let m: Box<dyn Metric> = Box::new(ExactMatch);
        assert_eq!(m.evaluate("hello", "hello"), 1.0);
        assert_eq!(m.evaluate("hello", "world"), 0.0);
        assert_eq!(m.name(), "exact_match");
    }

    #[test]
    fn test_ref_metric() {
        let m = ExactMatch;
        let r: &ExactMatch = &m;
        assert_eq!(r.evaluate("hello", "hello"), 1.0);
        assert_eq!(r.name(), "exact_match");
    }

    #[test]
    fn test_metric_via_box_dyn_dispatch() {
        let metrics: Vec<Box<dyn Metric>> = vec![
            Box::new(ExactMatch),
            Box::new(Contains),
            Box::new(F1Token),
            Box::new(FnMetric::new("always_half", |_, _| 0.5)),
        ];

        for m in &metrics {
            let _ = m.evaluate("hello", "hello");
            let _ = m.name();
        }

        assert_eq!(metrics[0].evaluate("hello", "hello"), 1.0);
        assert_eq!(metrics[1].evaluate("hello world", "world"), 1.0);
        assert_eq!(metrics[2].evaluate("hello", "hello"), 1.0);
        assert_eq!(metrics[3].evaluate("anything", "anything"), 0.5);
    }

    // ---- Edge cases ----

    #[test]
    fn test_unicode_handling() {
        let m = ExactMatch;
        assert_eq!(m.evaluate("cafe\u{0301}", "cafe\u{0301}"), 1.0);

        let m = Contains;
        assert_eq!(m.evaluate("I ate at the cafe\u{0301}", "cafe\u{0301}"), 1.0);

        let m = F1Token;
        assert_eq!(m.evaluate("cafe\u{0301} latte", "cafe\u{0301} latte"), 1.0);
    }

    #[test]
    fn test_multiline_strings() {
        let m = ExactMatch;
        assert_eq!(m.evaluate("line1\nline2", "line1\nline2"), 1.0);

        let m = Contains;
        assert_eq!(m.evaluate("line1\nline2\nline3", "line2"), 1.0);
    }

    #[test]
    fn test_f1_single_token() {
        let m = F1Token;
        assert_eq!(m.evaluate("hello", "hello"), 1.0);
        assert_eq!(m.evaluate("hello", "world"), 0.0);
    }

    #[test]
    fn test_f1_superset() {
        let m = F1Token;
        // pred is superset of expected
        // shared = 2, precision = 2/4 = 0.5, recall = 2/2 = 1.0
        // F1 = 2 * 0.5 * 1.0 / 1.5 = 2/3
        let score = m.evaluate("a b c d", "a b");
        assert!((score - 2.0 / 3.0).abs() < 1e-9);

        // expected is superset of pred
        // shared = 2, precision = 2/2 = 1.0, recall = 2/4 = 0.5
        // F1 = 2 * 1.0 * 0.5 / 1.5 = 2/3
        let score = m.evaluate("a b", "a b c d");
        assert!((score - 2.0 / 3.0).abs() < 1e-9);
    }
}