Skip to main content

adk_eval/
structured_judge.rs

1//! Structured LLM judge producing typed verdicts.
2//!
3//! The [`StructuredJudge`] evaluates responses using an LLM and produces
4//! machine-parseable [`StructuredVerdict`] results with scores, reasoning,
5//! and categorical verdicts (pass/fail/partial).
6//!
7//! It attempts function-calling (via `response_schema`) first, then falls
8//! back to prompting for JSON output with a lenient extractor.
9
10use crate::error::{EvalError, Result};
11use adk_core::{Content, GenerateContentConfig, Llm, LlmRequest};
12use futures::StreamExt;
13use serde::{Deserialize, Serialize};
14use std::sync::Arc;
15
16/// Verdict from the structured judge.
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct StructuredVerdict {
19    /// Score from 0.0 to 1.0.
20    pub score: f64,
21    /// Human-readable reasoning for the verdict.
22    pub reasoning: String,
23    /// Categorical verdict.
24    pub verdict: Verdict,
25}
26
27/// Categorical outcome of a structured judgment.
28#[derive(Debug, Clone, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30pub enum Verdict {
31    /// The response fully satisfies the criterion.
32    Pass,
33    /// The response does not satisfy the criterion.
34    Fail,
35    /// The response partially satisfies the criterion.
36    Partial,
37}
38
39/// Custom rubric for structured judging.
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct JudgeRubric {
42    /// Name of the rubric.
43    pub name: String,
44    /// Description of what the rubric evaluates.
45    pub description: String,
46    /// Scoring scale with defined points.
47    pub scale: Vec<ScalePoint>,
48}
49
50/// A single point on a rubric scoring scale.
51#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct ScalePoint {
53    /// Numeric score for this level.
54    pub score: f64,
55    /// Short label (e.g., "Excellent", "Poor").
56    pub label: String,
57    /// Detailed description of what this level means.
58    pub description: String,
59}
60
61/// Configuration for the structured judge.
62#[derive(Debug, Clone)]
63pub struct StructuredJudgeConfig {
64    /// Whether to attempt function calling (response_schema) first.
65    pub prefer_function_calling: bool,
66    /// Sampling temperature for the judge LLM; `None` omits it from the request, as models
67    /// that reject sampling parameters (Claude 5 models, OpenAI reasoning models) require.
68    pub temperature: Option<f64>,
69    /// Custom rubrics (optional).
70    pub rubrics: Vec<JudgeRubric>,
71}
72
73impl Default for StructuredJudgeConfig {
74    fn default() -> Self {
75        Self { prefer_function_calling: true, temperature: None, rubrics: Vec::new() }
76    }
77}
78
79/// Structured LLM judge that produces typed verdicts.
80///
81/// Tries function calling first (via response schema), then falls back
82/// to prompting for JSON output with a lenient parser.
83///
84/// Calls meter against the current [`ModelCallScope`](adk_core::ModelCallScope), as
85/// [`LlmJudge`](crate::LlmJudge) calls do.
86pub struct StructuredJudge {
87    model: Arc<dyn Llm>,
88    config: StructuredJudgeConfig,
89}
90
91impl StructuredJudge {
92    /// Create a new structured judge with default configuration.
93    pub fn new(model: Arc<dyn Llm>) -> Self {
94        Self { model, config: StructuredJudgeConfig::default() }
95    }
96
97    /// Create a structured judge with custom configuration.
98    pub fn with_config(model: Arc<dyn Llm>, config: StructuredJudgeConfig) -> Self {
99        Self { model, config }
100    }
101
102    /// Judge a response against expected output with a specific criterion.
103    ///
104    /// Tries function calling first, falls back to JSON extraction.
105    /// On unparseable response, returns score 0.0 with parse error in reasoning.
106    pub async fn judge(
107        &self,
108        expected: &str,
109        actual: &str,
110        criterion: &str,
111    ) -> Result<StructuredVerdict> {
112        let system_prompt = format!(
113            r#"You are an evaluation judge. Evaluate the actual response against the expected response for the given criterion.
114
115Criterion: {}
116
117You MUST respond with a JSON object containing exactly these fields:
118- "score": a number between 0.0 and 1.0
119- "reasoning": a string explaining your evaluation
120- "verdict": one of "pass", "fail", or "partial"
121
122Example response:
123{{"score": 0.85, "reasoning": "The response captures the key points but misses some details.", "verdict": "partial"}}"#,
124            criterion
125        );
126
127        let user_prompt =
128            format!("Expected response:\n\"{}\"\n\nActual response:\n\"{}\"", expected, actual);
129
130        self.execute_judgment(&system_prompt, &user_prompt).await
131    }
132
133    /// Judge with a custom rubric.
134    ///
135    /// Evaluates the response against the rubric's scale points and produces
136    /// a structured verdict.
137    pub async fn judge_with_rubric(
138        &self,
139        response: &str,
140        context: &str,
141        rubric: &JudgeRubric,
142    ) -> Result<StructuredVerdict> {
143        let mut scale_description = String::new();
144        for point in &rubric.scale {
145            scale_description.push_str(&format!(
146                "- {:.1} ({}): {}\n",
147                point.score, point.label, point.description
148            ));
149        }
150
151        let system_prompt = format!(
152            r#"You are an evaluation judge. Evaluate the response using the following rubric.
153
154Rubric: {}
155Description: {}
156
157Scoring Scale:
158{}
159You MUST respond with a JSON object containing exactly these fields:
160- "score": a number between 0.0 and 1.0 matching one of the scale points
161- "reasoning": a string explaining your evaluation
162- "verdict": one of "pass", "fail", or "partial"
163
164Example response:
165{{"score": 0.75, "reasoning": "The response demonstrates good understanding but lacks depth.", "verdict": "partial"}}"#,
166            rubric.name, rubric.description, scale_description
167        );
168
169        let user_prompt =
170            format!("Context:\n\"{}\"\n\nResponse to evaluate:\n\"{}\"", context, response);
171
172        self.execute_judgment(&system_prompt, &user_prompt).await
173    }
174
175    /// Execute a judgment using function-calling first, then JSON fallback.
176    async fn execute_judgment(
177        &self,
178        system_prompt: &str,
179        user_prompt: &str,
180    ) -> Result<StructuredVerdict> {
181        // Attempt 1: Try with response_schema (function-calling style)
182        if self.config.prefer_function_calling {
183            match self.call_with_schema(system_prompt, user_prompt).await {
184                Ok(verdict) => return Ok(verdict),
185                Err(_) => {
186                    // Fall through to JSON fallback
187                }
188            }
189        }
190
191        // Attempt 2: JSON fallback — prompt for JSON and parse leniently
192        self.call_with_json_fallback(system_prompt, user_prompt).await
193    }
194
195    /// Attempt judgment using response_schema for structured output.
196    async fn call_with_schema(
197        &self,
198        system_prompt: &str,
199        user_prompt: &str,
200    ) -> Result<StructuredVerdict> {
201        let schema = serde_json::json!({
202            "type": "object",
203            "properties": {
204                "score": { "type": "number", "minimum": 0.0, "maximum": 1.0 },
205                "reasoning": { "type": "string" },
206                "verdict": { "type": "string", "enum": ["pass", "fail", "partial"] }
207            },
208            "required": ["score", "reasoning", "verdict"]
209        });
210
211        let full_prompt = format!("{system_prompt}\n\n{user_prompt}");
212
213        let config = GenerateContentConfig {
214            temperature: self.config.temperature.map(|temperature| temperature as f32),
215            response_schema: Some(schema),
216            ..Default::default()
217        };
218
219        let request =
220            LlmRequest::new(self.model.name(), vec![Content::new("user").with_text(&full_prompt)])
221                .with_config(config);
222
223        let response_text = self.collect_response(request).await?;
224        self.parse_verdict_from_text(&response_text)
225    }
226
227    /// Attempt judgment by prompting for JSON and parsing leniently.
228    async fn call_with_json_fallback(
229        &self,
230        system_prompt: &str,
231        user_prompt: &str,
232    ) -> Result<StructuredVerdict> {
233        let full_prompt = format!("{system_prompt}\n\n{user_prompt}");
234
235        let config = GenerateContentConfig {
236            temperature: self.config.temperature.map(|temperature| temperature as f32),
237            ..Default::default()
238        };
239
240        let request =
241            LlmRequest::new(self.model.name(), vec![Content::new("user").with_text(&full_prompt)])
242                .with_config(config);
243
244        let response_text = self.collect_response(request).await?;
245        self.parse_verdict_from_text(&response_text)
246    }
247
248    /// Collect all text from an LLM response stream.
249    async fn collect_response(&self, request: LlmRequest) -> Result<String> {
250        // Metered against the current scope, as `LlmJudge` calls are.
251        let mut stream =
252            adk_core::generate_metered(self.model.as_ref(), request, false).await.map_err(|e| {
253                EvalError::from_model_error(e, |e| {
254                    EvalError::JudgeError(format!("LLM judge call failed: {e}"))
255                })
256            })?;
257
258        let mut response_text = String::new();
259        while let Some(result) = stream.next().await {
260            let response = result.map_err(|e| {
261                EvalError::from_model_error(e, |e| {
262                    EvalError::JudgeError(format!("LLM response error: {e}"))
263                })
264            })?;
265            if let Some(content) = &response.content {
266                for part in &content.parts {
267                    if let Some(text) = part.text() {
268                        response_text.push_str(text);
269                    }
270                }
271            }
272        }
273
274        if response_text.is_empty() {
275            return Err(EvalError::JudgeError("Empty response from judge".to_string()));
276        }
277
278        Ok(response_text)
279    }
280
281    /// Parse a StructuredVerdict from LLM response text.
282    ///
283    /// On failure, returns a fallback verdict with score 0.0 and the parse
284    /// error in the reasoning field.
285    fn parse_verdict_from_text(&self, text: &str) -> Result<StructuredVerdict> {
286        match extract_json_from_text(text) {
287            Some(json) => match serde_json::from_value::<StructuredVerdict>(json) {
288                Ok(mut verdict) => {
289                    // Clamp score to [0.0, 1.0]
290                    verdict.score = verdict.score.clamp(0.0, 1.0);
291                    Ok(verdict)
292                }
293                Err(e) => Ok(StructuredVerdict {
294                    score: 0.0,
295                    reasoning: format!("Parse error: failed to deserialize verdict: {e}"),
296                    verdict: Verdict::Fail,
297                }),
298            },
299            None => Ok(StructuredVerdict {
300                score: 0.0,
301                reasoning: format!(
302                    "Parse error: could not extract JSON from response: {}",
303                    truncate_for_error(text)
304                ),
305                verdict: Verdict::Fail,
306            }),
307        }
308    }
309}
310
311/// Lenient JSON extractor that finds JSON objects in arbitrary text.
312///
313/// Handles common LLM output patterns:
314/// - Raw JSON object
315/// - JSON wrapped in markdown code fences (```json ... ```)
316/// - JSON embedded in prose text
317pub fn extract_json_from_text(text: &str) -> Option<serde_json::Value> {
318    let trimmed = text.trim();
319
320    // Pattern 1: Raw JSON object — starts with `{`
321    if trimmed.starts_with('{')
322        && let Ok(value) = serde_json::from_str::<serde_json::Value>(trimmed)
323        && value.is_object()
324    {
325        return Some(value);
326    }
327
328    // Pattern 2: Markdown code fences (```json ... ``` or ``` ... ```)
329    if let Some(json_str) = extract_from_code_fence(trimmed)
330        && let Ok(value) = serde_json::from_str::<serde_json::Value>(json_str)
331        && value.is_object()
332    {
333        return Some(value);
334    }
335
336    // Pattern 3: Embedded JSON in prose — find the first `{` and try to parse
337    if let Some(start) = trimmed.find('{') {
338        // Try progressively from the outermost `{` to find a valid JSON object
339        let substring = &trimmed[start..];
340        if let Some(value) = try_parse_json_object(substring) {
341            return Some(value);
342        }
343    }
344
345    None
346}
347
348/// Extract content from markdown code fences.
349fn extract_from_code_fence(text: &str) -> Option<&str> {
350    // Look for ```json\n...\n``` or ```\n...\n```
351    let fence_start = text.find("```")?;
352    let after_fence = &text[fence_start + 3..];
353
354    // Skip optional language tag (e.g., "json")
355    let content_start = after_fence.find('\n')? + 1;
356    let content = &after_fence[content_start..];
357
358    // Find closing fence
359    let fence_end = content.find("```")?;
360    let inner = content[..fence_end].trim();
361
362    if inner.is_empty() { None } else { Some(inner) }
363}
364
365/// Try to parse a valid JSON object starting from the beginning of the string.
366///
367/// Uses brace counting to find the matching closing brace.
368fn try_parse_json_object(text: &str) -> Option<serde_json::Value> {
369    if !text.starts_with('{') {
370        return None;
371    }
372
373    let mut depth = 0i32;
374    let mut in_string = false;
375    let mut escape_next = false;
376
377    for (i, ch) in text.char_indices() {
378        if escape_next {
379            escape_next = false;
380            continue;
381        }
382
383        if ch == '\\' && in_string {
384            escape_next = true;
385            continue;
386        }
387
388        if ch == '"' {
389            in_string = !in_string;
390            continue;
391        }
392
393        if in_string {
394            continue;
395        }
396
397        match ch {
398            '{' => depth += 1,
399            '}' => {
400                depth -= 1;
401                if depth == 0 {
402                    let candidate = &text[..=i];
403                    if let Ok(value) = serde_json::from_str::<serde_json::Value>(candidate)
404                        && value.is_object()
405                    {
406                        return Some(value);
407                    }
408                    // If parse failed at this brace, keep going — there might
409                    // be a deeper valid match, but that's unlikely. Return None.
410                    return None;
411                }
412            }
413            _ => {}
414        }
415    }
416
417    None
418}
419
420/// Truncate text to 200 characters for inclusion in error messages.
421pub(crate) fn truncate_for_error(text: &str) -> String {
422    match text.char_indices().nth(200) {
423        Some((end, _)) => format!("{}...", &text[..end]),
424        None => text.to_string(),
425    }
426}
427
428#[cfg(test)]
429mod tests {
430    use super::*;
431
432    #[test]
433    fn test_extract_raw_json() {
434        let input = r#"{"score": 0.8, "reasoning": "Good answer", "verdict": "pass"}"#;
435        let result = extract_json_from_text(input).unwrap();
436        assert_eq!(result["score"], 0.8);
437        assert_eq!(result["reasoning"], "Good answer");
438        assert_eq!(result["verdict"], "pass");
439    }
440
441    #[test]
442    fn test_extract_json_with_whitespace() {
443        let input = r#"
444        {"score": 0.5, "reasoning": "Average", "verdict": "partial"}
445        "#;
446        let result = extract_json_from_text(input).unwrap();
447        assert_eq!(result["score"], 0.5);
448        assert_eq!(result["verdict"], "partial");
449    }
450
451    #[test]
452    fn test_extract_json_from_markdown_fence() {
453        let input = r#"Here is my evaluation:
454
455```json
456{"score": 0.9, "reasoning": "Excellent match", "verdict": "pass"}
457```
458
459That's my assessment."#;
460        let result = extract_json_from_text(input).unwrap();
461        assert_eq!(result["score"], 0.9);
462        assert_eq!(result["verdict"], "pass");
463    }
464
465    #[test]
466    fn test_extract_json_from_fence_without_language() {
467        let input = r#"```
468{"score": 0.3, "reasoning": "Poor", "verdict": "fail"}
469```"#;
470        let result = extract_json_from_text(input).unwrap();
471        assert_eq!(result["score"], 0.3);
472        assert_eq!(result["verdict"], "fail");
473    }
474
475    #[test]
476    fn test_extract_json_embedded_in_prose() {
477        let input = r#"After careful consideration, I believe the score should be:
478{"score": 0.7, "reasoning": "Mostly correct but missing key detail", "verdict": "partial"}
479That is my final answer."#;
480        let result = extract_json_from_text(input).unwrap();
481        assert_eq!(result["score"], 0.7);
482        assert_eq!(result["verdict"], "partial");
483    }
484
485    #[test]
486    fn test_extract_json_returns_none_for_garbage() {
487        let input = "This is just a bunch of random text with no JSON at all.";
488        assert!(extract_json_from_text(input).is_none());
489    }
490
491    #[test]
492    fn test_extract_json_returns_none_for_invalid_json() {
493        let input = r#"{"score": bad_value, "reasoning": "test"}"#;
494        assert!(extract_json_from_text(input).is_none());
495    }
496
497    #[test]
498    fn test_extract_json_handles_nested_braces() {
499        let input =
500            r#"{"score": 0.6, "reasoning": "The {nested} braces are fine", "verdict": "partial"}"#;
501        let result = extract_json_from_text(input).unwrap();
502        assert_eq!(result["score"], 0.6);
503        assert!(result["reasoning"].as_str().unwrap().contains("{nested}"));
504    }
505
506    #[test]
507    fn test_extract_json_handles_escaped_quotes() {
508        let input =
509            r#"{"score": 0.5, "reasoning": "He said \"hello\" to me", "verdict": "partial"}"#;
510        let result = extract_json_from_text(input).unwrap();
511        assert_eq!(result["score"], 0.5);
512    }
513
514    #[test]
515    fn test_parse_verdict_fallback_on_missing_fields() {
516        let judge = StructuredJudge::new(Arc::new(adk_model::MockLlm::new("test")));
517        // JSON missing "verdict" field
518        let result = judge.parse_verdict_from_text(r#"{"score": 0.5, "reasoning": "ok"}"#);
519        let verdict = result.unwrap();
520        assert_eq!(verdict.score, 0.0);
521        assert!(verdict.reasoning.contains("Parse error"));
522    }
523
524    #[test]
525    fn test_parse_verdict_fallback_on_no_json() {
526        let judge = StructuredJudge::new(Arc::new(adk_model::MockLlm::new("test")));
527        let result = judge.parse_verdict_from_text("I think the answer is good.");
528        let verdict = result.unwrap();
529        assert_eq!(verdict.score, 0.0);
530        assert!(verdict.reasoning.contains("Parse error"));
531    }
532
533    #[test]
534    fn test_parse_verdict_clamps_score() {
535        let judge = StructuredJudge::new(Arc::new(adk_model::MockLlm::new("test")));
536        let text = r#"{"score": 1.5, "reasoning": "Great", "verdict": "pass"}"#;
537        let verdict = judge.parse_verdict_from_text(text).unwrap();
538        assert_eq!(verdict.score, 1.0);
539
540        let text = r#"{"score": -0.3, "reasoning": "Bad", "verdict": "fail"}"#;
541        let verdict = judge.parse_verdict_from_text(text).unwrap();
542        assert_eq!(verdict.score, 0.0);
543    }
544
545    #[test]
546    fn test_structured_judge_config_defaults() {
547        let config = StructuredJudgeConfig::default();
548        assert!(config.prefer_function_calling);
549        assert_eq!(config.temperature, None);
550        assert!(config.rubrics.is_empty());
551    }
552}