Skip to main content

rig_evals/
evaluators.rs

1//! The built-in evaluators.
2//!
3//! | Evaluator | Name | Passes when |
4//! |---|---|---|
5//! | [`contains`], [`contains_all`] | `contains` | the answer contains every string |
6//! | [`regex()`] | `regex` | the answer matches the pattern |
7//! | [`equals`] | `equals` | the trimmed answer equals the case's `expected` |
8//! | [`json`] | `json` | the answer is JSON, with the required keys |
9//! | [`trajectory`] | `trajectory` | the tool calls match the case's `trajectory` |
10//! | [`budget`] | `budget` | tokens and latency are within limits |
11//! | [`no_error`] | `no_error` | the target did not fail |
12//! | [`LlmJudge`] | `llm_judge` | a judge model scores the answer at least the threshold |
13//! | [`LlmJudge::helpfulness`] | `helpfulness` | a judge model scores the answer at least the threshold: it does what was asked |
14//! | [`LlmJudge::faithfulness`] | `faithfulness` | a judge model scores the answer at least the threshold: it is supported by the evidence |
15//! | [`LlmJudge::goal_success`] | `goal_success` | a judge model scores the answer at least the threshold: the user's goal is met by the last turn |
16//!
17//! All of them fail a trial whose target failed.
18//! [`named`](crate::Evaluator::named) renames one, to use two of a kind.
19
20use std::time::Duration;
21
22use rig_core::wasm_compat::WasmBoxedFuture;
23use serde_json::Value;
24
25use crate::{Case, EvalError, Evaluator, ExpectedCall, Score, ToolCall, Trial};
26
27mod judge;
28
29pub use judge::{LlmJudge, Verdict};
30
31/// A failed score when the target failed.
32pub(crate) fn target_failed(name: &str, trial: &Trial) -> Option<Score> {
33    trial
34        .error
35        .as_ref()
36        .map(|error| Score::fail(name, format!("the target failed: {error}")))
37}
38
39/// An evaluator whose check is synchronous.
40fn ready<'a>(score: Result<Score, EvalError>) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
41    Box::pin(std::future::ready(score))
42}
43
44/// `found` of `total`, as a value from 0 to 1; 1 when there is nothing to
45/// find.
46fn ratio(found: usize, total: usize) -> f64 {
47    if total == 0 {
48        1.0
49    } else {
50        found as f64 / total as f64
51    }
52}
53
54/// See [`contains`].
55#[derive(Debug, Clone)]
56pub struct Contains {
57    needles: Vec<String>,
58    ignore_case: bool,
59}
60
61/// Passes when the answer contains `needle`.
62pub fn contains(needle: impl Into<String>) -> Contains {
63    contains_all([needle])
64}
65
66/// Passes when the answer contains every one of `needles`; the value is the
67/// share found.
68pub fn contains_all(needles: impl IntoIterator<Item = impl Into<String>>) -> Contains {
69    Contains {
70        needles: needles.into_iter().map(Into::into).collect(),
71        ignore_case: false,
72    }
73}
74
75impl Contains {
76    /// Ignore case.
77    #[must_use]
78    pub fn ignore_case(mut self) -> Self {
79        self.ignore_case = true;
80        self
81    }
82}
83
84impl Evaluator for Contains {
85    fn name(&self) -> &str {
86        "contains"
87    }
88
89    fn evaluate<'a>(
90        &'a self,
91        _case: &'a Case,
92        trial: &'a Trial,
93    ) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
94        if let Some(failed) = target_failed(self.name(), trial) {
95            return ready(Ok(failed));
96        }
97        let fold = |text: &str| {
98            if self.ignore_case {
99                text.to_lowercase()
100            } else {
101                text.to_owned()
102            }
103        };
104        let output = fold(&trial.output);
105        let missing: Vec<&str> = self
106            .needles
107            .iter()
108            .filter(|needle| !output.contains(&fold(needle)))
109            .map(String::as_str)
110            .collect();
111        let found = self.needles.len() - missing.len();
112        let score = Score::new(
113            self.name(),
114            ratio(found, self.needles.len()),
115            missing.is_empty(),
116        );
117        ready(Ok(if missing.is_empty() {
118            score
119        } else {
120            score.with_explanation(format!("missing {missing:?}"))
121        }))
122    }
123}
124
125/// See [`regex()`].
126#[derive(Debug, Clone)]
127pub struct Matches(regex::Regex);
128
129/// Passes when the answer matches `pattern` ([`regex`](https://docs.rs/regex)
130/// syntax; `(?i)` ignores case).
131pub fn regex(pattern: &str) -> Result<Matches, regex::Error> {
132    regex::Regex::new(pattern).map(Matches)
133}
134
135impl Evaluator for Matches {
136    fn name(&self) -> &str {
137        "regex"
138    }
139
140    fn evaluate<'a>(
141        &'a self,
142        _case: &'a Case,
143        trial: &'a Trial,
144    ) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
145        if let Some(failed) = target_failed(self.name(), trial) {
146            return ready(Ok(failed));
147        }
148        ready(Ok(if self.0.is_match(&trial.output) {
149            Score::pass(self.name())
150        } else {
151            Score::fail(self.name(), format!("does not match {}", self.0.as_str()))
152        }))
153    }
154}
155
156/// See [`equals`].
157#[derive(Debug, Clone, Default)]
158pub struct Equals {
159    ignore_case: bool,
160    skip_without_reference: bool,
161}
162
163/// Passes when the answer, trimmed, equals the case's `expected`, trimmed.
164/// A case without `expected` is an [`EvalError::MissingReference`].
165pub fn equals() -> Equals {
166    Equals::default()
167}
168
169impl Equals {
170    /// Ignore case.
171    #[must_use]
172    pub fn ignore_case(mut self) -> Self {
173        self.ignore_case = true;
174        self
175    }
176
177    /// Score a case without `expected` as not applicable (N/A) instead of
178    /// an error: for datasets that mix cases with and without an expected
179    /// answer.
180    #[must_use]
181    pub fn not_applicable_without_reference(mut self) -> Self {
182        self.skip_without_reference = true;
183        self
184    }
185}
186
187impl Evaluator for Equals {
188    fn name(&self) -> &str {
189        "equals"
190    }
191
192    fn evaluate<'a>(
193        &'a self,
194        case: &'a Case,
195        trial: &'a Trial,
196    ) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
197        if let Some(failed) = target_failed(self.name(), trial) {
198            return ready(Ok(failed));
199        }
200        let Some(expected) = &case.expected else {
201            if self.skip_without_reference {
202                return ready(Ok(Score::not_applicable(
203                    self.name(),
204                    "the case has no expected answer",
205                )));
206            }
207            return ready(Err(EvalError::MissingReference {
208                case: case.id.clone(),
209                field: "expected",
210            }));
211        };
212        let (expected, output) = (expected.trim(), trial.output.trim());
213        let equal = if self.ignore_case {
214            expected.to_lowercase() == output.to_lowercase()
215        } else {
216            expected == output
217        };
218        ready(Ok(if equal {
219            Score::pass(self.name())
220        } else {
221            Score::fail(
222                self.name(),
223                format!("expected {expected:?}, got {output:?}"),
224            )
225        }))
226    }
227}
228
229/// See [`json`].
230#[derive(Debug, Clone, Default)]
231pub struct Json {
232    required: Vec<String>,
233}
234
235/// Passes when the answer, trimmed, is JSON and, with
236/// [`require`](Json::require), an object with the required keys.
237pub fn json() -> Json {
238    Json::default()
239}
240
241impl Json {
242    /// Require the answer to be an object with `key`.
243    #[must_use]
244    pub fn require(mut self, key: impl Into<String>) -> Self {
245        self.required.push(key.into());
246        self
247    }
248}
249
250impl Evaluator for Json {
251    fn name(&self) -> &str {
252        "json"
253    }
254
255    fn evaluate<'a>(
256        &'a self,
257        _case: &'a Case,
258        trial: &'a Trial,
259    ) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
260        if let Some(failed) = target_failed(self.name(), trial) {
261            return ready(Ok(failed));
262        }
263        let value: Value = match serde_json::from_str(trial.output.trim()) {
264            Ok(value) => value,
265            Err(error) => return ready(Ok(Score::fail(self.name(), format!("not JSON: {error}")))),
266        };
267        if self.required.is_empty() {
268            return ready(Ok(Score::pass(self.name())));
269        }
270        let Some(object) = value.as_object() else {
271            return ready(Ok(Score::fail(self.name(), "not a JSON object")));
272        };
273        let missing: Vec<&str> = self
274            .required
275            .iter()
276            .filter(|key| !object.contains_key(key.as_str()))
277            .map(String::as_str)
278            .collect();
279        ready(Ok(if missing.is_empty() {
280            Score::pass(self.name())
281        } else {
282            Score::fail(self.name(), format!("missing keys {missing:?}"))
283        }))
284    }
285}
286
287/// How [`trajectory`] compares the tool calls with the expected ones.
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289#[non_exhaustive]
290pub enum TrajectoryMode {
291    /// The same calls in the same order, and no others.
292    Exact,
293    /// The expected calls in order; other calls may come between them.
294    InOrder,
295    /// The expected calls in any order; other calls may be made too.
296    AnyOrder,
297}
298
299/// See [`trajectory`].
300#[derive(Debug, Clone)]
301pub struct Trajectory {
302    mode: TrajectoryMode,
303    skip_without_reference: bool,
304}
305
306/// Passes when the tool calls match the case's `trajectory` in `mode`. The
307/// value is the share of expected calls matched. A case without a
308/// trajectory is an [`EvalError::MissingReference`], unless
309/// [`not_applicable_without_reference`](Trajectory::not_applicable_without_reference)
310/// is set, when it is not applicable (N/A).
311pub fn trajectory(mode: TrajectoryMode) -> Trajectory {
312    Trajectory {
313        mode,
314        skip_without_reference: false,
315    }
316}
317
318impl Trajectory {
319    /// Score a case without a `trajectory` as not applicable (N/A) instead
320    /// of an error: for datasets that mix cases with and without one.
321    #[must_use]
322    pub fn not_applicable_without_reference(mut self) -> Self {
323        self.skip_without_reference = true;
324        self
325    }
326}
327
328/// Whether `actual` is a call `expected` describes.
329fn call_matches(expected: &ExpectedCall, actual: &ToolCall) -> bool {
330    expected.name == actual.name
331        && expected
332            .args
333            .as_ref()
334            .is_none_or(|args| match (args, &actual.args) {
335                (Value::Object(want), Value::Object(got)) => {
336                    want.iter().all(|(key, value)| got.get(key) == Some(value))
337                }
338                (want, got) => want == got,
339            })
340}
341
342/// How many expected calls `actual` matches in `mode`, and the count that
343/// means a full match.
344fn matched(mode: TrajectoryMode, expected: &[ExpectedCall], actual: &[ToolCall]) -> (usize, usize) {
345    match mode {
346        TrajectoryMode::Exact => {
347            let pairs = expected
348                .iter()
349                .zip(actual)
350                .filter(|(want, got)| call_matches(want, got))
351                .count();
352            (pairs, expected.len().max(actual.len()))
353        }
354        TrajectoryMode::InOrder => {
355            let mut wanted = expected.iter().peekable();
356            for call in actual {
357                wanted.next_if(|want| call_matches(want, call));
358            }
359            (expected.len() - wanted.count(), expected.len())
360        }
361        TrajectoryMode::AnyOrder => {
362            // Calls with arguments first: a call without takes any leftover.
363            let mut free: Vec<&ToolCall> = actual.iter().collect();
364            let mut found = 0;
365            let specific = expected.iter().filter(|call| call.args.is_some());
366            let any = expected.iter().filter(|call| call.args.is_none());
367            for want in specific.chain(any) {
368                if let Some(at) = free.iter().position(|got| call_matches(want, got)) {
369                    free.swap_remove(at);
370                    found += 1;
371                }
372            }
373            (found, expected.len())
374        }
375    }
376}
377
378impl Evaluator for Trajectory {
379    fn name(&self) -> &str {
380        "trajectory"
381    }
382
383    fn evaluate<'a>(
384        &'a self,
385        case: &'a Case,
386        trial: &'a Trial,
387    ) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
388        if let Some(failed) = target_failed(self.name(), trial) {
389            return ready(Ok(failed));
390        }
391        let Some(expected) = &case.trajectory else {
392            if self.skip_without_reference {
393                return ready(Ok(Score::not_applicable(
394                    self.name(),
395                    "the case has no trajectory",
396                )));
397            }
398            return ready(Err(EvalError::MissingReference {
399                case: case.id.clone(),
400                field: "trajectory",
401            }));
402        };
403        let (found, total) = matched(self.mode, expected, &trial.tool_calls);
404        let passed = found == total;
405        let score = Score::new(self.name(), ratio(found, total), passed);
406        if passed {
407            return ready(Ok(score));
408        }
409        let want: Vec<&str> = expected.iter().map(|call| call.name.as_str()).collect();
410        let got: Vec<&str> = trial
411            .tool_calls
412            .iter()
413            .map(|call| call.name.as_str())
414            .collect();
415        ready(Ok(score.with_explanation(format!(
416            "expected {want:?} ({:?}), got {got:?}",
417            self.mode
418        ))))
419    }
420}
421
422/// See [`budget`].
423#[derive(Debug, Clone, Default)]
424pub struct Budget {
425    output_tokens: Option<u64>,
426    total_tokens: Option<u64>,
427    latency: Option<Duration>,
428}
429
430/// Passes when the run stays within the limits set. A token limit fails a
431/// run whose model did not report that count.
432pub fn budget() -> Budget {
433    Budget::default()
434}
435
436impl Budget {
437    /// At most `tokens` output tokens.
438    #[must_use]
439    pub fn max_output_tokens(mut self, tokens: u64) -> Self {
440        self.output_tokens = Some(tokens);
441        self
442    }
443
444    /// At most `tokens` tokens in all: the reported total, or input plus
445    /// output.
446    #[must_use]
447    pub fn max_total_tokens(mut self, tokens: u64) -> Self {
448        self.total_tokens = Some(tokens);
449        self
450    }
451
452    /// At most `latency` for the run.
453    #[must_use]
454    pub fn max_latency(mut self, latency: Duration) -> Self {
455        self.latency = Some(latency);
456        self
457    }
458}
459
460impl Evaluator for Budget {
461    fn name(&self) -> &str {
462        "budget"
463    }
464
465    fn evaluate<'a>(
466        &'a self,
467        _case: &'a Case,
468        trial: &'a Trial,
469    ) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
470        if let Some(failed) = target_failed(self.name(), trial) {
471            return ready(Ok(failed));
472        }
473        let usage = &trial.usage;
474        let total = usage
475            .total_tokens
476            .or(match (usage.input_tokens, usage.output_tokens) {
477                (None, None) => None,
478                (input, output) => Some(input.unwrap_or(0) + output.unwrap_or(0)),
479            });
480        let mut over = Vec::new();
481        for (what, limit, used) in [
482            ("output tokens", self.output_tokens, usage.output_tokens),
483            ("total tokens", self.total_tokens, total),
484        ] {
485            match (limit, used) {
486                (Some(limit), Some(used)) if used > limit => {
487                    over.push(format!("{what}: {used} > {limit}"));
488                }
489                (Some(_), None) => over.push(format!("{what}: not reported")),
490                _ => {}
491            }
492        }
493        if let Some(limit) = self.latency
494            && trial.latency > limit
495        {
496            over.push(format!("latency: {:?} > {limit:?}", trial.latency));
497        }
498        ready(Ok(if over.is_empty() {
499            Score::pass(self.name())
500        } else {
501            Score::fail(self.name(), over.join("; "))
502        }))
503    }
504}
505
506/// See [`no_error`].
507#[derive(Debug, Clone, Default)]
508pub struct NoError;
509
510/// Passes when the target did not fail.
511pub fn no_error() -> NoError {
512    NoError
513}
514
515impl Evaluator for NoError {
516    fn name(&self) -> &str {
517        "no_error"
518    }
519
520    fn evaluate<'a>(
521        &'a self,
522        _case: &'a Case,
523        trial: &'a Trial,
524    ) -> WasmBoxedFuture<'a, Result<Score, EvalError>> {
525        ready(Ok(
526            target_failed(self.name(), trial).unwrap_or_else(|| Score::pass(self.name()))
527        ))
528    }
529}