Skip to main content

rig_evals/
experiment.rs

1//! Running a target on a dataset and scoring every run.
2
3use std::collections::HashSet;
4use std::time::{Duration, Instant};
5
6use futures::StreamExt;
7use tracing::Instrument;
8
9use crate::evaluator::clamp;
10use crate::target::{TRIAL_DEADLINE, deadline_in, timeout_message};
11use crate::{
12    Case, Dataset, Evaluator, Report, Score, Sink, SinkError, Target, Trial, TrialResult,
13    TurnFailed,
14};
15
16/// An evaluation: a target run on every case of a dataset, a number of
17/// times, each run scored by every evaluator; the report goes to the sinks.
18///
19/// Each run is an `eval.trial` span (fields `eval.experiment`, `eval.case`,
20/// `eval.repetition`) inside an `eval.experiment` span, and the target's own
21/// spans (an agent's `invoke_agent`) nest in it. After scoring, each score is
22/// a `gen_ai.evaluation.result` event on the trial span, with the
23/// OpenTelemetry GenAI fields `gen_ai.evaluation.name`,
24/// `gen_ai.evaluation.score.value`, `gen_ai.evaluation.score.label` (the
25/// score's label, else `pass` or `fail`). The explanation is the judge's
26/// text, which can quote the agent's answer or the prompt, so it is recorded
27/// only with [`record_content`](Self::record_content).
28pub struct Experiment {
29    name: String,
30    dataset: Dataset,
31    target: Option<Box<dyn Target>>,
32    evaluators: Vec<Box<dyn Evaluator>>,
33    repetitions: usize,
34    concurrency: usize,
35    thresholds: Vec<(String, f64)>,
36    sinks: Vec<Box<dyn Sink>>,
37    trial_timeout: Option<Duration>,
38    record_content: bool,
39}
40
41impl Experiment {
42    /// An experiment named `name`: one repetition, four runs at a time.
43    pub fn new(name: impl Into<String>) -> Self {
44        Self {
45            name: name.into(),
46            dataset: Dataset::default(),
47            target: None,
48            evaluators: Vec::new(),
49            repetitions: 1,
50            concurrency: 4,
51            thresholds: Vec::new(),
52            sinks: Vec::new(),
53            trial_timeout: None,
54            record_content: false,
55        }
56    }
57
58    /// The cases to run.
59    #[must_use]
60    pub fn dataset(mut self, dataset: impl Into<Dataset>) -> Self {
61        self.dataset = dataset.into();
62        self
63    }
64
65    /// What to run.
66    #[must_use]
67    pub fn target(mut self, target: impl Target + 'static) -> Self {
68        self.target = Some(Box::new(target));
69        self
70    }
71
72    /// Add an evaluator. Each one scores every run.
73    #[must_use]
74    pub fn evaluator(mut self, evaluator: impl Evaluator + 'static) -> Self {
75        self.evaluators.push(Box::new(evaluator));
76        self
77    }
78
79    /// Run each case `repetitions` times, to measure how often a
80    /// nondeterministic target passes.
81    #[must_use]
82    pub fn repetitions(mut self, repetitions: usize) -> Self {
83        self.repetitions = repetitions;
84        self
85    }
86
87    /// Run at most `concurrency` trials at a time (0 counts as 1).
88    #[must_use]
89    pub fn concurrency(mut self, concurrency: usize) -> Self {
90        self.concurrency = concurrency;
91        self
92    }
93
94    /// The report passes only if `evaluator` passes at least `min_pass_rate`
95    /// (0 to 1) of the runs. Without one, an evaluator must pass every run.
96    #[must_use]
97    pub fn threshold(mut self, evaluator: impl Into<String>, min_pass_rate: f64) -> Self {
98        self.thresholds.push((evaluator.into(), min_pass_rate));
99        self
100    }
101
102    /// Add a sink for the report.
103    #[must_use]
104    pub fn sink(mut self, sink: impl Sink + 'static) -> Self {
105        self.sinks.push(Box::new(sink));
106        self
107    }
108
109    /// Record each score's explanation on its `gen_ai.evaluation.result`
110    /// event as `gen_ai.evaluation.explanation`. Off by default: the
111    /// explanation is the judge's text, which can quote the agent's answer or
112    /// the prompt, and telemetry is shared with the backend. The report keeps
113    /// the explanation either way.
114    #[must_use]
115    pub fn record_content(mut self, record: bool) -> Self {
116        self.record_content = record;
117        self
118    }
119
120    /// Give each target run and each evaluator call at most `limit`. One
121    /// that takes longer fails and the other trials carry on: a target that
122    /// times out makes a trial with the error `timed out after <n>s`, which
123    /// the built-in evaluators fail; an evaluator that times out gives a
124    /// failed score labelled `error`. An agent target keeps the turns it
125    /// completed, as a failed turn does.
126    ///
127    /// The limit is per trial, not per run, and per call: a trial with `n`
128    /// evaluators can take up to `n + 1` times `limit`. The turns of one
129    /// multi-turn case share the one limit (a five-turn case gets one limit
130    /// in all, not five). A timed-out judge's token usage is dropped, so the
131    /// report's judge tokens undercount. A limit too large for the clock
132    /// (such as `Duration::MAX`) is no limit. Needs a running tokio runtime,
133    /// since the limit is a `tokio::time` timer. Off unless set.
134    #[must_use]
135    pub fn trial_timeout(mut self, limit: Duration) -> Self {
136        self.trial_timeout = Some(limit);
137        self
138    }
139
140    /// Run every case, score every run, and hand the report to the sinks.
141    ///
142    /// A target that fails makes a trial with an
143    /// [`error`](crate::Trial::error); an evaluator that fails makes a failed
144    /// score labelled `error`. Neither stops the experiment.
145    pub async fn run(&self) -> Result<Report, ExperimentError> {
146        let target = self.check()?;
147        let span = tracing::info_span!("eval.experiment", eval.experiment = %self.name);
148        // Lazy: a trial starts when buffer_unordered polls it.
149        let mut runs = Vec::with_capacity(self.dataset.cases.len() * self.repetitions);
150        for (index, case) in self.dataset.cases.iter().enumerate() {
151            for repetition in 1..=self.repetitions {
152                runs.push(self.trial(target, index, case, repetition, &span));
153            }
154        }
155        let mut trials: Vec<(usize, TrialResult)> = futures::stream::iter(runs)
156            .buffer_unordered(self.concurrency.max(1))
157            .collect()
158            .instrument(span.clone())
159            .await;
160        trials.sort_by_key(|(index, result)| (*index, result.trial.repetition));
161        let evaluators: Vec<(String, Option<f64>)> = self
162            .evaluators
163            .iter()
164            .map(|e| (e.name().to_owned(), e.pass_cutoff()))
165            .collect();
166        let report = Report::new(
167            self.name.clone(),
168            self.repetitions,
169            trials.into_iter().map(|(_, result)| result).collect(),
170            &evaluators,
171            &self.thresholds,
172        );
173        for sink in &self.sinks {
174            if let Err(source) = sink.record(&report).await {
175                return Err(ExperimentError::Sink {
176                    source,
177                    report: Box::new(report),
178                });
179            }
180        }
181        Ok(report)
182    }
183
184    /// The target, once the experiment is known to make sense.
185    fn check(&self) -> Result<&dyn Target, ExperimentError> {
186        let target = self.target.as_deref().ok_or(ExperimentError::NoTarget)?;
187        if self.dataset.cases.is_empty() {
188            return Err(ExperimentError::EmptyDataset);
189        }
190        if let Some(case) = self
191            .dataset
192            .cases
193            .iter()
194            .find(|case| !case.input.is_empty() && !case.turns.is_empty())
195        {
196            return Err(ExperimentError::InputAndTurns(case.id.clone()));
197        }
198        if self.evaluators.is_empty() {
199            return Err(ExperimentError::NoEvaluators);
200        }
201        if self.repetitions == 0 {
202            return Err(ExperimentError::NoRepetitions);
203        }
204        let mut seen = HashSet::new();
205        if let Some(case) = self
206            .dataset
207            .cases
208            .iter()
209            .find(|case| !seen.insert(&case.id))
210        {
211            return Err(ExperimentError::DuplicateCase(case.id.clone()));
212        }
213        let mut seen = HashSet::new();
214        if let Some(evaluator) = self.evaluators.iter().find(|e| !seen.insert(e.name())) {
215            return Err(ExperimentError::DuplicateEvaluator(
216                evaluator.name().to_owned(),
217            ));
218        }
219        for (evaluator, min) in &self.thresholds {
220            if !seen.contains(evaluator.as_str()) {
221                return Err(ExperimentError::UnknownThreshold(evaluator.clone()));
222            }
223            if !(0.0..=1.0).contains(min) {
224                return Err(ExperimentError::InvalidThreshold {
225                    evaluator: evaluator.clone(),
226                    min_pass_rate: *min,
227                });
228            }
229        }
230        Ok(target)
231    }
232
233    /// Run `case` (number `index` in the dataset) once and score the run, in
234    /// an `eval.trial` span.
235    async fn trial(
236        &self,
237        target: &dyn Target,
238        index: usize,
239        case: &Case,
240        repetition: usize,
241        parent: &tracing::Span,
242    ) -> (usize, TrialResult) {
243        let span = tracing::info_span!(
244            parent: parent,
245            "eval.trial",
246            eval.experiment = %self.name,
247            eval.case = %case.id,
248            eval.repetition = repetition as i64,
249        );
250        async move {
251            let started = Instant::now();
252            let deadline = self.trial_timeout.and_then(deadline_in);
253            let run = TRIAL_DEADLINE.scope(deadline, target.run(case));
254            let ran = match deadline {
255                Some(deadline) => tokio::time::timeout_at(deadline.at, run)
256                    .await
257                    .unwrap_or_else(|_| Err(timeout_message(deadline.limit).into())),
258                None => run.await,
259            };
260            let mut trial = Trial::new(case.id.clone(), repetition, "");
261            trial.latency = started.elapsed();
262            match ran {
263                Ok(output) => {
264                    trial.output = output.output;
265                    trial.tool_calls = output.tool_calls;
266                    trial.usage = output.usage;
267                    trial.session_id = output.session_id;
268                    trial.transcript = output.transcript;
269                }
270                Err(error) => {
271                    // A multi-turn run that failed part way keeps the turns
272                    // it completed.
273                    if let Some(failed) = error.downcast_ref::<TurnFailed>() {
274                        trial.output = failed.partial.output.clone();
275                        trial.tool_calls = failed.partial.tool_calls.clone();
276                        trial.usage = failed.partial.usage;
277                        trial.session_id = failed.partial.session_id.clone();
278                        trial.transcript = failed.partial.transcript.clone();
279                    }
280                    trial.error = Some(error.to_string());
281                }
282            }
283            let mut scores = Vec::with_capacity(self.evaluators.len());
284            for evaluator in &self.evaluators {
285                let name = evaluator.name();
286                let failed =
287                    |explanation: String| Score::fail(name, explanation).with_label("error");
288                let mut score = match self.trial_timeout.and_then(deadline_in) {
289                    Some(deadline) => {
290                        match tokio::time::timeout_at(deadline.at, evaluator.evaluate(case, &trial))
291                            .await
292                        {
293                            Ok(result) => result.unwrap_or_else(|error| failed(error.to_string())),
294                            Err(_) => failed(timeout_message(deadline.limit)),
295                        }
296                    }
297                    None => evaluator
298                        .evaluate(case, &trial)
299                        .await
300                        .unwrap_or_else(|error| failed(error.to_string())),
301                };
302                score.evaluator = name.to_owned();
303                score.value = clamp(score.value);
304                let label =
305                    score
306                        .label
307                        .as_deref()
308                        .unwrap_or(if score.passed { "pass" } else { "fail" });
309                let explanation = if self.record_content {
310                    score.explanation.as_deref()
311                } else {
312                    None
313                };
314                tracing::info!(
315                    gen_ai.evaluation.name = %score.evaluator,
316                    gen_ai.evaluation.score.value = score.value,
317                    gen_ai.evaluation.score.label = %label,
318                    gen_ai.evaluation.explanation = explanation,
319                    "gen_ai.evaluation.result"
320                );
321                scores.push(score);
322            }
323            (index, TrialResult { trial, scores })
324        }
325        .instrument(span)
326        .await
327    }
328}
329
330/// Why an experiment could not run, or could not deliver its report.
331#[derive(Debug, thiserror::Error)]
332#[non_exhaustive]
333pub enum ExperimentError {
334    /// No target was set.
335    #[error("the experiment has no target")]
336    NoTarget,
337    /// The dataset has no cases.
338    #[error("the dataset has no cases")]
339    EmptyDataset,
340    /// No evaluator was added.
341    #[error("the experiment has no evaluators")]
342    NoEvaluators,
343    /// Repetitions set to 0.
344    #[error("repetitions must be at least 1")]
345    NoRepetitions,
346    /// Two cases share an id.
347    #[error("two cases have the id {0:?}")]
348    DuplicateCase(String),
349    /// A case sets both `input` and `turns`; it sets one of them.
350    #[error("case {0:?} sets both input and turns; set one of them")]
351    InputAndTurns(String),
352    /// Two evaluators share a name; rename one with `named`.
353    #[error("two evaluators are named {0:?}; rename one with named()")]
354    DuplicateEvaluator(String),
355    /// A threshold names no evaluator of the experiment.
356    #[error("a threshold names {0:?}, which is not an evaluator of the experiment")]
357    UnknownThreshold(String),
358    /// A threshold outside 0..=1.
359    #[error("the threshold of {evaluator:?} is {min_pass_rate}; it must be from 0 to 1")]
360    InvalidThreshold {
361        /// The evaluator.
362        evaluator: String,
363        /// The threshold given.
364        min_pass_rate: f64,
365    },
366    /// A sink failed. The experiment ran: here is its report.
367    #[error("a sink failed: {source}")]
368    Sink {
369        /// The sink's error.
370        source: SinkError,
371        /// The report.
372        report: Box<Report>,
373    },
374}