Skip to main content

adk_eval/
report.rs

1//! Evaluation result reporting
2//!
3//! Structures for representing and formatting evaluation results.
4
5use 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/// Complete evaluation report for a test file or eval set
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct EvaluationReport {
17    /// Unique identifier for this evaluation run
18    pub run_id: String,
19    /// When the evaluation started
20    pub started_at: chrono::DateTime<chrono::Utc>,
21    /// When the evaluation completed
22    pub completed_at: chrono::DateTime<chrono::Utc>,
23    /// Total duration
24    pub duration: Duration,
25    /// Results for each test case
26    pub results: Vec<EvaluationResult>,
27    /// Summary statistics
28    pub summary: EvaluationSummary,
29}
30
31impl EvaluationReport {
32    /// Create a new report
33    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    /// Check if all tests passed
46    ///
47    /// A report without results has not passed: it evaluated nothing.
48    pub fn all_passed(&self) -> bool {
49        self.summary.total > 0 && self.summary.failed == 0
50    }
51
52    /// Get failed results only
53    pub fn failures(&self) -> Vec<&EvaluationResult> {
54        self.results.iter().filter(|r| !r.passed).collect()
55    }
56
57    /// Format as a human-readable string
58    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    /// Export to JSON
95    pub fn to_json(&self) -> Result<String, serde_json::Error> {
96        serde_json::to_string_pretty(self)
97    }
98}
99
100/// Summary statistics for an evaluation run
101#[derive(Debug, Clone, Default, Serialize, Deserialize)]
102pub struct EvaluationSummary {
103    /// Total number of test cases
104    pub total: usize,
105    /// Number of passed test cases
106    pub passed: usize,
107    /// Number of failed test cases
108    pub failed: usize,
109    /// Pass rate (0.0 - 1.0)
110    pub pass_rate: f64,
111    /// Average scores by criterion
112    pub avg_scores: HashMap<String, f64>,
113}
114
115impl EvaluationSummary {
116    /// Calculate summary from results
117    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        // Calculate average scores
124        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/// Result for a single test case
141#[derive(Debug, Clone, Serialize, Deserialize)]
142pub struct EvaluationResult {
143    /// Test case identifier
144    pub eval_id: String,
145    /// Whether the test passed all criteria
146    pub passed: bool,
147    /// Scores for each criterion
148    pub scores: HashMap<String, f64>,
149    /// Failures (criteria that didn't meet threshold)
150    pub failures: Vec<Failure>,
151    /// Execution duration
152    pub duration: Duration,
153    /// Detailed turn results
154    #[serde(default)]
155    pub turn_results: Vec<TurnResult>,
156    /// Cost and latency metrics (populated when CostTracker is active)
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub cost_metrics: Option<CostMetrics>,
159    /// Trace analysis results (populated when TraceAnalyzer is active)
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub trace_analysis: Option<TraceAnalysis>,
162    /// Structured verdicts from the judge
163    #[serde(default)]
164    pub verdicts: Vec<StructuredVerdict>,
165}
166
167impl EvaluationResult {
168    /// Create a passed result
169    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    /// Create a failed result
184    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    /// Add turn results
204    pub fn with_turn_results(mut self, turn_results: Vec<TurnResult>) -> Self {
205        self.turn_results = turn_results;
206        self
207    }
208}
209
210/// A single failure in evaluation
211#[derive(Debug, Clone, Serialize, Deserialize)]
212pub struct Failure {
213    /// Criterion that failed
214    pub criterion: String,
215    /// Expected value
216    pub expected: Value,
217    /// Actual value
218    pub actual: Value,
219    /// Score achieved
220    pub score: f64,
221    /// Threshold required
222    pub threshold: f64,
223    /// Additional details
224    #[serde(default)]
225    pub details: Option<String>,
226}
227
228impl Failure {
229    /// Create a new failure
230    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    /// Add details
241    pub fn with_details(mut self, details: &str) -> Self {
242        self.details = Some(details.to_string());
243        self
244    }
245
246    /// Format as human-readable string
247    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/// Result for a single conversation turn
260#[derive(Debug, Clone, Serialize, Deserialize)]
261pub struct TurnResult {
262    /// Turn/invocation identifier
263    pub invocation_id: String,
264    /// Actual response from the agent
265    pub actual_response: Option<String>,
266    /// Expected response
267    pub expected_response: Option<String>,
268    /// Actual tool calls made
269    pub actual_tool_calls: Vec<crate::schema::ToolUse>,
270    /// Expected tool calls
271    pub expected_tool_calls: Vec<crate::schema::ToolUse>,
272    /// Perception answer read from the turn's vision tool responses
273    #[serde(default, skip_serializing_if = "Option::is_none")]
274    pub actual_vision: Option<crate::vision::VisionAnswer>,
275    /// Scores for this turn
276    pub scores: HashMap<String, f64>,
277}
278
279/// Result for a single test case (alias for backward compatibility)
280pub 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}