Skip to main content

rig_evals/
evaluator.rs

1//! Scoring a run.
2
3use rig_agent::completion::StructuredOutputError;
4use rig_core::completion::Usage;
5use rig_core::error::BoxError;
6use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
7use serde::{Deserialize, Serialize};
8
9use crate::{Case, Trial};
10
11/// One evaluator's verdict on one run.
12#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
13#[non_exhaustive]
14pub struct Score {
15    /// The evaluator's name. An experiment sets it to
16    /// [`Evaluator::name`].
17    pub evaluator: String,
18    /// From 0 (worst) to 1 (best).
19    pub value: f64,
20    /// Whether the run passes this evaluator.
21    pub passed: bool,
22    /// A category, such as a judge's grade; `"error"` when the evaluator
23    /// itself failed.
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub label: Option<String>,
26    /// Why, in words.
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    pub explanation: Option<String>,
29    /// Whether the evaluator could not apply to this run, such as a
30    /// reference the case lacks. Such a score is shown as N/A and left out
31    /// of pass rates and means; `passed` is false.
32    #[serde(default, skip_serializing_if = "is_false")]
33    pub not_applicable: bool,
34    /// The model tokens the evaluator spent, when it called a model (an
35    /// [`LlmJudge`](crate::LlmJudge)'s). The report adds them to its totals.
36    #[serde(default, skip_serializing_if = "Option::is_none")]
37    pub usage: Option<Usage>,
38}
39
40fn is_false(value: &bool) -> bool {
41    !value
42}
43
44impl Score {
45    /// A score of `value`, clamped to 0..=1 (`NaN` is 0).
46    pub fn new(evaluator: impl Into<String>, value: f64, passed: bool) -> Self {
47        Self {
48            evaluator: evaluator.into(),
49            value: clamp(value),
50            passed,
51            label: None,
52            explanation: None,
53            not_applicable: false,
54            usage: None,
55        }
56    }
57
58    /// Not applicable to the run, with why: shown as N/A and left out of
59    /// pass rates and means.
60    pub fn not_applicable(evaluator: impl Into<String>, explanation: impl Into<String>) -> Self {
61        Self {
62            not_applicable: true,
63            ..Self::new(evaluator, 0.0, false)
64                .with_label("n/a")
65                .with_explanation(explanation)
66        }
67    }
68
69    /// A pass: 1.
70    pub fn pass(evaluator: impl Into<String>) -> Self {
71        Self::new(evaluator, 1.0, true)
72    }
73
74    /// A failure: 0, with why.
75    pub fn fail(evaluator: impl Into<String>, explanation: impl Into<String>) -> Self {
76        Self::new(evaluator, 0.0, false).with_explanation(explanation)
77    }
78
79    /// Set the label.
80    #[must_use]
81    pub fn with_label(mut self, label: impl Into<String>) -> Self {
82        self.label = Some(label.into());
83        self
84    }
85
86    /// Set the explanation.
87    #[must_use]
88    pub fn with_explanation(mut self, explanation: impl Into<String>) -> Self {
89        self.explanation = Some(explanation.into());
90        self
91    }
92
93    /// Record the model tokens the evaluation spent.
94    #[must_use]
95    pub fn with_usage(mut self, usage: Usage) -> Self {
96        self.usage = Some(usage);
97        self
98    }
99}
100
101/// `value` within 0..=1; `NaN` is 0.
102pub(crate) fn clamp(value: f64) -> f64 {
103    if value.is_nan() {
104        0.0
105    } else {
106        value.clamp(0.0, 1.0)
107    }
108}
109
110/// Why an evaluator could not score a run. An experiment records it as a
111/// failed score labelled `"error"` and carries on.
112#[derive(Debug, thiserror::Error)]
113#[non_exhaustive]
114pub enum EvalError {
115    /// The case lacks the reference the evaluator compares with.
116    #[error("case {case:?} has no {field} to compare with")]
117    MissingReference {
118        /// The case.
119        case: String,
120        /// The missing field: `expected` or `trajectory`.
121        field: &'static str,
122    },
123    /// The judge model did not return a verdict. `LlmJudge` reports this as
124    /// a failed score labelled `error` (keeping the tokens it spent) instead.
125    #[error("the judge returned no verdict: {0}")]
126    Judge(#[from] StructuredOutputError),
127    /// Any other failure, such as a remote evaluator's.
128    #[error(transparent)]
129    Other(BoxError),
130}
131
132/// Scores runs.
133pub trait Evaluator: WasmCompatSend + WasmCompatSync {
134    /// Names the evaluator in scores, summaries and thresholds; unique
135    /// within an experiment.
136    fn name(&self) -> &str;
137
138    /// Score `trial`, a run of `case`. A trial whose target failed has an
139    /// [`error`](Trial::error); evaluators should fail it.
140    fn evaluate<'a>(
141        &'a self,
142        case: &'a Case,
143        trial: &'a Trial,
144    ) -> WasmBoxedFuture<'a, Result<Score, EvalError>>;
145
146    /// The score at or above which a run passes, for an evaluator with a
147    /// cutoff such as an [`LlmJudge`](crate::LlmJudge)'s threshold. The
148    /// report shows it next to the evaluator's results. `None`, the default,
149    /// for an evaluator without one.
150    fn pass_cutoff(&self) -> Option<f64> {
151        None
152    }
153
154    /// This evaluator under another name: to use two of a kind in one
155    /// experiment.
156    fn named(self, name: impl Into<String>) -> Named<Self>
157    where
158        Self: Sized,
159    {
160        Named {
161            name: name.into(),
162            inner: self,
163        }
164    }
165}
166
167/// An evaluator renamed by [`Evaluator::named`].
168pub struct Named<E> {
169    name: String,
170    inner: E,
171}
172
173impl<E: Evaluator> Evaluator for Named<E> {
174    fn name(&self) -> &str {
175        &self.name
176    }
177
178    fn evaluate<'a>(
179        &'a self,
180        case: &'a Case,
181        trial: &'a Trial,
182    ) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
183        self.inner.evaluate(case, trial)
184    }
185
186    fn pass_cutoff(&self) -> Option<f64> {
187        self.inner.pass_cutoff()
188    }
189}