Skip to main content

graphrt_eval/
judge.rs

1//! LLM judges written as ordinary graphrt workflows.
2//!
3//! `{type: judge, workflow: judges/faithfulness.yaml}` runs the judge workflow
4//! on what the test produced and reads a verdict from its outputs. A judge is
5//! versioned by its workflow fingerprint (recorded with every result), runs on
6//! any provider (including `replay` cassettes), and is calibrated like any
7//! other workflow: an eval whose target is the judge and whose `expected`
8//! values are human labels (see `calibration` in the eval file).
9//!
10//! **Inputs.** The judge's start node receives, by name (only the variables it
11//! declares):
12//!
13//! | Input | Value |
14//! | --- | --- |
15//! | `output` | The value under test (the run output, or the `transform` path). |
16//! | `vars` | The test's vars (an object). |
17//! | `expected` | The test's `expected` value (absent when there is none). |
18//! | `contexts` | The text of every chunk the run's `knowledge-retrieval` nodes returned, in rank order. |
19//! | `trajectory` | The run's agent tool calls: `[{node_id, name, provider?, tool?, arguments, is_error?}]`. |
20//! | anything in `inputs` | Extra inputs from the assertion, e.g. `inputs: { question: "{{question}}" }`. |
21//!
22//! Text inputs (`paragraph`, `text-input`, `string`...) get text: strings as
23//! is, a list of strings joined by blank lines, anything else as JSON. `json`,
24//! `object` and array inputs get the value itself.
25//!
26//! **Outputs.** The judge's outputs (or its single object output, e.g. an
27//! `llm` node's `structured_output`) carry `verdict: pass | fail | unknown`
28//! and/or a numeric `score` in `0..=1`, plus an optional `reasoning`. A verdict
29//! decides; a score alone passes at `threshold` (default 0.5). `unknown`
30//! fails the assertion unless `unknown: exclude`, which reports it without
31//! scoring or gating it.
32
33use std::collections::HashMap;
34use std::fmt;
35use std::path::{Path, PathBuf};
36use std::sync::{Arc, Mutex, PoisonError};
37
38use futures::future::BoxFuture;
39use graphrt_core::event::Usage;
40use serde::{Deserialize, Serialize};
41use serde_json::{Map, Value as Json};
42
43use crate::assertion::{Assertion, AssertionContext, AssertionRegistry, Outcome, brief, only_keys, transform_of};
44use crate::capture::RunStatus;
45use crate::config::{AssertionSpec, TestCase};
46use crate::error::EvalError;
47use crate::path::JsonPath;
48use crate::report::WorkflowInfo;
49use crate::runner::Target;
50
51/// A judge's binary verdict, with an explicit way out.
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(rename_all = "snake_case")]
54pub enum Verdict {
55    Pass,
56    Fail,
57    /// The judge could not tell (missing context, ambiguous case...).
58    Unknown,
59}
60
61impl Verdict {
62    /// `pass` / `fail` / `unknown` (any case), `yes` / `no`, `true` / `false`.
63    pub fn parse(value: &Json) -> Option<Self> {
64        match value {
65            Json::Bool(pass) => Some(if *pass { Self::Pass } else { Self::Fail }),
66            Json::String(text) => match text.trim().to_ascii_lowercase().as_str() {
67                "pass" | "passed" | "yes" | "true" => Some(Self::Pass),
68                "fail" | "failed" | "no" | "false" => Some(Self::Fail),
69                "unknown" | "unsure" => Some(Self::Unknown),
70                _ => None,
71            },
72            _ => None,
73        }
74    }
75
76    pub fn as_str(self) -> &'static str {
77        match self {
78            Self::Pass => "pass",
79            Self::Fail => "fail",
80            Self::Unknown => "unknown",
81        }
82    }
83}
84
85impl fmt::Display for Verdict {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        f.write_str(self.as_str())
88    }
89}
90
91/// What a judge decided, recorded with the assertion result.
92#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
93#[non_exhaustive]
94pub struct JudgeRecord {
95    /// The judge workflow file.
96    pub workflow: String,
97    /// Its `graphrt.workflow.fingerprint`: changes whenever the judge's prompt,
98    /// model or schema does.
99    pub fingerprint: String,
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub verdict: Option<Verdict>,
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub score: Option<f64>,
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub reasoning: Option<String>,
106    #[serde(default, skip_serializing_if = "String::is_empty")]
107    pub run_id: String,
108    pub latency_ms: u64,
109    pub usage: Usage,
110}
111
112/// A verdict and/or score read from a judge's outputs.
113#[derive(Clone, Debug, Default, PartialEq)]
114#[non_exhaustive]
115pub struct Judgement {
116    pub verdict: Option<Verdict>,
117    pub score: Option<f64>,
118    pub reasoning: Option<String>,
119}
120
121impl Judgement {
122    /// Read `verdict`, `score` and `reasoning` from a judge's outputs, or from
123    /// its single output when that is an object (or JSON text of one).
124    pub fn read(outputs: &Map<String, Json>) -> Result<Self, String> {
125        let has_fields = |map: &Map<String, Json>| map.contains_key("verdict") || map.contains_key("score");
126        if has_fields(outputs) {
127            return Self::from_fields(outputs);
128        }
129        let only = match (outputs.len(), outputs.values().next()) {
130            (1, Some(Json::String(text))) => serde_json::from_str::<Json>(text).ok(),
131            (1, Some(value)) => Some(value.clone()),
132            _ => None,
133        };
134        match only {
135            Some(Json::Object(map)) if has_fields(&map) => Self::from_fields(&map),
136            _ => {
137                let keys: Vec<&str> = outputs.keys().map(String::as_str).collect();
138                Err(format!("no `verdict` or `score` in the judge outputs ({})", keys.join(", ")))
139            }
140        }
141    }
142
143    fn from_fields(map: &Map<String, Json>) -> Result<Self, String> {
144        let verdict = match map.get("verdict") {
145            None | Some(Json::Null) => None,
146            Some(raw) => Some(
147                Verdict::parse(raw).ok_or_else(|| format!("verdict {} is not pass, fail or unknown", brief(raw)))?,
148            ),
149        };
150        let score = match map.get("score") {
151            None | Some(Json::Null) => None,
152            Some(raw) => {
153                let number = raw.as_f64().or_else(|| raw.as_str().and_then(|s| s.trim().parse().ok()));
154                Some(
155                    number
156                        .filter(|n| (0.0..=1.0).contains(n))
157                        .ok_or_else(|| format!("score {} is not a number between 0 and 1", brief(raw)))?,
158                )
159            }
160        };
161        if verdict.is_none() && score.is_none() {
162            return Err("the judge returned neither a verdict nor a score".into());
163        }
164        let reasoning = ["reasoning", "reason", "explanation"]
165            .iter()
166            .find_map(|key| map.get(*key).and_then(Json::as_str))
167            .map(str::to_owned);
168        Ok(Self { verdict, score, reasoning })
169    }
170
171    /// The binary decision: the verdict, else `score >= threshold`.
172    pub fn decide(&self, threshold: f64) -> Verdict {
173        match (self.verdict, self.score) {
174            (Some(verdict), _) => verdict,
175            (None, Some(score)) if score + 1e-9 >= threshold => Verdict::Pass,
176            _ => Verdict::Fail,
177        }
178    }
179}
180
181/// What to do with a judge's `unknown` verdict.
182#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
183#[serde(rename_all = "snake_case")]
184pub enum UnknownPolicy {
185    /// Count it as a failure (the default for judge assertions).
186    #[default]
187    Fail,
188    /// Report it, but leave it out of scores, gates and agreement metrics.
189    Exclude,
190}
191
192impl UnknownPolicy {
193    /// The `unknown` key of an assertion or calibration block.
194    pub fn from_config(value: Option<&Json>) -> Result<Self, EvalError> {
195        match value.and_then(Json::as_str) {
196            None if value.is_none() => Ok(Self::Fail),
197            Some("fail") => Ok(Self::Fail),
198            Some("exclude") => Ok(Self::Exclude),
199            _ => Err(EvalError::invalid("`unknown` must be `fail` or `exclude`")),
200        }
201    }
202}
203
204/// Compiles judge workflows for `judge` assertions. Called once per distinct
205/// workflow file; the result is shared by every test.
206pub trait JudgeLoader: Send + Sync {
207    /// Load and compile the judge at `path` (already resolved against the
208    /// eval file's directory).
209    fn load(&self, path: &Path) -> Result<Arc<dyn Target>, EvalError>;
210}
211
212impl<F> JudgeLoader for F
213where
214    F: Fn(&Path) -> Result<Arc<dyn Target>, EvalError> + Send + Sync,
215{
216    fn load(&self, path: &Path) -> Result<Arc<dyn Target>, EvalError> {
217        self(path)
218    }
219}
220
221/// A compiled judge with what the harness needs to call it.
222struct Judge {
223    target: Arc<dyn Target>,
224    info: WorkflowInfo,
225    /// Declared start variables and their input types; empty = pass every input as is.
226    inputs: Vec<(String, String)>,
227}
228
229/// Compiled judges by path.
230struct Judges {
231    base: PathBuf,
232    loader: Box<dyn JudgeLoader>,
233    cache: Mutex<HashMap<PathBuf, Arc<Judge>>>,
234}
235
236impl Judges {
237    fn get(&self, workflow: &str) -> Result<Arc<Judge>, EvalError> {
238        let path = normalize(&self.base.join(workflow));
239        let key = path.canonicalize().unwrap_or_else(|_| path.clone());
240        let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner);
241        if let Some(judge) = cache.get(&key) {
242            return Ok(Arc::clone(judge));
243        }
244        let target = self.loader.load(&path)?;
245        let mut info = target.workflow();
246        if info.path.is_empty() {
247            info.path = path.display().to_string();
248        }
249        let judge = Arc::new(Judge { inputs: target.start_variables(), target, info });
250        cache.insert(key, Arc::clone(&judge));
251        Ok(judge)
252    }
253}
254
255/// Drop `.` and fold `dir/..` (lexically, no file system access), so reports
256/// name `evals/judges/x.yaml` rather than `evals/suite/../judges/x.yaml`.
257fn normalize(path: &Path) -> PathBuf {
258    use std::path::Component;
259    let mut out = PathBuf::new();
260    for component in path.components() {
261        match component {
262            Component::CurDir => {}
263            Component::ParentDir if matches!(out.components().next_back(), Some(Component::Normal(_))) => {
264                out.pop();
265            }
266            other => out.push(other),
267        }
268    }
269    out
270}
271
272/// Register the `judge` assertion type. Judge `workflow` paths are resolved
273/// against `base` (the eval file's directory); each judge is compiled once by
274/// `loader` and reused by every test.
275pub fn register(registry: &mut AssertionRegistry, base: impl Into<PathBuf>, loader: impl JudgeLoader + 'static) {
276    let judges = Arc::new(Judges { base: base.into(), loader: Box::new(loader), cache: Mutex::default() });
277    registry.register("judge", move |spec| prepare(&judges, spec));
278}
279
280fn prepare(judges: &Judges, spec: &AssertionSpec) -> Result<Box<dyn Assertion>, EvalError> {
281    only_keys(spec, &["workflow", "inputs", "unknown"])?;
282    let workflow = match spec.config.get("workflow") {
283        Some(Json::String(path)) if !path.trim().is_empty() => path,
284        _ => return Err(EvalError::invalid("`workflow` (the judge workflow file) is required")),
285    };
286    let inputs = match spec.config.get("inputs") {
287        None | Some(Json::Null) => Map::new(),
288        Some(Json::Object(map)) => map.clone(),
289        Some(_) => return Err(EvalError::invalid("`inputs` must be a mapping of judge start inputs")),
290    };
291    let threshold = spec.threshold.unwrap_or(0.5);
292    if !(0.0..=1.0).contains(&threshold) {
293        return Err(EvalError::invalid("`threshold` must be between 0 and 1"));
294    }
295    Ok(Box::new(JudgeAssertion {
296        judge: judges.get(workflow)?,
297        inputs,
298        transform: transform_of(spec)?,
299        unknown: UnknownPolicy::from_config(spec.config.get("unknown"))?,
300        threshold,
301    }))
302}
303
304struct JudgeAssertion {
305    judge: Arc<Judge>,
306    inputs: Map<String, Json>,
307    transform: Option<JsonPath>,
308    unknown: UnknownPolicy,
309    threshold: f64,
310}
311
312impl fmt::Debug for JudgeAssertion {
313    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
314        f.debug_struct("JudgeAssertion").field("workflow", &self.judge.info.path).finish()
315    }
316}
317
318impl Assertion for JudgeAssertion {
319    fn evaluate<'a>(&'a self, ctx: AssertionContext<'a>) -> BoxFuture<'a, Outcome> {
320        Box::pin(self.judge(ctx))
321    }
322}
323
324impl JudgeAssertion {
325    async fn judge(&self, ctx: AssertionContext<'_>) -> Outcome {
326        let Some(subject) = ctx.subject(self.transform.as_ref()) else {
327            return Outcome::check(false, "transform path not found in the run");
328        };
329        let mut record = JudgeRecord {
330            workflow: self.judge.info.path.clone(),
331            fingerprint: self.judge.info.fingerprint.clone(),
332            ..JudgeRecord::default()
333        };
334        let case = TestCase::new(format!("{}:judge", ctx.case.id), self.judge_inputs(ctx, subject));
335        let capture = match self.judge.target.run(&case).await {
336            Ok(capture) => capture,
337            Err(e) => return Outcome::check(false, format!("judge could not run: {e}")).with_judge(record),
338        };
339        record.run_id.clone_from(&capture.run_id);
340        record.latency_ms = capture.latency_ms;
341        record.usage = capture.usage;
342        if capture.status != RunStatus::Succeeded {
343            let error = capture.error.as_deref().unwrap_or("no details");
344            return Outcome::check(false, format!("judge run did not succeed: {error}")).with_judge(record);
345        }
346        let judgement = match Judgement::read(&capture.outputs) {
347            Ok(judgement) => judgement,
348            Err(why) => return Outcome::check(false, format!("judge: {why}")).with_judge(record),
349        };
350        let verdict = judgement.decide(self.threshold);
351        let reason = match (&judgement.reasoning, judgement.score) {
352            (Some(why), _) => format!("judge: {verdict}: {}", shorten(why)),
353            (None, Some(score)) => format!("judge: {verdict} (score {score:.2})"),
354            (None, None) => format!("judge: {verdict}"),
355        };
356        record.verdict = judgement.verdict;
357        record.score = judgement.score;
358        record.reasoning = judgement.reasoning;
359        let outcome = match (verdict, self.unknown) {
360            (Verdict::Unknown, UnknownPolicy::Exclude) => Outcome::excluded(format!("{reason} (excluded)")),
361            (Verdict::Pass, _) => Outcome::graded(true, judgement.score.unwrap_or(1.0), reason),
362            _ => Outcome::graded(false, judgement.score.unwrap_or(0.0), reason),
363        };
364        outcome.with_judge(record)
365    }
366
367    /// The judge's start inputs: the input contract (module docs), then the
368    /// assertion's `inputs`, typed for the variables the judge declares.
369    fn judge_inputs(&self, ctx: AssertionContext<'_>, subject: Json) -> Map<String, Json> {
370        let mut all = Map::new();
371        all.insert("output".into(), subject);
372        all.insert("vars".into(), Json::Object(ctx.case.vars.clone()));
373        if let Some(expected) = &ctx.case.expected {
374            all.insert("expected".into(), expected.clone());
375        }
376        let hits = ctx.capture.retrieval_hits();
377        if !hits.is_empty() {
378            all.insert("contexts".into(), hits.into_iter().map(|h| Json::String(h.content)).collect());
379        }
380        let calls = ctx.capture.tool_calls();
381        all.insert("trajectory".into(), serde_json::to_value(calls).unwrap_or_default());
382        all.extend(self.inputs.clone());
383        if self.judge.inputs.is_empty() {
384            return all;
385        }
386        self.judge
387            .inputs
388            .iter()
389            .filter_map(|(name, kind)| all.remove(name).map(|value| (name.clone(), typed_input(kind, value))))
390            .collect()
391    }
392}
393
394/// Shape a value for a start variable of input type `kind`.
395fn typed_input(kind: &str, value: Json) -> Json {
396    match (kind, value) {
397        ("text-input" | "paragraph" | "select" | "string" | "text", value) => Json::String(as_text(value)),
398        // `json` inputs parse strings as JSON: send a string as a JSON string literal.
399        ("json", Json::String(text)) => Json::String(Json::String(text).to_string()),
400        (_, value) => value,
401    }
402}
403
404fn as_text(value: Json) -> String {
405    match value {
406        Json::String(text) => text,
407        Json::Null => String::new(),
408        Json::Array(items) if items.iter().all(Json::is_string) => {
409            items.iter().filter_map(Json::as_str).collect::<Vec<_>>().join("\n\n")
410        }
411        other => serde_json::to_string_pretty(&other).unwrap_or_default(),
412    }
413}
414
415/// The first 200 characters of a judge's reasoning, on one line.
416fn shorten(text: &str) -> String {
417    let line = text.split_whitespace().collect::<Vec<_>>().join(" ");
418    if line.chars().count() <= 200 { line } else { format!("{}...", line.chars().take(197).collect::<String>()) }
419}
420
421#[cfg(test)]
422mod tests {
423    #![allow(clippy::unwrap_used, clippy::expect_used)]
424
425    use super::*;
426    use serde_json::json;
427
428    fn outputs(value: Json) -> Map<String, Json> {
429        value.as_object().cloned().unwrap()
430    }
431
432    #[test]
433    fn reads_verdicts_scores_and_nested_outputs() {
434        let read = |v: Json| Judgement::read(&outputs(v));
435        let j = read(json!({"verdict": "PASS", "reasoning": "grounded"})).unwrap();
436        assert_eq!((j.verdict, j.reasoning.as_deref()), (Some(Verdict::Pass), Some("grounded")));
437        let j = read(json!({"result": {"verdict": "unknown", "explanation": "no context"}})).unwrap();
438        assert_eq!(j.verdict, Some(Verdict::Unknown));
439        assert_eq!(j.reasoning.as_deref(), Some("no context"));
440        let j = read(json!({"text": "{\"score\": 0.4}"})).unwrap();
441        assert_eq!((j.verdict, j.score), (None, Some(0.4)));
442        assert_eq!(j.decide(0.5), Verdict::Fail);
443        assert_eq!(j.decide(0.4), Verdict::Pass);
444        assert_eq!(read(json!({"verdict": true})).unwrap().verdict, Some(Verdict::Pass));
445        assert!(read(json!({"verdict": "maybe"})).unwrap_err().contains("not pass, fail or unknown"));
446        assert!(read(json!({"score": 3})).unwrap_err().contains("between 0 and 1"));
447        assert!(read(json!({"a": 1, "b": 2})).unwrap_err().contains("no `verdict`"));
448        assert!(read(json!({"verdict": null})).unwrap_err().contains("neither"));
449    }
450
451    #[test]
452    fn inputs_are_typed_for_the_declared_variables() {
453        assert_eq!(typed_input("paragraph", json!(["a", "b"])), json!("a\n\nb"));
454        assert_eq!(typed_input("paragraph", json!({"k": 1})), json!("{\n  \"k\": 1\n}"));
455        assert_eq!(typed_input("json", json!("hi")), json!("\"hi\""));
456        assert_eq!(typed_input("json", json!({"k": 1})), json!({"k": 1}));
457        assert_eq!(typed_input("array[string]", json!(["a"])), json!(["a"]));
458    }
459
460    #[test]
461    fn unknown_policy_parses() {
462        assert_eq!(UnknownPolicy::from_config(None).unwrap(), UnknownPolicy::Fail);
463        assert_eq!(UnknownPolicy::from_config(Some(&json!("exclude"))).unwrap(), UnknownPolicy::Exclude);
464        assert!(UnknownPolicy::from_config(Some(&json!("skip"))).is_err());
465        assert!(UnknownPolicy::from_config(Some(&json!(null))).is_err());
466    }
467}