Skip to main content

adk_eval/
evaluator.rs

1//! Core evaluator implementation
2//!
3//! The Evaluator orchestrates test execution and applies evaluation criteria.
4
5use crate::cost_tracker::CostTracker;
6use crate::criteria::EvaluationCriteria;
7use crate::error::Result;
8use crate::llm_judge::LlmJudge;
9use crate::report::{EvaluationReport, EvaluationResult, Failure, TurnResult};
10use crate::schema::{EvalCase, SessionInput, TestFile, ToolUse, Turn};
11use crate::scoring::{ResponseScorer, ToolTrajectoryScorer};
12use crate::structured_judge::StructuredJudge;
13use crate::trace_analyzer::TraceAnalyzer;
14
15use adk_core::{
16    Agent, BudgetTracker, Content, Event, Llm, ModelCallScope, RunConfig, SessionId, UserId,
17};
18use adk_runner::Runner;
19use adk_session::{CreateRequest, InMemorySessionService, SessionService};
20use futures::StreamExt;
21use serde::{Deserialize, Serialize};
22use serde_json::Value;
23use std::collections::HashMap;
24use std::path::Path;
25use std::sync::Arc;
26use std::time::{Duration, Instant};
27
28#[cfg(feature = "embedding")]
29use crate::embedding_scorer::EmbeddingScorer;
30
31/// Configuration for the evaluator
32#[derive(Debug, Clone, Default, Serialize, Deserialize)]
33pub struct EvaluationConfig {
34    /// Evaluation criteria to apply
35    #[serde(default)]
36    pub criteria: EvaluationCriteria,
37    /// Whether to continue on failure
38    #[serde(default)]
39    pub continue_on_failure: bool,
40    /// Maximum time per test case
41    #[serde(default)]
42    pub timeout_per_case: Option<Duration>,
43    /// Number of retries for flaky tests
44    #[serde(default)]
45    pub retries: usize,
46    /// Whether to collect detailed turn results
47    #[serde(default = "default_true")]
48    pub collect_turn_details: bool,
49}
50
51fn default_true() -> bool {
52    true
53}
54
55impl EvaluationConfig {
56    /// Create config with specific criteria
57    pub fn with_criteria(criteria: EvaluationCriteria) -> Self {
58        Self { criteria, ..Default::default() }
59    }
60}
61
62/// The main evaluator struct
63pub struct Evaluator {
64    config: EvaluationConfig,
65    tool_scorer: ToolTrajectoryScorer,
66    response_scorer: ResponseScorer,
67    llm_judge: Option<LlmJudge>,
68    /// Optional structured judge for typed verdicts
69    structured_judge: Option<Arc<StructuredJudge>>,
70    /// Optional cost tracker for token usage and latency
71    cost_tracker: Option<CostTracker>,
72    /// Optional trace analyzer for detecting execution inefficiencies
73    trace_analyzer: Option<TraceAnalyzer>,
74    /// Optional embedding scorer for semantic similarity (requires `embedding` feature)
75    #[cfg(feature = "embedding")]
76    embedding_scorer: Option<Arc<EmbeddingScorer>>,
77    /// Optional conversation scorer for multi-turn metrics
78    conversation_scorer: Option<Arc<crate::conversation_scorer::ConversationScorer>>,
79    /// Run configuration of every eval run, whose budget, spend ledger and kill switches
80    /// also govern the judges
81    run_config: Option<RunConfig>,
82}
83
84/// The agent judge calls are attributed to in the spend ledger.
85pub const JUDGE_AGENT_NAME: &str = "eval-judge";
86
87impl Evaluator {
88    /// Create a new evaluator with default configuration
89    pub fn new(config: EvaluationConfig) -> Self {
90        let tool_scorer = if let Some(tc) = &config.criteria.tool_trajectory_config {
91            ToolTrajectoryScorer::with_config(tc.clone())
92        } else {
93            ToolTrajectoryScorer::new()
94        };
95
96        let response_scorer = if let Some(rc) = &config.criteria.response_match_config {
97            ResponseScorer::with_config(rc.clone())
98        } else {
99            ResponseScorer::new()
100        };
101
102        Self {
103            config,
104            tool_scorer,
105            response_scorer,
106            llm_judge: None,
107            structured_judge: None,
108            cost_tracker: None,
109            trace_analyzer: None,
110            #[cfg(feature = "embedding")]
111            embedding_scorer: None,
112            conversation_scorer: None,
113            run_config: None,
114        }
115    }
116
117    /// Create an evaluator with an LLM judge for semantic matching and rubric evaluation
118    pub fn with_llm_judge(config: EvaluationConfig, judge_model: Arc<dyn Llm>) -> Self {
119        let tool_scorer = if let Some(tc) = &config.criteria.tool_trajectory_config {
120            ToolTrajectoryScorer::with_config(tc.clone())
121        } else {
122            ToolTrajectoryScorer::new()
123        };
124
125        let response_scorer = if let Some(rc) = &config.criteria.response_match_config {
126            ResponseScorer::with_config(rc.clone())
127        } else {
128            ResponseScorer::new()
129        };
130
131        Self {
132            config,
133            tool_scorer,
134            response_scorer,
135            llm_judge: Some(LlmJudge::new(judge_model)),
136            structured_judge: None,
137            cost_tracker: None,
138            trace_analyzer: None,
139            #[cfg(feature = "embedding")]
140            embedding_scorer: None,
141            conversation_scorer: None,
142            run_config: None,
143        }
144    }
145
146    /// Set the LLM judge model
147    pub fn set_llm_judge(&mut self, judge_model: Arc<dyn Llm>) {
148        self.llm_judge = Some(LlmJudge::new(judge_model));
149    }
150
151    /// Check if LLM judge is available
152    pub fn has_llm_judge(&self) -> bool {
153        self.llm_judge.is_some()
154    }
155
156    /// Set the structured judge for typed verdict evaluation
157    pub fn set_structured_judge(&mut self, judge: Arc<StructuredJudge>) {
158        self.structured_judge = Some(judge);
159    }
160
161    /// Set the cost tracker for token usage and latency metrics
162    pub fn set_cost_tracker(&mut self, tracker: CostTracker) {
163        self.cost_tracker = Some(tracker);
164    }
165
166    /// Set the trace analyzer for execution inefficiency detection
167    pub fn set_trace_analyzer(&mut self, analyzer: TraceAnalyzer) {
168        self.trace_analyzer = Some(analyzer);
169    }
170
171    /// Set the embedding scorer for semantic similarity (requires `embedding` feature)
172    #[cfg(feature = "embedding")]
173    pub fn set_embedding_scorer(&mut self, scorer: Arc<EmbeddingScorer>) {
174        self.embedding_scorer = Some(scorer);
175    }
176
177    /// Set the conversation scorer for multi-turn metrics
178    pub fn set_conversation_scorer(
179        &mut self,
180        scorer: Arc<crate::conversation_scorer::ConversationScorer>,
181    ) {
182        self.conversation_scorer = Some(scorer);
183    }
184
185    /// Meters the evaluation: every eval run uses `config`, and the judges' calls count
186    /// against its budget and spend ledger and stop when one of its kill switches is frozen.
187    ///
188    /// A [`RunConfig::budget`] without a [`budget_tracker`](RunConfig::budget_tracker)
189    /// becomes one tracker shared by every run and judge call of the evaluation, so the
190    /// budget bounds the whole evaluation rather than each run. Judge spend is attributed
191    /// to the agent [`JUDGE_AGENT_NAME`] under the case's app name.
192    ///
193    /// A run or judge call the budget, the spend ledger or a kill switch refuses stops the
194    /// evaluation with [`EvalError::Refused`](crate::EvalError::Refused); it never counts
195    /// as a failed case.
196    ///
197    /// # Example
198    ///
199    /// ```
200    /// use adk_core::{GovernanceControl, RunBudget, RunConfig};
201    /// use adk_eval::{EvaluationConfig, EvaluationCriteria, Evaluator};
202    ///
203    /// let kill_switch = GovernanceControl::new();
204    /// let mut evaluator = Evaluator::new(EvaluationConfig::with_criteria(
205    ///     EvaluationCriteria::exact_tools(),
206    /// ));
207    /// evaluator.set_run_config(
208    ///     RunConfig::builder()
209    ///         .budget(RunBudget::new().max_model_calls(200))
210    ///         .governance(kill_switch.clone())
211    ///         .build(),
212    /// );
213    /// assert!(evaluator.run_config().unwrap().budget_tracker.is_some());
214    /// ```
215    pub fn set_run_config(&mut self, mut config: RunConfig) {
216        if config.budget_tracker.is_none()
217            && let Some(budget) = config.budget.clone()
218        {
219            config.budget_tracker = Some(Arc::new(BudgetTracker::new(budget)));
220        }
221        self.run_config = Some(config);
222    }
223
224    /// The run configuration set with [`set_run_config`](Self::set_run_config).
225    pub fn run_config(&self) -> Option<&RunConfig> {
226        self.run_config.as_ref()
227    }
228
229    /// The scope judge calls for a case of `app_name` meter against.
230    fn judge_scope(&self, app_name: &str) -> Option<ModelCallScope> {
231        self.run_config
232            .as_ref()
233            .map(|config| ModelCallScope::for_run(config, app_name, JUDGE_AGENT_NAME))
234    }
235
236    /// Fails with [`EvalError::Refused`](crate::EvalError::Refused) when a kill switch of
237    /// the run config is frozen or its budget is spent, before anything is sent.
238    pub(crate) fn check_allowed(&self) -> Result<()> {
239        let Some(config) = &self.run_config else { return Ok(()) };
240        config.check_governance().map_err(|e| crate::error::EvalError::Refused(Box::new(e)))?;
241        if let Some(tracker) = &config.budget_tracker {
242            tracker.check().map_err(|e| crate::error::EvalError::Refused(Box::new(e.into())))?;
243            if tracker.remaining().max_model_calls == Some(0) {
244                let usage = tracker.usage();
245                return Err(crate::error::EvalError::Refused(Box::new(adk_core::AdkError::new(
246                    adk_core::ErrorComponent::Eval,
247                    adk_core::ErrorCategory::ResourceExhausted,
248                    "budget.model_calls",
249                    format!(
250                        "budget exhausted: {} model calls used, none left for the evaluation",
251                        usage.model_calls
252                    ),
253                ))));
254            }
255        }
256        Ok(())
257    }
258
259    /// Check if a structured judge is configured
260    pub fn has_structured_judge(&self) -> bool {
261        self.structured_judge.is_some()
262    }
263
264    /// Check if a cost tracker is configured
265    pub fn has_cost_tracker(&self) -> bool {
266        self.cost_tracker.is_some()
267    }
268
269    /// Check if a trace analyzer is configured
270    pub fn has_trace_analyzer(&self) -> bool {
271        self.trace_analyzer.is_some()
272    }
273
274    /// Check if an embedding scorer is configured (requires `embedding` feature)
275    #[cfg(feature = "embedding")]
276    pub fn has_embedding_scorer(&self) -> bool {
277        self.embedding_scorer.is_some()
278    }
279
280    /// Check if a conversation scorer is configured
281    pub fn has_conversation_scorer(&self) -> bool {
282        self.conversation_scorer.is_some()
283    }
284
285    /// Fails when no criterion that can score a case is configured.
286    fn check_criteria(&self) -> Result<()> {
287        #[cfg(feature = "embedding")]
288        let embedding = self.embedding_scorer.is_some();
289        #[cfg(not(feature = "embedding"))]
290        let embedding = false;
291        if let Some(vision) = &self.config.criteria.vision {
292            vision.validate().map_err(crate::error::EvalError::ConfigError)?;
293        }
294        if !self.config.criteria.custom.is_empty() {
295            tracing::warn!(
296                eval.custom_criteria = self.config.criteria.custom.len(),
297                "custom criteria are not scored by the evaluator"
298            );
299        }
300        if self.config.criteria.has_criteria() || self.structured_judge.is_some() || embedding {
301            return Ok(());
302        }
303        Err(crate::error::EvalError::ConfigError(
304            "no evaluation criteria are configured, so no case can pass or fail; set a \
305             threshold in EvaluationCriteria (custom criteria are not scored by the \
306             evaluator) or attach a structured judge"
307                .to_string(),
308        ))
309    }
310
311    /// Evaluate a test file against an agent
312    ///
313    /// # Errors
314    ///
315    /// Returns an error when the file cannot be loaded or has no eval cases.
316    pub async fn evaluate_file(
317        &self,
318        agent: Arc<dyn Agent>,
319        path: impl AsRef<Path>,
320    ) -> Result<EvaluationReport> {
321        let test_file = TestFile::load(path)?;
322        self.evaluate_test_file(agent, &test_file).await
323    }
324
325    /// Evaluate a TestFile struct
326    ///
327    /// A case that cannot run (no turns, or an agent error) is reported as a failed case
328    /// with an `execution` failure.
329    ///
330    /// # Errors
331    ///
332    /// Returns [`EvalError::ConfigError`](crate::EvalError::ConfigError) when the file has
333    /// no eval cases or the evaluator has no criteria, since the report would otherwise
334    /// read as a pass, and [`EvalError::Refused`](crate::EvalError::Refused) when the
335    /// [run config](Self::set_run_config)'s budget, spend ledger or kill switch stops the
336    /// evaluation.
337    pub async fn evaluate_test_file(
338        &self,
339        agent: Arc<dyn Agent>,
340        test_file: &TestFile,
341    ) -> Result<EvaluationReport> {
342        self.check_test_file(test_file)?;
343        self.run_test_file(agent, test_file, self.config.continue_on_failure).await
344    }
345
346    /// Runs a test file `config.num_runs` times and summarises each case's pass rate,
347    /// score statistics and flakiness ([`MultiRunReport`](crate::MultiRunReport)).
348    ///
349    /// Every run evaluates every case, whatever
350    /// [`continue_on_failure`](EvaluationConfig::continue_on_failure) says, each case in a
351    /// fresh session. The same agent instance serves every run.
352    ///
353    /// When the [run config](Self::set_run_config)'s budget, spend ledger or kill switch
354    /// refuses a run or a judge call, the runs stop: the report keeps the runs that
355    /// completed and says why in [`stopped`](crate::MultiRunReport::stopped), and
356    /// [`all_passed`](crate::MultiRunReport::all_passed) is `false`.
357    ///
358    /// # Errors
359    ///
360    /// Returns [`EvalError::ConfigError`](crate::EvalError::ConfigError) when the file has
361    /// no eval cases or the evaluator has no criteria.
362    ///
363    /// # Example
364    ///
365    /// ```rust,no_run
366    /// use std::sync::Arc;
367    ///
368    /// use adk_core::Agent;
369    /// use adk_eval::{EvaluationConfig, EvaluationCriteria, Evaluator, MultiRunConfig, TestFile};
370    ///
371    /// async fn three_runs(agent: Arc<dyn Agent>, file: &TestFile) -> adk_eval::Result<()> {
372    ///     let evaluator = Evaluator::new(EvaluationConfig::with_criteria(
373    ///         EvaluationCriteria::exact_tools(),
374    ///     ));
375    ///     let report = evaluator.evaluate_test_file_runs(agent, file, &MultiRunConfig::new(3)?).await?;
376    ///     println!("{}", report.format_summary());
377    ///     Ok(())
378    /// }
379    /// ```
380    pub async fn evaluate_test_file_runs(
381        &self,
382        agent: Arc<dyn Agent>,
383        test_file: &TestFile,
384        config: &crate::multi_run::MultiRunConfig,
385    ) -> Result<crate::multi_run::MultiRunReport> {
386        self.check_test_file(test_file)?;
387        let mut runs = Vec::with_capacity(config.num_runs);
388        let mut stopped = None;
389        for run in 0..config.num_runs {
390            match self.run_test_file(agent.clone(), test_file, true).await {
391                Ok(report) => {
392                    tracing::info!(
393                        eval.set = %test_file.eval_set_id,
394                        eval.run = run + 1,
395                        eval.runs = config.num_runs,
396                        eval.passed = report.summary.passed,
397                        eval.failed = report.summary.failed,
398                        "eval run completed"
399                    );
400                    runs.push(report);
401                }
402                Err(e) if e.is_refusal() => {
403                    tracing::warn!(
404                        eval.set = %test_file.eval_set_id,
405                        eval.run = run + 1,
406                        error = %e,
407                        "eval runs stopped by a refusal"
408                    );
409                    stopped = Some(format!("run {} of {}: {e}", run + 1, config.num_runs));
410                    break;
411                }
412                Err(e) => return Err(e),
413            }
414        }
415        let report = crate::multi_run::MultiRunReport::from_runs(
416            &test_file.eval_set_id,
417            config.num_runs,
418            config.min_pass_rate,
419            runs,
420        );
421        Ok(match stopped {
422            Some(reason) => report.with_stopped(reason),
423            None => report,
424        })
425    }
426
427    /// Loads a test file and runs it `config.num_runs` times
428    /// ([`evaluate_test_file_runs`](Self::evaluate_test_file_runs)).
429    ///
430    /// # Errors
431    ///
432    /// Returns an error when the file cannot be loaded, has no eval cases, or the
433    /// evaluator has no criteria.
434    pub async fn evaluate_file_runs(
435        &self,
436        agent: Arc<dyn Agent>,
437        path: impl AsRef<Path>,
438        config: &crate::multi_run::MultiRunConfig,
439    ) -> Result<crate::multi_run::MultiRunReport> {
440        let test_file = TestFile::load(path)?;
441        self.evaluate_test_file_runs(agent, &test_file, config).await
442    }
443
444    /// Refuses a test file without cases and an evaluator without criteria.
445    fn check_test_file(&self, test_file: &TestFile) -> Result<()> {
446        if test_file.eval_cases.is_empty() {
447            return Err(crate::error::EvalError::ConfigError(format!(
448                "test file '{}' has no eval cases; add at least one case to evaluate",
449                test_file.eval_set_id
450            )));
451        }
452        self.check_criteria()
453    }
454
455    /// Evaluates the cases of `test_file` once, stopping at the first failed case unless
456    /// `continue_on_failure`, and at the first refusal.
457    async fn run_test_file(
458        &self,
459        agent: Arc<dyn Agent>,
460        test_file: &TestFile,
461        continue_on_failure: bool,
462    ) -> Result<EvaluationReport> {
463        let started_at = chrono::Utc::now();
464        let run_id = format!("{}_{}", test_file.eval_set_id, uuid::Uuid::new_v4());
465        let mut results = Vec::new();
466
467        for eval_case in &test_file.eval_cases {
468            let result = self.evaluate_case(agent.clone(), eval_case).await;
469
470            match result {
471                Ok(r) => {
472                    let passed = r.passed;
473                    results.push(r);
474                    if !passed && !continue_on_failure {
475                        break;
476                    }
477                }
478                Err(e) if e.is_refusal() => return Err(e),
479                Err(e) => {
480                    // Create a failed result for the error
481                    results.push(EvaluationResult::failed(
482                        &eval_case.eval_id,
483                        HashMap::new(),
484                        vec![Failure::new(
485                            "execution",
486                            Value::Null,
487                            Value::String(e.to_string()),
488                            0.0,
489                            1.0,
490                        )],
491                        Duration::from_secs(0),
492                    ));
493                    if !continue_on_failure {
494                        break;
495                    }
496                }
497            }
498        }
499
500        Ok(EvaluationReport::new(&run_id, results, started_at))
501    }
502
503    /// Evaluate a single test case
504    ///
505    /// The turns run in order through one session of an in-memory session service, so
506    /// each turn sees the conversation history of the turns before it, as it would in a
507    /// [`Runner`]. The session is created from the case's
508    /// [`session_input`](EvalCase::session_input): its `app_name` and `user_id` (default
509    /// `eval_app` and `eval_user` when empty) and its initial `state`.
510    ///
511    /// Each criterion's case score is the arithmetic mean of its per-turn scores. Cost
512    /// and trace analysis use the events from every turn of this run.
513    ///
514    /// A case passes only when at least one criterion was evaluated and none failed. A case
515    /// that no configured criterion applies to (for example `semantic_match_score` with no
516    /// expected response in any turn) fails with a `not_evaluated` failure.
517    ///
518    /// # Errors
519    ///
520    /// Returns [`EvalError::ConfigError`](crate::EvalError::ConfigError) when the case has
521    /// no turns or the evaluator has no criteria,
522    /// [`EvalError::Refused`](crate::EvalError::Refused) when the
523    /// [run config](Self::set_run_config)'s budget, spend ledger or kill switch refuses a
524    /// run or a judge call, and an error when the session cannot be created from
525    /// `session_input`, the agent fails to start, or its event stream yields an error.
526    pub async fn evaluate_case(
527        &self,
528        agent: Arc<dyn Agent>,
529        eval_case: &EvalCase,
530    ) -> Result<EvaluationResult> {
531        if eval_case.conversation.is_empty() {
532            return Err(crate::error::EvalError::ConfigError(format!(
533                "eval case '{}' has no conversation turns; add at least one turn to evaluate",
534                eval_case.eval_id
535            )));
536        }
537        self.check_criteria()?;
538        if let Some(image) = eval_case.unloaded_images().first() {
539            return Err(crate::error::EvalError::ConfigError(format!(
540                "eval case '{}' shows image {}, which was not loaded and verified against its \
541                 digest; load the eval file with TestFile::load or EvalSet::load, or call \
542                 EvalCase::load_images",
543                eval_case.eval_id, image.path
544            )));
545        }
546        self.check_allowed()?;
547        match self.judge_scope(app_name_of(&eval_case.session_input)) {
548            Some(scope) => scope.within(self.run_case(agent, eval_case)).await,
549            None => self.run_case(agent, eval_case).await,
550        }
551    }
552
553    /// Runs and scores one case; [`evaluate_case`](Self::evaluate_case) has checked it.
554    async fn run_case(
555        &self,
556        agent: Arc<dyn Agent>,
557        eval_case: &EvalCase,
558    ) -> Result<EvaluationResult> {
559        let start = Instant::now();
560        let mut score_totals: HashMap<String, (f64, usize)> = HashMap::new();
561        let mut all_failures: Vec<Failure> = Vec::new();
562        let mut turn_results: Vec<TurnResult> = Vec::new();
563        let mut all_events: Vec<Event> = Vec::new();
564        let mut last_turn: Option<TurnResult> = None;
565
566        let conversation =
567            EvalConversation::start(agent, &eval_case.session_input, self.run_config.clone())
568                .await?;
569
570        // Execute each turn in the conversation
571        for turn in &eval_case.conversation {
572            let (turn_result, events) = self.execute_turn(&conversation, turn).await?;
573            all_events.extend(events);
574
575            // Score this turn
576            let (scores, failures) = self.score_turn(turn, &turn_result).await?;
577            for (criterion, score) in scores {
578                let (sum, count) = score_totals.entry(criterion).or_insert((0.0, 0));
579                *sum += score;
580                *count += 1;
581            }
582            all_failures.extend(failures);
583
584            if self.config.collect_turn_details {
585                turn_results.push(turn_result.clone());
586            }
587            last_turn = Some(turn_result);
588        }
589
590        let mut all_scores: HashMap<String, f64> = score_totals
591            .into_iter()
592            .map(|(criterion, (sum, count))| (criterion, sum / count as f64))
593            .collect();
594
595        let duration = start.elapsed();
596
597        // Invoke CostTracker if configured
598        let cost_metrics = self
599            .cost_tracker
600            .as_ref()
601            .map(|tracker| tracker.extract_metrics(&all_events, duration));
602
603        // Invoke TraceAnalyzer if configured
604        let trace_analysis =
605            self.trace_analyzer.as_ref().map(|analyzer| analyzer.analyze(&all_events));
606
607        // Invoke StructuredJudge if configured; a fail verdict or a judge error fails the case
608        let mut verdicts = Vec::new();
609        if let Some(judge) = &self.structured_judge
610            && let Some(last_turn) = &last_turn
611            && let Some(expected) = &last_turn.expected_response
612        {
613            match &last_turn.actual_response {
614                Some(actual) => match judge.judge(expected, actual, "overall_quality").await {
615                    Ok(verdict) => {
616                        all_scores.insert("structured_judge".to_string(), verdict.score);
617                        if matches!(verdict.verdict, crate::structured_judge::Verdict::Fail) {
618                            all_failures.push(
619                                Failure::new(
620                                    "structured_judge",
621                                    Value::String(expected.clone()),
622                                    Value::String(actual.clone()),
623                                    verdict.score,
624                                    1.0,
625                                )
626                                .with_details(&format!(
627                                    "Structured judge returned a fail verdict: {}",
628                                    verdict.reasoning
629                                )),
630                            );
631                        }
632                        verdicts.push(verdict);
633                    }
634                    Err(e) if e.is_refusal() => return Err(e),
635                    Err(e) => {
636                        tracing::warn!(error = %e, "structured judge failed");
637                        all_scores.insert("structured_judge".to_string(), 0.0);
638                        all_failures.push(
639                            Failure::new(
640                                "structured_judge",
641                                Value::String(expected.clone()),
642                                Value::String(actual.clone()),
643                                0.0,
644                                1.0,
645                            )
646                            .with_details(&format!("Structured judge error: {e}")),
647                        );
648                        verdicts.push(crate::structured_judge::StructuredVerdict {
649                            score: 0.0,
650                            reasoning: format!("Judge error: {e}"),
651                            verdict: crate::structured_judge::Verdict::Fail,
652                        });
653                    }
654                },
655                None => {
656                    all_scores.insert("structured_judge".to_string(), 0.0);
657                    all_failures.push(unjudged("structured_judge", 1.0, NO_RESPONSE));
658                }
659            }
660        }
661
662        // Invoke EmbeddingScorer if configured
663        #[cfg(feature = "embedding")]
664        if let Some(scorer) = &self.embedding_scorer
665            && let Some(last_turn) = &last_turn
666            && let (Some(expected), Some(actual)) =
667                (&last_turn.expected_response, &last_turn.actual_response)
668        {
669            match scorer.score(expected, actual).await {
670                Ok(score) => {
671                    all_scores.insert("embedding_similarity".to_string(), score);
672                }
673                Err(e) => {
674                    tracing::warn!("Embedding scorer failed: {e}");
675                }
676            }
677        }
678
679        if all_scores.is_empty() && all_failures.is_empty() {
680            all_failures.push(unjudged(
681                "not_evaluated",
682                0.0,
683                "no configured criterion applied to this case, so it was not evaluated; give \
684                 its turns the expected responses or tool calls the criteria compare against",
685            ));
686        }
687
688        let passed = all_failures.is_empty();
689
690        let mut result = if passed {
691            EvaluationResult::passed(&eval_case.eval_id, all_scores, duration)
692        } else {
693            EvaluationResult::failed(&eval_case.eval_id, all_scores, all_failures, duration)
694        };
695
696        if self.config.collect_turn_details {
697            result = result.with_turn_results(turn_results);
698        }
699
700        // Populate extended fields
701        result.cost_metrics = cost_metrics;
702        result.trace_analysis = trace_analysis;
703        result.verdicts = verdicts;
704
705        Ok(result)
706    }
707
708    /// Execute a single turn, returning its result and the events the agent emitted
709    async fn execute_turn(
710        &self,
711        conversation: &EvalConversation,
712        turn: &Turn,
713    ) -> Result<(TurnResult, Vec<Event>)> {
714        let events = conversation.send(turn.user_content.to_adk_content()).await?;
715
716        // Extract response and tool calls from events
717        let (actual_response, actual_tool_calls) = self.extract_from_events(&events);
718        let actual_vision = turn
719            .expected_vision
720            .as_ref()
721            .and_then(|_| crate::vision::answer_from_events(&events, actual_response.as_deref()));
722
723        // Get expected values
724        let expected_response = turn.final_response.as_ref().map(|c| c.get_text());
725        let expected_tool_calls =
726            turn.intermediate_data.as_ref().map(|d| d.tool_uses.clone()).unwrap_or_default();
727
728        let turn_result = TurnResult {
729            invocation_id: turn.invocation_id.clone(),
730            actual_response,
731            expected_response,
732            actual_tool_calls,
733            expected_tool_calls,
734            actual_vision,
735            scores: HashMap::new(),
736        };
737        Ok((turn_result, events))
738    }
739
740    /// Extract response text and tool calls from events
741    pub(crate) fn extract_from_events(&self, events: &[Event]) -> (Option<String>, Vec<ToolUse>) {
742        let mut response_text = String::new();
743        let mut tool_calls = Vec::new();
744        let complete_ids: std::collections::HashSet<_> = events
745            .iter()
746            .filter(|event| {
747                !event.llm_response.partial
748                    && event
749                        .llm_response
750                        .provider_metadata
751                        .as_ref()
752                        .and_then(|metadata| metadata.get("content_complete"))
753                        .and_then(serde_json::Value::as_bool)
754                        == Some(true)
755            })
756            .map(|event| (&event.invocation_id, &event.id))
757            .collect();
758
759        for event in events {
760            if event.llm_response.partial
761                && complete_ids.contains(&(&event.invocation_id, &event.id))
762            {
763                continue;
764            }
765            // Extract text content
766            if let Some(content) = event.content() {
767                for part in &content.parts {
768                    // Extract text content
769                    if let Some(text) = part.text() {
770                        response_text.push_str(text);
771                    }
772                    // Extract function calls using pattern matching
773                    if let adk_core::Part::FunctionCall { name, args, .. } = part {
774                        tool_calls.push(ToolUse {
775                            name: name.clone(),
776                            args: args.clone(),
777                            expected_response: None,
778                        });
779                    }
780                }
781            }
782        }
783
784        let response = if response_text.is_empty() { None } else { Some(response_text) };
785
786        (response, tool_calls)
787    }
788
789    /// Score a turn against criteria
790    ///
791    /// A judge error fails its criterion, except a refusal by the evaluation's budget,
792    /// spend ledger or kill switch, which is returned.
793    pub(crate) async fn score_turn(
794        &self,
795        turn: &Turn,
796        result: &TurnResult,
797    ) -> Result<(HashMap<String, f64>, Vec<Failure>)> {
798        let mut scores = HashMap::new();
799        let mut failures = Vec::new();
800
801        // Tool trajectory scoring
802        if let Some(threshold) = self.config.criteria.tool_trajectory_score {
803            let score =
804                self.tool_scorer.score(&result.expected_tool_calls, &result.actual_tool_calls);
805            scores.insert("tool_trajectory".to_string(), score);
806
807            if score < threshold {
808                failures.push(
809                    Failure::new(
810                        "tool_trajectory",
811                        serde_json::to_value(&result.expected_tool_calls).unwrap_or_default(),
812                        serde_json::to_value(&result.actual_tool_calls).unwrap_or_default(),
813                        score,
814                        threshold,
815                    )
816                    .with_details(&format!(
817                        "Expected {} tool calls, got {}",
818                        result.expected_tool_calls.len(),
819                        result.actual_tool_calls.len()
820                    )),
821                );
822            }
823        }
824
825        // Response similarity scoring (text-based)
826        if let Some(threshold) = self.config.criteria.response_similarity {
827            if let (Some(expected), Some(actual)) =
828                (&result.expected_response, &result.actual_response)
829            {
830                let score = self.response_scorer.score(expected, actual);
831                scores.insert("response_similarity".to_string(), score);
832
833                if score < threshold {
834                    failures.push(
835                        Failure::new(
836                            "response_similarity",
837                            Value::String(expected.clone()),
838                            Value::String(actual.clone()),
839                            score,
840                            threshold,
841                        )
842                        .with_details("Response text differs from expected"),
843                    );
844                }
845            } else if result.expected_response.is_some() && result.actual_response.is_none() {
846                scores.insert("response_similarity".to_string(), 0.0);
847                failures.push(
848                    Failure::new(
849                        "response_similarity",
850                        Value::String(result.expected_response.clone().unwrap_or_default()),
851                        Value::Null,
852                        0.0,
853                        threshold,
854                    )
855                    .with_details("No response received"),
856                );
857            }
858        }
859
860        // The LLM-judged criteria below fail, rather than skip, a turn they cannot judge.
861
862        // LLM-judged semantic matching; turns without an expected response are not compared.
863        // An EQUIVALENT: NO verdict fails regardless of the score.
864        if let Some(threshold) = self.config.criteria.semantic_match_score
865            && let Some(expected) = &result.expected_response
866        {
867            match (&self.llm_judge, &result.actual_response) {
868                (Some(judge), Some(actual)) => match judge
869                    .semantic_match(
870                        expected,
871                        actual,
872                        self.config.criteria.semantic_match_config.as_ref(),
873                    )
874                    .await
875                {
876                    Ok(semantic_result) => {
877                        scores.insert("semantic_match".to_string(), semantic_result.score);
878                        if !semantic_result.equivalent || semantic_result.score < threshold {
879                            let verdict = if semantic_result.equivalent {
880                                "equivalent"
881                            } else {
882                                "not equivalent"
883                            };
884                            failures.push(
885                                Failure::new(
886                                    "semantic_match",
887                                    Value::String(expected.clone()),
888                                    Value::String(actual.clone()),
889                                    semantic_result.score,
890                                    threshold,
891                                )
892                                .with_details(&format!(
893                                    "Judge verdict: {verdict}. {}",
894                                    semantic_result.reasoning
895                                )),
896                            );
897                        }
898                    }
899                    Err(e) if e.is_refusal() => return Err(e),
900                    Err(e) => {
901                        scores.insert("semantic_match".to_string(), 0.0);
902                        failures.push(
903                            Failure::new(
904                                "semantic_match",
905                                Value::String(expected.clone()),
906                                Value::String(actual.clone()),
907                                0.0,
908                                threshold,
909                            )
910                            .with_details(&format!("LLM judge error: {}", e)),
911                        );
912                    }
913                },
914                (None, _) => {
915                    scores.insert("semantic_match".to_string(), 0.0);
916                    failures.push(unjudged("semantic_match", threshold, NO_LLM_JUDGE));
917                }
918                (Some(_), None) => {
919                    scores.insert("semantic_match".to_string(), 0.0);
920                    failures.push(unjudged("semantic_match", threshold, NO_RESPONSE));
921                }
922            }
923        }
924
925        // Rubric-based evaluation
926        if let Some(threshold) = self.config.criteria.rubric_quality_score {
927            let rubric_config = self
928                .config
929                .criteria
930                .rubric_config
931                .as_ref()
932                .filter(|config| !config.rubrics.is_empty());
933            match (&self.llm_judge, rubric_config, &result.actual_response) {
934                (Some(judge), Some(rubric_config), Some(actual)) => {
935                    // Use user input as context for rubric evaluation
936                    let context = turn.user_content.get_text();
937                    match judge.evaluate_rubrics(actual, &context, rubric_config).await {
938                        Ok(rubric_result) => {
939                            scores
940                                .insert("rubric_quality".to_string(), rubric_result.overall_score);
941                            // Also store individual rubric scores
942                            for rs in &rubric_result.rubric_scores {
943                                scores.insert(format!("rubric_{}", rs.name), rs.score);
944                            }
945                            if rubric_result.overall_score < threshold {
946                                let details = rubric_result
947                                    .rubric_scores
948                                    .iter()
949                                    .map(|rs| {
950                                        format!("{}: {:.2} - {}", rs.name, rs.score, rs.reasoning)
951                                    })
952                                    .collect::<Vec<_>>()
953                                    .join("; ");
954                                failures.push(
955                                    Failure::new(
956                                        "rubric_quality",
957                                        Value::Number(
958                                            serde_json::Number::from_f64(threshold)
959                                                .unwrap_or(serde_json::Number::from(0)),
960                                        ),
961                                        Value::Number(
962                                            serde_json::Number::from_f64(
963                                                rubric_result.overall_score,
964                                            )
965                                            .unwrap_or(serde_json::Number::from(0)),
966                                        ),
967                                        rubric_result.overall_score,
968                                        threshold,
969                                    )
970                                    .with_details(&details),
971                                );
972                            }
973                        }
974                        Err(e) if e.is_refusal() => return Err(e),
975                        Err(e) => {
976                            scores.insert("rubric_quality".to_string(), 0.0);
977                            failures.push(
978                                Failure::new(
979                                    "rubric_quality",
980                                    Value::Null,
981                                    Value::Null,
982                                    0.0,
983                                    threshold,
984                                )
985                                .with_details(&format!("LLM judge error: {}", e)),
986                            );
987                        }
988                    }
989                }
990                (None, _, _) => {
991                    scores.insert("rubric_quality".to_string(), 0.0);
992                    failures.push(unjudged("rubric_quality", threshold, NO_LLM_JUDGE));
993                }
994                (Some(_), None, _) => {
995                    scores.insert("rubric_quality".to_string(), 0.0);
996                    failures.push(unjudged(
997                        "rubric_quality",
998                        threshold,
999                        "rubric_quality_score is set but rubric_config has no rubrics; \
1000                         add them with EvaluationCriteria::with_rubrics",
1001                    ));
1002                }
1003                (Some(_), Some(_), None) => {
1004                    scores.insert("rubric_quality".to_string(), 0.0);
1005                    failures.push(unjudged("rubric_quality", threshold, NO_RESPONSE));
1006                }
1007            }
1008        }
1009
1010        // Safety evaluation; a SAFE: NO verdict fails regardless of the score
1011        if let Some(threshold) = self.config.criteria.safety_score {
1012            match (&self.llm_judge, &result.actual_response) {
1013                (Some(judge), Some(actual)) => match judge.evaluate_safety(actual).await {
1014                    Ok(safety_result) => {
1015                        scores.insert("safety".to_string(), safety_result.score);
1016                        if !safety_result.is_safe || safety_result.score < threshold {
1017                            let verdict = if safety_result.is_safe { "safe" } else { "unsafe" };
1018                            failures.push(
1019                                Failure::new(
1020                                    "safety",
1021                                    Value::Number(
1022                                        serde_json::Number::from_f64(threshold)
1023                                            .unwrap_or(serde_json::Number::from(0)),
1024                                    ),
1025                                    Value::Number(
1026                                        serde_json::Number::from_f64(safety_result.score)
1027                                            .unwrap_or(serde_json::Number::from(0)),
1028                                    ),
1029                                    safety_result.score,
1030                                    threshold,
1031                                )
1032                                .with_details(&format!(
1033                                    "Judge verdict: {verdict}. Safety issues: {}",
1034                                    safety_result.issues.join(", ")
1035                                )),
1036                            );
1037                        }
1038                    }
1039                    Err(e) if e.is_refusal() => return Err(e),
1040                    Err(e) => {
1041                        scores.insert("safety".to_string(), 0.0);
1042                        failures.push(
1043                            Failure::new("safety", Value::Null, Value::Null, 0.0, threshold)
1044                                .with_details(&format!("LLM judge error: {}", e)),
1045                        );
1046                    }
1047                },
1048                (None, _) => {
1049                    scores.insert("safety".to_string(), 0.0);
1050                    failures.push(unjudged("safety", threshold, NO_LLM_JUDGE));
1051                }
1052                (Some(_), None) => {
1053                    scores.insert("safety".to_string(), 0.0);
1054                    failures.push(unjudged("safety", threshold, NO_RESPONSE));
1055                }
1056            }
1057        }
1058
1059        // Hallucination detection; a HALLUCINATION_FREE: NO verdict fails regardless of the score
1060        if let Some(threshold) = self.config.criteria.hallucination_score {
1061            match (&self.llm_judge, &result.actual_response) {
1062                (Some(judge), Some(actual)) => {
1063                    let context = turn.user_content.get_text();
1064                    let ground_truth = result.expected_response.as_deref();
1065                    match judge.detect_hallucinations(actual, &context, ground_truth).await {
1066                        Ok(hallucination_result) => {
1067                            scores.insert("hallucination".to_string(), hallucination_result.score);
1068                            if !hallucination_result.hallucination_free
1069                                || hallucination_result.score < threshold
1070                            {
1071                                let verdict = if hallucination_result.hallucination_free {
1072                                    "hallucination-free"
1073                                } else {
1074                                    "hallucinations found"
1075                                };
1076                                failures.push(
1077                                    Failure::new(
1078                                        "hallucination",
1079                                        Value::Number(
1080                                            serde_json::Number::from_f64(threshold)
1081                                                .unwrap_or(serde_json::Number::from(0)),
1082                                        ),
1083                                        Value::Number(
1084                                            serde_json::Number::from_f64(
1085                                                hallucination_result.score,
1086                                            )
1087                                            .unwrap_or(serde_json::Number::from(0)),
1088                                        ),
1089                                        hallucination_result.score,
1090                                        threshold,
1091                                    )
1092                                    .with_details(&format!(
1093                                        "Judge verdict: {verdict}. Hallucinations detected: {}",
1094                                        hallucination_result.issues.join(", ")
1095                                    )),
1096                                );
1097                            }
1098                        }
1099                        Err(e) if e.is_refusal() => return Err(e),
1100                        Err(e) => {
1101                            scores.insert("hallucination".to_string(), 0.0);
1102                            failures.push(
1103                                Failure::new(
1104                                    "hallucination",
1105                                    Value::Null,
1106                                    Value::Null,
1107                                    0.0,
1108                                    threshold,
1109                                )
1110                                .with_details(&format!("LLM judge error: {}", e)),
1111                            );
1112                        }
1113                    }
1114                }
1115                (None, _) => {
1116                    scores.insert("hallucination".to_string(), 0.0);
1117                    failures.push(unjudged("hallucination", threshold, NO_LLM_JUDGE));
1118                }
1119                (Some(_), None) => {
1120                    scores.insert("hallucination".to_string(), 0.0);
1121                    failures.push(unjudged("hallucination", threshold, NO_RESPONSE));
1122                }
1123            }
1124        }
1125
1126        // Vision scores, for the parts the turn expects; a missing answer scores 0.
1127        if let Some(criteria) = &self.config.criteria.vision
1128            && let Some(expected) = &turn.expected_vision
1129        {
1130            let answer = result.actual_vision.clone().unwrap_or_default();
1131            let vision = crate::vision::score(expected, &answer, criteria);
1132            for (name, threshold) in criteria.thresholds() {
1133                let (Some(threshold), Some(value)) = (threshold, vision.get(name)) else {
1134                    continue;
1135                };
1136                scores.insert(name.to_string(), value);
1137                if value < threshold {
1138                    let mut details = format!("{name} {value:.3} is below {threshold:.3}");
1139                    if let Some(error) = vision.max_box_error_px {
1140                        details.push_str(&format!("; largest box edge error {error:.1} px"));
1141                    }
1142                    if result.actual_vision.is_none() {
1143                        details.push_str(
1144                            "; the turn has no vision tool response (vision_detect, \
1145                             vision_segment, vision_read or vision_describe) to score",
1146                        );
1147                    }
1148                    for note in &vision.notes {
1149                        details.push_str("; ");
1150                        details.push_str(note);
1151                    }
1152                    failures.push(
1153                        Failure::new(
1154                            name,
1155                            serde_json::to_value(expected).unwrap_or_default(),
1156                            serde_json::to_value(&answer).unwrap_or_default(),
1157                            value,
1158                            threshold,
1159                        )
1160                        .with_details(&details),
1161                    );
1162                }
1163            }
1164        }
1165
1166        Ok((scores, failures))
1167    }
1168
1169    /// Evaluate multiple test cases in parallel
1170    ///
1171    /// Runs up to `concurrency` cases at a time and returns one result per case, in the
1172    /// order of `cases`.
1173    ///
1174    /// # Errors
1175    ///
1176    /// Returns [`EvalError::ConfigError`](crate::EvalError::ConfigError) when `concurrency`
1177    /// is 0, which could never run a case, or `cases` is empty.
1178    pub async fn evaluate_cases_parallel(
1179        &self,
1180        agent: Arc<dyn Agent>,
1181        cases: &[EvalCase],
1182        concurrency: usize,
1183    ) -> Result<Vec<Result<EvaluationResult>>> {
1184        use futures::stream::{self, StreamExt};
1185
1186        if concurrency == 0 {
1187            return Err(crate::error::EvalError::ConfigError(
1188                "concurrency must be at least 1".to_string(),
1189            ));
1190        }
1191        if cases.is_empty() {
1192            return Err(crate::error::EvalError::ConfigError(
1193                "no eval cases to evaluate; pass at least one case".to_string(),
1194            ));
1195        }
1196
1197        Ok(stream::iter(cases)
1198            .map(|case| {
1199                let agent = agent.clone();
1200                async move { self.evaluate_case(agent, case).await }
1201            })
1202            .buffered(concurrency)
1203            .collect()
1204            .await)
1205    }
1206
1207    /// Evaluate a directory of test files
1208    ///
1209    /// Evaluates every `*.test.json` file in `dir`.
1210    ///
1211    /// # Errors
1212    ///
1213    /// Returns an error when the directory cannot be read, a test file fails to load or
1214    /// has no cases, or the directory holds no `*.test.json` file.
1215    pub async fn evaluate_directory(
1216        &self,
1217        agent: Arc<dyn Agent>,
1218        dir: impl AsRef<Path>,
1219    ) -> Result<Vec<EvaluationReport>> {
1220        let dir = dir.as_ref();
1221        let mut reports = Vec::new();
1222
1223        let entries = std::fs::read_dir(dir)?;
1224        for entry in entries {
1225            let entry = entry?;
1226            let path = entry.path();
1227
1228            if path.extension().is_some_and(|ext| ext == "json")
1229                && let Some(name) = path.file_name().and_then(|n| n.to_str())
1230                && name.ends_with(".test.json")
1231            {
1232                let report = self.evaluate_file(agent.clone(), &path).await?;
1233                reports.push(report);
1234            }
1235        }
1236
1237        if reports.is_empty() {
1238            return Err(crate::error::EvalError::ConfigError(format!(
1239                "no *.test.json files in {}",
1240                dir.display()
1241            )));
1242        }
1243        Ok(reports)
1244    }
1245
1246    /// Run a multi-turn conversation between a [`UserSimulator`](crate::personas::UserSimulator)
1247    /// and the agent under test for a configurable number of turns.
1248    ///
1249    /// Each turn consists of:
1250    /// 1. The `UserSimulator` generates a user message based on the conversation history
1251    /// 2. The agent processes the user message and produces a response
1252    /// 3. Both messages are appended to the conversation history
1253    ///
1254    /// Returns the full conversation history as a `Vec<Content>`.
1255    ///
1256    /// # Errors
1257    ///
1258    /// Returns an error if the simulator or agent fails during any turn.
1259    #[cfg(feature = "personas")]
1260    pub async fn evaluate_multi_turn(
1261        &self,
1262        agent: Arc<dyn Agent>,
1263        simulator: &crate::personas::UserSimulator,
1264        num_turns: usize,
1265    ) -> Result<Vec<Content>> {
1266        let mut history: Vec<Content> = Vec::new();
1267        let conversation =
1268            EvalConversation::start(agent, &SessionInput::default(), self.run_config.clone())
1269                .await?;
1270
1271        for _turn_idx in 0..num_turns {
1272            // 1. Generate user message from the simulator
1273            let user_message = simulator.generate_message(&history).await?;
1274            history.push(user_message.clone());
1275
1276            // 2. Run the agent with the user message, in the same session as earlier turns
1277            let events = conversation.send(user_message).await?;
1278
1279            // 3. Extract the agent's response text
1280            let (response_text, _tool_calls) = self.extract_from_events(&events);
1281            if let Some(text) = response_text {
1282                history.push(Content::new("model").with_text(text));
1283            }
1284        }
1285
1286        Ok(history)
1287    }
1288}
1289
1290const NO_LLM_JUDGE: &str = "this criterion needs an LLM judge; build the evaluator with \
1291                            Evaluator::with_llm_judge or call Evaluator::set_llm_judge";
1292
1293const NO_RESPONSE: &str = "the agent produced no text response to judge";
1294
1295/// A failure for a configured criterion that could not be judged.
1296fn unjudged(criterion: &str, threshold: f64, reason: &str) -> Failure {
1297    Failure::new(criterion, Value::Null, Value::Null, 0.0, threshold).with_details(reason)
1298}
1299
1300impl Default for Evaluator {
1301    fn default() -> Self {
1302        Self::new(EvaluationConfig::default())
1303    }
1304}
1305
1306/// App name for a case whose `session_input.app_name` is empty.
1307const DEFAULT_APP_NAME: &str = "eval_app";
1308
1309/// User id for a case whose `session_input.user_id` is empty.
1310const DEFAULT_USER_ID: &str = "eval_user";
1311
1312/// One conversation with the agent under test.
1313///
1314/// Every turn runs through a [`Runner`] against the same session of a private in-memory
1315/// session service, so the agent sees the history and state that earlier turns left.
1316struct EvalConversation {
1317    runner: Runner,
1318    user_id: UserId,
1319    session_id: SessionId,
1320}
1321
1322/// The app name a case runs under: its `session_input.app_name`, or [`DEFAULT_APP_NAME`].
1323fn app_name_of(session_input: &SessionInput) -> &str {
1324    if session_input.app_name.is_empty() { DEFAULT_APP_NAME } else { &session_input.app_name }
1325}
1326
1327impl EvalConversation {
1328    /// Creates the session described by `session_input` and a runner for `agent` that runs
1329    /// every turn with `run_config`, when there is one.
1330    async fn start(
1331        agent: Arc<dyn Agent>,
1332        session_input: &SessionInput,
1333        run_config: Option<RunConfig>,
1334    ) -> Result<Self> {
1335        let app_name = app_name_of(session_input);
1336        let user_id = if session_input.user_id.is_empty() {
1337            DEFAULT_USER_ID
1338        } else {
1339            session_input.user_id.as_str()
1340        };
1341        let invalid_input = |e: String| {
1342            crate::error::EvalError::ConfigError(format!(
1343                "cannot create the eval session from session_input (app_name '{app_name}', \
1344                 user_id '{user_id}'): {e}"
1345            ))
1346        };
1347
1348        let session_service = Arc::new(InMemorySessionService::new());
1349        let session = session_service
1350            .create(CreateRequest {
1351                app_name: app_name.to_string(),
1352                user_id: user_id.to_string(),
1353                session_id: None,
1354                state: session_input.state.clone(),
1355            })
1356            .await
1357            .map_err(|e| invalid_input(e.to_string()))?;
1358        let session_id =
1359            SessionId::try_from(session.id()).map_err(|e| invalid_input(e.to_string()))?;
1360        let user_id = UserId::try_from(user_id).map_err(|e| invalid_input(e.to_string()))?;
1361
1362        let builder =
1363            Runner::builder().app_name(app_name).agent(agent).session_service(session_service);
1364        let builder = match run_config {
1365            Some(config) => builder.run_config(config),
1366            None => builder,
1367        };
1368        let runner = builder.build().map_err(|e| {
1369            crate::error::EvalError::ExecutionError(format!("cannot build the eval runner: {e}"))
1370        })?;
1371
1372        Ok(Self { runner, user_id, session_id })
1373    }
1374
1375    /// Runs one turn and collects its events, failing on the first stream error.
1376    ///
1377    /// A refusal by the run's budget, spend ledger or kill switch is returned as
1378    /// [`EvalError::Refused`](crate::EvalError::Refused).
1379    async fn send(&self, input: Content) -> Result<Vec<Event>> {
1380        use crate::error::EvalError;
1381
1382        let mut stream =
1383            self.runner.run(self.user_id.clone(), self.session_id.clone(), input).await.map_err(
1384                |e| {
1385                    EvalError::from_model_error(e, |e| {
1386                        EvalError::ExecutionError(format!("Agent run failed: {e}"))
1387                    })
1388                },
1389            )?;
1390
1391        let mut events = Vec::new();
1392        while let Some(item) = stream.next().await {
1393            let event = item.map_err(|e| {
1394                EvalError::from_model_error(e, |e| {
1395                    EvalError::ExecutionError(format!(
1396                        "agent event stream failed after {} event(s): {e}",
1397                        events.len()
1398                    ))
1399                })
1400            })?;
1401            events.push(event);
1402        }
1403
1404        Ok(events)
1405    }
1406}
1407
1408#[cfg(test)]
1409mod tests {
1410    use super::*;
1411    use crate::criteria::{ResponseMatchConfig, SimilarityAlgorithm};
1412    use crate::schema::ContentData;
1413    use async_trait::async_trait;
1414
1415    /// Replies with the user's message, optionally followed by a stream error.
1416    struct EchoAgent {
1417        fail_stream: bool,
1418    }
1419
1420    #[async_trait]
1421    impl Agent for EchoAgent {
1422        fn name(&self) -> &str {
1423            "echo"
1424        }
1425
1426        fn description(&self) -> &str {
1427            "echoes the user message"
1428        }
1429
1430        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
1431            &[]
1432        }
1433
1434        async fn run(
1435            &self,
1436            ctx: Arc<dyn adk_core::InvocationContext>,
1437        ) -> adk_core::Result<adk_core::EventStream> {
1438            let text: String = ctx.user_content().parts.iter().filter_map(|p| p.text()).collect();
1439            let mut event = Event::new(ctx.invocation_id());
1440            event.llm_response.content = Some(Content::new("model").with_text(text));
1441            let mut items = vec![Ok(event)];
1442            if self.fail_stream {
1443                items.push(Err(adk_core::AdkError::model("connection reset")));
1444            }
1445            Ok(Box::pin(futures::stream::iter(items)))
1446        }
1447    }
1448
1449    fn echo_agent() -> Arc<dyn Agent> {
1450        Arc::new(EchoAgent { fail_stream: false })
1451    }
1452
1453    fn judge_replying(text: &str) -> Arc<dyn Llm> {
1454        Arc::new(
1455            adk_model::MockLlm::new("judge")
1456                .with_response(adk_core::LlmResponse::new(Content::new("model").with_text(text))),
1457        )
1458    }
1459
1460    fn turn(user: &str, expected: &str) -> Turn {
1461        Turn {
1462            invocation_id: format!("inv-{user}"),
1463            user_content: ContentData::text(user),
1464            final_response: Some(ContentData::model_response(expected)),
1465            intermediate_data: None,
1466            expected_vision: None,
1467        }
1468    }
1469
1470    fn case(turns: Vec<Turn>) -> EvalCase {
1471        EvalCase {
1472            eval_id: "case_1".to_string(),
1473            description: String::new(),
1474            conversation: turns,
1475            session_input: Default::default(),
1476            tags: vec![],
1477            metadata: None,
1478        }
1479    }
1480
1481    fn criteria(criteria: EvaluationCriteria) -> EvaluationConfig {
1482        EvaluationConfig { collect_turn_details: true, ..EvaluationConfig::with_criteria(criteria) }
1483    }
1484
1485    fn failure_details(result: &EvaluationResult) -> Vec<(String, String)> {
1486        result
1487            .failures
1488            .iter()
1489            .map(|f| (f.criterion.clone(), f.details.clone().unwrap_or_default()))
1490            .collect()
1491    }
1492
1493    #[tokio::test]
1494    async fn case_score_is_the_mean_of_turn_scores() {
1495        let evaluator = Evaluator::new(criteria(EvaluationCriteria {
1496            response_similarity: Some(0.0),
1497            response_match_config: Some(ResponseMatchConfig {
1498                algorithm: SimilarityAlgorithm::Exact,
1499                ..Default::default()
1500            }),
1501            ..Default::default()
1502        }));
1503        let eval_case =
1504            case(vec![turn("one", "different"), turn("two", "two"), turn("three", "three")]);
1505
1506        let result = evaluator.evaluate_case(echo_agent(), &eval_case).await.unwrap();
1507
1508        let score = result.scores["response_similarity"];
1509        assert!((score - 2.0 / 3.0).abs() < 1e-9, "score was {score}");
1510    }
1511
1512    #[tokio::test]
1513    async fn stream_error_fails_the_case() {
1514        let evaluator = Evaluator::new(criteria(EvaluationCriteria::response_similarity(0.5)));
1515        let test_file = TestFile {
1516            eval_set_id: "set".to_string(),
1517            name: "set".to_string(),
1518            description: String::new(),
1519            eval_cases: vec![case(vec![turn("hello", "hello")])],
1520        };
1521
1522        let agent: Arc<dyn Agent> = Arc::new(EchoAgent { fail_stream: true });
1523        let err =
1524            evaluator.evaluate_case(agent.clone(), &test_file.eval_cases[0]).await.unwrap_err();
1525        assert!(err.to_string().contains("connection reset"), "{err}");
1526
1527        let report = evaluator.evaluate_test_file(agent, &test_file).await.unwrap();
1528        assert!(!report.all_passed());
1529        assert_eq!(report.results[0].failures[0].criterion, "execution");
1530    }
1531
1532    #[tokio::test]
1533    async fn judge_criteria_without_a_judge_fail() {
1534        let evaluator = Evaluator::new(criteria(EvaluationCriteria {
1535            semantic_match_score: Some(0.8),
1536            rubric_quality_score: Some(0.8),
1537            safety_score: Some(0.9),
1538            hallucination_score: Some(0.9),
1539            ..Default::default()
1540        }));
1541
1542        let result =
1543            evaluator.evaluate_case(echo_agent(), &case(vec![turn("hi", "hi")])).await.unwrap();
1544
1545        assert!(!result.passed);
1546        let mut details = failure_details(&result);
1547        details.sort();
1548        assert_eq!(
1549            details,
1550            vec![
1551                ("hallucination".to_string(), NO_LLM_JUDGE.to_string()),
1552                ("rubric_quality".to_string(), NO_LLM_JUDGE.to_string()),
1553                ("safety".to_string(), NO_LLM_JUDGE.to_string()),
1554                ("semantic_match".to_string(), NO_LLM_JUDGE.to_string()),
1555            ]
1556        );
1557    }
1558
1559    #[tokio::test]
1560    async fn rubric_criterion_without_rubrics_fails() {
1561        let evaluator = Evaluator::with_llm_judge(
1562            criteria(EvaluationCriteria { rubric_quality_score: Some(0.5), ..Default::default() }),
1563            judge_replying("SCORE: 1.0\nREASONING: fine"),
1564        );
1565
1566        let result =
1567            evaluator.evaluate_case(echo_agent(), &case(vec![turn("hi", "hi")])).await.unwrap();
1568
1569        assert!(!result.passed);
1570        assert!(result.failures[0].details.as_deref().unwrap().contains("no rubrics"));
1571    }
1572
1573    #[tokio::test]
1574    async fn unsafe_verdict_fails_despite_high_score() {
1575        let evaluator = Evaluator::with_llm_judge(
1576            criteria(EvaluationCriteria { safety_score: Some(0.9), ..Default::default() }),
1577            judge_replying("SAFE: NO\nSCORE: 1.0\nISSUES: discloses a home address"),
1578        );
1579
1580        let result =
1581            evaluator.evaluate_case(echo_agent(), &case(vec![turn("hi", "hi")])).await.unwrap();
1582
1583        assert!(!result.passed);
1584        assert_eq!(result.failures[0].criterion, "safety");
1585        assert!(result.failures[0].details.as_deref().unwrap().contains("unsafe"));
1586    }
1587
1588    #[tokio::test]
1589    async fn hallucination_verdict_fails_despite_high_score() {
1590        let evaluator = Evaluator::with_llm_judge(
1591            criteria(EvaluationCriteria { hallucination_score: Some(0.9), ..Default::default() }),
1592            judge_replying("HALLUCINATION_FREE: NO\nSCORE: 0.95\nISSUES: invented a date"),
1593        );
1594
1595        let result =
1596            evaluator.evaluate_case(echo_agent(), &case(vec![turn("hi", "hi")])).await.unwrap();
1597
1598        assert!(!result.passed);
1599        assert_eq!(result.failures[0].criterion, "hallucination");
1600    }
1601
1602    #[tokio::test]
1603    async fn not_equivalent_verdict_fails_despite_high_score() {
1604        let evaluator = Evaluator::with_llm_judge(
1605            criteria(EvaluationCriteria::semantic_match(0.8)),
1606            judge_replying("EQUIVALENT: NO\nSCORE: 0.95\nREASONING: names the wrong city"),
1607        );
1608
1609        let result =
1610            evaluator.evaluate_case(echo_agent(), &case(vec![turn("hi", "hi")])).await.unwrap();
1611
1612        assert!(!result.passed);
1613        assert_eq!(
1614            failure_details(&result),
1615            vec![(
1616                "semantic_match".to_string(),
1617                "Judge verdict: not equivalent. names the wrong city".to_string()
1618            )]
1619        );
1620    }
1621
1622    /// Replies with the user text of every earlier turn in its session, then the
1623    /// session's `topic` state value, so a test can see what the agent was given.
1624    struct HistoryAgent;
1625
1626    #[async_trait]
1627    impl Agent for HistoryAgent {
1628        fn name(&self) -> &str {
1629            "history"
1630        }
1631
1632        fn description(&self) -> &str {
1633            "reports the conversation it can see"
1634        }
1635
1636        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
1637            &[]
1638        }
1639
1640        async fn run(
1641            &self,
1642            ctx: Arc<dyn adk_core::InvocationContext>,
1643        ) -> adk_core::Result<adk_core::EventStream> {
1644            let earlier: Vec<String> = ctx
1645                .session()
1646                .conversation_history()
1647                .iter()
1648                .filter(|content| content.role == "user")
1649                .map(|content| content.parts.iter().filter_map(|p| p.text()).collect())
1650                .collect();
1651            let topic = ctx.session().state().get("topic").unwrap_or(Value::Null);
1652            let mut event = Event::new(ctx.invocation_id());
1653            event.author = self.name().to_string();
1654            event.llm_response.content = Some(Content::new("model").with_text(format!(
1655                "{} | {topic} | {}",
1656                earlier.join(","),
1657                ctx.user_id()
1658            )));
1659            Ok(Box::pin(futures::stream::iter(vec![Ok(event)])))
1660        }
1661    }
1662
1663    #[tokio::test]
1664    async fn later_turns_see_the_history_of_earlier_turns() {
1665        let evaluator = Evaluator::new(criteria(EvaluationCriteria {
1666            response_similarity: Some(1.0),
1667            response_match_config: Some(ResponseMatchConfig {
1668                algorithm: SimilarityAlgorithm::Exact,
1669                ..Default::default()
1670            }),
1671            ..Default::default()
1672        }));
1673        let eval_case = case(vec![
1674            turn("my name is Ada", "my name is Ada | null | eval_user"),
1675            turn("what is my name?", "my name is Ada,what is my name? | null | eval_user"),
1676        ]);
1677
1678        let result = evaluator.evaluate_case(Arc::new(HistoryAgent), &eval_case).await.unwrap();
1679
1680        assert!(result.passed, "{:?}", result.turn_results);
1681    }
1682
1683    #[tokio::test]
1684    async fn session_input_sets_the_user_and_initial_state() {
1685        let evaluator = Evaluator::new(criteria(EvaluationCriteria {
1686            response_similarity: Some(1.0),
1687            response_match_config: Some(ResponseMatchConfig {
1688                algorithm: SimilarityAlgorithm::Exact,
1689                ..Default::default()
1690            }),
1691            ..Default::default()
1692        }));
1693        let mut eval_case = case(vec![turn("hi", "hi | \"billing\" | ada")]);
1694        eval_case.session_input = SessionInput {
1695            app_name: "support".to_string(),
1696            user_id: "ada".to_string(),
1697            state: HashMap::from([("topic".to_string(), serde_json::json!("billing"))]),
1698        };
1699
1700        let result = evaluator.evaluate_case(Arc::new(HistoryAgent), &eval_case).await.unwrap();
1701
1702        assert!(result.passed, "{:?}", result.turn_results);
1703    }
1704
1705    #[tokio::test]
1706    async fn malformed_judge_score_fails_the_criterion() {
1707        let evaluator = Evaluator::with_llm_judge(
1708            criteria(EvaluationCriteria { safety_score: Some(0.9), ..Default::default() }),
1709            judge_replying("SAFE: YES\nSCORE: very safe\nISSUES: None"),
1710        );
1711
1712        let result =
1713            evaluator.evaluate_case(echo_agent(), &case(vec![turn("hi", "hi")])).await.unwrap();
1714
1715        assert!(!result.passed);
1716        assert_eq!(result.scores["safety"], 0.0);
1717        assert!(result.failures[0].details.as_deref().unwrap().contains("no valid SCORE line"));
1718    }
1719
1720    #[tokio::test]
1721    async fn structured_fail_verdict_fails_the_case() {
1722        for collect_turn_details in [true, false] {
1723            let mut evaluator = Evaluator::new(EvaluationConfig {
1724                collect_turn_details,
1725                ..EvaluationConfig::default()
1726            });
1727            evaluator.set_structured_judge(Arc::new(StructuredJudge::new(judge_replying(
1728                r#"{"score": 0.9, "reasoning": "answers a different question", "verdict": "fail"}"#,
1729            ))));
1730
1731            let result =
1732                evaluator.evaluate_case(echo_agent(), &case(vec![turn("hi", "hi")])).await.unwrap();
1733
1734            assert!(!result.passed, "collect_turn_details = {collect_turn_details}");
1735            assert_eq!(result.verdicts.len(), 1);
1736            assert_eq!(
1737                failure_details(&result),
1738                vec![(
1739                    "structured_judge".to_string(),
1740                    "Structured judge returned a fail verdict: answers a different question"
1741                        .to_string()
1742                )]
1743            );
1744        }
1745    }
1746
1747    #[tokio::test]
1748    async fn structured_pass_verdict_passes_the_case() {
1749        let mut evaluator = Evaluator::new(EvaluationConfig::default());
1750        evaluator.set_structured_judge(Arc::new(StructuredJudge::new(judge_replying(
1751            r#"{"score": 1.0, "reasoning": "same answer", "verdict": "pass"}"#,
1752        ))));
1753
1754        let result =
1755            evaluator.evaluate_case(echo_agent(), &case(vec![turn("hi", "hi")])).await.unwrap();
1756
1757        assert!(result.passed);
1758        assert_eq!(result.scores["structured_judge"], 1.0);
1759    }
1760
1761    fn exact_similarity() -> EvaluationConfig {
1762        criteria(EvaluationCriteria {
1763            response_similarity: Some(1.0),
1764            response_match_config: Some(ResponseMatchConfig {
1765                algorithm: SimilarityAlgorithm::Exact,
1766                ..Default::default()
1767            }),
1768            ..Default::default()
1769        })
1770    }
1771
1772    fn config_error(error: crate::EvalError) -> String {
1773        match error {
1774            crate::EvalError::ConfigError(message) => message,
1775            other => panic!("expected a config error, got {other}"),
1776        }
1777    }
1778
1779    #[tokio::test]
1780    async fn a_test_file_without_cases_is_rejected() {
1781        let test_file = TestFile {
1782            eval_set_id: "empty_set".to_string(),
1783            name: "empty".to_string(),
1784            description: String::new(),
1785            eval_cases: vec![],
1786        };
1787        let error = Evaluator::new(exact_similarity())
1788            .evaluate_test_file(echo_agent(), &test_file)
1789            .await
1790            .unwrap_err();
1791        assert!(config_error(error).contains("'empty_set' has no eval cases"));
1792    }
1793
1794    #[tokio::test]
1795    async fn a_case_without_turns_is_rejected() {
1796        let error = Evaluator::new(exact_similarity())
1797            .evaluate_case(echo_agent(), &case(vec![]))
1798            .await
1799            .unwrap_err();
1800        assert!(config_error(error).contains("'case_1' has no conversation turns"));
1801    }
1802
1803    #[tokio::test]
1804    async fn an_evaluator_without_criteria_is_rejected() {
1805        let error = Evaluator::new(EvaluationConfig::default())
1806            .evaluate_case(echo_agent(), &case(vec![turn("hi", "hi")]))
1807            .await
1808            .unwrap_err();
1809        assert!(config_error(error).contains("no evaluation criteria are configured"));
1810
1811        // Custom criteria are not scored by the evaluator, so alone they are no criteria.
1812        let tone = crate::criteria::CustomCriterion {
1813            name: "tone".to_string(),
1814            description: "friendly".to_string(),
1815            threshold: 0.5,
1816            config: Value::Null,
1817        };
1818        let custom = Evaluator::new(criteria(EvaluationCriteria {
1819            custom: vec![tone.clone()],
1820            ..Default::default()
1821        }));
1822        let error =
1823            custom.evaluate_case(echo_agent(), &case(vec![turn("hi", "hi")])).await.unwrap_err();
1824        assert!(config_error(error).contains("no evaluation criteria are configured"));
1825
1826        // Beside a scored criterion they are carried and the case is scored by the other.
1827        let mixed = Evaluator::new(criteria(EvaluationCriteria {
1828            custom: vec![tone],
1829            ..exact_similarity().criteria
1830        }));
1831        let result = mixed.evaluate_case(echo_agent(), &case(vec![turn("hi", "hi")])).await;
1832        assert!(result.unwrap().passed);
1833    }
1834
1835    #[tokio::test]
1836    async fn a_case_no_criterion_applies_to_is_not_evaluated() {
1837        let evaluator = Evaluator::with_llm_judge(
1838            criteria(EvaluationCriteria::semantic_match(0.8)),
1839            judge_replying("EQUIVALENT: YES\nSCORE: 1.0\nREASONING: same"),
1840        );
1841        let unexpected = Turn { final_response: None, ..turn("hi", "unused") };
1842
1843        let result = evaluator.evaluate_case(echo_agent(), &case(vec![unexpected])).await.unwrap();
1844
1845        assert!(!result.passed);
1846        assert_eq!(failure_details(&result)[0].0, "not_evaluated");
1847        assert!(result.scores.is_empty());
1848    }
1849
1850    #[tokio::test]
1851    async fn a_zero_concurrency_is_rejected_without_waiting() {
1852        let evaluator = Evaluator::new(exact_similarity());
1853        let cases = vec![case(vec![turn("hi", "hi")])];
1854        let outcome = tokio::time::timeout(
1855            Duration::from_secs(5),
1856            evaluator.evaluate_cases_parallel(echo_agent(), &cases, 0),
1857        )
1858        .await
1859        .expect("concurrency 0 must not hang");
1860        assert_eq!(config_error(outcome.unwrap_err()), "concurrency must be at least 1");
1861
1862        let empty = evaluator.evaluate_cases_parallel(echo_agent(), &[], 2).await;
1863        assert!(config_error(empty.unwrap_err()).contains("no eval cases"));
1864    }
1865
1866    #[tokio::test]
1867    async fn parallel_results_follow_case_order() {
1868        let evaluator = Evaluator::new(exact_similarity());
1869        let cases: Vec<EvalCase> = (0..6)
1870            .map(|index| EvalCase {
1871                eval_id: format!("case_{index}"),
1872                ..case(vec![turn(&format!("m{index}"), &format!("m{index}"))])
1873            })
1874            .collect();
1875
1876        let results = evaluator.evaluate_cases_parallel(echo_agent(), &cases, 3).await.unwrap();
1877
1878        let ids: Vec<String> = results.into_iter().map(|r| r.unwrap().eval_id).collect();
1879        let expected: Vec<String> = cases.iter().map(|c| c.eval_id.clone()).collect();
1880        assert_eq!(ids, expected);
1881    }
1882
1883    #[tokio::test]
1884    async fn a_directory_without_test_files_is_rejected() {
1885        let dir = tempfile::tempdir().unwrap();
1886        let error = Evaluator::new(exact_similarity())
1887            .evaluate_directory(echo_agent(), dir.path())
1888            .await
1889            .unwrap_err();
1890        assert!(config_error(error).contains("no *.test.json files"));
1891    }
1892
1893    #[test]
1894    fn complete_snapshots_replace_partial_text_and_calls() {
1895        let evaluator = Evaluator::new(EvaluationConfig::default());
1896        let mut partial = Event::with_id("response", "invocation");
1897        partial.llm_response.partial = true;
1898        partial.llm_response.content = Some(Content::new("model").with_text("Draft"));
1899        let mut final_event = partial.clone();
1900        final_event.llm_response.partial = false;
1901        final_event.llm_response.provider_metadata =
1902            Some(serde_json::json!({"content_complete":true}));
1903        final_event.llm_response.content = Some(Content::new("model").with_text("Corrected"));
1904        let (text, calls) = evaluator.extract_from_events(&[partial, final_event]);
1905        assert_eq!(text.as_deref(), Some("Corrected"));
1906        assert!(calls.is_empty());
1907    }
1908
1909    #[test]
1910    fn test_evaluator_creation() {
1911        let config = EvaluationConfig::with_criteria(
1912            EvaluationCriteria::exact_tools().with_response_similarity(0.8),
1913        );
1914        let evaluator = Evaluator::new(config);
1915        assert!(evaluator.config.criteria.tool_trajectory_score.is_some());
1916        assert!(evaluator.config.criteria.response_similarity.is_some());
1917    }
1918
1919    #[tokio::test]
1920    async fn test_turn_scoring() {
1921        let config = EvaluationConfig::with_criteria(EvaluationCriteria {
1922            tool_trajectory_score: Some(1.0),
1923            response_similarity: Some(0.8),
1924            ..Default::default()
1925        });
1926        let evaluator = Evaluator::new(config);
1927
1928        let turn = Turn {
1929            invocation_id: "test".to_string(),
1930            user_content: crate::schema::ContentData::text("Hello"),
1931            final_response: Some(crate::schema::ContentData::model_response("Hi there!")),
1932            intermediate_data: Some(crate::schema::IntermediateData {
1933                tool_uses: vec![ToolUse::new("greet")],
1934                ..Default::default()
1935            }),
1936            expected_vision: None,
1937        };
1938
1939        let result = TurnResult {
1940            invocation_id: "test".to_string(),
1941            actual_response: Some("Hi there!".to_string()),
1942            expected_response: Some("Hi there!".to_string()),
1943            actual_tool_calls: vec![ToolUse::new("greet")],
1944            expected_tool_calls: vec![ToolUse::new("greet")],
1945            actual_vision: None,
1946            scores: HashMap::new(),
1947        };
1948
1949        let (scores, failures) = evaluator.score_turn(&turn, &result).await.unwrap();
1950        assert!(failures.is_empty());
1951        assert_eq!(scores.get("tool_trajectory"), Some(&1.0));
1952        assert_eq!(scores.get("response_similarity"), Some(&1.0));
1953    }
1954}