1use 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
15pub 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 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 #[must_use]
53 pub fn dataset(mut self, dataset: impl Into<Dataset>) -> Self {
54 self.dataset = dataset.into();
55 self
56 }
57
58 #[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 #[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 #[must_use]
75 pub fn repetitions(mut self, repetitions: usize) -> Self {
76 self.repetitions = repetitions;
77 self
78 }
79
80 #[must_use]
82 pub fn concurrency(mut self, concurrency: usize) -> Self {
83 self.concurrency = concurrency;
84 self
85 }
86
87 #[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 #[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 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 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 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 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 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#[derive(Debug, thiserror::Error)]
272#[non_exhaustive]
273pub enum ExperimentError {
274 #[error("the experiment has no target")]
276 NoTarget,
277 #[error("the dataset has no cases")]
279 EmptyDataset,
280 #[error("the experiment has no evaluators")]
282 NoEvaluators,
283 #[error("repetitions must be at least 1")]
285 NoRepetitions,
286 #[error("two cases have the id {0:?}")]
288 DuplicateCase(String),
289 #[error("case {0:?} sets both input and turns; set one of them")]
291 InputAndTurns(String),
292 #[error("two evaluators are named {0:?}; rename one with named()")]
294 DuplicateEvaluator(String),
295 #[error("a threshold names {0:?}, which is not an evaluator of the experiment")]
297 UnknownThreshold(String),
298 #[error("the threshold of {evaluator:?} is {min_pass_rate}; it must be from 0 to 1")]
300 InvalidThreshold {
301 evaluator: String,
303 min_pass_rate: f64,
305 },
306 #[error("a sink failed: {source}")]
308 Sink {
309 source: SinkError,
311 report: Box<Report>,
313 },
314}