Skip to main content

adk_eval/
schema.rs

1//! Test file schema definitions
2//!
3//! Defines the structure for test files (`.test.json`) and eval sets (`.evalset.json`).
4//!
5//! A turn can show the agent images: an [`ImageFixture`] part names an image file by its
6//! path, relative to the eval file, and its SHA-256. Loading the file verifies every
7//! fixture's digest, so a case never runs against an image that changed after its
8//! expectations were written.
9
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12use sha2::{Digest as _, Sha256};
13use std::collections::HashMap;
14use std::path::{Path, PathBuf};
15use std::sync::Arc;
16
17use crate::error::{EvalError, Result};
18use crate::test_generator::EvalCaseMetadata;
19use crate::vision::VisionExpected;
20
21/// The directory relative fixture paths in the file at `path` resolve against.
22fn base_dir(path: &Path) -> &Path {
23    path.parent().unwrap_or(Path::new("."))
24}
25
26/// A complete test file containing multiple evaluation cases
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct TestFile {
29    /// Unique identifier for this eval set
30    pub eval_set_id: String,
31    /// Human-readable name
32    pub name: String,
33    /// Description of what these tests cover
34    #[serde(default)]
35    pub description: String,
36    /// List of evaluation cases
37    pub eval_cases: Vec<EvalCase>,
38}
39
40impl TestFile {
41    /// Load a test file from disk, verifying every image fixture against its digest.
42    ///
43    /// # Errors
44    ///
45    /// Returns an error when the file cannot be read or parsed, or an image fixture is
46    /// missing or does not match its digest.
47    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
48        let content = std::fs::read_to_string(path.as_ref())?;
49        let mut test_file: TestFile = serde_json::from_str(&content)?;
50        for eval_case in &mut test_file.eval_cases {
51            eval_case.load_images(base_dir(path.as_ref()))?;
52        }
53        Ok(test_file)
54    }
55
56    /// Save test file to disk
57    pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
58        let content = serde_json::to_string_pretty(self)?;
59        std::fs::write(path, content)?;
60        Ok(())
61    }
62}
63
64/// An eval set references multiple test files
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct EvalSet {
67    /// Unique identifier
68    pub eval_set_id: String,
69    /// Human-readable name
70    pub name: String,
71    /// Description
72    #[serde(default)]
73    pub description: String,
74    /// List of test file paths or inline eval cases
75    #[serde(default)]
76    pub test_files: Vec<String>,
77    /// Inline eval cases (alternative to test_files)
78    #[serde(default)]
79    pub eval_cases: Vec<EvalCase>,
80}
81
82impl EvalSet {
83    /// Load an eval set from disk, verifying the image fixtures of its inline cases.
84    ///
85    /// # Errors
86    ///
87    /// Returns an error when the file cannot be read or parsed, or an image fixture is
88    /// missing or does not match its digest.
89    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
90        let content = std::fs::read_to_string(path.as_ref())?;
91        let mut eval_set: EvalSet = serde_json::from_str(&content)?;
92        for eval_case in &mut eval_set.eval_cases {
93            eval_case.load_images(base_dir(path.as_ref()))?;
94        }
95        Ok(eval_set)
96    }
97
98    /// Get all eval cases, loading from test files if needed
99    pub fn get_all_cases(&self, base_path: impl AsRef<Path>) -> Result<Vec<EvalCase>> {
100        let mut all_cases = self.eval_cases.clone();
101
102        for test_file_path in &self.test_files {
103            let full_path = base_path.as_ref().join(test_file_path);
104            let test_file = TestFile::load(&full_path).map_err(|e| {
105                EvalError::LoadError(format!("Failed to load {}: {}", test_file_path, e))
106            })?;
107            all_cases.extend(test_file.eval_cases);
108        }
109
110        Ok(all_cases)
111    }
112}
113
114/// A single evaluation case (test case)
115#[derive(Debug, Clone, Serialize, Deserialize)]
116pub struct EvalCase {
117    /// Unique identifier for this test case
118    pub eval_id: String,
119    /// Optional description
120    #[serde(default)]
121    pub description: String,
122    /// The conversation turns to evaluate
123    pub conversation: Vec<Turn>,
124    /// Session configuration
125    #[serde(default)]
126    pub session_input: SessionInput,
127    /// Optional tags for filtering
128    #[serde(default)]
129    pub tags: Vec<String>,
130    /// Optional metadata (generation info, etc.)
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub metadata: Option<EvalCaseMetadata>,
133}
134
135impl EvalCase {
136    /// Reads and verifies every image fixture in the case's turns, resolving relative paths
137    /// against `base_dir`. [`TestFile::load`] and [`EvalSet::load`] call it; call it
138    /// yourself for a case built or parsed in code.
139    ///
140    /// # Errors
141    ///
142    /// Returns [`EvalError::LoadError`] naming the first fixture that is missing, unreadable,
143    /// larger than [`adk_core::MAX_INLINE_DATA_SIZE`], or not the file its digest pins.
144    pub fn load_images(&mut self, base_dir: &Path) -> Result<()> {
145        for turn in &mut self.conversation {
146            for content in std::iter::once(&mut turn.user_content).chain(&mut turn.final_response) {
147                for part in &mut content.parts {
148                    if let Part::Image { image } = part {
149                        image.load(base_dir).map_err(|e| {
150                            EvalError::LoadError(format!("eval case '{}': {e}", self.eval_id))
151                        })?;
152                    }
153                }
154            }
155        }
156        Ok(())
157    }
158
159    /// The image fixtures in the case's turns that have not been loaded and verified.
160    pub fn unloaded_images(&self) -> Vec<&ImageFixture> {
161        self.conversation
162            .iter()
163            .flat_map(|turn| std::iter::once(&turn.user_content).chain(&turn.final_response))
164            .flat_map(|content| &content.parts)
165            .filter_map(|part| match part {
166                Part::Image { image } if image.bytes().is_none() => Some(image),
167                _ => None,
168            })
169            .collect()
170    }
171}
172
173/// A single turn in a conversation
174#[derive(Debug, Clone, Serialize, Deserialize)]
175pub struct Turn {
176    /// Unique identifier for this turn
177    pub invocation_id: String,
178    /// User input content
179    pub user_content: ContentData,
180    /// Expected final response from the agent
181    #[serde(default)]
182    pub final_response: Option<ContentData>,
183    /// Expected intermediate data (tool calls, etc.)
184    #[serde(default)]
185    pub intermediate_data: Option<IntermediateData>,
186    /// Expected perception output — regions, page text, fields, click targets — scored by
187    /// the [`vision`](crate::criteria::EvaluationCriteria::vision) criteria.
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub expected_vision: Option<VisionExpected>,
190}
191
192/// Content data structure (matches ADK Content)
193#[derive(Debug, Clone, Serialize, Deserialize)]
194pub struct ContentData {
195    /// Content parts
196    pub parts: Vec<Part>,
197    /// Role (user, model, tool)
198    #[serde(default = "default_role")]
199    pub role: String,
200}
201
202fn default_role() -> String {
203    "user".to_string()
204}
205
206impl ContentData {
207    /// Create content from text
208    pub fn text(text: &str) -> Self {
209        Self { parts: vec![Part::Text { text: text.to_string() }], role: "user".to_string() }
210    }
211
212    /// Create model response content
213    pub fn model_response(text: &str) -> Self {
214        Self { parts: vec![Part::Text { text: text.to_string() }], role: "model".to_string() }
215    }
216
217    /// Get all text parts concatenated
218    pub fn get_text(&self) -> String {
219        self.parts
220            .iter()
221            .filter_map(|p| match p {
222                Part::Text { text } => Some(text.as_str()),
223                _ => None,
224            })
225            .collect::<Vec<_>>()
226            .join("")
227    }
228
229    /// Convert to ADK Content
230    ///
231    /// A loaded [`ImageFixture`] becomes `Part::InlineData` carrying the verified bytes, with
232    /// the fixture's resolved path and digest in its annotations under `adkEvalFixture`; an
233    /// image that was not loaded is left out.
234    pub fn to_adk_content(&self) -> adk_core::Content {
235        let mut content = adk_core::Content::new(&self.role);
236        for part in &self.parts {
237            match part {
238                Part::Text { text } => {
239                    content = content.with_text(text);
240                }
241                Part::Image { image } => {
242                    if let Some(part) = image.to_inline_part() {
243                        content.parts.push(part);
244                    }
245                }
246                Part::FunctionCall { .. } | Part::FunctionResponse { .. } => {
247                    // Function calls/responses are handled separately in the evaluation
248                    // The Content type doesn't have direct methods for these
249                }
250            }
251        }
252        content
253    }
254}
255
256/// Content part variants
257#[derive(Debug, Clone, Serialize, Deserialize)]
258#[serde(untagged)]
259pub enum Part {
260    /// Text content
261    Text { text: String },
262    /// Function/tool call
263    FunctionCall { name: String, args: Value },
264    /// Function/tool response
265    FunctionResponse { name: String, response: Value },
266    /// An image file shown to the agent, pinned by its digest: `{"image": {"path", "digest"}}`
267    Image { image: ImageFixture },
268}
269
270/// An image an eval case shows the agent: a file named by its path, relative to the eval
271/// file's directory, and pinned by its SHA-256.
272///
273/// # Example
274///
275/// ```
276/// use adk_eval::ImageFixture;
277///
278/// let dir = tempfile::tempdir().unwrap();
279/// std::fs::write(dir.path().join("page.png"), b"not really a png").unwrap();
280/// let mut image = ImageFixture::new("page.png", &format!("sha256:{}", "0".repeat(64)));
281/// let err = image.load(dir.path()).unwrap_err();
282/// assert!(err.to_string().contains("does not match"), "{err}");
283///
284/// let digest = ImageFixture::digest_of(b"not really a png");
285/// let mut image = ImageFixture::new("page.png", &digest);
286/// image.load(dir.path()).unwrap();
287/// assert_eq!(image.bytes(), Some(&b"not really a png"[..]));
288/// assert_eq!(image.mime_type(), "image/png");
289/// ```
290#[derive(Debug, Clone, Serialize, Deserialize)]
291pub struct ImageFixture {
292    /// The image file, relative to the eval file's directory (or absolute).
293    pub path: String,
294    /// The file's SHA-256 as `sha256:<64 hex digits>`; the bare digits are accepted.
295    pub digest: String,
296    /// The MIME type; inferred from the extension when absent.
297    #[serde(default, skip_serializing_if = "Option::is_none")]
298    pub mime_type: Option<String>,
299    /// The verified file, once loaded.
300    #[serde(skip)]
301    loaded: Option<LoadedImage>,
302}
303
304#[derive(Debug, Clone)]
305struct LoadedImage {
306    path: PathBuf,
307    bytes: Arc<[u8]>,
308}
309
310impl ImageFixture {
311    /// A fixture for the file at `path` with this digest.
312    pub fn new(path: impl Into<String>, digest: &str) -> Self {
313        Self { path: path.into(), digest: digest.to_string(), mime_type: None, loaded: None }
314    }
315
316    /// The digest of `bytes` in the form fixtures pin: `sha256:<64 hex digits>`.
317    pub fn digest_of(bytes: &[u8]) -> String {
318        let hex: String = Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect();
319        format!("sha256:{hex}")
320    }
321
322    /// Reads the file, resolving a relative path against `base_dir`, and checks it against
323    /// the digest.
324    ///
325    /// # Errors
326    ///
327    /// Returns [`EvalError::LoadError`] when the digest is malformed, or the file is
328    /// missing, unreadable, larger than [`adk_core::MAX_INLINE_DATA_SIZE`], or has another
329    /// digest.
330    pub fn load(&mut self, base_dir: &Path) -> Result<()> {
331        let want = self.digest.strip_prefix("sha256:").unwrap_or(&self.digest).to_ascii_lowercase();
332        if want.len() != 64 || !want.bytes().all(|b| b.is_ascii_hexdigit()) {
333            return Err(EvalError::LoadError(format!(
334                "image fixture {} has digest {:?}; write it as sha256:<64 hex digits>",
335                self.path, self.digest
336            )));
337        }
338        let path = base_dir.join(&self.path);
339        let bytes = std::fs::read(&path).map_err(|e| {
340            EvalError::LoadError(format!("image fixture {} could not be read: {e}", path.display()))
341        })?;
342        if bytes.len() > adk_core::MAX_INLINE_DATA_SIZE {
343            return Err(EvalError::LoadError(format!(
344                "image fixture {} is {} bytes, over the {} byte inline limit; downscale it",
345                path.display(),
346                bytes.len(),
347                adk_core::MAX_INLINE_DATA_SIZE
348            )));
349        }
350        let actual = Self::digest_of(&bytes);
351        if actual.strip_prefix("sha256:") != Some(want.as_str()) {
352            return Err(EvalError::LoadError(format!(
353                "image fixture {} is {actual}, which does not match the pinned sha256:{want}; \
354                 the file changed since the case was written, so restore it or update the digest \
355                 and the case's expectations",
356                path.display()
357            )));
358        }
359        self.loaded = Some(LoadedImage { path, bytes: bytes.into() });
360        Ok(())
361    }
362
363    /// The verified bytes, once [`load`](Self::load)ed.
364    pub fn bytes(&self) -> Option<&[u8]> {
365        self.loaded.as_ref().map(|loaded| &*loaded.bytes)
366    }
367
368    /// The resolved path, once [`load`](Self::load)ed.
369    pub fn resolved_path(&self) -> Option<&Path> {
370        self.loaded.as_ref().map(|loaded| loaded.path.as_path())
371    }
372
373    /// The MIME type: the one given, else from the extension (`png`, `jpg`/`jpeg`, `webp`,
374    /// `gif`), else `application/octet-stream`.
375    pub fn mime_type(&self) -> String {
376        if let Some(mime) = &self.mime_type {
377            return mime.clone();
378        }
379        let extension = Path::new(&self.path)
380            .extension()
381            .and_then(|e| e.to_str())
382            .map(str::to_ascii_lowercase)
383            .unwrap_or_default();
384        match extension.as_str() {
385            "png" => "image/png",
386            "jpg" | "jpeg" => "image/jpeg",
387            "webp" => "image/webp",
388            "gif" => "image/gif",
389            _ => "application/octet-stream",
390        }
391        .to_string()
392    }
393
394    /// The fixture as `Part::InlineData`, or `None` before it is loaded.
395    fn to_inline_part(&self) -> Option<adk_core::Part> {
396        let loaded = self.loaded.as_ref()?;
397        Some(adk_core::Part::InlineData {
398            mime_type: self.mime_type(),
399            data: loaded.bytes.to_vec(),
400            uri: None,
401            annotations: Some(serde_json::json!({
402                "adkEvalFixture": {
403                    "path": loaded.path.to_string_lossy(),
404                    "digest": Self::digest_of(&loaded.bytes),
405                }
406            })),
407        })
408    }
409}
410
411/// Intermediate data during a turn (tool calls, etc.)
412#[derive(Debug, Clone, Default, Serialize, Deserialize)]
413pub struct IntermediateData {
414    /// Expected tool calls in order
415    #[serde(default)]
416    pub tool_uses: Vec<ToolUse>,
417    /// Intermediate responses before final
418    #[serde(default)]
419    pub intermediate_responses: Vec<ContentData>,
420}
421
422/// A tool use (function call)
423#[derive(Debug, Clone, Serialize, Deserialize)]
424pub struct ToolUse {
425    /// Tool/function name
426    pub name: String,
427    /// Arguments passed to the tool.
428    ///
429    /// In an expected tool use, `Value::Null` (the value when `args` is omitted from a
430    /// test file) places no constraint on the actual arguments.
431    #[serde(default)]
432    pub args: Value,
433    /// Expected response (optional, for mocking)
434    #[serde(default)]
435    pub expected_response: Option<Value>,
436}
437
438impl ToolUse {
439    /// Create a new tool use
440    pub fn new(name: &str) -> Self {
441        Self {
442            name: name.to_string(),
443            args: Value::Object(Default::default()),
444            expected_response: None,
445        }
446    }
447
448    /// Add arguments
449    pub fn with_args(mut self, args: Value) -> Self {
450        self.args = args;
451        self
452    }
453
454    /// Checks whether `other`, an actual tool call, satisfies this expected tool use.
455    ///
456    /// Names must be equal. Expected arguments of `Value::Null` match any arguments.
457    /// Otherwise arguments are compared recursively, and numbers compare by value, so
458    /// `1` matches `1.0`.
459    ///
460    /// | `strict_args` | Objects | Arrays |
461    /// |---------------|---------|--------|
462    /// | `false` | every expected key is present with a matching value; extra keys are allowed at any depth | same length, matched element by element |
463    /// | `true` | same key set, values matched recursively | same length, matched element by element |
464    ///
465    /// # Example
466    ///
467    /// ```
468    /// use adk_eval::ToolUse;
469    /// use serde_json::json;
470    ///
471    /// let expected = ToolUse::new("search").with_args(json!({"filter": {"limit": 10}}));
472    /// let actual = ToolUse::new("search")
473    ///     .with_args(json!({"query": "rust", "filter": {"limit": 10.0, "page": 2}}));
474    ///
475    /// assert!(expected.matches(&actual, false));
476    /// assert!(!expected.matches(&actual, true));
477    /// ```
478    pub fn matches(&self, other: &ToolUse, strict_args: bool) -> bool {
479        self.name == other.name
480            && (self.args.is_null() || json_matches(&self.args, &other.args, strict_args))
481    }
482}
483
484/// Compares an expected JSON value against an actual one; see [`ToolUse::matches`].
485fn json_matches(expected: &Value, actual: &Value, strict: bool) -> bool {
486    match (expected, actual) {
487        (Value::Number(expected), Value::Number(actual)) => {
488            // Integers compare exactly so values beyond 2^53 do not collapse in f64.
489            if let (Some(expected), Some(actual)) = (expected.as_i64(), actual.as_i64()) {
490                expected == actual
491            } else if let (Some(expected), Some(actual)) = (expected.as_u64(), actual.as_u64()) {
492                expected == actual
493            } else {
494                expected.as_f64() == actual.as_f64()
495            }
496        }
497        (Value::Object(expected), Value::Object(actual)) => {
498            (!strict || expected.len() == actual.len())
499                && expected.iter().all(|(key, value)| {
500                    actual.get(key).is_some_and(|actual| json_matches(value, actual, strict))
501                })
502        }
503        (Value::Array(expected), Value::Array(actual)) => {
504            expected.len() == actual.len()
505                && expected.iter().zip(actual).all(|(e, a)| json_matches(e, a, strict))
506        }
507        _ => expected == actual,
508    }
509}
510
511/// Session input configuration
512#[derive(Debug, Clone, Default, Serialize, Deserialize)]
513pub struct SessionInput {
514    /// Application name
515    #[serde(default)]
516    pub app_name: String,
517    /// User identifier
518    #[serde(default)]
519    pub user_id: String,
520    /// Initial state
521    #[serde(default)]
522    pub state: HashMap<String, Value>,
523}
524
525#[cfg(test)]
526mod tests {
527    use super::*;
528    use serde_json::json;
529
530    #[test]
531    fn test_parse_test_file() {
532        let json = r#"{
533            "eval_set_id": "test_set",
534            "name": "Test Set",
535            "description": "A test set",
536            "eval_cases": [
537                {
538                    "eval_id": "test_1",
539                    "conversation": [
540                        {
541                            "invocation_id": "inv_1",
542                            "user_content": {
543                                "parts": [{"text": "Hello"}],
544                                "role": "user"
545                            },
546                            "final_response": {
547                                "parts": [{"text": "Hi there!"}],
548                                "role": "model"
549                            }
550                        }
551                    ]
552                }
553            ]
554        }"#;
555
556        let test_file: TestFile = serde_json::from_str(json).unwrap();
557        assert_eq!(test_file.eval_set_id, "test_set");
558        assert_eq!(test_file.eval_cases.len(), 1);
559        assert_eq!(test_file.eval_cases[0].eval_id, "test_1");
560    }
561
562    #[test]
563    fn test_tool_use_matching() {
564        let expected = ToolUse::new("get_weather").with_args(json!({"location": "NYC"}));
565
566        let actual_exact = ToolUse::new("get_weather").with_args(json!({"location": "NYC"}));
567        assert!(expected.matches(&actual_exact, true));
568
569        let actual_extra =
570            ToolUse::new("get_weather").with_args(json!({"location": "NYC", "unit": "celsius"}));
571        assert!(!expected.matches(&actual_extra, true)); // Strict fails
572        assert!(expected.matches(&actual_extra, false)); // Partial passes
573
574        let actual_wrong = ToolUse::new("get_weather").with_args(json!({"location": "LA"}));
575        assert!(!expected.matches(&actual_wrong, true));
576        assert!(!expected.matches(&actual_wrong, false));
577    }
578
579    #[test]
580    fn partial_args_match_nested_objects_as_subsets() {
581        let expected = ToolUse::new("book")
582            .with_args(json!({"trip": {"from": "NBO", "legs": [{"seat": "12A"}]}}));
583        let actual = ToolUse::new("book").with_args(json!({
584            "trip": {"from": "NBO", "to": "LHR", "legs": [{"seat": "12A", "meal": "veg"}]},
585            "currency": "KES"
586        }));
587        assert!(expected.matches(&actual, false));
588        assert!(!expected.matches(&actual, true));
589
590        let wrong_nested = ToolUse::new("book")
591            .with_args(json!({"trip": {"from": "MBA", "legs": [{"seat": "12A"}]}}));
592        assert!(!expected.matches(&wrong_nested, false));
593
594        let missing_element =
595            ToolUse::new("book").with_args(json!({"trip": {"from": "NBO", "legs": []}}));
596        assert!(!expected.matches(&missing_element, false));
597    }
598
599    #[test]
600    fn numbers_match_by_value() {
601        let expected = ToolUse::new("set_volume").with_args(json!({"level": 1, "gain": 0.5}));
602        let actual = ToolUse::new("set_volume").with_args(json!({"level": 1.0, "gain": 0.5}));
603        assert!(expected.matches(&actual, false));
604        assert!(expected.matches(&actual, true));
605
606        let different = ToolUse::new("set_volume").with_args(json!({"level": 2, "gain": 0.5}));
607        assert!(!expected.matches(&different, true));
608
609        let large = ToolUse::new("seek").with_args(json!({"offset": 9_007_199_254_740_993_u64}));
610        let off_by_one =
611            ToolUse::new("seek").with_args(json!({"offset": 9_007_199_254_740_992_u64}));
612        assert!(!large.matches(&off_by_one, true));
613    }
614
615    #[test]
616    fn omitted_expected_args_match_any_args() {
617        let expected: ToolUse = serde_json::from_value(json!({"name": "get_time"})).unwrap();
618        let actual = ToolUse::new("get_time").with_args(json!({"timezone": "Africa/Nairobi"}));
619        assert!(expected.matches(&actual, false));
620        assert!(expected.matches(&actual, true));
621        assert!(!expected.matches(&ToolUse::new("get_date"), false));
622    }
623
624    #[test]
625    fn test_content_data() {
626        let content = ContentData::text("Hello world");
627        assert_eq!(content.get_text(), "Hello world");
628        assert_eq!(content.role, "user");
629
630        let model = ContentData::model_response("Hi there!");
631        assert_eq!(model.role, "model");
632    }
633}