Skip to main content

gemini_adk_rs/evaluation/
response_evaluator.rs

1//! Response evaluator — evaluates final response quality.
2//!
3//! Compares the agent's final response text against expected output
4//! using configurable matching strategies.
5
6use async_trait::async_trait;
7
8use super::eval_case::Invocation;
9use super::eval_result::{EvalMetric, EvalResult, PerInvocationResult};
10use super::evaluator::{EvalError, Evaluator};
11
12/// Strategy for comparing actual vs. expected responses.
13#[derive(Debug, Clone, Copy, Default)]
14pub enum MatchStrategy {
15    /// Exact string match.
16    Exact,
17    /// Case-insensitive containment.
18    #[default]
19    Contains,
20    /// Fuzzy match using Levenshtein-like distance.
21    Fuzzy {
22        /// Minimum similarity threshold (0.0–1.0).
23        threshold: f64,
24    },
25}
26
27/// Evaluates the agent's final response against expected output.
28#[derive(Debug, Clone)]
29pub struct ResponseEvaluator {
30    strategy: MatchStrategy,
31    metric_name: String,
32}
33
34impl ResponseEvaluator {
35    /// Create a new response evaluator with the given matching strategy.
36    pub fn new(strategy: MatchStrategy) -> Self {
37        Self {
38            strategy,
39            metric_name: "response_match".into(),
40        }
41    }
42
43    /// Set a custom metric name.
44    pub fn with_metric_name(mut self, name: impl Into<String>) -> Self {
45        self.metric_name = name.into();
46        self
47    }
48
49    /// Get the final model response from an invocation.
50    fn last_model_response(inv: &Invocation) -> Option<&str> {
51        inv.turns
52            .iter()
53            .rev()
54            .find(|t| t.role == "model")
55            .map(|t| t.content.as_str())
56    }
57
58    /// Score a single pair of actual/expected responses.
59    fn score_pair(&self, actual: &str, expected: &str) -> (f64, String) {
60        match self.strategy {
61            MatchStrategy::Exact => {
62                if actual == expected {
63                    (1.0, "Exact match".into())
64                } else {
65                    (0.0, "No exact match".into())
66                }
67            }
68            MatchStrategy::Contains => {
69                let actual_lower = actual.to_lowercase();
70                let expected_lower = expected.to_lowercase();
71                if actual_lower.contains(&expected_lower) || expected_lower.contains(&actual_lower)
72                {
73                    (1.0, "Contains match".into())
74                } else {
75                    (0.0, "No containment match".into())
76                }
77            }
78            MatchStrategy::Fuzzy { threshold } => {
79                let similarity = string_similarity(actual, expected);
80                if similarity >= threshold {
81                    (similarity, format!("Fuzzy match: {similarity:.2}"))
82                } else {
83                    (
84                        similarity,
85                        format!("Below threshold {threshold:.2}: {similarity:.2}"),
86                    )
87                }
88            }
89        }
90    }
91}
92
93impl Default for ResponseEvaluator {
94    fn default() -> Self {
95        Self::new(MatchStrategy::default())
96    }
97}
98
99#[async_trait]
100impl Evaluator for ResponseEvaluator {
101    async fn evaluate(
102        &self,
103        actual: &[Invocation],
104        expected: Option<&[Invocation]>,
105    ) -> Result<EvalResult, EvalError> {
106        let expected = expected.ok_or_else(|| {
107            EvalError::InvalidInput("ResponseEvaluator requires expected invocations".into())
108        })?;
109
110        let mut per_invocation = Vec::new();
111        let mut total_score = 0.0;
112
113        for (i, actual_inv) in actual.iter().enumerate() {
114            let actual_resp = Self::last_model_response(actual_inv).unwrap_or("");
115            let expected_resp = expected
116                .get(i)
117                .and_then(|e| Self::last_model_response(e))
118                .unwrap_or("");
119
120            let (score, explanation) = self.score_pair(actual_resp, expected_resp);
121            total_score += score;
122
123            per_invocation.push(PerInvocationResult {
124                invocation_id: if actual_inv.id.is_empty() {
125                    format!("inv-{i}")
126                } else {
127                    actual_inv.id.clone()
128                },
129                score,
130                explanation: Some(explanation),
131            });
132        }
133
134        let overall_score = if actual.is_empty() {
135            0.0
136        } else {
137            total_score / actual.len() as f64
138        };
139
140        Ok(EvalResult {
141            overall_score,
142            metrics: vec![EvalMetric {
143                name: self.metric_name.clone(),
144                score: overall_score,
145                per_invocation,
146            }],
147        })
148    }
149}
150
151/// Simple character-based similarity (normalized Levenshtein-like).
152fn string_similarity(a: &str, b: &str) -> f64 {
153    if a.is_empty() && b.is_empty() {
154        return 1.0;
155    }
156    let max_len = a.len().max(b.len()) as f64;
157    if max_len == 0.0 {
158        return 1.0;
159    }
160
161    let distance = crate::utils::text::levenshtein(a, b) as f64;
162    1.0 - (distance / max_len)
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168    use crate::evaluation::eval_case::InvocationTurn;
169
170    fn make_invocation(model_response: &str) -> Invocation {
171        Invocation {
172            id: String::new(),
173            turns: vec![
174                InvocationTurn {
175                    role: "user".into(),
176                    content: "What is 2+2?".into(),
177                    tool_calls: vec![],
178                    tool_results: vec![],
179                },
180                InvocationTurn {
181                    role: "model".into(),
182                    content: model_response.into(),
183                    tool_calls: vec![],
184                    tool_results: vec![],
185                },
186            ],
187            metadata: serde_json::Value::Null,
188        }
189    }
190
191    #[tokio::test]
192    async fn exact_match() {
193        let evaluator = ResponseEvaluator::new(MatchStrategy::Exact);
194        let actual = vec![make_invocation("4")];
195        let expected = vec![make_invocation("4")];
196        let result = evaluator.evaluate(&actual, Some(&expected)).await.unwrap();
197        assert!((result.overall_score - 1.0).abs() < f64::EPSILON);
198    }
199
200    #[tokio::test]
201    async fn exact_mismatch() {
202        let evaluator = ResponseEvaluator::new(MatchStrategy::Exact);
203        let actual = vec![make_invocation("four")];
204        let expected = vec![make_invocation("4")];
205        let result = evaluator.evaluate(&actual, Some(&expected)).await.unwrap();
206        assert!((result.overall_score - 0.0).abs() < f64::EPSILON);
207    }
208
209    #[tokio::test]
210    async fn contains_match() {
211        let evaluator = ResponseEvaluator::new(MatchStrategy::Contains);
212        let actual = vec![make_invocation("The answer is 4")];
213        let expected = vec![make_invocation("4")];
214        let result = evaluator.evaluate(&actual, Some(&expected)).await.unwrap();
215        assert!((result.overall_score - 1.0).abs() < f64::EPSILON);
216    }
217
218    #[tokio::test]
219    async fn fuzzy_match() {
220        let evaluator = ResponseEvaluator::new(MatchStrategy::Fuzzy { threshold: 0.5 });
221        let actual = vec![make_invocation("hello world")];
222        let expected = vec![make_invocation("hello worl")];
223        let result = evaluator.evaluate(&actual, Some(&expected)).await.unwrap();
224        assert!(result.overall_score > 0.5);
225    }
226
227    #[tokio::test]
228    async fn requires_expected() {
229        let evaluator = ResponseEvaluator::default();
230        let actual = vec![make_invocation("test")];
231        let result = evaluator.evaluate(&actual, None).await;
232        assert!(result.is_err());
233    }
234
235    #[test]
236    fn similarity_identical() {
237        assert!((string_similarity("hello", "hello") - 1.0).abs() < f64::EPSILON);
238    }
239
240    #[test]
241    fn similarity_empty() {
242        assert!((string_similarity("", "") - 1.0).abs() < f64::EPSILON);
243    }
244}