Skip to main content

rig_evals/
evaluator.rs

1//! Scoring a run.
2
3use rig_agent::completion::StructuredOutputError;
4use rig_core::error::BoxError;
5use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
6use serde::{Deserialize, Serialize};
7
8use crate::{Case, Trial};
9
10/// One evaluator's verdict on one run.
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12#[non_exhaustive]
13pub struct Score {
14    /// The evaluator's name. An experiment sets it to
15    /// [`Evaluator::name`].
16    pub evaluator: String,
17    /// From 0 (worst) to 1 (best).
18    pub value: f64,
19    /// Whether the run passes this evaluator.
20    pub passed: bool,
21    /// A category, such as a judge's grade; `"error"` when the evaluator
22    /// itself failed.
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub label: Option<String>,
25    /// Why, in words.
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub explanation: Option<String>,
28}
29
30impl Score {
31    /// A score of `value`, clamped to 0..=1 (`NaN` is 0).
32    pub fn new(evaluator: impl Into<String>, value: f64, passed: bool) -> Self {
33        Self {
34            evaluator: evaluator.into(),
35            value: clamp(value),
36            passed,
37            label: None,
38            explanation: None,
39        }
40    }
41
42    /// A pass: 1.
43    pub fn pass(evaluator: impl Into<String>) -> Self {
44        Self::new(evaluator, 1.0, true)
45    }
46
47    /// A failure: 0, with why.
48    pub fn fail(evaluator: impl Into<String>, explanation: impl Into<String>) -> Self {
49        Self::new(evaluator, 0.0, false).with_explanation(explanation)
50    }
51
52    /// Set the label.
53    #[must_use]
54    pub fn with_label(mut self, label: impl Into<String>) -> Self {
55        self.label = Some(label.into());
56        self
57    }
58
59    /// Set the explanation.
60    #[must_use]
61    pub fn with_explanation(mut self, explanation: impl Into<String>) -> Self {
62        self.explanation = Some(explanation.into());
63        self
64    }
65}
66
67/// `value` within 0..=1; `NaN` is 0.
68pub(crate) fn clamp(value: f64) -> f64 {
69    if value.is_nan() {
70        0.0
71    } else {
72        value.clamp(0.0, 1.0)
73    }
74}
75
76/// Why an evaluator could not score a run. An experiment records it as a
77/// failed score labelled `"error"` and carries on.
78#[derive(Debug, thiserror::Error)]
79#[non_exhaustive]
80pub enum EvalError {
81    /// The case lacks the reference the evaluator compares with.
82    #[error("case {case:?} has no {field} to compare with")]
83    MissingReference {
84        /// The case.
85        case: String,
86        /// The missing field: `expected` or `trajectory`.
87        field: &'static str,
88    },
89    /// The judge model did not return a verdict.
90    #[error("the judge returned no verdict: {0}")]
91    Judge(#[from] StructuredOutputError),
92    /// Any other failure, such as a remote evaluator's.
93    #[error(transparent)]
94    Other(BoxError),
95}
96
97/// Scores runs.
98pub trait Evaluator: WasmCompatSend + WasmCompatSync {
99    /// Names the evaluator in scores, summaries and thresholds; unique
100    /// within an experiment.
101    fn name(&self) -> &str;
102
103    /// Score `trial`, a run of `case`. A trial whose target failed has an
104    /// [`error`](Trial::error); evaluators should fail it.
105    fn evaluate<'a>(
106        &'a self,
107        case: &'a Case,
108        trial: &'a Trial,
109    ) -> WasmBoxedFuture<'a, Result<Score, EvalError>>;
110
111    /// This evaluator under another name: to use two of a kind in one
112    /// experiment.
113    fn named(self, name: impl Into<String>) -> Named<Self>
114    where
115        Self: Sized,
116    {
117        Named {
118            name: name.into(),
119            inner: self,
120        }
121    }
122}
123
124/// An evaluator renamed by [`Evaluator::named`].
125pub struct Named<E> {
126    name: String,
127    inner: E,
128}
129
130impl<E: Evaluator> Evaluator for Named<E> {
131    fn name(&self) -> &str {
132        &self.name
133    }
134
135    fn evaluate<'a>(
136        &'a self,
137        case: &'a Case,
138        trial: &'a Trial,
139    ) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
140        self.inner.evaluate(case, trial)
141    }
142}