1use 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
21fn base_dir(path: &Path) -> &Path {
23 path.parent().unwrap_or(Path::new("."))
24}
25
26#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct TestFile {
29 pub eval_set_id: String,
31 pub name: String,
33 #[serde(default)]
35 pub description: String,
36 pub eval_cases: Vec<EvalCase>,
38}
39
40impl TestFile {
41 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct EvalSet {
67 pub eval_set_id: String,
69 pub name: String,
71 #[serde(default)]
73 pub description: String,
74 #[serde(default)]
76 pub test_files: Vec<String>,
77 #[serde(default)]
79 pub eval_cases: Vec<EvalCase>,
80}
81
82impl EvalSet {
83 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
116pub struct EvalCase {
117 pub eval_id: String,
119 #[serde(default)]
121 pub description: String,
122 pub conversation: Vec<Turn>,
124 #[serde(default)]
126 pub session_input: SessionInput,
127 #[serde(default)]
129 pub tags: Vec<String>,
130 #[serde(default, skip_serializing_if = "Option::is_none")]
132 pub metadata: Option<EvalCaseMetadata>,
133}
134
135impl EvalCase {
136 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
175pub struct Turn {
176 pub invocation_id: String,
178 pub user_content: ContentData,
180 #[serde(default)]
182 pub final_response: Option<ContentData>,
183 #[serde(default)]
185 pub intermediate_data: Option<IntermediateData>,
186 #[serde(default, skip_serializing_if = "Option::is_none")]
189 pub expected_vision: Option<VisionExpected>,
190}
191
192#[derive(Debug, Clone, Serialize, Deserialize)]
194pub struct ContentData {
195 pub parts: Vec<Part>,
197 #[serde(default = "default_role")]
199 pub role: String,
200}
201
202fn default_role() -> String {
203 "user".to_string()
204}
205
206impl ContentData {
207 pub fn text(text: &str) -> Self {
209 Self { parts: vec![Part::Text { text: text.to_string() }], role: "user".to_string() }
210 }
211
212 pub fn model_response(text: &str) -> Self {
214 Self { parts: vec![Part::Text { text: text.to_string() }], role: "model".to_string() }
215 }
216
217 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 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 }
250 }
251 }
252 content
253 }
254}
255
256#[derive(Debug, Clone, Serialize, Deserialize)]
258#[serde(untagged)]
259pub enum Part {
260 Text { text: String },
262 FunctionCall { name: String, args: Value },
264 FunctionResponse { name: String, response: Value },
266 Image { image: ImageFixture },
268}
269
270#[derive(Debug, Clone, Serialize, Deserialize)]
291pub struct ImageFixture {
292 pub path: String,
294 pub digest: String,
296 #[serde(default, skip_serializing_if = "Option::is_none")]
298 pub mime_type: Option<String>,
299 #[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 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 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 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 pub fn bytes(&self) -> Option<&[u8]> {
365 self.loaded.as_ref().map(|loaded| &*loaded.bytes)
366 }
367
368 pub fn resolved_path(&self) -> Option<&Path> {
370 self.loaded.as_ref().map(|loaded| loaded.path.as_path())
371 }
372
373 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 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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
413pub struct IntermediateData {
414 #[serde(default)]
416 pub tool_uses: Vec<ToolUse>,
417 #[serde(default)]
419 pub intermediate_responses: Vec<ContentData>,
420}
421
422#[derive(Debug, Clone, Serialize, Deserialize)]
424pub struct ToolUse {
425 pub name: String,
427 #[serde(default)]
432 pub args: Value,
433 #[serde(default)]
435 pub expected_response: Option<Value>,
436}
437
438impl ToolUse {
439 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 pub fn with_args(mut self, args: Value) -> Self {
450 self.args = args;
451 self
452 }
453
454 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
484fn json_matches(expected: &Value, actual: &Value, strict: bool) -> bool {
486 match (expected, actual) {
487 (Value::Number(expected), Value::Number(actual)) => {
488 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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
513pub struct SessionInput {
514 #[serde(default)]
516 pub app_name: String,
517 #[serde(default)]
519 pub user_id: String,
520 #[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)); assert!(expected.matches(&actual_extra, false)); 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}