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::collections::HashMap;
5use std::path::{Path, PathBuf};
6
7use serde::{Deserialize, Serialize};
8use serde_json::{Map, Value};
9
10/// One input to run the target on, with the references evaluators check the
11/// run against: the expected answer, the expected tool calls, and
12/// assertions in plain language (for an LLM judge).
13///
14/// A case is single-turn (`input`) or multi-turn (`turns`): see
15/// [`Case::turns`]. The same three references as AWS Bedrock AgentCore's
16/// evaluation reference inputs and Strands Evals' cases.
17#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
18#[serde(try_from = "CaseWire")]
19#[non_exhaustive]
20pub struct Case {
21    /// Names the case in reports; unique within a dataset.
22    pub id: String,
23    /// The prompt the target gets. Empty for a multi-turn case, which sets
24    /// `turns` instead; a case sets one or the other.
25    #[serde(skip_serializing_if = "String::is_empty")]
26    pub input: String,
27    /// The user turns of a multi-turn case, sent in order on one
28    /// conversation. Empty for a single-turn case.
29    #[serde(skip_serializing_if = "Vec::is_empty")]
30    pub turns: Vec<String>,
31    /// The expected answer.
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub expected: Option<String>,
34    /// The tool calls the target is expected to make.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub trajectory: Option<Vec<ExpectedCall>>,
37    /// Statements the answer must satisfy, in plain language.
38    #[serde(default, skip_serializing_if = "Vec::is_empty")]
39    pub assertions: Vec<String>,
40    /// Anything else, kept in reports.
41    #[serde(default, skip_serializing_if = "Map::is_empty")]
42    pub metadata: Map<String, Value>,
43}
44
45impl Case {
46    /// A case `id` with prompt `input` and no references.
47    pub fn new(id: impl Into<String>, input: impl Into<String>) -> Self {
48        Self {
49            id: id.into(),
50            input: input.into(),
51            turns: Vec::new(),
52            expected: None,
53            trajectory: None,
54            assertions: Vec::new(),
55            metadata: Map::new(),
56        }
57    }
58
59    /// A multi-turn case `id`: each of `turns` is a user message, sent in
60    /// order on one conversation, so a turn can refer to the answers before
61    /// it. The target answers the last turn; evaluators see the whole
62    /// transcript as well (see [`Trial::transcript`](crate::Trial::transcript)).
63    ///
64    /// ```
65    /// use rig_evals::Case;
66    /// let case = Case::multi_turn("trip", ["Plan a trip to Lisbon.", "Which month is best?"]);
67    /// assert_eq!(case.prompts().len(), 2);
68    /// ```
69    pub fn multi_turn<I, S>(id: impl Into<String>, turns: I) -> Self
70    where
71        I: IntoIterator<Item = S>,
72        S: Into<String>,
73    {
74        Self::new(id, "").turns(turns)
75    }
76
77    /// Make this a multi-turn case with `turns`, replacing `input`.
78    #[must_use]
79    pub fn turns<I, S>(mut self, turns: I) -> Self
80    where
81        I: IntoIterator<Item = S>,
82        S: Into<String>,
83    {
84        self.input.clear();
85        self.turns = turns.into_iter().map(Into::into).collect();
86        self
87    }
88
89    /// The user turns, in order: `turns` of a multi-turn case, else the one
90    /// `input`.
91    pub fn prompts(&self) -> Vec<&str> {
92        if self.turns.is_empty() {
93            vec![self.input.as_str()]
94        } else {
95            self.turns.iter().map(String::as_str).collect()
96        }
97    }
98
99    /// Set the expected answer.
100    #[must_use]
101    pub fn expected(mut self, expected: impl Into<String>) -> Self {
102        self.expected = Some(expected.into());
103        self
104    }
105
106    /// Set the expected tool calls.
107    #[must_use]
108    pub fn trajectory(mut self, calls: impl IntoIterator<Item = ExpectedCall>) -> Self {
109        self.trajectory = Some(calls.into_iter().collect());
110        self
111    }
112
113    /// Add an assertion.
114    #[must_use]
115    pub fn assertion(mut self, assertion: impl Into<String>) -> Self {
116        self.assertions.push(assertion.into());
117        self
118    }
119
120    /// Add a metadata entry.
121    #[must_use]
122    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
123        self.metadata.insert(key.into(), value.into());
124        self
125    }
126}
127
128/// The JSON form of a [`Case`]: a case has `input` or `turns`, not both.
129#[derive(Deserialize)]
130struct CaseWire {
131    id: String,
132    #[serde(default)]
133    input: Option<String>,
134    #[serde(default)]
135    turns: Vec<String>,
136    #[serde(default)]
137    expected: Option<String>,
138    #[serde(default)]
139    trajectory: Option<Vec<ExpectedCall>>,
140    #[serde(default)]
141    assertions: Vec<String>,
142    #[serde(default)]
143    metadata: Map<String, Value>,
144}
145
146impl TryFrom<CaseWire> for Case {
147    type Error = String;
148
149    fn try_from(wire: CaseWire) -> Result<Self, Self::Error> {
150        let input = match (wire.input, wire.turns.is_empty()) {
151            (Some(input), true) => input,
152            (None, false) => String::new(),
153            (Some(_), false) => {
154                return Err(format!("case {:?} sets both input and turns", wire.id));
155            }
156            (None, true) => return Err(format!("case {:?} sets neither input nor turns", wire.id)),
157        };
158        Ok(Self {
159            id: wire.id,
160            input,
161            turns: wire.turns,
162            expected: wire.expected,
163            trajectory: wire.trajectory,
164            assertions: wire.assertions,
165            metadata: wire.metadata,
166        })
167    }
168}
169
170/// A tool call a case expects.
171#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
172pub struct ExpectedCall {
173    /// The tool's name.
174    pub name: String,
175    /// The arguments; `None` accepts any. An object matches when each of its
176    /// keys has the same value in the call (the call may have more keys).
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub args: Option<Value>,
179}
180
181impl ExpectedCall {
182    /// A call to `name` with any arguments.
183    pub fn new(name: impl Into<String>) -> Self {
184        Self {
185            name: name.into(),
186            args: None,
187        }
188    }
189
190    /// Expect these arguments.
191    #[must_use]
192    pub fn args(mut self, args: Value) -> Self {
193        self.args = Some(args);
194        self
195    }
196}
197
198/// The cases of an experiment.
199#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
200#[serde(transparent)]
201pub struct Dataset {
202    /// The cases, in order.
203    pub cases: Vec<Case>,
204}
205
206impl Dataset {
207    /// A dataset of `cases`.
208    pub fn new(cases: impl IntoIterator<Item = Case>) -> Self {
209        Self {
210            cases: cases.into_iter().collect(),
211        }
212    }
213
214    /// Parse a JSON array of cases.
215    ///
216    /// A case id that repeats is logged as a warning; the experiment refuses
217    /// to run such a dataset (see [`ExperimentError::DuplicateCase`](crate::ExperimentError::DuplicateCase)).
218    /// For errors that name the element's index, see [`Dataset::load_named`].
219    pub fn from_json(text: &str) -> Result<Self, DatasetError> {
220        let cases: Vec<Case> = serde_json::from_str(text)?;
221        let places: Vec<String> = (0..cases.len()).map(|i| format!("index {i}")).collect();
222        warn_repeated_ids(&cases, &places);
223        Ok(Self { cases })
224    }
225
226    /// Parse JSON Lines: one case per line, blank lines skipped. A bad line
227    /// is a [`DatasetError::Line`] naming its line number (from 1).
228    ///
229    /// A repeated case id is logged as a warning, as in [`Dataset::from_json`].
230    pub fn from_jsonl(text: &str) -> Result<Self, DatasetError> {
231        let mut cases = Vec::new();
232        let mut places = Vec::new();
233        for (index, line) in text.lines().enumerate() {
234            if line.trim().is_empty() {
235                continue;
236            }
237            let case = serde_json::from_str(line).map_err(|source| DatasetError::Line {
238                line: index + 1,
239                source,
240            })?;
241            cases.push(case);
242            places.push(format!("line {}", index + 1));
243        }
244        warn_repeated_ids(&cases, &places);
245        Ok(Self { cases })
246    }
247
248    /// Read a file: `.json` as a JSON array, `.jsonl` or `.ndjson` as JSON
249    /// Lines. Errors are the same as [`Dataset::load_named`] without the
250    /// path and index.
251    pub fn load(path: impl AsRef<Path>) -> Result<Self, DatasetError> {
252        let path = path.as_ref();
253        let parse: fn(&str) -> Result<Self, DatasetError> =
254            match path.extension().and_then(|extension| extension.to_str()) {
255                Some("json") => Self::from_json,
256                Some("jsonl" | "ndjson") => Self::from_jsonl,
257                _ => return Err(DatasetError::UnknownFormat(path.to_owned())),
258            };
259        let text = std::fs::read_to_string(path).map_err(|source| DatasetError::Read {
260            path: path.to_owned(),
261            source,
262        })?;
263        parse(&text)
264    }
265
266    /// Read a file like [`Dataset::load`], but with errors that say where
267    /// they are: a parse error is [`DatasetError::InFile`], which names the
268    /// path and wraps the inner error. Inside it, a bad JSON Lines line is
269    /// `Line` (its line number, from 1) and a bad JSON array element is
270    /// [`DatasetError::Element`] (its index, from 0).
271    ///
272    /// ```no_run
273    /// # fn main() -> Result<(), rig_evals::DatasetError> {
274    /// let dataset = rig_evals::Dataset::load_named("cases.jsonl")?;
275    /// # let _ = dataset;
276    /// # Ok(())
277    /// # }
278    /// ```
279    pub fn load_named(path: impl AsRef<Path>) -> Result<Self, DatasetError> {
280        let path = path.as_ref();
281        let json = match path.extension().and_then(|extension| extension.to_str()) {
282            Some("json") => true,
283            Some("jsonl" | "ndjson") => false,
284            _ => return Err(DatasetError::UnknownFormat(path.to_owned())),
285        };
286        let text = std::fs::read_to_string(path).map_err(|source| DatasetError::Read {
287            path: path.to_owned(),
288            source,
289        })?;
290        let parsed = if json {
291            parse_json_elements(&text)
292        } else {
293            Self::from_jsonl(&text)
294        };
295        parsed.map_err(|source| DatasetError::InFile {
296            path: path.to_owned(),
297            source: Box::new(source),
298        })
299    }
300}
301
302/// Parse a JSON array one element at a time, so an element that is not a
303/// case is a [`DatasetError::Element`] with its index.
304fn parse_json_elements(text: &str) -> Result<Dataset, DatasetError> {
305    let elements: Vec<Value> = serde_json::from_str(text)?;
306    let cases = elements
307        .into_iter()
308        .enumerate()
309        .map(|(index, element)| {
310            serde_json::from_value(element)
311                .map_err(|source| DatasetError::Element { index, source })
312        })
313        .collect::<Result<Vec<Case>, _>>()?;
314    let places: Vec<String> = (0..cases.len()).map(|i| format!("index {i}")).collect();
315    warn_repeated_ids(&cases, &places);
316    Ok(Dataset { cases })
317}
318
319/// Log a warning for each case whose id an earlier case already has. `places`
320/// names where each case came from, in the same order as `cases`.
321fn warn_repeated_ids(cases: &[Case], places: &[String]) {
322    let mut first_seen: HashMap<&str, &str> = HashMap::new();
323    for (case, place) in cases.iter().zip(places) {
324        match first_seen.get(case.id.as_str()) {
325            Some(first) => tracing::warn!(
326                id = %case.id,
327                first = %first,
328                second = %place,
329                "dataset repeats a case id; an experiment will refuse to run it"
330            ),
331            None => {
332                first_seen.insert(case.id.as_str(), place.as_str());
333            }
334        }
335    }
336}
337
338impl From<Vec<Case>> for Dataset {
339    fn from(cases: Vec<Case>) -> Self {
340        Self { cases }
341    }
342}
343
344impl FromIterator<Case> for Dataset {
345    fn from_iter<I: IntoIterator<Item = Case>>(cases: I) -> Self {
346        Self::new(cases)
347    }
348}
349
350/// Why a dataset could not be read.
351#[derive(Debug, thiserror::Error)]
352#[non_exhaustive]
353pub enum DatasetError {
354    /// The file could not be read.
355    #[error("cannot read {path}: {source}")]
356    Read {
357        /// The file.
358        path: PathBuf,
359        /// The I/O error.
360        source: std::io::Error,
361    },
362    /// The JSON is not an array of cases.
363    #[error("invalid dataset: {0}")]
364    Json(#[from] serde_json::Error),
365    /// A JSON Lines line is not a case.
366    #[error("invalid case on line {line}: {source}")]
367    Line {
368        /// The line number, from 1.
369        line: usize,
370        /// The parse error.
371        source: serde_json::Error,
372    },
373    /// The file's extension is not `.json`, `.jsonl` or `.ndjson`.
374    #[error("{0}: expected a .json, .jsonl or .ndjson file")]
375    UnknownFormat(PathBuf),
376    /// A JSON array element is not a case, from [`Dataset::load_named`]. `index`
377    /// counts from 0.
378    #[error("invalid case at index {index}: {source}")]
379    Element {
380        /// The element's position in the array, from 0.
381        index: usize,
382        /// The parse error.
383        source: serde_json::Error,
384    },
385    /// A file's contents do not parse, from [`Dataset::load_named`]. The inner
386    /// error (`Json`, `Line` or `Element`) says what is wrong; this names the
387    /// file.
388    #[error("{path}: {source}")]
389    InFile {
390        /// The file.
391        path: PathBuf,
392        /// The parse error.
393        source: Box<DatasetError>,
394    },
395}