Skip to main content

graphrt_eval/
schema.rs

1//! JSON Schema of eval files, published as `schema/eval-v1.schema.json`.
2//!
3//! Regenerate the checked-in file with
4//! `cargo run -q -p graphrt-eval --example eval-schema > schema/eval-v1.schema.json`.
5
6use serde_json::{Value as Json, json};
7
8/// Where the schema is published.
9pub const EVAL_SCHEMA_URL: &str = "https://raw.githubusercontent.com/Graphrt/graphrt/main/schema/eval-v1.schema.json";
10
11/// Assertion types built into graphrt-eval, with a one-line description each.
12pub const BUILTIN_ASSERTIONS: &[(&str, &str)] = &[
13    ("equals", "The output (or `transform` path) equals `value`; non-string values compare as JSON."),
14    ("contains", "The output contains the `value` text."),
15    ("icontains", "Case-insensitive `contains`."),
16    ("contains-any", "The output contains at least one of the `value` texts."),
17    ("icontains-any", "Case-insensitive `contains-any`."),
18    ("contains-all", "The output contains every `value` text (score: fraction found)."),
19    ("icontains-all", "Case-insensitive `contains-all`."),
20    ("starts-with", "The output starts with the `value` text."),
21    ("regex", "The output matches the `value` regular expression (Rust syntax; `(?i)` for case-insensitive)."),
22    ("is-json", "The output is JSON; when `value` is a JSON Schema, it must also match it."),
23    ("json-schema", "The output is JSON matching the `value` JSON Schema."),
24    ("latency", "The run took at most `threshold` milliseconds."),
25    ("tokens", "The run used at most `threshold` tokens (`value`: total, prompt or completion)."),
26    ("trajectory:tool-used", "Agents called the `value` tool(s); `{name, min, max}` bounds the count."),
27    ("trajectory:tool-sequence", "Agents called the `value` tools in order (`{steps, mode: in_order|exact}`)."),
28    ("trajectory:tool-args-match", "A call of `value.name` had `value.args` (`mode: partial|exact`)."),
29    ("trajectory:step-count", "The number of tool calls, agent steps or node runs is within `{min, max}`."),
30    ("retrieval:recall-at-k", "Fraction of the `value` document ids in the top `k` knowledge-retrieval hits."),
31    ("retrieval:precision-at-k", "Fraction of the top `k` hits that are relevant (`value` ids)."),
32    ("retrieval:mrr", "Reciprocal rank of the first relevant hit in the top `k`."),
33    ("verdict", "The run is a judge whose verdict (or `score` >= `threshold`) equals the `value` label."),
34];
35
36/// Assertion types a host registers (they need to compile workflows): the
37/// `graphrt eval` command provides them.
38pub const HOST_ASSERTIONS: &[(&str, &str)] =
39    &[("judge", "Run the `workflow` judge on the output and read its verdict or score.")];
40
41fn assertion_types() -> Vec<Json> {
42    BUILTIN_ASSERTIONS
43        .iter()
44        .chain(HOST_ASSERTIONS)
45        .flat_map(|(kind, _)| [Json::String((*kind).to_owned()), Json::String(format!("not-{kind}"))])
46        .collect()
47}
48
49/// The eval file schema (draft 2020-12).
50pub fn eval_file_schema() -> Json {
51    json!({
52        "$schema": "https://json-schema.org/draft/2020-12/schema",
53        "$id": EVAL_SCHEMA_URL,
54        "title": "graphrt eval file",
55        "description": "Test cases and assertions for `graphrt eval`. The `tests` / `assert` / `defaultTest` shape follows Promptfoo.",
56        "type": "object",
57        "required": ["workflow"],
58        "properties": {
59            "description": { "type": "string" },
60            "workflow": { "type": "string", "description": "Workflow under test, relative to this file." },
61            "providers": { "type": "string", "description": "Model providers file (e.g. with `kind: replay` entries), relative to this file." },
62            "knowledge": { "type": "string", "description": "Knowledge base config for knowledge-retrieval nodes, relative to this file." },
63            "mcp": { "type": "string", "description": "MCP servers file, relative to this file." },
64            "plugins": { "type": "array", "items": { "type": "string" }, "description": "Plugin directories, relative to this file." },
65            "dataset": { "type": "string", "description": "JSONL file: one `{id?, vars, expected?, tags?, metadata?, assert?}` object per line." },
66            "defaultTest": { "$ref": "#/$defs/defaultTest" },
67            "tests": { "type": "array", "items": { "$ref": "#/$defs/test" } },
68            "gate": {
69                "type": "object",
70                "additionalProperties": false,
71                "properties": {
72                    "pass_rate": { "type": "number", "minimum": 0, "maximum": 1, "default": 1, "description": "Minimum fraction of passing test runs (every trial counts); below it `graphrt eval` exits with code 5." },
73                    "pass_hat_k": { "type": "number", "minimum": 0, "maximum": 1, "description": "Minimum mean pass^k over the test cases (all k trials pass); use with `--trials`." },
74                    "k": { "type": "integer", "minimum": 1, "description": "k of pass@k and pass^k (default: the number of trials)." },
75                    "baseline": {
76                        "type": "object",
77                        "additionalProperties": false,
78                        "description": "Tolerances against `--baseline`: any regression beyond them fails the gate.",
79                        "properties": {
80                            "tolerance": { "type": "number", "minimum": 0, "maximum": 1, "default": 0.05, "description": "Largest allowed drop of a metric's mean score." },
81                            "test_tolerance": { "type": "number", "minimum": 0, "maximum": 1, "default": 0, "description": "Largest allowed drop of a test's pass rate across its trials." },
82                            "metrics": { "type": "object", "additionalProperties": { "type": "number", "minimum": 0, "maximum": 1 }, "description": "Per-metric tolerances." }
83                        }
84                    }
85                }
86            },
87            "calibration": {
88                "type": "object",
89                "additionalProperties": false,
90                "description": "Judge calibration: the workflow is a judge and each `expected` is a human label (pass / fail). Reports agreement, TPR, TNR and Cohen's kappa.",
91                "properties": {
92                    "unknown": { "enum": ["exclude", "fail"], "default": "exclude", "description": "`unknown` verdicts: left out of the confusion matrix, or counted as fail." },
93                    "threshold": { "type": "number", "minimum": 0, "maximum": 1, "default": 0.5, "description": "Score at which a score-only judge says pass." },
94                    "min_kappa": { "type": "number", "minimum": -1, "maximum": 1, "description": "Gate: minimum Cohen's kappa." },
95                    "min_tpr": { "type": "number", "minimum": 0, "maximum": 1, "description": "Gate: minimum true positive rate." },
96                    "min_tnr": { "type": "number", "minimum": 0, "maximum": 1, "description": "Gate: minimum true negative rate." }
97                }
98            }
99        },
100        "patternProperties": { "^x-": {} },
101        "additionalProperties": false,
102        "$defs": {
103            "test": {
104                "type": "object",
105                "properties": {
106                    "id": { "type": "string", "description": "Unique test id (default: `test-<n>`)." },
107                    "description": { "type": "string" },
108                    "vars": { "type": "object", "description": "Start inputs of the workflow." },
109                    "expected": { "description": "Expected output; a test without assertions checks `equals: expected`. Available as `{{expected}}`." },
110                    "tags": { "type": "array", "items": { "type": "string" } },
111                    "metadata": { "type": "object" },
112                    "threshold": { "type": "number", "minimum": 0, "maximum": 1, "description": "Pass when the weighted assertion score reaches this, instead of requiring every assertion." },
113                    "assert": { "type": "array", "items": { "$ref": "#/$defs/assertion" } }
114                },
115                "patternProperties": { "^x-": {} },
116                "additionalProperties": false
117            },
118            "defaultTest": {
119                "type": "object",
120                "description": "Merged into every test: vars and metadata as defaults, tags and assertions prepended.",
121                "properties": {
122                    "description": { "type": "string" },
123                    "vars": { "type": "object" },
124                    "tags": { "type": "array", "items": { "type": "string" } },
125                    "metadata": { "type": "object" },
126                    "threshold": { "type": "number", "minimum": 0, "maximum": 1 },
127                    "assert": { "type": "array", "items": { "$ref": "#/$defs/assertion" } }
128                },
129                "additionalProperties": false
130            },
131            "assertion": {
132                "type": "object",
133                "required": ["type"],
134                "properties": {
135                    "type": {
136                        "type": "string",
137                        "description": "Assertion type; any type can be negated with a `not-` prefix.",
138                        "anyOf": [ { "enum": assertion_types() }, { "type": "string" } ]
139                    },
140                    "value": { "description": "Expected value; strings may reference test variables as `{{name}}`." },
141                    "threshold": { "type": "number" },
142                    "weight": { "type": "number", "minimum": 0, "default": 1, "description": "Weight in the test score; 0 reports the result without failing the test." },
143                    "metric": { "type": "string", "description": "Name the score is aggregated under in the summary." },
144                    "transform": { "type": "string", "description": "Path to the value under test, e.g. `output.field` or `outputs.text` (no JavaScript)." },
145                    "k": { "type": "integer", "minimum": 1, "description": "retrieval:*: rank cut-off." },
146                    "node": { "type": "string", "description": "retrieval:*: only this knowledge-retrieval node." },
147                    "workflow": { "type": "string", "description": "judge: the judge workflow file, relative to this eval file." },
148                    "inputs": { "type": "object", "description": "judge: extra start inputs of the judge (values may reference test variables)." },
149                    "unknown": { "enum": ["fail", "exclude"], "default": "fail", "description": "judge: an `unknown` verdict fails, or is reported without scoring or gating." }
150                }
151            }
152        }
153    })
154}
155
156#[cfg(test)]
157mod tests {
158    #![allow(clippy::unwrap_used)]
159
160    use super::*;
161    use crate::assertion::AssertionRegistry;
162
163    #[test]
164    fn every_builtin_type_is_listed() {
165        let listed: Vec<&str> = BUILTIN_ASSERTIONS.iter().map(|(k, _)| *k).collect();
166        let registry = AssertionRegistry::with_builtins();
167        let registered: Vec<&str> = registry.kinds().collect();
168        assert_eq!(listed, registered);
169    }
170}