use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Case {
pub id: String,
pub input: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expected: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trajectory: Option<Vec<ExpectedCall>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub assertions: Vec<String>,
#[serde(default, skip_serializing_if = "Map::is_empty")]
pub metadata: Map<String, Value>,
}
impl Case {
pub fn new(id: impl Into<String>, input: impl Into<String>) -> Self {
Self {
id: id.into(),
input: input.into(),
expected: None,
trajectory: None,
assertions: Vec::new(),
metadata: Map::new(),
}
}
#[must_use]
pub fn expected(mut self, expected: impl Into<String>) -> Self {
self.expected = Some(expected.into());
self
}
#[must_use]
pub fn trajectory(mut self, calls: impl IntoIterator<Item = ExpectedCall>) -> Self {
self.trajectory = Some(calls.into_iter().collect());
self
}
#[must_use]
pub fn assertion(mut self, assertion: impl Into<String>) -> Self {
self.assertions.push(assertion.into());
self
}
#[must_use]
pub fn metadata(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
self.metadata.insert(key.into(), value.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExpectedCall {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub args: Option<Value>,
}
impl ExpectedCall {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
args: None,
}
}
#[must_use]
pub fn args(mut self, args: Value) -> Self {
self.args = Some(args);
self
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Dataset {
pub cases: Vec<Case>,
}
impl Dataset {
pub fn new(cases: impl IntoIterator<Item = Case>) -> Self {
Self {
cases: cases.into_iter().collect(),
}
}
pub fn from_json(text: &str) -> Result<Self, DatasetError> {
Ok(serde_json::from_str(text)?)
}
pub fn from_jsonl(text: &str) -> Result<Self, DatasetError> {
text.lines()
.enumerate()
.filter(|(_, line)| !line.trim().is_empty())
.map(|(index, line)| {
serde_json::from_str(line).map_err(|source| DatasetError::Line {
line: index + 1,
source,
})
})
.collect()
}
pub fn load(path: impl AsRef<Path>) -> Result<Self, DatasetError> {
let path = path.as_ref();
let read = || {
std::fs::read_to_string(path).map_err(|source| DatasetError::Read {
path: path.to_owned(),
source,
})
};
match path.extension().and_then(|extension| extension.to_str()) {
Some("json") => Self::from_json(&read()?),
Some("jsonl" | "ndjson") => Self::from_jsonl(&read()?),
_ => Err(DatasetError::UnknownFormat(path.to_owned())),
}
}
}
impl From<Vec<Case>> for Dataset {
fn from(cases: Vec<Case>) -> Self {
Self { cases }
}
}
impl FromIterator<Case> for Dataset {
fn from_iter<I: IntoIterator<Item = Case>>(cases: I) -> Self {
Self::new(cases)
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DatasetError {
#[error("cannot read {path}: {source}")]
Read {
path: PathBuf,
source: std::io::Error,
},
#[error("invalid dataset: {0}")]
Json(#[from] serde_json::Error),
#[error("invalid case on line {line}: {source}")]
Line {
line: usize,
source: serde_json::Error,
},
#[error("{0}: expected a .json, .jsonl or .ndjson file")]
UnknownFormat(PathBuf),
}