1use 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
16pub 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 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 #[must_use]
60 pub fn dataset(mut self, dataset: impl Into<Dataset>) -> Self {
61 self.dataset = dataset.into();
62 self
63 }
64
65 #[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 #[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 #[must_use]
82 pub fn repetitions(mut self, repetitions: usize) -> Self {
83 self.repetitions = repetitions;
84 self
85 }
86
87 #[must_use]
89 pub fn concurrency(mut self, concurrency: usize) -> Self {
90 self.concurrency = concurrency;
91 self
92 }
93
94 #[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 #[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 #[must_use]
115 pub fn record_content(mut self, record: bool) -> Self {
116 self.record_content = record;
117 self
118 }
119
120 #[must_use]
135 pub fn trial_timeout(mut self, limit: Duration) -> Self {
136 self.trial_timeout = Some(limit);
137 self
138 }
139
140 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 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 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 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 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#[derive(Debug, thiserror::Error)]
332#[non_exhaustive]
333pub enum ExperimentError {
334 #[error("the experiment has no target")]
336 NoTarget,
337 #[error("the dataset has no cases")]
339 EmptyDataset,
340 #[error("the experiment has no evaluators")]
342 NoEvaluators,
343 #[error("repetitions must be at least 1")]
345 NoRepetitions,
346 #[error("two cases have the id {0:?}")]
348 DuplicateCase(String),
349 #[error("case {0:?} sets both input and turns; set one of them")]
351 InputAndTurns(String),
352 #[error("two evaluators are named {0:?}; rename one with named()")]
354 DuplicateEvaluator(String),
355 #[error("a threshold names {0:?}, which is not an evaluator of the experiment")]
357 UnknownThreshold(String),
358 #[error("the threshold of {evaluator:?} is {min_pass_rate}; it must be from 0 to 1")]
360 InvalidThreshold {
361 evaluator: String,
363 min_pass_rate: f64,
365 },
366 #[error("a sink failed: {source}")]
368 Sink {
369 source: SinkError,
371 report: Box<Report>,
373 },
374}