1use serde::{Deserialize, Serialize};
6use serde_json::Value;
7use std::collections::HashMap;
8use std::time::Duration;
9
10use crate::cost_tracker::CostMetrics;
11use crate::structured_judge::StructuredVerdict;
12use crate::trace_analyzer::TraceAnalysis;
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct EvaluationReport {
17 pub run_id: String,
19 pub started_at: chrono::DateTime<chrono::Utc>,
21 pub completed_at: chrono::DateTime<chrono::Utc>,
23 pub duration: Duration,
25 pub results: Vec<EvaluationResult>,
27 pub summary: EvaluationSummary,
29}
30
31impl EvaluationReport {
32 pub fn new(
34 run_id: &str,
35 results: Vec<EvaluationResult>,
36 started_at: chrono::DateTime<chrono::Utc>,
37 ) -> Self {
38 let completed_at = chrono::Utc::now();
39 let duration = (completed_at - started_at).to_std().unwrap_or_default();
40 let summary = EvaluationSummary::from_results(&results);
41
42 Self { run_id: run_id.to_string(), started_at, completed_at, duration, results, summary }
43 }
44
45 pub fn all_passed(&self) -> bool {
49 self.summary.total > 0 && self.summary.failed == 0
50 }
51
52 pub fn failures(&self) -> Vec<&EvaluationResult> {
54 self.results.iter().filter(|r| !r.passed).collect()
55 }
56
57 pub fn format_summary(&self) -> String {
59 let mut output = String::new();
60 output.push_str(&format!("Evaluation Report: {}\n", self.run_id));
61 output.push_str(&format!("Duration: {:?}\n", self.duration));
62 output.push_str("\nSummary:\n");
63 output.push_str(&format!(" Total: {}\n", self.summary.total));
64 output.push_str(&format!(" Passed: {}\n", self.summary.passed));
65 output.push_str(&format!(" Failed: {}\n", self.summary.failed));
66 output.push_str(&format!(" Pass Rate: {:.1}%\n", self.summary.pass_rate * 100.0));
67
68 if !self.summary.avg_scores.is_empty() {
69 output.push_str("\nAverage Scores:\n");
70 for (criterion, score) in &self.summary.avg_scores {
71 output.push_str(&format!(" {}: {:.3}\n", criterion, score));
72 }
73 }
74
75 if self.summary.failed > 0 {
76 output.push_str("\nFailed Tests:\n");
77 for result in self.failures() {
78 output.push_str(&format!(
79 " - {} ({})\n",
80 result.eval_id,
81 result
82 .failures
83 .iter()
84 .map(|f| f.criterion.as_str())
85 .collect::<Vec<_>>()
86 .join(", ")
87 ));
88 }
89 }
90
91 output
92 }
93
94 pub fn to_json(&self) -> Result<String, serde_json::Error> {
96 serde_json::to_string_pretty(self)
97 }
98}
99
100#[derive(Debug, Clone, Default, Serialize, Deserialize)]
102pub struct EvaluationSummary {
103 pub total: usize,
105 pub passed: usize,
107 pub failed: usize,
109 pub pass_rate: f64,
111 pub avg_scores: HashMap<String, f64>,
113}
114
115impl EvaluationSummary {
116 pub fn from_results(results: &[EvaluationResult]) -> Self {
118 let total = results.len();
119 let passed = results.iter().filter(|r| r.passed).count();
120 let failed = total - passed;
121 let pass_rate = if total > 0 { passed as f64 / total as f64 } else { 0.0 };
122
123 let mut score_sums: HashMap<String, (f64, usize)> = HashMap::new();
125 for result in results {
126 for (criterion, score) in &result.scores {
127 let entry = score_sums.entry(criterion.clone()).or_insert((0.0, 0));
128 entry.0 += score;
129 entry.1 += 1;
130 }
131 }
132
133 let avg_scores =
134 score_sums.into_iter().map(|(k, (sum, count))| (k, sum / count as f64)).collect();
135
136 Self { total, passed, failed, pass_rate, avg_scores }
137 }
138}
139
140#[derive(Debug, Clone, Serialize, Deserialize)]
142pub struct EvaluationResult {
143 pub eval_id: String,
145 pub passed: bool,
147 pub scores: HashMap<String, f64>,
149 pub failures: Vec<Failure>,
151 pub duration: Duration,
153 #[serde(default)]
155 pub turn_results: Vec<TurnResult>,
156 #[serde(default, skip_serializing_if = "Option::is_none")]
158 pub cost_metrics: Option<CostMetrics>,
159 #[serde(default, skip_serializing_if = "Option::is_none")]
161 pub trace_analysis: Option<TraceAnalysis>,
162 #[serde(default)]
164 pub verdicts: Vec<StructuredVerdict>,
165}
166
167impl EvaluationResult {
168 pub fn passed(eval_id: &str, scores: HashMap<String, f64>, duration: Duration) -> Self {
170 Self {
171 eval_id: eval_id.to_string(),
172 passed: true,
173 scores,
174 failures: vec![],
175 duration,
176 turn_results: vec![],
177 cost_metrics: None,
178 trace_analysis: None,
179 verdicts: vec![],
180 }
181 }
182
183 pub fn failed(
185 eval_id: &str,
186 scores: HashMap<String, f64>,
187 failures: Vec<Failure>,
188 duration: Duration,
189 ) -> Self {
190 Self {
191 eval_id: eval_id.to_string(),
192 passed: false,
193 scores,
194 failures,
195 duration,
196 turn_results: vec![],
197 cost_metrics: None,
198 trace_analysis: None,
199 verdicts: vec![],
200 }
201 }
202
203 pub fn with_turn_results(mut self, turn_results: Vec<TurnResult>) -> Self {
205 self.turn_results = turn_results;
206 self
207 }
208}
209
210#[derive(Debug, Clone, Serialize, Deserialize)]
212pub struct Failure {
213 pub criterion: String,
215 pub expected: Value,
217 pub actual: Value,
219 pub score: f64,
221 pub threshold: f64,
223 #[serde(default)]
225 pub details: Option<String>,
226}
227
228impl Failure {
229 pub fn new(
231 criterion: &str,
232 expected: Value,
233 actual: Value,
234 score: f64,
235 threshold: f64,
236 ) -> Self {
237 Self { criterion: criterion.to_string(), expected, actual, score, threshold, details: None }
238 }
239
240 pub fn with_details(mut self, details: &str) -> Self {
242 self.details = Some(details.to_string());
243 self
244 }
245
246 pub fn format(&self) -> String {
248 let mut s = format!(
249 "{}: score {:.3} < threshold {:.3}",
250 self.criterion, self.score, self.threshold
251 );
252 if let Some(details) = &self.details {
253 s.push_str(&format!("\n Details: {}", details));
254 }
255 s
256 }
257}
258
259#[derive(Debug, Clone, Serialize, Deserialize)]
261pub struct TurnResult {
262 pub invocation_id: String,
264 pub actual_response: Option<String>,
266 pub expected_response: Option<String>,
268 pub actual_tool_calls: Vec<crate::schema::ToolUse>,
270 pub expected_tool_calls: Vec<crate::schema::ToolUse>,
272 #[serde(default, skip_serializing_if = "Option::is_none")]
274 pub actual_vision: Option<crate::vision::VisionAnswer>,
275 pub scores: HashMap<String, f64>,
277}
278
279pub type TestCaseResult = EvaluationResult;
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285
286 #[test]
287 fn test_evaluation_summary() {
288 let results = vec![
289 EvaluationResult::passed(
290 "test_1",
291 HashMap::from([("tool_trajectory".to_string(), 1.0)]),
292 Duration::from_millis(100),
293 ),
294 EvaluationResult::passed(
295 "test_2",
296 HashMap::from([("tool_trajectory".to_string(), 0.8)]),
297 Duration::from_millis(150),
298 ),
299 EvaluationResult::failed(
300 "test_3",
301 HashMap::from([("tool_trajectory".to_string(), 0.5)]),
302 vec![Failure::new("tool_trajectory", Value::Null, Value::Null, 0.5, 0.8)],
303 Duration::from_millis(200),
304 ),
305 ];
306
307 let summary = EvaluationSummary::from_results(&results);
308 assert_eq!(summary.total, 3);
309 assert_eq!(summary.passed, 2);
310 assert_eq!(summary.failed, 1);
311 assert!((summary.pass_rate - 0.666).abs() < 0.01);
312 }
313
314 #[test]
315 fn an_empty_report_has_not_passed() {
316 let report = EvaluationReport::new("run", vec![], chrono::Utc::now());
317 assert!(!report.all_passed());
318
319 let passed = EvaluationReport::new(
320 "run",
321 vec![EvaluationResult::passed("t", HashMap::new(), Duration::ZERO)],
322 chrono::Utc::now(),
323 );
324 assert!(passed.all_passed());
325 }
326
327 #[test]
328 fn test_failure_format() {
329 let failure = Failure::new(
330 "response_similarity",
331 Value::String("expected".to_string()),
332 Value::String("actual".to_string()),
333 0.6,
334 0.8,
335 )
336 .with_details("Responses differ significantly");
337
338 let formatted = failure.format();
339 assert!(formatted.contains("response_similarity"));
340 assert!(formatted.contains("0.600"));
341 assert!(formatted.contains("0.800"));
342 }
343}