Skip to main content

lc_evaluation/
criteria.rs

1//! 评测核心类型与 trait:EvalError、Score、Example、Dataset,
2//! 以及 Evaluator / Predictor trait。
3
4use async_trait::async_trait;
5use serde::{Deserialize, Serialize};
6
7/// 评测错误
8#[derive(Debug, thiserror::Error)]
9#[non_exhaustive]
10pub enum EvalError {
11    /// 底层 IO 错误(如文件读取失败)。
12    #[error("IO error: {0}")]
13    IoError(String),
14    /// 数据解析错误(如 JSON/JSONL 解析失败)。
15    #[error("parse error: {0}")]
16    ParseError(String),
17    /// 嵌入(embedding)计算错误。
18    #[error("embedding error: {0}")]
19    EmbeddingError(String),
20    /// 预测器(predictor)执行错误。
21    #[error("prediction error: {0}")]
22    PredictorError(String),
23    /// corpus 级评测的预测/参考样本数不一致(逐条对应)。
24    #[error(
25        "length mismatch: {predictions} predictions vs {references} references; \
26         sample counts must match"
27    )]
28    LengthMismatch {
29        /// 预测样本数
30        predictions: usize,
31        /// 参考样本数
32        references: usize,
33    },
34}
35
36/// P2-6: 共享裁判内核(lc-core::judge)的错误映射进评测错误域,
37/// 让 `structured_call(...).await?` 在 `Result<_, EvalError>` 上下文里直接可用。
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/// 评测分数(0.0–1.0,1.0 为最佳)
51#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct Score {
53    /// 分数值(0.0–1.0)
54    pub value: f64,
55    /// 可选的分数标签
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub label: Option<String>,
58}
59
60impl Score {
61    /// 构造 0.0–1.0 之间的分数。
62    ///
63    /// P2-8: Rust 的 `f64::clamp(0.0, 1.0)` 对 NaN 返回 NaN,会污染
64    /// summary 均值/标准差。这里先做 NaN 前置检查,按 0.0 处理(负无穷、
65    /// 正无穷交给 `clamp` 收敛到边界)。
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    /// 附加分数标签(builder 风格)。
80    pub fn with_label(mut self, label: impl Into<String>) -> Self {
81        self.label = Some(label.into());
82        self
83    }
84}
85
86/// 评测样例
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct Example {
89    /// 评测输入
90    pub input: String,
91    /// 参考答案
92    pub reference: String,
93}
94
95impl Example {
96    /// 构造评测样例。
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/// 数据集
106#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct Dataset {
108    /// 数据集中的评测样例列表
109    pub examples: Vec<Example>,
110}
111
112impl Dataset {
113    /// 构造数据集。
114    pub fn new(examples: Vec<Example>) -> Self {
115        Self { examples }
116    }
117
118    /// 从 JSONL 文件加载(每行一个 ``{input, reference}``)。
119    ///
120    /// P2-2: 异步 I/O(`tokio::fs`),避免同步阻塞落在 async 评测链路里。
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    /// 返回样例数量。
139    pub fn len(&self) -> usize {
140        self.examples.len()
141    }
142
143    /// 数据集是否为空。
144    pub fn is_empty(&self) -> bool {
145        self.examples.is_empty()
146    }
147}
148
149/// 评测器 trait
150#[async_trait]
151pub trait Evaluator: Send + Sync {
152    /// 对单条预测打分
153    async fn eval(
154        &self,
155        input: &str,
156        prediction: &str,
157        reference: &str,
158    ) -> Result<Score, EvalError>;
159
160    /// 评测器名称(用于报告汇总)
161    fn name(&self) -> &str;
162}
163
164/// 成对比较评测器 trait(竞技场模式):对同一输入的 A/B 两个回答判优劣。
165///
166/// P1-1: 与单点 `Evaluator` 并列的一等公民,`EvalRunner` 同时收纳两种,
167/// 竞技场评测因此也能进统一报告。得分约定:1.0 = A 优、0.5 = 平局、0.0 = B 优。
168#[async_trait]
169pub trait PairwiseEvaluator: Send + Sync {
170    /// 比较 A、B 两个回答,返回 0-1 得分
171    /// (1.0 = A 优,0.5 = 平局,0.0 = B 优)。
172    async fn eval_pair(&self, input: &str, a: &str, b: &str) -> Result<Score, EvalError>;
173
174    /// 评测器名称(用于报告汇总)
175    fn name(&self) -> &str;
176}
177
178/// 预测器 trait(待评测的对象:LLMChain / Agent 等)
179#[async_trait]
180pub trait Predictor: Send + Sync {
181    /// 对单条输入进行预测,返回文本结果。
182    async fn predict(&self, input: &str) -> Result<String, EvalError>;
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188
189    #[test]
190    fn test_score_new_normal() {
191        assert!((Score::new(0.5).value - 0.5).abs() < 1e-9);
192    }
193
194    #[test]
195    fn test_score_new_clamps_overflow() {
196        assert_eq!(Score::new(2.0).value, 1.0);
197        assert_eq!(Score::new(-1.0).value, 0.0);
198        assert_eq!(Score::new(f64::INFINITY).value, 1.0);
199        assert_eq!(Score::new(f64::NEG_INFINITY).value, 0.0);
200    }
201
202    /// P2-8: NaN 不再穿透 `.clamp(0.0, 1.0)` 污染汇总统计。
203    #[test]
204    fn test_score_new_nan_guarded() {
205        assert_eq!(Score::new(f64::NAN).value, 0.0);
206        // 保证 NaN 被清掉,而不是残留在统计里
207        assert!(Score::new(f64::NAN).value.is_finite());
208    }
209
210    /// P2-2: from_jsonl 异步读文件,单行解析失败带行号。
211    #[tokio::test]
212    async fn test_from_jsonl_async() {
213        let dir = tempfile::tempdir().unwrap();
214        let path = dir.path().join("data.jsonl");
215        std::fs::write(
216            &path,
217            "{\"input\":\"q1\",\"reference\":\"a1\"}\n\n{\"input\":\"q2\",\"reference\":\"a2\"}\n",
218        )
219        .unwrap();
220        let dataset = Dataset::from_jsonl(path.to_str().unwrap()).await.unwrap();
221        assert_eq!(dataset.len(), 2);
222        assert_eq!(dataset.examples[1].input, "q2");
223        assert_eq!(dataset.examples[1].reference, "a2");
224    }
225
226    #[tokio::test]
227    async fn test_from_jsonl_missing_file() {
228        let err = Dataset::from_jsonl("不存在-的文件.jsonl")
229            .await
230            .unwrap_err();
231        assert!(matches!(err, EvalError::IoError(_)));
232    }
233
234    #[tokio::test]
235    async fn test_from_jsonl_bad_line() {
236        let dir = tempfile::tempdir().unwrap();
237        let path = dir.path().join("bad.jsonl");
238        std::fs::write(&path, "{\"input\":\"q\"}\n").unwrap();
239        let err = Dataset::from_jsonl(path.to_str().unwrap())
240            .await
241            .unwrap_err();
242        assert!(matches!(err, EvalError::ParseError(_)));
243    }
244}