Skip to main content

lc_evaluation/
criteria.rs

1//! Core evaluation types and traits: EvalError, Score, Example, Dataset,
2//! plus the Evaluator / Predictor traits.
3
4use async_trait::async_trait;
5use serde::{Deserialize, Serialize};
6
7/// Evaluation error
8#[derive(Debug, thiserror::Error)]
9#[non_exhaustive]
10pub enum EvalError {
11    /// Underlying IO error (e.g. file read failure).
12    #[error("IO error: {0}")]
13    IoError(String),
14    /// Data parse error (e.g. JSON/JSONL parse failure).
15    #[error("parse error: {0}")]
16    ParseError(String),
17    /// Embedding computation error.
18    #[error("embedding error: {0}")]
19    EmbeddingError(String),
20    /// Predictor execution error.
21    #[error("prediction error: {0}")]
22    PredictorError(String),
23    /// Prediction/reference sample counts differ in corpus-level evaluation (one-to-one).
24    #[error(
25        "length mismatch: {predictions} predictions vs {references} references; \
26         sample counts must match"
27    )]
28    LengthMismatch {
29        /// Prediction sample count
30        predictions: usize,
31        /// Reference sample count
32        references: usize,
33    },
34}
35
36/// P2-6: errors from the shared judge core (lc-core::judge) map into the evaluation error domain,
37/// so `structured_call(...).await?` works directly in a `Result<_, EvalError>` context.
38impl From<lc_core::judge::StructuredJudgeError> for EvalError {
39    fn from(e: lc_core::judge::StructuredJudgeError) -> Self {
40        match e {
41            lc_core::judge::StructuredJudgeError::Call(s) => EvalError::PredictorError(s),
42            lc_core::judge::StructuredJudgeError::Parse(s) => EvalError::ParseError(s),
43            // `StructuredJudgeError` is `#[non_exhaustive]`; forward any future
44            // variants to the generic predictor-error slot.
45            _ => EvalError::PredictorError(e.to_string()),
46        }
47    }
48}
49
50/// Evaluation score (0.0–1.0, 1.0 is best)
51#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct Score {
53    /// Score value (0.0–1.0)
54    pub value: f64,
55    /// Optional score label
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub label: Option<String>,
58}
59
60impl Score {
61    /// Constructs a score between 0.0 and 1.0.
62    ///
63    /// P2-8: Rust's `f64::clamp(0.0, 1.0)` returns NaN for NaN input, polluting
64    /// the summary mean/std. A NaN pre-check is done here, treating it as 0.0
65    /// (negative/positive infinity are left to `clamp` to converge to the bounds).
66    pub fn new(value: f64) -> Self {
67        let value = if value.is_nan() {
68            log::warn!("Score::new received NaN, treating as 0.0");
69            0.0
70        } else {
71            value
72        };
73        Self {
74            value: value.clamp(0.0, 1.0),
75            label: None,
76        }
77    }
78
79    /// Attaches a score label (builder style).
80    pub fn with_label(mut self, label: impl Into<String>) -> Self {
81        self.label = Some(label.into());
82        self
83    }
84}
85
86/// Evaluation example
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct Example {
89    /// Evaluation input
90    pub input: String,
91    /// Reference answer
92    pub reference: String,
93}
94
95impl Example {
96    /// Constructs an evaluation example.
97    pub fn new(input: impl Into<String>, reference: impl Into<String>) -> Self {
98        Self {
99            input: input.into(),
100            reference: reference.into(),
101        }
102    }
103}
104
105/// Dataset
106#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct Dataset {
108    /// Evaluation examples in the dataset
109    pub examples: Vec<Example>,
110}
111
112impl Dataset {
113    /// Constructs a dataset.
114    pub fn new(examples: Vec<Example>) -> Self {
115        Self { examples }
116    }
117
118    /// Loads from a JSONL file (one `{input, reference}` per line).
119    ///
120    /// P2-2: async I/O (`tokio::fs`), avoiding synchronous blocking in the async evaluation pipeline.
121    pub async fn from_jsonl(path: &str) -> Result<Self, EvalError> {
122        let content = tokio::fs::read_to_string(path)
123            .await
124            .map_err(|e| EvalError::IoError(e.to_string()))?;
125        let mut examples = Vec::new();
126        for (i, line) in content.lines().enumerate() {
127            let line = line.trim();
128            if line.is_empty() {
129                continue;
130            }
131            let ex: Example = serde_json::from_str(line)
132                .map_err(|e| EvalError::ParseError(format!("line {}: {}", i + 1, e)))?;
133            examples.push(ex);
134        }
135        Ok(Self { examples })
136    }
137
138    /// Returns the number of examples.
139    pub fn len(&self) -> usize {
140        self.examples.len()
141    }
142
143    /// Whether the dataset is empty.
144    pub fn is_empty(&self) -> bool {
145        self.examples.is_empty()
146    }
147}
148
149/// Evaluator trait
150#[async_trait]
151pub trait Evaluator: Send + Sync {
152    /// Scores a single prediction
153    async fn eval(
154        &self,
155        input: &str,
156        prediction: &str,
157        reference: &str,
158    ) -> Result<Score, EvalError>;
159
160    /// Evaluator name (used in report summaries)
161    fn name(&self) -> &str;
162}
163
164/// Pairwise-comparison evaluator trait (arena mode): judges which of two answers (A/B) for the same input is better.
165///
166/// P1-1: a first-class citizen alongside the pointwise `Evaluator`; `EvalRunner` accepts both,
167/// so arena evaluation also enters the unified report. Scoring: 1.0 = A wins, 0.5 = tie, 0.0 = B wins.
168#[async_trait]
169pub trait PairwiseEvaluator: Send + Sync {
170    /// Compares answers A and B, returning a 0-1 score
171    /// (1.0 = A wins, 0.5 = tie, 0.0 = B wins).
172    async fn eval_pair(&self, input: &str, a: &str, b: &str) -> Result<Score, EvalError>;
173
174    /// Evaluator name (used in report summaries)
175    fn name(&self) -> &str;
176}
177
178/// Predictor trait (the object under evaluation: LLMChain / Agent, etc.)
179#[async_trait]
180pub trait Predictor: Send + Sync {
181    /// Predicts on a single input, returning the text result.
182    async fn predict(&self, input: &str) -> Result<String, EvalError>;
183
184    /// Reports the token usage of the most recent [`predict`](Self::predict) call, if the
185    /// predictor meters it (E1). Defaults to `None` — evaluators with no token metering keep
186    /// the report's cost ledger at zero (zero behavior change).
187    async fn report_token_usage(&self) -> Option<crate::TokenUsage> {
188        None
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    #[test]
197    fn test_score_new_normal() {
198        assert!((Score::new(0.5).value - 0.5).abs() < 1e-9);
199    }
200
201    #[test]
202    fn test_score_new_clamps_overflow() {
203        assert_eq!(Score::new(2.0).value, 1.0);
204        assert_eq!(Score::new(-1.0).value, 0.0);
205        assert_eq!(Score::new(f64::INFINITY).value, 1.0);
206        assert_eq!(Score::new(f64::NEG_INFINITY).value, 0.0);
207    }
208
209    /// P2-8: NaN no longer passes through `.clamp(0.0, 1.0)` to pollute the summary statistics.
210    #[test]
211    fn test_score_new_nan_guarded() {
212        assert_eq!(Score::new(f64::NAN).value, 0.0);
213        // ensure NaN is cleaned up rather than lingering in the statistics
214        assert!(Score::new(f64::NAN).value.is_finite());
215    }
216
217    /// P2-2: from_jsonl reads the file asynchronously; a per-line parse failure carries the line number.
218    #[tokio::test]
219    async fn test_from_jsonl_async() {
220        let dir = tempfile::tempdir().unwrap();
221        let path = dir.path().join("data.jsonl");
222        std::fs::write(
223            &path,
224            "{\"input\":\"q1\",\"reference\":\"a1\"}\n\n{\"input\":\"q2\",\"reference\":\"a2\"}\n",
225        )
226        .unwrap();
227        let dataset = Dataset::from_jsonl(path.to_str().unwrap()).await.unwrap();
228        assert_eq!(dataset.len(), 2);
229        assert_eq!(dataset.examples[1].input, "q2");
230        assert_eq!(dataset.examples[1].reference, "a2");
231    }
232
233    #[tokio::test]
234    async fn test_from_jsonl_missing_file() {
235        let err = Dataset::from_jsonl("不存在-的文件.jsonl")
236            .await
237            .unwrap_err();
238        assert!(matches!(err, EvalError::IoError(_)));
239    }
240
241    #[tokio::test]
242    async fn test_from_jsonl_bad_line() {
243        let dir = tempfile::tempdir().unwrap();
244        let path = dir.path().join("bad.jsonl");
245        std::fs::write(&path, "{\"input\":\"q\"}\n").unwrap();
246        let err = Dataset::from_jsonl(path.to_str().unwrap())
247            .await
248            .unwrap_err();
249        assert!(matches!(err, EvalError::ParseError(_)));
250    }
251}