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::Instant;
5
6use futures::StreamExt;
7use tracing::Instrument;
8
9use crate::evaluator::clamp;
10use crate::{Case, Dataset, Evaluator, Report, Score, Sink, SinkError, Target, Trial, TrialResult};
11
12/// An evaluation: a target run on every case of a dataset, a number of
13/// times, each run scored by every evaluator; the report goes to the sinks.
14///
15/// Each run is an `eval.trial` span (fields `eval.experiment`, `eval.case`,
16/// `eval.repetition`) inside an `eval.experiment` span, and the target's own
17/// spans (an agent's `invoke_agent`) nest in it. After scoring, each score is
18/// a `gen_ai.evaluation.result` event on the trial span, with the
19/// OpenTelemetry GenAI fields `gen_ai.evaluation.name`,
20/// `gen_ai.evaluation.score.value`, `gen_ai.evaluation.score.label` (the
21/// score's label, else `pass` or `fail`) and `gen_ai.evaluation.explanation`.
22pub struct Experiment {
23    name: String,
24    dataset: Dataset,
25    target: Option<Box<dyn Target>>,
26    evaluators: Vec<Box<dyn Evaluator>>,
27    repetitions: usize,
28    concurrency: usize,
29    thresholds: Vec<(String, f64)>,
30    sinks: Vec<Box<dyn Sink>>,
31}
32
33impl Experiment {
34    /// An experiment named `name`: one repetition, four runs at a time.
35    pub fn new(name: impl Into<String>) -> Self {
36        Self {
37            name: name.into(),
38            dataset: Dataset::default(),
39            target: None,
40            evaluators: Vec::new(),
41            repetitions: 1,
42            concurrency: 4,
43            thresholds: Vec::new(),
44            sinks: Vec::new(),
45        }
46    }
47
48    /// The cases to run.
49    #[must_use]
50    pub fn dataset(mut self, dataset: impl Into<Dataset>) -> Self {
51        self.dataset = dataset.into();
52        self
53    }
54
55    /// What to run.
56    #[must_use]
57    pub fn target(mut self, target: impl Target + 'static) -> Self {
58        self.target = Some(Box::new(target));
59        self
60    }
61
62    /// Add an evaluator. Each one scores every run.
63    #[must_use]
64    pub fn evaluator(mut self, evaluator: impl Evaluator + 'static) -> Self {
65        self.evaluators.push(Box::new(evaluator));
66        self
67    }
68
69    /// Run each case `repetitions` times, to measure how often a
70    /// nondeterministic target passes.
71    #[must_use]
72    pub fn repetitions(mut self, repetitions: usize) -> Self {
73        self.repetitions = repetitions;
74        self
75    }
76
77    /// Run at most `concurrency` trials at a time (0 counts as 1).
78    #[must_use]
79    pub fn concurrency(mut self, concurrency: usize) -> Self {
80        self.concurrency = concurrency;
81        self
82    }
83
84    /// The report passes only if `evaluator` passes at least `min_pass_rate`
85    /// (0 to 1) of the runs. Without one, an evaluator must pass every run.
86    #[must_use]
87    pub fn threshold(mut self, evaluator: impl Into<String>, min_pass_rate: f64) -> Self {
88        self.thresholds.push((evaluator.into(), min_pass_rate));
89        self
90    }
91
92    /// Add a sink for the report.
93    #[must_use]
94    pub fn sink(mut self, sink: impl Sink + 'static) -> Self {
95        self.sinks.push(Box::new(sink));
96        self
97    }
98
99    /// Run every case, score every run, and hand the report to the sinks.
100    ///
101    /// A target that fails makes a trial with an
102    /// [`error`](crate::Trial::error); an evaluator that fails makes a failed
103    /// score labelled `error`. Neither stops the experiment.
104    pub async fn run(&self) -> Result<Report, ExperimentError> {
105        let target = self.check()?;
106        let span = tracing::info_span!("eval.experiment", eval.experiment = %self.name);
107        // Lazy: a trial starts when buffer_unordered polls it.
108        let mut runs = Vec::with_capacity(self.dataset.cases.len() * self.repetitions);
109        for (index, case) in self.dataset.cases.iter().enumerate() {
110            for repetition in 1..=self.repetitions {
111                runs.push(self.trial(target, index, case, repetition, &span));
112            }
113        }
114        let mut trials: Vec<(usize, TrialResult)> = futures::stream::iter(runs)
115            .buffer_unordered(self.concurrency.max(1))
116            .collect()
117            .instrument(span.clone())
118            .await;
119        trials.sort_by_key(|(index, result)| (*index, result.trial.repetition));
120        let evaluators: Vec<String> = self
121            .evaluators
122            .iter()
123            .map(|e| e.name().to_owned())
124            .collect();
125        let report = Report::new(
126            self.name.clone(),
127            self.repetitions,
128            trials.into_iter().map(|(_, result)| result).collect(),
129            &evaluators,
130            &self.thresholds,
131        );
132        for sink in &self.sinks {
133            if let Err(source) = sink.record(&report).await {
134                return Err(ExperimentError::Sink {
135                    source,
136                    report: Box::new(report),
137                });
138            }
139        }
140        Ok(report)
141    }
142
143    /// The target, once the experiment is known to make sense.
144    fn check(&self) -> Result<&dyn Target, ExperimentError> {
145        let target = self.target.as_deref().ok_or(ExperimentError::NoTarget)?;
146        if self.dataset.cases.is_empty() {
147            return Err(ExperimentError::EmptyDataset);
148        }
149        if self.evaluators.is_empty() {
150            return Err(ExperimentError::NoEvaluators);
151        }
152        if self.repetitions == 0 {
153            return Err(ExperimentError::NoRepetitions);
154        }
155        let mut seen = HashSet::new();
156        if let Some(case) = self
157            .dataset
158            .cases
159            .iter()
160            .find(|case| !seen.insert(&case.id))
161        {
162            return Err(ExperimentError::DuplicateCase(case.id.clone()));
163        }
164        let mut seen = HashSet::new();
165        if let Some(evaluator) = self.evaluators.iter().find(|e| !seen.insert(e.name())) {
166            return Err(ExperimentError::DuplicateEvaluator(
167                evaluator.name().to_owned(),
168            ));
169        }
170        for (evaluator, min) in &self.thresholds {
171            if !seen.contains(evaluator.as_str()) {
172                return Err(ExperimentError::UnknownThreshold(evaluator.clone()));
173            }
174            if !(0.0..=1.0).contains(min) {
175                return Err(ExperimentError::InvalidThreshold {
176                    evaluator: evaluator.clone(),
177                    min_pass_rate: *min,
178                });
179            }
180        }
181        Ok(target)
182    }
183
184    /// Run `case` (number `index` in the dataset) once and score the run, in
185    /// an `eval.trial` span.
186    async fn trial(
187        &self,
188        target: &dyn Target,
189        index: usize,
190        case: &Case,
191        repetition: usize,
192        parent: &tracing::Span,
193    ) -> (usize, TrialResult) {
194        let span = tracing::info_span!(
195            parent: parent,
196            "eval.trial",
197            eval.experiment = %self.name,
198            eval.case = %case.id,
199            eval.repetition = repetition as i64,
200        );
201        async move {
202            let started = Instant::now();
203            let ran = target.run(case).await;
204            let mut trial = Trial::new(case.id.clone(), repetition, "");
205            trial.latency = started.elapsed();
206            match ran {
207                Ok(output) => {
208                    trial.output = output.output;
209                    trial.tool_calls = output.tool_calls;
210                    trial.usage = output.usage;
211                    trial.session_id = output.session_id;
212                }
213                Err(error) => trial.error = Some(error.to_string()),
214            }
215            let mut scores = Vec::with_capacity(self.evaluators.len());
216            for evaluator in &self.evaluators {
217                let name = evaluator.name();
218                let mut score = evaluator
219                    .evaluate(case, &trial)
220                    .await
221                    .unwrap_or_else(|error| {
222                        Score::fail(name, error.to_string()).with_label("error")
223                    });
224                score.evaluator = name.to_owned();
225                score.value = clamp(score.value);
226                let label =
227                    score
228                        .label
229                        .as_deref()
230                        .unwrap_or(if score.passed { "pass" } else { "fail" });
231                tracing::info!(
232                    gen_ai.evaluation.name = %score.evaluator,
233                    gen_ai.evaluation.score.value = score.value,
234                    gen_ai.evaluation.score.label = %label,
235                    gen_ai.evaluation.explanation = score.explanation.as_deref(),
236                    "gen_ai.evaluation.result"
237                );
238                scores.push(score);
239            }
240            (index, TrialResult { trial, scores })
241        }
242        .instrument(span)
243        .await
244    }
245}
246
247/// Why an experiment could not run, or could not deliver its report.
248#[derive(Debug, thiserror::Error)]
249#[non_exhaustive]
250pub enum ExperimentError {
251    /// No target was set.
252    #[error("the experiment has no target")]
253    NoTarget,
254    /// The dataset has no cases.
255    #[error("the dataset has no cases")]
256    EmptyDataset,
257    /// No evaluator was added.
258    #[error("the experiment has no evaluators")]
259    NoEvaluators,
260    /// Repetitions set to 0.
261    #[error("repetitions must be at least 1")]
262    NoRepetitions,
263    /// Two cases share an id.
264    #[error("two cases have the id {0:?}")]
265    DuplicateCase(String),
266    /// Two evaluators share a name; rename one with `named`.
267    #[error("two evaluators are named {0:?}; rename one with named()")]
268    DuplicateEvaluator(String),
269    /// A threshold names no evaluator of the experiment.
270    #[error("a threshold names {0:?}, which is not an evaluator of the experiment")]
271    UnknownThreshold(String),
272    /// A threshold outside 0..=1.
273    #[error("the threshold of {evaluator:?} is {min_pass_rate}; it must be from 0 to 1")]
274    InvalidThreshold {
275        /// The evaluator.
276        evaluator: String,
277        /// The threshold given.
278        min_pass_rate: f64,
279    },
280    /// A sink failed. The experiment ran: here is its report.
281    #[error("a sink failed: {source}")]
282    Sink {
283        /// The sink's error.
284        source: SinkError,
285        /// The report.
286        report: Box<Report>,
287    },
288}