Skip to main content

adk_eval/
criteria.rs

1//! Evaluation criteria definitions
2//!
3//! Defines the various criteria that can be used to evaluate agent responses.
4
5use serde::{Deserialize, Serialize};
6
7use crate::vision::VisionCriteria;
8
9/// Collection of evaluation criteria
10#[derive(Debug, Clone, Default, Serialize, Deserialize)]
11pub struct EvaluationCriteria {
12    /// Tool trajectory matching score threshold (0.0 - 1.0)
13    /// Checks if the agent called the expected tools in the expected order
14    #[serde(default)]
15    pub tool_trajectory_score: Option<f64>,
16
17    /// Tool trajectory configuration
18    #[serde(default)]
19    pub tool_trajectory_config: Option<ToolTrajectoryConfig>,
20
21    /// Response text similarity threshold (0.0 - 1.0)
22    /// Uses text similarity metrics to compare expected vs actual response
23    #[serde(default)]
24    pub response_similarity: Option<f64>,
25
26    /// Response matching configuration
27    #[serde(default)]
28    pub response_match_config: Option<ResponseMatchConfig>,
29
30    /// LLM-judged semantic match threshold (0.0 - 1.0)
31    /// Uses an LLM to judge if responses are semantically equivalent
32    #[serde(default)]
33    pub semantic_match_score: Option<f64>,
34
35    /// Semantic match configuration
36    #[serde(default)]
37    pub semantic_match_config: Option<SemanticMatchConfig>,
38
39    /// Rubric-based quality score threshold (0.0 - 1.0)
40    /// Evaluates response quality against defined rubrics
41    #[serde(default)]
42    pub rubric_quality_score: Option<f64>,
43
44    /// Rubric configuration
45    #[serde(default)]
46    pub rubric_config: Option<RubricConfig>,
47
48    /// Safety score threshold (0.0 - 1.0)
49    /// Checks for unsafe or harmful content
50    #[serde(default)]
51    pub safety_score: Option<f64>,
52
53    /// Hallucination detection threshold (0.0 - 1.0)
54    /// Detects factual inaccuracies or made-up information
55    #[serde(default)]
56    pub hallucination_score: Option<f64>,
57
58    /// Vision scores — regions, masks, OCR text, fields, detections and click targets —
59    /// checked against each turn's [`expected_vision`](crate::Turn::expected_vision); see
60    /// [`vision`](crate::vision).
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub vision: Option<VisionCriteria>,
63
64    /// Criteria your own code scores; carried with the configuration for it.
65    ///
66    /// [`Evaluator`](crate::Evaluator) does not score them, so they do not count toward
67    /// [`has_criteria`](Self::has_criteria): a configuration with only custom criteria is
68    /// rejected like an empty one.
69    #[serde(default)]
70    pub custom: Vec<CustomCriterion>,
71}
72
73impl EvaluationCriteria {
74    /// Create criteria requiring exact tool trajectory match
75    pub fn exact_tools() -> Self {
76        Self {
77            tool_trajectory_score: Some(1.0),
78            tool_trajectory_config: Some(ToolTrajectoryConfig {
79                strict_order: true,
80                strict_args: true,
81            }),
82            ..Default::default()
83        }
84    }
85
86    /// Create criteria for semantic response matching
87    pub fn semantic_match(threshold: f64) -> Self {
88        Self { semantic_match_score: Some(threshold), ..Default::default() }
89    }
90
91    /// Create criteria with response similarity
92    pub fn response_similarity(threshold: f64) -> Self {
93        Self { response_similarity: Some(threshold), ..Default::default() }
94    }
95
96    /// Add tool trajectory requirement
97    pub fn with_tool_trajectory(mut self, threshold: f64) -> Self {
98        self.tool_trajectory_score = Some(threshold);
99        self
100    }
101
102    /// Add response similarity requirement
103    pub fn with_response_similarity(mut self, threshold: f64) -> Self {
104        self.response_similarity = Some(threshold);
105        self
106    }
107
108    /// Add semantic match requirement
109    pub fn with_semantic_match(mut self, threshold: f64) -> Self {
110        self.semantic_match_score = Some(threshold);
111        self
112    }
113
114    /// Add rubric-based evaluation
115    pub fn with_rubrics(mut self, threshold: f64, rubrics: Vec<Rubric>) -> Self {
116        self.rubric_quality_score = Some(threshold);
117        self.rubric_config = Some(RubricConfig { rubrics });
118        self
119    }
120
121    /// Add vision thresholds.
122    ///
123    /// # Example
124    ///
125    /// ```
126    /// use adk_eval::EvaluationCriteria;
127    /// use adk_eval::vision::VisionCriteria;
128    ///
129    /// let criteria = EvaluationCriteria::default().with_vision(VisionCriteria {
130    ///     region_iou: Some(0.75),
131    ///     ocr_char_accuracy: Some(0.98),
132    ///     ..Default::default()
133    /// });
134    /// assert!(criteria.has_criteria());
135    /// ```
136    pub fn with_vision(mut self, vision: VisionCriteria) -> Self {
137        self.vision = Some(vision);
138        self
139    }
140
141    /// Whether any criterion [`Evaluator`](crate::Evaluator) scores has a threshold.
142    ///
143    /// [`custom`](Self::custom) criteria are not counted, since the evaluator does not score
144    /// them.
145    ///
146    /// # Example
147    ///
148    /// ```
149    /// use adk_eval::EvaluationCriteria;
150    /// use adk_eval::criteria::CustomCriterion;
151    ///
152    /// let custom_only = EvaluationCriteria {
153    ///     custom: vec![CustomCriterion {
154    ///         name: "tone".to_string(),
155    ///         description: "The reply is friendly".to_string(),
156    ///         threshold: 0.8,
157    ///         config: serde_json::Value::Null,
158    ///     }],
159    ///     ..Default::default()
160    /// };
161    /// assert!(!custom_only.has_criteria());
162    /// assert!(custom_only.with_response_similarity(0.8).has_criteria());
163    /// ```
164    pub fn has_criteria(&self) -> bool {
165        self.tool_trajectory_score.is_some()
166            || self.response_similarity.is_some()
167            || self.semantic_match_score.is_some()
168            || self.rubric_quality_score.is_some()
169            || self.safety_score.is_some()
170            || self.hallucination_score.is_some()
171            || self.vision.as_ref().is_some_and(VisionCriteria::has_thresholds)
172    }
173}
174
175/// Configuration for tool trajectory matching
176#[derive(Debug, Clone, Serialize, Deserialize)]
177pub struct ToolTrajectoryConfig {
178    /// Require tools to be called in the expected order (default `true`).
179    ///
180    /// Applies to both [`ToolTrajectoryScorer::score`](crate::ToolTrajectoryScorer::score)
181    /// and [`ToolTrajectoryScorer::compare`](crate::ToolTrajectoryScorer::compare).
182    #[serde(default = "default_true")]
183    pub strict_order: bool,
184    /// Require exact argument match instead of a subset match (default `false`).
185    ///
186    /// With `false`, expected arguments match when every expected key is present in the
187    /// actual call with a matching value, recursively; extra keys are allowed at any depth.
188    /// With `true`, objects must have the same keys at every depth. In both modes arrays
189    /// match element by element, numbers compare by value (`1` matches `1.0`), and an
190    /// expected tool use without `args` matches any arguments. See
191    /// [`ToolUse::matches`](crate::ToolUse::matches).
192    #[serde(default)]
193    pub strict_args: bool,
194}
195
196impl Default for ToolTrajectoryConfig {
197    fn default() -> Self {
198        Self { strict_order: true, strict_args: false }
199    }
200}
201
202/// Configuration for response matching
203#[derive(Debug, Clone, Serialize, Deserialize)]
204pub struct ResponseMatchConfig {
205    /// Similarity algorithm to use
206    #[serde(default)]
207    pub algorithm: SimilarityAlgorithm,
208    /// Whether to normalize text before comparison
209    #[serde(default = "default_true")]
210    pub normalize: bool,
211    /// Whether to ignore case
212    #[serde(default = "default_true")]
213    pub ignore_case: bool,
214    /// Whether to ignore punctuation
215    #[serde(default)]
216    pub ignore_punctuation: bool,
217}
218
219impl Default for ResponseMatchConfig {
220    fn default() -> Self {
221        Self {
222            algorithm: SimilarityAlgorithm::default(),
223            normalize: true,
224            ignore_case: true,
225            ignore_punctuation: false,
226        }
227    }
228}
229
230/// Similarity algorithms for text comparison
231#[derive(Debug, Clone, Default, Serialize, Deserialize)]
232#[serde(rename_all = "snake_case")]
233pub enum SimilarityAlgorithm {
234    /// Exact string match
235    Exact,
236    /// Contains check
237    Contains,
238    /// Levenshtein distance based
239    Levenshtein,
240    /// Jaccard similarity (word overlap)
241    #[default]
242    Jaccard,
243    /// ROUGE-1 (unigram overlap)
244    Rouge1,
245    /// ROUGE-2 (bigram overlap)
246    Rouge2,
247    /// ROUGE-L (longest common subsequence)
248    RougeL,
249}
250
251/// Configuration for LLM-judged semantic matching
252#[derive(Debug, Clone, Serialize, Deserialize)]
253pub struct SemanticMatchConfig {
254    /// Model to use for judging
255    #[serde(default = "default_judge_model")]
256    pub judge_model: String,
257    /// Custom prompt for the judge (optional)
258    ///
259    /// `{expected}` and `{actual}` are replaced with the two responses. The prompt must
260    /// ask for an `EQUIVALENT: YES/NO/PARTIAL` line and a `SCORE:` line from 0.0 to 1.0;
261    /// a reply without either is a judge error.
262    pub custom_prompt: Option<String>,
263}
264
265impl Default for SemanticMatchConfig {
266    fn default() -> Self {
267        Self { judge_model: default_judge_model(), custom_prompt: None }
268    }
269}
270
271fn default_judge_model() -> String {
272    "gemini-3.8-flash".to_string()
273}
274
275/// Configuration for rubric-based evaluation
276#[derive(Debug, Clone, Default, Serialize, Deserialize)]
277pub struct RubricConfig {
278    /// List of rubrics to evaluate against
279    pub rubrics: Vec<Rubric>,
280}
281
282impl RubricConfig {
283    /// A rubric with one criterion per item, each named by its own text, as the
284    /// [`OutcomeGrader`](crate::OutcomeGrader) grades them. Blank items are skipped.
285    ///
286    /// # Example
287    ///
288    /// ```rust
289    /// let rubric = adk_eval::RubricConfig::from_criteria(["poem.md has three lines", "it rhymes"]);
290    /// assert_eq!(rubric.rubrics.len(), 2);
291    /// assert_eq!(rubric.rubrics[1].description, "it rhymes");
292    /// ```
293    pub fn from_criteria<I, S>(criteria: I) -> Self
294    where
295        I: IntoIterator<Item = S>,
296        S: AsRef<str>,
297    {
298        let rubrics = criteria
299            .into_iter()
300            .map(|criterion| criterion.as_ref().trim().to_string())
301            .filter(|criterion| !criterion.is_empty())
302            .map(|criterion| Rubric::new(&criterion, &criterion))
303            .collect();
304        Self { rubrics }
305    }
306
307    /// Reads criteria from Markdown: each list item (`-`, `*`, `+`, `1.`, `1)`, with or
308    /// without a `[ ]` checkbox) is one criterion, and indented lines below an item continue
309    /// it. Without list items, each paragraph is one criterion. Headings are ignored.
310    ///
311    /// # Example
312    ///
313    /// ```rust
314    /// let rubric = adk_eval::RubricConfig::from_markdown(
315    ///     "# Rubric\n\n- `poem.md` has exactly three lines\n- The poem mentions ownership,\n  borrowing or lifetimes\n1. [ ] It has a title line\n",
316    /// );
317    /// let criteria: Vec<&str> = rubric.rubrics.iter().map(|r| r.description.as_str()).collect();
318    /// assert_eq!(
319    ///     criteria,
320    ///     [
321    ///         "`poem.md` has exactly three lines",
322    ///         "The poem mentions ownership, borrowing or lifetimes",
323    ///         "It has a title line",
324    ///     ]
325    /// );
326    /// ```
327    pub fn from_markdown(text: &str) -> Self {
328        let mut items: Vec<String> = Vec::new();
329        let mut in_item = false;
330        for line in text.lines() {
331            let trimmed = line.trim();
332            if trimmed.is_empty() || trimmed.starts_with('#') {
333                in_item = false;
334                continue;
335            }
336            let indented = line.starts_with([' ', '\t']);
337            if let Some(item) = list_item(trimmed).filter(|_| !(indented && in_item)) {
338                items.push(item.to_string());
339                in_item = true;
340            } else if indented
341                && in_item
342                && let Some(current) = items.last_mut()
343            {
344                current.push(' ');
345                current.push_str(list_item(trimmed).unwrap_or(trimmed));
346            } else {
347                in_item = false;
348            }
349        }
350        if items.is_empty() {
351            let mut paragraph = String::new();
352            for line in text.lines().map(str::trim) {
353                if line.is_empty() || line.starts_with('#') {
354                    items.extend((!paragraph.is_empty()).then(|| std::mem::take(&mut paragraph)));
355                } else {
356                    if !paragraph.is_empty() {
357                        paragraph.push(' ');
358                    }
359                    paragraph.push_str(line);
360                }
361            }
362            items.extend((!paragraph.is_empty()).then_some(paragraph));
363        }
364        Self::from_criteria(items)
365    }
366}
367
368/// The text of a Markdown list item, without its marker and checkbox.
369fn list_item(line: &str) -> Option<&str> {
370    let rest = if let Some(rest) = line
371        .strip_prefix("- ")
372        .or_else(|| line.strip_prefix("* "))
373        .or_else(|| line.strip_prefix("+ "))
374    {
375        rest
376    } else {
377        let digits = line.bytes().take_while(u8::is_ascii_digit).count();
378        let marker =
379            line[digits..].strip_prefix(". ").or_else(|| line[digits..].strip_prefix(") "));
380        match marker {
381            Some(rest) if digits > 0 => rest,
382            _ => return None,
383        }
384    };
385    let rest = rest.trim_start();
386    let rest = ["[ ] ", "[x] ", "[X] "]
387        .iter()
388        .find_map(|checkbox| rest.strip_prefix(checkbox))
389        .unwrap_or(rest);
390    Some(rest.trim())
391}
392
393/// A single rubric for quality assessment
394#[derive(Debug, Clone, Serialize, Deserialize)]
395pub struct Rubric {
396    /// Rubric name
397    pub name: String,
398    /// What this rubric measures
399    pub description: String,
400    /// Weight for this rubric (0.0 - 1.0)
401    #[serde(default = "default_weight")]
402    pub weight: f64,
403    /// Scoring levels (optional)
404    #[serde(default)]
405    pub levels: Vec<RubricLevel>,
406}
407
408impl Rubric {
409    /// Create a new rubric
410    pub fn new(name: &str, description: &str) -> Self {
411        Self {
412            name: name.to_string(),
413            description: description.to_string(),
414            weight: 1.0,
415            levels: vec![],
416        }
417    }
418
419    /// Set weight
420    pub fn with_weight(mut self, weight: f64) -> Self {
421        self.weight = weight;
422        self
423    }
424
425    /// Add scoring levels
426    pub fn with_levels(mut self, levels: Vec<RubricLevel>) -> Self {
427        self.levels = levels;
428        self
429    }
430}
431
432/// A scoring level for a rubric
433#[derive(Debug, Clone, Serialize, Deserialize)]
434pub struct RubricLevel {
435    /// Score for this level (0.0 - 1.0)
436    pub score: f64,
437    /// Description of what qualifies for this level
438    pub description: String,
439}
440
441/// Custom evaluation criterion
442#[derive(Debug, Clone, Serialize, Deserialize)]
443pub struct CustomCriterion {
444    /// Criterion name
445    pub name: String,
446    /// Description of what this measures
447    pub description: String,
448    /// Score threshold (0.0 - 1.0)
449    pub threshold: f64,
450    /// Custom configuration as JSON
451    #[serde(default)]
452    pub config: serde_json::Value,
453}
454
455fn default_true() -> bool {
456    true
457}
458
459fn default_weight() -> f64 {
460    1.0
461}
462
463#[cfg(test)]
464mod tests {
465    use super::*;
466
467    #[test]
468    fn test_criteria_builder() {
469        let criteria = EvaluationCriteria::exact_tools()
470            .with_response_similarity(0.8)
471            .with_semantic_match(0.9);
472
473        assert_eq!(criteria.tool_trajectory_score, Some(1.0));
474        assert_eq!(criteria.response_similarity, Some(0.8));
475        assert_eq!(criteria.semantic_match_score, Some(0.9));
476        assert!(criteria.has_criteria());
477    }
478
479    #[test]
480    fn test_rubric_creation() {
481        let rubric = Rubric::new("Accuracy", "Response is factually correct")
482            .with_weight(0.7)
483            .with_levels(vec![
484                RubricLevel { score: 1.0, description: "Completely accurate".to_string() },
485                RubricLevel { score: 0.5, description: "Partially accurate".to_string() },
486                RubricLevel { score: 0.0, description: "Inaccurate".to_string() },
487            ]);
488
489        assert_eq!(rubric.name, "Accuracy");
490        assert_eq!(rubric.weight, 0.7);
491        assert_eq!(rubric.levels.len(), 3);
492    }
493
494    #[test]
495    fn test_default_criteria() {
496        let criteria = EvaluationCriteria::default();
497        assert!(!criteria.has_criteria());
498    }
499
500    #[test]
501    fn custom_criteria_alone_are_not_criteria() {
502        let criteria = EvaluationCriteria {
503            custom: vec![CustomCriterion {
504                name: "tone".to_string(),
505                description: "friendly".to_string(),
506                threshold: 0.5,
507                config: serde_json::Value::Null,
508            }],
509            ..Default::default()
510        };
511        assert!(!criteria.has_criteria());
512    }
513}