1use std::path::{Path, PathBuf};
5
6use serde::{Deserialize, Serialize};
7use serde_json::{Map, Value};
8
9#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
17#[serde(try_from = "CaseWire")]
18#[non_exhaustive]
19pub struct Case {
20 pub id: String,
22 #[serde(skip_serializing_if = "String::is_empty")]
25 pub input: String,
26 #[serde(skip_serializing_if = "Vec::is_empty")]
29 pub turns: Vec<String>,
30 #[serde(default, skip_serializing_if = "Option::is_none")]
32 pub expected: Option<String>,
33 #[serde(default, skip_serializing_if = "Option::is_none")]
35 pub trajectory: Option<Vec<ExpectedCall>>,
36 #[serde(default, skip_serializing_if = "Vec::is_empty")]
38 pub assertions: Vec<String>,
39 #[serde(default, skip_serializing_if = "Map::is_empty")]
41 pub metadata: Map<String, Value>,
42}
43
44impl Case {
45 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 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 #[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 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 #[must_use]
100 pub fn expected(mut self, expected: impl Into<String>) -> Self {
101 self.expected = Some(expected.into());
102 self
103 }
104
105 #[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 #[must_use]
114 pub fn assertion(mut self, assertion: impl Into<String>) -> Self {
115 self.assertions.push(assertion.into());
116 self
117 }
118
119 #[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#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
171pub struct ExpectedCall {
172 pub name: String,
174 #[serde(default, skip_serializing_if = "Option::is_none")]
177 pub args: Option<Value>,
178}
179
180impl ExpectedCall {
181 pub fn new(name: impl Into<String>) -> Self {
183 Self {
184 name: name.into(),
185 args: None,
186 }
187 }
188
189 #[must_use]
191 pub fn args(mut self, args: Value) -> Self {
192 self.args = Some(args);
193 self
194 }
195}
196
197#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
199#[serde(transparent)]
200pub struct Dataset {
201 pub cases: Vec<Case>,
203}
204
205impl Dataset {
206 pub fn new(cases: impl IntoIterator<Item = Case>) -> Self {
208 Self {
209 cases: cases.into_iter().collect(),
210 }
211 }
212
213 pub fn from_json(text: &str) -> Result<Self, DatasetError> {
215 Ok(serde_json::from_str(text)?)
216 }
217
218 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 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#[derive(Debug, thiserror::Error)]
264#[non_exhaustive]
265pub enum DatasetError {
266 #[error("cannot read {path}: {source}")]
268 Read {
269 path: PathBuf,
271 source: std::io::Error,
273 },
274 #[error("invalid dataset: {0}")]
276 Json(#[from] serde_json::Error),
277 #[error("invalid case on line {line}: {source}")]
279 Line {
280 line: usize,
282 source: serde_json::Error,
284 },
285 #[error("{0}: expected a .json, .jsonl or .ndjson file")]
287 UnknownFormat(PathBuf),
288}