1use std::collections::HashMap;
5use std::path::{Path, PathBuf};
6
7use serde::{Deserialize, Serialize};
8use serde_json::{Map, Value};
9
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
18#[serde(try_from = "CaseWire")]
19#[non_exhaustive]
20pub struct Case {
21 pub id: String,
23 #[serde(skip_serializing_if = "String::is_empty")]
26 pub input: String,
27 #[serde(skip_serializing_if = "Vec::is_empty")]
30 pub turns: Vec<String>,
31 #[serde(default, skip_serializing_if = "Option::is_none")]
33 pub expected: Option<String>,
34 #[serde(default, skip_serializing_if = "Option::is_none")]
36 pub trajectory: Option<Vec<ExpectedCall>>,
37 #[serde(default, skip_serializing_if = "Vec::is_empty")]
39 pub assertions: Vec<String>,
40 #[serde(default, skip_serializing_if = "Map::is_empty")]
42 pub metadata: Map<String, Value>,
43}
44
45impl Case {
46 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 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 #[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 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 #[must_use]
101 pub fn expected(mut self, expected: impl Into<String>) -> Self {
102 self.expected = Some(expected.into());
103 self
104 }
105
106 #[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 #[must_use]
115 pub fn assertion(mut self, assertion: impl Into<String>) -> Self {
116 self.assertions.push(assertion.into());
117 self
118 }
119
120 #[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#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
172pub struct ExpectedCall {
173 pub name: String,
175 #[serde(default, skip_serializing_if = "Option::is_none")]
178 pub args: Option<Value>,
179}
180
181impl ExpectedCall {
182 pub fn new(name: impl Into<String>) -> Self {
184 Self {
185 name: name.into(),
186 args: None,
187 }
188 }
189
190 #[must_use]
192 pub fn args(mut self, args: Value) -> Self {
193 self.args = Some(args);
194 self
195 }
196}
197
198#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
200#[serde(transparent)]
201pub struct Dataset {
202 pub cases: Vec<Case>,
204}
205
206impl Dataset {
207 pub fn new(cases: impl IntoIterator<Item = Case>) -> Self {
209 Self {
210 cases: cases.into_iter().collect(),
211 }
212 }
213
214 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 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 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 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
302fn 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
319fn 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#[derive(Debug, thiserror::Error)]
352#[non_exhaustive]
353pub enum DatasetError {
354 #[error("cannot read {path}: {source}")]
356 Read {
357 path: PathBuf,
359 source: std::io::Error,
361 },
362 #[error("invalid dataset: {0}")]
364 Json(#[from] serde_json::Error),
365 #[error("invalid case on line {line}: {source}")]
367 Line {
368 line: usize,
370 source: serde_json::Error,
372 },
373 #[error("{0}: expected a .json, .jsonl or .ndjson file")]
375 UnknownFormat(PathBuf),
376 #[error("invalid case at index {index}: {source}")]
379 Element {
380 index: usize,
382 source: serde_json::Error,
384 },
385 #[error("{path}: {source}")]
389 InFile {
390 path: PathBuf,
392 source: Box<DatasetError>,
394 },
395}