Skip to main content

adk_eval/
test_generator.rs

1//! LLM-driven test case generation.
2//!
3//! Generates evaluation test cases from natural language descriptions (via LLM)
4//! or from production event logs (direct extraction). Produced cases follow
5//! the standard [`TestFile`](crate::TestFile) JSON format and include generation metadata.
6//!
7//! # Example
8//!
9//! ```rust,ignore
10//! use adk_eval::test_generator::{TestGenerator, GeneratorConfig};
11//! use std::sync::Arc;
12//!
13//! let generator = TestGenerator::with_config(model, GeneratorConfig {
14//!     cases_per_description: 3,
15//!     include_tool_expectations: true,
16//! });
17//!
18//! let cases = generator
19//!     .generate_from_description("A weather assistant that can look up forecasts")
20//!     .await?;
21//! ```
22
23use std::sync::Arc;
24
25use adk_core::{Event, Llm, LlmRequest, Part};
26use futures::StreamExt;
27use serde::{Deserialize, Serialize};
28use tracing::warn;
29
30use crate::error::{EvalError, Result};
31use crate::schema::{ContentData, EvalCase, Turn};
32
33/// Configuration for test case generation.
34#[derive(Debug, Clone)]
35pub struct GeneratorConfig {
36    /// Number of cases to generate per description.
37    pub cases_per_description: usize,
38    /// Whether to include tool use expectations in generated cases.
39    pub include_tool_expectations: bool,
40}
41
42impl Default for GeneratorConfig {
43    fn default() -> Self {
44        Self { cases_per_description: 5, include_tool_expectations: true }
45    }
46}
47
48/// Metadata for generated eval cases.
49#[derive(Debug, Clone, Default, Serialize, Deserialize)]
50pub struct EvalCaseMetadata {
51    /// Whether this case was auto-generated.
52    #[serde(default)]
53    pub generated: bool,
54    /// Source description (e.g., "description: ..." or "events").
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub source: Option<String>,
57}
58
59/// Generates evaluation test cases from descriptions or event logs.
60pub struct TestGenerator {
61    model: Arc<dyn Llm>,
62    config: GeneratorConfig,
63}
64
65impl TestGenerator {
66    /// Creates a new test generator with default configuration.
67    pub fn new(model: Arc<dyn Llm>) -> Self {
68        Self { model, config: GeneratorConfig::default() }
69    }
70
71    /// Creates a new test generator with custom configuration.
72    pub fn with_config(model: Arc<dyn Llm>, config: GeneratorConfig) -> Self {
73        Self { model, config }
74    }
75
76    /// Generate eval cases from a natural language description.
77    ///
78    /// Prompts the LLM to produce eval case definitions as JSON. On parse failure
79    /// for any individual case, a warning is logged and that case is skipped
80    /// without aborting the batch.
81    pub async fn generate_from_description(&self, description: &str) -> Result<Vec<EvalCase>> {
82        let prompt = self.build_generation_prompt(description);
83
84        let request = LlmRequest::new(
85            self.model.name().to_string(),
86            vec![adk_core::Content::new("user").with_text(&prompt)],
87        );
88
89        let mut stream = self
90            .model
91            .generate_content(request, false)
92            .await
93            .map_err(|e| EvalError::GenerationError(format!("LLM request failed: {e}")))?;
94
95        // Collect the full response text
96        let mut response_text = String::new();
97        while let Some(chunk) = stream.next().await {
98            match chunk {
99                Ok(response) => {
100                    if let Some(content) = &response.content {
101                        for part in &content.parts {
102                            if let Part::Text { text } = part {
103                                response_text.push_str(text);
104                            }
105                        }
106                    }
107                }
108                Err(e) => {
109                    return Err(EvalError::GenerationError(format!("LLM stream error: {e}")));
110                }
111            }
112        }
113
114        // Parse the response into eval cases
115        self.parse_generated_cases(&response_text, description)
116    }
117
118    /// Generate eval cases from production event logs.
119    ///
120    /// Extracts conversation turns from the provided events, constructing
121    /// [`EvalCase`] objects directly without invoking the LLM.
122    pub fn generate_from_events(&self, events: &[Event]) -> Result<Vec<EvalCase>> {
123        if events.is_empty() {
124            return Ok(Vec::new());
125        }
126
127        // Group events by invocation_id to form conversation turns
128        let mut invocations: Vec<(String, Vec<&Event>)> = Vec::new();
129        for event in events {
130            if let Some(last) = invocations.last_mut()
131                && last.0 == event.invocation_id
132            {
133                last.1.push(event);
134                continue;
135            }
136            invocations.push((event.invocation_id.clone(), vec![event]));
137        }
138
139        let mut turns = Vec::new();
140
141        for (invocation_id, inv_events) in &invocations {
142            let mut user_text = String::new();
143            let mut model_text = String::new();
144            let mut tool_uses = Vec::new();
145
146            for event in inv_events {
147                if let Some(content) = event.content() {
148                    match content.role.as_str() {
149                        "user" => {
150                            for part in &content.parts {
151                                if let Part::Text { text } = part {
152                                    if !user_text.is_empty() {
153                                        user_text.push(' ');
154                                    }
155                                    user_text.push_str(text);
156                                }
157                            }
158                        }
159                        "model" => {
160                            for part in &content.parts {
161                                match part {
162                                    Part::Text { text } => {
163                                        if !model_text.is_empty() {
164                                            model_text.push(' ');
165                                        }
166                                        model_text.push_str(text);
167                                    }
168                                    Part::FunctionCall { name, args, .. }
169                                        if self.config.include_tool_expectations =>
170                                    {
171                                        tool_uses.push(crate::schema::ToolUse {
172                                            name: name.clone(),
173                                            args: args.clone(),
174                                            expected_response: None,
175                                        });
176                                    }
177                                    _ => {}
178                                }
179                            }
180                        }
181                        _ => {}
182                    }
183                }
184            }
185
186            // Only create a turn if we have user content
187            if !user_text.is_empty() {
188                let final_response = if model_text.is_empty() {
189                    None
190                } else {
191                    Some(ContentData::model_response(&model_text))
192                };
193
194                let intermediate_data = if tool_uses.is_empty() {
195                    None
196                } else {
197                    Some(crate::schema::IntermediateData {
198                        tool_uses,
199                        intermediate_responses: Vec::new(),
200                    })
201                };
202
203                turns.push(Turn {
204                    invocation_id: invocation_id.clone(),
205                    user_content: ContentData::text(&user_text),
206                    final_response,
207                    intermediate_data,
208                    expected_vision: None,
209                });
210            }
211        }
212
213        if turns.is_empty() {
214            return Ok(Vec::new());
215        }
216
217        let eval_case = EvalCase {
218            eval_id: format!("generated_from_events_{}", uuid::Uuid::new_v4()),
219            description: "Generated from event logs".to_string(),
220            conversation: turns,
221            session_input: Default::default(),
222            tags: vec!["generated".to_string()],
223            metadata: Some(EvalCaseMetadata {
224                generated: true,
225                source: Some("events".to_string()),
226            }),
227        };
228
229        Ok(vec![eval_case])
230    }
231
232    /// Build the prompt for LLM-based case generation.
233    fn build_generation_prompt(&self, description: &str) -> String {
234        let tool_instruction = if self.config.include_tool_expectations {
235            r#"Include "intermediate_data" with "tool_uses" where appropriate, each with "name" and "args" fields."#
236        } else {
237            r#"Do not include "intermediate_data" in the output."#
238        };
239
240        format!(
241            r#"Generate exactly {count} evaluation test cases for the following agent description:
242
243"{description}"
244
245Each test case must be a JSON object with these fields:
246- "eval_id": a unique string identifier (e.g., "test_1", "test_2")
247- "description": a brief description of what the test case validates
248- "conversation": an array of conversation turns, each with:
249  - "invocation_id": a unique string (e.g., "inv_1")
250  - "user_content": object with "parts": [{{"text": "..."}}] and "role": "user"
251  - "final_response": object with "parts": [{{"text": "..."}}] and "role": "model"
252  {tool_instruction}
253
254Output ONLY a JSON array of test case objects. No markdown fences, no explanation text.
255Example format:
256[
257  {{
258    "eval_id": "test_1",
259    "description": "Basic greeting test",
260    "conversation": [
261      {{
262        "invocation_id": "inv_1",
263        "user_content": {{"parts": [{{"text": "Hello"}}], "role": "user"}},
264        "final_response": {{"parts": [{{"text": "Hi there! How can I help?"}}], "role": "model"}}
265      }}
266    ]
267  }}
268]"#,
269            count = self.config.cases_per_description,
270            description = description,
271            tool_instruction = tool_instruction,
272        )
273    }
274
275    /// Parse the LLM response text into eval cases, skipping unparseable entries.
276    fn parse_generated_cases(
277        &self,
278        response_text: &str,
279        description: &str,
280    ) -> Result<Vec<EvalCase>> {
281        let json_text = extract_json_array(response_text).unwrap_or(response_text);
282
283        // Try parsing as an array of eval cases
284        let raw_cases: Vec<serde_json::Value> = match serde_json::from_str(json_text) {
285            Ok(cases) => cases,
286            Err(e) => {
287                // Try to extract JSON array from the text
288                warn!("failed to parse LLM response as JSON array: {e}");
289                return Err(EvalError::GenerationError(format!(
290                    "LLM returned unparseable response: {e}"
291                )));
292            }
293        };
294
295        let source = format!("description: {description}");
296        let mut cases = Vec::new();
297
298        for (i, raw_case) in raw_cases.iter().enumerate() {
299            match serde_json::from_value::<EvalCase>(raw_case.clone()) {
300                Ok(mut eval_case) => {
301                    // Add generation tags
302                    if !eval_case.tags.contains(&"generated".to_string()) {
303                        eval_case.tags.push("generated".to_string());
304                    }
305                    cases.push(eval_case);
306                }
307                Err(e) => {
308                    // Log warning and skip this case without aborting the batch
309                    warn!(
310                        case_index = i,
311                        error = %e,
312                        "skipping unparseable generated case"
313                    );
314                }
315            }
316        }
317
318        if cases.is_empty() && !raw_cases.is_empty() {
319            return Err(EvalError::GenerationError(format!(
320                "all {count} generated cases failed to parse (source: {source})",
321                count = raw_cases.len(),
322            )));
323        }
324
325        // Attach metadata as tags for traceability
326        // The full EvalCaseMetadata integration happens in task 16.2
327        for case in &mut cases {
328            if !case.tags.contains(&source) {
329                case.tags.push(source.clone());
330            }
331        }
332
333        Ok(cases)
334    }
335}
336
337/// Extract a JSON array from text that may contain markdown fences or prose.
338///
339/// Handles common LLM output patterns:
340/// - Raw JSON array
341/// - JSON wrapped in ```json ... ``` fences
342/// - JSON embedded in prose text
343fn extract_json_array(text: &str) -> Option<&str> {
344    let trimmed = text.trim();
345
346    // If it already starts with '[', use it directly
347    if trimmed.starts_with('[') {
348        return Some(trimmed);
349    }
350
351    // Try to find JSON within markdown code fences
352    if let Some(start) = trimmed.find("```json") {
353        let content_start = start + "```json".len();
354        if let Some(end) = trimmed[content_start..].find("```") {
355            let json_content = trimmed[content_start..content_start + end].trim();
356            if json_content.starts_with('[') {
357                return Some(json_content);
358            }
359        }
360    }
361
362    // Try generic code fences
363    if let Some(start) = trimmed.find("```") {
364        let content_start = start + 3;
365        // Skip the optional language identifier on the same line
366        let line_end = trimmed[content_start..]
367            .find('\n')
368            .map(|i| content_start + i + 1)
369            .unwrap_or(content_start);
370        if let Some(end) = trimmed[line_end..].find("```") {
371            let json_content = trimmed[line_end..line_end + end].trim();
372            if json_content.starts_with('[') {
373                return Some(json_content);
374            }
375        }
376    }
377
378    // Try to find a JSON array anywhere in the text
379    if let Some(start) = trimmed.find('[')
380        && let Some(end) = trimmed.rfind(']')
381        && end > start
382    {
383        return Some(&trimmed[start..=end]);
384    }
385
386    None
387}
388
389#[cfg(test)]
390mod tests {
391    use super::*;
392
393    #[test]
394    fn test_generator_config_defaults() {
395        let config = GeneratorConfig::default();
396        assert_eq!(config.cases_per_description, 5);
397        assert!(config.include_tool_expectations);
398    }
399
400    #[test]
401    fn test_extract_json_array_raw() {
402        let input = r#"[{"eval_id": "test_1"}]"#;
403        let result = extract_json_array(input);
404        assert_eq!(result, Some(input));
405    }
406
407    #[test]
408    fn test_extract_json_array_fenced() {
409        let input = "Here are the cases:\n```json\n[{\"eval_id\": \"test_1\"}]\n```\nDone!";
410        let result = extract_json_array(input);
411        assert_eq!(result, Some(r#"[{"eval_id": "test_1"}]"#));
412    }
413
414    #[test]
415    fn test_extract_json_array_embedded() {
416        let input = "Sure, here are the cases: [{\"eval_id\": \"test_1\"}] and that's all.";
417        let result = extract_json_array(input);
418        assert_eq!(result, Some(r#"[{"eval_id": "test_1"}]"#));
419    }
420
421    #[test]
422    fn test_extract_json_array_no_array() {
423        let input = "No JSON here at all.";
424        let result = extract_json_array(input);
425        assert_eq!(result, None);
426    }
427
428    #[test]
429    fn test_extract_json_array_with_whitespace() {
430        let input = "  \n  [{\"eval_id\": \"test_1\"}]  \n  ";
431        let result = extract_json_array(input);
432        assert_eq!(result, Some(r#"[{"eval_id": "test_1"}]"#));
433    }
434
435    #[test]
436    fn test_generate_from_events_empty() {
437        use adk_core::Llm;
438        use async_trait::async_trait;
439
440        struct MockLlm;
441
442        #[async_trait]
443        impl Llm for MockLlm {
444            fn name(&self) -> &str {
445                "mock"
446            }
447            async fn generate_content(
448                &self,
449                _req: LlmRequest,
450                _stream: bool,
451            ) -> adk_core::Result<adk_core::LlmResponseStream> {
452                unimplemented!()
453            }
454        }
455
456        let generator = TestGenerator::new(Arc::new(MockLlm));
457        let result = generator.generate_from_events(&[]).unwrap();
458        assert!(result.is_empty());
459    }
460
461    #[test]
462    fn test_generate_from_events_with_conversation() {
463        use adk_core::{Content, Llm, LlmResponse};
464        use async_trait::async_trait;
465
466        struct MockLlm;
467
468        #[async_trait]
469        impl Llm for MockLlm {
470            fn name(&self) -> &str {
471                "mock"
472            }
473            async fn generate_content(
474                &self,
475                _req: LlmRequest,
476                _stream: bool,
477            ) -> adk_core::Result<adk_core::LlmResponseStream> {
478                unimplemented!()
479            }
480        }
481
482        let mut events = Vec::new();
483
484        // User event
485        let mut user_event = Event::new("inv_1");
486        user_event.author = "user".to_string();
487        user_event.llm_response = LlmResponse {
488            content: Some(Content::new("user").with_text("What is the weather?")),
489            ..Default::default()
490        };
491        events.push(user_event);
492
493        // Model response event
494        let mut model_event = Event::new("inv_1");
495        model_event.author = "model".to_string();
496        model_event.llm_response = LlmResponse {
497            content: Some(Content::new("model").with_text("The weather is sunny.")),
498            ..Default::default()
499        };
500        events.push(model_event);
501
502        let generator = TestGenerator::new(Arc::new(MockLlm));
503        let cases = generator.generate_from_events(&events).unwrap();
504
505        assert_eq!(cases.len(), 1);
506        let case = &cases[0];
507        assert!(case.eval_id.starts_with("generated_from_events_"));
508        assert_eq!(case.conversation.len(), 1);
509
510        let turn = &case.conversation[0];
511        assert_eq!(turn.invocation_id, "inv_1");
512        assert_eq!(turn.user_content.get_text(), "What is the weather?");
513        assert_eq!(turn.final_response.as_ref().unwrap().get_text(), "The weather is sunny.");
514        assert!(case.tags.contains(&"generated".to_string()));
515    }
516
517    #[test]
518    fn test_generate_from_events_with_tool_calls() {
519        use adk_core::{Content, Llm, LlmResponse, Part};
520        use async_trait::async_trait;
521
522        struct MockLlm;
523
524        #[async_trait]
525        impl Llm for MockLlm {
526            fn name(&self) -> &str {
527                "mock"
528            }
529            async fn generate_content(
530                &self,
531                _req: LlmRequest,
532                _stream: bool,
533            ) -> adk_core::Result<adk_core::LlmResponseStream> {
534                unimplemented!()
535            }
536        }
537
538        let mut events = Vec::new();
539
540        // User event
541        let mut user_event = Event::new("inv_1");
542        user_event.llm_response = LlmResponse {
543            content: Some(Content::new("user").with_text("Get weather in NYC")),
544            ..Default::default()
545        };
546        events.push(user_event);
547
548        // Model event with tool call and text
549        let mut model_event = Event::new("inv_1");
550        model_event.llm_response = LlmResponse {
551            content: Some(Content {
552                role: "model".to_string(),
553                parts: vec![
554                    Part::FunctionCall {
555                        name: "get_weather".to_string(),
556                        args: serde_json::json!({"location": "NYC"}),
557                        id: Some("call_1".to_string()),
558                        thought_signature: None,
559                    },
560                    Part::Text { text: "It's 72°F in NYC.".to_string() },
561                ],
562            }),
563            ..Default::default()
564        };
565        events.push(model_event);
566
567        let generator = TestGenerator::new(Arc::new(MockLlm));
568        let cases = generator.generate_from_events(&events).unwrap();
569
570        assert_eq!(cases.len(), 1);
571        let turn = &cases[0].conversation[0];
572        let intermediate = turn.intermediate_data.as_ref().unwrap();
573        assert_eq!(intermediate.tool_uses.len(), 1);
574        assert_eq!(intermediate.tool_uses[0].name, "get_weather");
575        assert_eq!(intermediate.tool_uses[0].args, serde_json::json!({"location": "NYC"}));
576    }
577
578    #[test]
579    fn test_parse_generated_cases_valid() {
580        use adk_core::Llm;
581        use async_trait::async_trait;
582
583        struct MockLlm;
584
585        #[async_trait]
586        impl Llm for MockLlm {
587            fn name(&self) -> &str {
588                "mock"
589            }
590            async fn generate_content(
591                &self,
592                _req: LlmRequest,
593                _stream: bool,
594            ) -> adk_core::Result<adk_core::LlmResponseStream> {
595                unimplemented!()
596            }
597        }
598
599        let generator = TestGenerator::new(Arc::new(MockLlm));
600        let response = r#"[
601            {
602                "eval_id": "test_1",
603                "description": "Greeting test",
604                "conversation": [{
605                    "invocation_id": "inv_1",
606                    "user_content": {"parts": [{"text": "Hello"}], "role": "user"},
607                    "final_response": {"parts": [{"text": "Hi!"}], "role": "model"}
608                }]
609            }
610        ]"#;
611
612        let cases = generator.parse_generated_cases(response, "test agent").unwrap();
613        assert_eq!(cases.len(), 1);
614        assert_eq!(cases[0].eval_id, "test_1");
615        assert!(cases[0].tags.contains(&"generated".to_string()));
616        assert!(cases[0].tags.contains(&"description: test agent".to_string()));
617    }
618
619    #[test]
620    fn test_parse_generated_cases_partial_failure() {
621        use adk_core::Llm;
622        use async_trait::async_trait;
623
624        struct MockLlm;
625
626        #[async_trait]
627        impl Llm for MockLlm {
628            fn name(&self) -> &str {
629                "mock"
630            }
631            async fn generate_content(
632                &self,
633                _req: LlmRequest,
634                _stream: bool,
635            ) -> adk_core::Result<adk_core::LlmResponseStream> {
636                unimplemented!()
637            }
638        }
639
640        let generator = TestGenerator::new(Arc::new(MockLlm));
641        // Mix of valid and invalid cases
642        let response = r#"[
643            {
644                "eval_id": "test_1",
645                "description": "Valid case",
646                "conversation": [{
647                    "invocation_id": "inv_1",
648                    "user_content": {"parts": [{"text": "Hello"}], "role": "user"},
649                    "final_response": {"parts": [{"text": "Hi!"}], "role": "model"}
650                }]
651            },
652            {
653                "invalid_field": "This is not a valid EvalCase"
654            }
655        ]"#;
656
657        let cases = generator.parse_generated_cases(response, "test").unwrap();
658        // Should parse the valid case and skip the invalid one
659        assert_eq!(cases.len(), 1);
660        assert_eq!(cases[0].eval_id, "test_1");
661    }
662
663    #[test]
664    fn test_parse_generated_cases_all_invalid() {
665        use adk_core::Llm;
666        use async_trait::async_trait;
667
668        struct MockLlm;
669
670        #[async_trait]
671        impl Llm for MockLlm {
672            fn name(&self) -> &str {
673                "mock"
674            }
675            async fn generate_content(
676                &self,
677                _req: LlmRequest,
678                _stream: bool,
679            ) -> adk_core::Result<adk_core::LlmResponseStream> {
680                unimplemented!()
681            }
682        }
683
684        let generator = TestGenerator::new(Arc::new(MockLlm));
685        let response = r#"[{"bad": true}, {"also_bad": "yes"}]"#;
686
687        let result = generator.parse_generated_cases(response, "test");
688        assert!(result.is_err());
689        let err = result.unwrap_err().to_string();
690        assert!(err.contains("all 2 generated cases failed to parse"));
691    }
692
693    #[test]
694    fn test_eval_case_metadata_serialization() {
695        let meta = EvalCaseMetadata { generated: true, source: Some("events".to_string()) };
696
697        let json = serde_json::to_string(&meta).unwrap();
698        assert!(json.contains("\"generated\":true"));
699        assert!(json.contains("\"source\":\"events\""));
700
701        let deserialized: EvalCaseMetadata = serde_json::from_str(&json).unwrap();
702        assert!(deserialized.generated);
703        assert_eq!(deserialized.source.as_deref(), Some("events"));
704    }
705
706    #[test]
707    fn test_eval_case_metadata_defaults() {
708        let meta = EvalCaseMetadata::default();
709        assert!(!meta.generated);
710        assert!(meta.source.is_none());
711
712        // source field should be skipped when None
713        let json = serde_json::to_string(&meta).unwrap();
714        assert!(!json.contains("source"));
715    }
716
717    #[test]
718    fn test_generate_from_events_no_tool_expectations() {
719        use adk_core::{Content, Llm, LlmResponse, Part};
720        use async_trait::async_trait;
721
722        struct MockLlm;
723
724        #[async_trait]
725        impl Llm for MockLlm {
726            fn name(&self) -> &str {
727                "mock"
728            }
729            async fn generate_content(
730                &self,
731                _req: LlmRequest,
732                _stream: bool,
733            ) -> adk_core::Result<adk_core::LlmResponseStream> {
734                unimplemented!()
735            }
736        }
737
738        let config = GeneratorConfig { cases_per_description: 5, include_tool_expectations: false };
739        let generator = TestGenerator::with_config(Arc::new(MockLlm), config);
740
741        let mut events = Vec::new();
742
743        let mut user_event = Event::new("inv_1");
744        user_event.llm_response = LlmResponse {
745            content: Some(Content::new("user").with_text("Get weather")),
746            ..Default::default()
747        };
748        events.push(user_event);
749
750        let mut model_event = Event::new("inv_1");
751        model_event.llm_response = LlmResponse {
752            content: Some(Content {
753                role: "model".to_string(),
754                parts: vec![
755                    Part::FunctionCall {
756                        name: "get_weather".to_string(),
757                        args: serde_json::json!({"location": "NYC"}),
758                        id: None,
759                        thought_signature: None,
760                    },
761                    Part::Text { text: "Sunny".to_string() },
762                ],
763            }),
764            ..Default::default()
765        };
766        events.push(model_event);
767
768        let cases = generator.generate_from_events(&events).unwrap();
769        assert_eq!(cases.len(), 1);
770        // Tool expectations should NOT be included
771        assert!(cases[0].conversation[0].intermediate_data.is_none());
772    }
773}