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