1use 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
12pub 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 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 #[must_use]
50 pub fn dataset(mut self, dataset: impl Into<Dataset>) -> Self {
51 self.dataset = dataset.into();
52 self
53 }
54
55 #[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 #[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 #[must_use]
72 pub fn repetitions(mut self, repetitions: usize) -> Self {
73 self.repetitions = repetitions;
74 self
75 }
76
77 #[must_use]
79 pub fn concurrency(mut self, concurrency: usize) -> Self {
80 self.concurrency = concurrency;
81 self
82 }
83
84 #[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 #[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 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 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 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 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#[derive(Debug, thiserror::Error)]
249#[non_exhaustive]
250pub enum ExperimentError {
251 #[error("the experiment has no target")]
253 NoTarget,
254 #[error("the dataset has no cases")]
256 EmptyDataset,
257 #[error("the experiment has no evaluators")]
259 NoEvaluators,
260 #[error("repetitions must be at least 1")]
262 NoRepetitions,
263 #[error("two cases have the id {0:?}")]
265 DuplicateCase(String),
266 #[error("two evaluators are named {0:?}; rename one with named()")]
268 DuplicateEvaluator(String),
269 #[error("a threshold names {0:?}, which is not an evaluator of the experiment")]
271 UnknownThreshold(String),
272 #[error("the threshold of {evaluator:?} is {min_pass_rate}; it must be from 0 to 1")]
274 InvalidThreshold {
275 evaluator: String,
277 min_pass_rate: f64,
279 },
280 #[error("a sink failed: {source}")]
282 Sink {
283 source: SinkError,
285 report: Box<Report>,
287 },
288}