Skip to main content

rig_evals/
case.rs

1//! Cases and datasets: what an experiment runs, and what each run is checked
2//! against.
3
4use std::path::{Path, PathBuf};
5
6use serde::{Deserialize, Serialize};
7use serde_json::{Map, Value};
8
9/// One input to run the target on, with the references evaluators check the
10/// run against: the expected answer, the expected tool calls, and
11/// assertions in plain language (for an LLM judge).
12///
13/// The same three references as AWS Bedrock AgentCore's evaluation
14/// reference inputs and Strands Evals' cases.
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
16#[non_exhaustive]
17pub struct Case {
18    /// Names the case in reports; unique within a dataset.
19    pub id: String,
20    /// The prompt the target gets.
21    pub input: String,
22    /// The expected answer.
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub expected: Option<String>,
25    /// The tool calls the target is expected to make.
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub trajectory: Option<Vec<ExpectedCall>>,
28    /// Statements the answer must satisfy, in plain language.
29    #[serde(default, skip_serializing_if = "Vec::is_empty")]
30    pub assertions: Vec<String>,
31    /// Anything else, kept in reports.
32    #[serde(default, skip_serializing_if = "Map::is_empty")]
33    pub metadata: Map<String, Value>,
34}
35
36impl Case {
37    /// A case `id` with prompt `input` and no references.
38    pub fn new(id: impl Into<String>, input: impl Into<String>) -> Self {
39        Self {
40            id: id.into(),
41            input: input.into(),
42            expected: None,
43            trajectory: None,
44            assertions: Vec::new(),
45            metadata: Map::new(),
46        }
47    }
48
49    /// Set the expected answer.
50    #[must_use]
51    pub fn expected(mut self, expected: impl Into<String>) -> Self {
52        self.expected = Some(expected.into());
53        self
54    }
55
56    /// Set the expected tool calls.
57    #[must_use]
58    pub fn trajectory(mut self, calls: impl IntoIterator<Item = ExpectedCall>) -> Self {
59        self.trajectory = Some(calls.into_iter().collect());
60        self
61    }
62
63    /// Add an assertion.
64    #[must_use]
65    pub fn assertion(mut self, assertion: impl Into<String>) -> Self {
66        self.assertions.push(assertion.into());
67        self
68    }
69
70    /// Add a metadata entry.
71    #[must_use]
72    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
73        self.metadata.insert(key.into(), value.into());
74        self
75    }
76}
77
78/// A tool call a case expects.
79#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
80pub struct ExpectedCall {
81    /// The tool's name.
82    pub name: String,
83    /// The arguments; `None` accepts any. An object matches when each of its
84    /// keys has the same value in the call (the call may have more keys).
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub args: Option<Value>,
87}
88
89impl ExpectedCall {
90    /// A call to `name` with any arguments.
91    pub fn new(name: impl Into<String>) -> Self {
92        Self {
93            name: name.into(),
94            args: None,
95        }
96    }
97
98    /// Expect these arguments.
99    #[must_use]
100    pub fn args(mut self, args: Value) -> Self {
101        self.args = Some(args);
102        self
103    }
104}
105
106/// The cases of an experiment.
107#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
108#[serde(transparent)]
109pub struct Dataset {
110    /// The cases, in order.
111    pub cases: Vec<Case>,
112}
113
114impl Dataset {
115    /// A dataset of `cases`.
116    pub fn new(cases: impl IntoIterator<Item = Case>) -> Self {
117        Self {
118            cases: cases.into_iter().collect(),
119        }
120    }
121
122    /// Parse a JSON array of cases.
123    pub fn from_json(text: &str) -> Result<Self, DatasetError> {
124        Ok(serde_json::from_str(text)?)
125    }
126
127    /// Parse JSON Lines: one case per line, blank lines skipped.
128    pub fn from_jsonl(text: &str) -> Result<Self, DatasetError> {
129        text.lines()
130            .enumerate()
131            .filter(|(_, line)| !line.trim().is_empty())
132            .map(|(index, line)| {
133                serde_json::from_str(line).map_err(|source| DatasetError::Line {
134                    line: index + 1,
135                    source,
136                })
137            })
138            .collect()
139    }
140
141    /// Read a file: `.json` as a JSON array, `.jsonl` or `.ndjson` as JSON
142    /// Lines.
143    pub fn load(path: impl AsRef<Path>) -> Result<Self, DatasetError> {
144        let path = path.as_ref();
145        let read = || {
146            std::fs::read_to_string(path).map_err(|source| DatasetError::Read {
147                path: path.to_owned(),
148                source,
149            })
150        };
151        match path.extension().and_then(|extension| extension.to_str()) {
152            Some("json") => Self::from_json(&read()?),
153            Some("jsonl" | "ndjson") => Self::from_jsonl(&read()?),
154            _ => Err(DatasetError::UnknownFormat(path.to_owned())),
155        }
156    }
157}
158
159impl From<Vec<Case>> for Dataset {
160    fn from(cases: Vec<Case>) -> Self {
161        Self { cases }
162    }
163}
164
165impl FromIterator<Case> for Dataset {
166    fn from_iter<I: IntoIterator<Item = Case>>(cases: I) -> Self {
167        Self::new(cases)
168    }
169}
170
171/// Why a dataset could not be read.
172#[derive(Debug, thiserror::Error)]
173#[non_exhaustive]
174pub enum DatasetError {
175    /// The file could not be read.
176    #[error("cannot read {path}: {source}")]
177    Read {
178        /// The file.
179        path: PathBuf,
180        /// The I/O error.
181        source: std::io::Error,
182    },
183    /// The JSON is not an array of cases.
184    #[error("invalid dataset: {0}")]
185    Json(#[from] serde_json::Error),
186    /// A JSON Lines line is not a case.
187    #[error("invalid case on line {line}: {source}")]
188    Line {
189        /// The line number, from 1.
190        line: usize,
191        /// The parse error.
192        source: serde_json::Error,
193    },
194    /// The file's extension is not `.json`, `.jsonl` or `.ndjson`.
195    #[error("{0}: expected a .json, .jsonl or .ndjson file")]
196    UnknownFormat(PathBuf),
197}