use std::collections::HashMap;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "CaseWire")]
#[non_exhaustive]
pub struct Case {
pub id: String,
#[serde(skip_serializing_if = "String::is_empty")]
pub input: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub turns: Vec<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(),
turns: Vec::new(),
expected: None,
trajectory: None,
assertions: Vec::new(),
metadata: Map::new(),
}
}
pub fn multi_turn<I, S>(id: impl Into<String>, turns: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Self::new(id, "").turns(turns)
}
#[must_use]
pub fn turns<I, S>(mut self, turns: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.input.clear();
self.turns = turns.into_iter().map(Into::into).collect();
self
}
pub fn prompts(&self) -> Vec<&str> {
if self.turns.is_empty() {
vec![self.input.as_str()]
} else {
self.turns.iter().map(String::as_str).collect()
}
}
#[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(Deserialize)]
struct CaseWire {
id: String,
#[serde(default)]
input: Option<String>,
#[serde(default)]
turns: Vec<String>,
#[serde(default)]
expected: Option<String>,
#[serde(default)]
trajectory: Option<Vec<ExpectedCall>>,
#[serde(default)]
assertions: Vec<String>,
#[serde(default)]
metadata: Map<String, Value>,
}
impl TryFrom<CaseWire> for Case {
type Error = String;
fn try_from(wire: CaseWire) -> Result<Self, Self::Error> {
let input = match (wire.input, wire.turns.is_empty()) {
(Some(input), true) => input,
(None, false) => String::new(),
(Some(_), false) => {
return Err(format!("case {:?} sets both input and turns", wire.id));
}
(None, true) => return Err(format!("case {:?} sets neither input nor turns", wire.id)),
};
Ok(Self {
id: wire.id,
input,
turns: wire.turns,
expected: wire.expected,
trajectory: wire.trajectory,
assertions: wire.assertions,
metadata: wire.metadata,
})
}
}
#[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> {
let cases: Vec<Case> = serde_json::from_str(text)?;
let places: Vec<String> = (0..cases.len()).map(|i| format!("index {i}")).collect();
warn_repeated_ids(&cases, &places);
Ok(Self { cases })
}
pub fn from_jsonl(text: &str) -> Result<Self, DatasetError> {
let mut cases = Vec::new();
let mut places = Vec::new();
for (index, line) in text.lines().enumerate() {
if line.trim().is_empty() {
continue;
}
let case = serde_json::from_str(line).map_err(|source| DatasetError::Line {
line: index + 1,
source,
})?;
cases.push(case);
places.push(format!("line {}", index + 1));
}
warn_repeated_ids(&cases, &places);
Ok(Self { cases })
}
pub fn load(path: impl AsRef<Path>) -> Result<Self, DatasetError> {
let path = path.as_ref();
let parse: fn(&str) -> Result<Self, DatasetError> =
match path.extension().and_then(|extension| extension.to_str()) {
Some("json") => Self::from_json,
Some("jsonl" | "ndjson") => Self::from_jsonl,
_ => return Err(DatasetError::UnknownFormat(path.to_owned())),
};
let text = std::fs::read_to_string(path).map_err(|source| DatasetError::Read {
path: path.to_owned(),
source,
})?;
parse(&text)
}
pub fn load_named(path: impl AsRef<Path>) -> Result<Self, DatasetError> {
let path = path.as_ref();
let json = match path.extension().and_then(|extension| extension.to_str()) {
Some("json") => true,
Some("jsonl" | "ndjson") => false,
_ => return Err(DatasetError::UnknownFormat(path.to_owned())),
};
let text = std::fs::read_to_string(path).map_err(|source| DatasetError::Read {
path: path.to_owned(),
source,
})?;
let parsed = if json {
parse_json_elements(&text)
} else {
Self::from_jsonl(&text)
};
parsed.map_err(|source| DatasetError::InFile {
path: path.to_owned(),
source: Box::new(source),
})
}
}
fn parse_json_elements(text: &str) -> Result<Dataset, DatasetError> {
let elements: Vec<Value> = serde_json::from_str(text)?;
let cases = elements
.into_iter()
.enumerate()
.map(|(index, element)| {
serde_json::from_value(element)
.map_err(|source| DatasetError::Element { index, source })
})
.collect::<Result<Vec<Case>, _>>()?;
let places: Vec<String> = (0..cases.len()).map(|i| format!("index {i}")).collect();
warn_repeated_ids(&cases, &places);
Ok(Dataset { cases })
}
fn warn_repeated_ids(cases: &[Case], places: &[String]) {
let mut first_seen: HashMap<&str, &str> = HashMap::new();
for (case, place) in cases.iter().zip(places) {
match first_seen.get(case.id.as_str()) {
Some(first) => tracing::warn!(
id = %case.id,
first = %first,
second = %place,
"dataset repeats a case id; an experiment will refuse to run it"
),
None => {
first_seen.insert(case.id.as_str(), place.as_str());
}
}
}
}
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),
#[error("invalid case at index {index}: {source}")]
Element {
index: usize,
source: serde_json::Error,
},
#[error("{path}: {source}")]
InFile {
path: PathBuf,
source: Box<DatasetError>,
},
}