1use std::path::{Path, PathBuf};
5
6use serde::{Deserialize, Serialize};
7use serde_json::{Map, Value};
8
9#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
16#[non_exhaustive]
17pub struct Case {
18 pub id: String,
20 pub input: String,
22 #[serde(default, skip_serializing_if = "Option::is_none")]
24 pub expected: Option<String>,
25 #[serde(default, skip_serializing_if = "Option::is_none")]
27 pub trajectory: Option<Vec<ExpectedCall>>,
28 #[serde(default, skip_serializing_if = "Vec::is_empty")]
30 pub assertions: Vec<String>,
31 #[serde(default, skip_serializing_if = "Map::is_empty")]
33 pub metadata: Map<String, Value>,
34}
35
36impl Case {
37 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 #[must_use]
51 pub fn expected(mut self, expected: impl Into<String>) -> Self {
52 self.expected = Some(expected.into());
53 self
54 }
55
56 #[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 #[must_use]
65 pub fn assertion(mut self, assertion: impl Into<String>) -> Self {
66 self.assertions.push(assertion.into());
67 self
68 }
69
70 #[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
80pub struct ExpectedCall {
81 pub name: String,
83 #[serde(default, skip_serializing_if = "Option::is_none")]
86 pub args: Option<Value>,
87}
88
89impl ExpectedCall {
90 pub fn new(name: impl Into<String>) -> Self {
92 Self {
93 name: name.into(),
94 args: None,
95 }
96 }
97
98 #[must_use]
100 pub fn args(mut self, args: Value) -> Self {
101 self.args = Some(args);
102 self
103 }
104}
105
106#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
108#[serde(transparent)]
109pub struct Dataset {
110 pub cases: Vec<Case>,
112}
113
114impl Dataset {
115 pub fn new(cases: impl IntoIterator<Item = Case>) -> Self {
117 Self {
118 cases: cases.into_iter().collect(),
119 }
120 }
121
122 pub fn from_json(text: &str) -> Result<Self, DatasetError> {
124 Ok(serde_json::from_str(text)?)
125 }
126
127 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 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#[derive(Debug, thiserror::Error)]
173#[non_exhaustive]
174pub enum DatasetError {
175 #[error("cannot read {path}: {source}")]
177 Read {
178 path: PathBuf,
180 source: std::io::Error,
182 },
183 #[error("invalid dataset: {0}")]
185 Json(#[from] serde_json::Error),
186 #[error("invalid case on line {line}: {source}")]
188 Line {
189 line: usize,
191 source: serde_json::Error,
193 },
194 #[error("{0}: expected a .json, .jsonl or .ndjson file")]
196 UnknownFormat(PathBuf),
197}