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/// A case is single-turn (`input`) or multi-turn (`turns`): see
14/// [`Case::turns`]. The same three references as AWS Bedrock AgentCore's
15/// evaluation reference inputs and Strands Evals' cases.
16#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
17#[serde(try_from = "CaseWire")]
18#[non_exhaustive]
19pub struct Case {
20    /// Names the case in reports; unique within a dataset.
21    pub id: String,
22    /// The prompt the target gets. Empty for a multi-turn case, which sets
23    /// `turns` instead; a case sets one or the other.
24    #[serde(skip_serializing_if = "String::is_empty")]
25    pub input: String,
26    /// The user turns of a multi-turn case, sent in order on one
27    /// conversation. Empty for a single-turn case.
28    #[serde(skip_serializing_if = "Vec::is_empty")]
29    pub turns: Vec<String>,
30    /// The expected answer.
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub expected: Option<String>,
33    /// The tool calls the target is expected to make.
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub trajectory: Option<Vec<ExpectedCall>>,
36    /// Statements the answer must satisfy, in plain language.
37    #[serde(default, skip_serializing_if = "Vec::is_empty")]
38    pub assertions: Vec<String>,
39    /// Anything else, kept in reports.
40    #[serde(default, skip_serializing_if = "Map::is_empty")]
41    pub metadata: Map<String, Value>,
42}
43
44impl Case {
45    /// A case `id` with prompt `input` and no references.
46    pub fn new(id: impl Into<String>, input: impl Into<String>) -> Self {
47        Self {
48            id: id.into(),
49            input: input.into(),
50            turns: Vec::new(),
51            expected: None,
52            trajectory: None,
53            assertions: Vec::new(),
54            metadata: Map::new(),
55        }
56    }
57
58    /// A multi-turn case `id`: each of `turns` is a user message, sent in
59    /// order on one conversation, so a turn can refer to the answers before
60    /// it. The target answers the last turn; evaluators see the whole
61    /// transcript as well (see [`Trial::transcript`](crate::Trial::transcript)).
62    ///
63    /// ```
64    /// use rig_evals::Case;
65    /// let case = Case::multi_turn("trip", ["Plan a trip to Lisbon.", "Which month is best?"]);
66    /// assert_eq!(case.prompts().len(), 2);
67    /// ```
68    pub fn multi_turn<I, S>(id: impl Into<String>, turns: I) -> Self
69    where
70        I: IntoIterator<Item = S>,
71        S: Into<String>,
72    {
73        Self::new(id, "").turns(turns)
74    }
75
76    /// Make this a multi-turn case with `turns`, replacing `input`.
77    #[must_use]
78    pub fn turns<I, S>(mut self, turns: I) -> Self
79    where
80        I: IntoIterator<Item = S>,
81        S: Into<String>,
82    {
83        self.input.clear();
84        self.turns = turns.into_iter().map(Into::into).collect();
85        self
86    }
87
88    /// The user turns, in order: `turns` of a multi-turn case, else the one
89    /// `input`.
90    pub fn prompts(&self) -> Vec<&str> {
91        if self.turns.is_empty() {
92            vec![self.input.as_str()]
93        } else {
94            self.turns.iter().map(String::as_str).collect()
95        }
96    }
97
98    /// Set the expected answer.
99    #[must_use]
100    pub fn expected(mut self, expected: impl Into<String>) -> Self {
101        self.expected = Some(expected.into());
102        self
103    }
104
105    /// Set the expected tool calls.
106    #[must_use]
107    pub fn trajectory(mut self, calls: impl IntoIterator<Item = ExpectedCall>) -> Self {
108        self.trajectory = Some(calls.into_iter().collect());
109        self
110    }
111
112    /// Add an assertion.
113    #[must_use]
114    pub fn assertion(mut self, assertion: impl Into<String>) -> Self {
115        self.assertions.push(assertion.into());
116        self
117    }
118
119    /// Add a metadata entry.
120    #[must_use]
121    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
122        self.metadata.insert(key.into(), value.into());
123        self
124    }
125}
126
127/// The JSON form of a [`Case`]: a case has `input` or `turns`, not both.
128#[derive(Deserialize)]
129struct CaseWire {
130    id: String,
131    #[serde(default)]
132    input: Option<String>,
133    #[serde(default)]
134    turns: Vec<String>,
135    #[serde(default)]
136    expected: Option<String>,
137    #[serde(default)]
138    trajectory: Option<Vec<ExpectedCall>>,
139    #[serde(default)]
140    assertions: Vec<String>,
141    #[serde(default)]
142    metadata: Map<String, Value>,
143}
144
145impl TryFrom<CaseWire> for Case {
146    type Error = String;
147
148    fn try_from(wire: CaseWire) -> Result<Self, Self::Error> {
149        let input = match (wire.input, wire.turns.is_empty()) {
150            (Some(input), true) => input,
151            (None, false) => String::new(),
152            (Some(_), false) => {
153                return Err(format!("case {:?} sets both input and turns", wire.id));
154            }
155            (None, true) => return Err(format!("case {:?} sets neither input nor turns", wire.id)),
156        };
157        Ok(Self {
158            id: wire.id,
159            input,
160            turns: wire.turns,
161            expected: wire.expected,
162            trajectory: wire.trajectory,
163            assertions: wire.assertions,
164            metadata: wire.metadata,
165        })
166    }
167}
168
169/// A tool call a case expects.
170#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
171pub struct ExpectedCall {
172    /// The tool's name.
173    pub name: String,
174    /// The arguments; `None` accepts any. An object matches when each of its
175    /// keys has the same value in the call (the call may have more keys).
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub args: Option<Value>,
178}
179
180impl ExpectedCall {
181    /// A call to `name` with any arguments.
182    pub fn new(name: impl Into<String>) -> Self {
183        Self {
184            name: name.into(),
185            args: None,
186        }
187    }
188
189    /// Expect these arguments.
190    #[must_use]
191    pub fn args(mut self, args: Value) -> Self {
192        self.args = Some(args);
193        self
194    }
195}
196
197/// The cases of an experiment.
198#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
199#[serde(transparent)]
200pub struct Dataset {
201    /// The cases, in order.
202    pub cases: Vec<Case>,
203}
204
205impl Dataset {
206    /// A dataset of `cases`.
207    pub fn new(cases: impl IntoIterator<Item = Case>) -> Self {
208        Self {
209            cases: cases.into_iter().collect(),
210        }
211    }
212
213    /// Parse a JSON array of cases.
214    pub fn from_json(text: &str) -> Result<Self, DatasetError> {
215        Ok(serde_json::from_str(text)?)
216    }
217
218    /// Parse JSON Lines: one case per line, blank lines skipped.
219    pub fn from_jsonl(text: &str) -> Result<Self, DatasetError> {
220        text.lines()
221            .enumerate()
222            .filter(|(_, line)| !line.trim().is_empty())
223            .map(|(index, line)| {
224                serde_json::from_str(line).map_err(|source| DatasetError::Line {
225                    line: index + 1,
226                    source,
227                })
228            })
229            .collect()
230    }
231
232    /// Read a file: `.json` as a JSON array, `.jsonl` or `.ndjson` as JSON
233    /// Lines.
234    pub fn load(path: impl AsRef<Path>) -> Result<Self, DatasetError> {
235        let path = path.as_ref();
236        let read = || {
237            std::fs::read_to_string(path).map_err(|source| DatasetError::Read {
238                path: path.to_owned(),
239                source,
240            })
241        };
242        match path.extension().and_then(|extension| extension.to_str()) {
243            Some("json") => Self::from_json(&read()?),
244            Some("jsonl" | "ndjson") => Self::from_jsonl(&read()?),
245            _ => Err(DatasetError::UnknownFormat(path.to_owned())),
246        }
247    }
248}
249
250impl From<Vec<Case>> for Dataset {
251    fn from(cases: Vec<Case>) -> Self {
252        Self { cases }
253    }
254}
255
256impl FromIterator<Case> for Dataset {
257    fn from_iter<I: IntoIterator<Item = Case>>(cases: I) -> Self {
258        Self::new(cases)
259    }
260}
261
262/// Why a dataset could not be read.
263#[derive(Debug, thiserror::Error)]
264#[non_exhaustive]
265pub enum DatasetError {
266    /// The file could not be read.
267    #[error("cannot read {path}: {source}")]
268    Read {
269        /// The file.
270        path: PathBuf,
271        /// The I/O error.
272        source: std::io::Error,
273    },
274    /// The JSON is not an array of cases.
275    #[error("invalid dataset: {0}")]
276    Json(#[from] serde_json::Error),
277    /// A JSON Lines line is not a case.
278    #[error("invalid case on line {line}: {source}")]
279    Line {
280        /// The line number, from 1.
281        line: usize,
282        /// The parse error.
283        source: serde_json::Error,
284    },
285    /// The file's extension is not `.json`, `.jsonl` or `.ndjson`.
286    #[error("{0}: expected a .json, .jsonl or .ndjson file")]
287    UnknownFormat(PathBuf),
288}