use indexmap::IndexMap;
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::content::{Content, non_null_schema};
use crate::de;
use crate::validate::{MAX_CHOICE_OPTIONS, MAX_SCORE_LEVELS, MIN_SCORE_LEVELS};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "lowercase")]
#[schemars(
description = "One typed question. The `type` field selects the kind: `noul`, `choice` or `score`. The question id is never sent to the model, so put the full meaning in `instructions`."
)]
#[non_exhaustive]
pub enum Question {
#[schemars(extend("unevaluatedProperties" = false))]
Noul(Noul),
#[schemars(extend("unevaluatedProperties" = false))]
Choice(Choice),
#[schemars(extend("unevaluatedProperties" = false))]
Score(Score),
}
impl Question {
#[must_use]
pub const fn type_name(&self) -> &'static str {
match self {
Self::Noul(_) => "noul",
Self::Choice(_) => "choice",
Self::Score(_) => "score",
}
}
#[must_use]
pub const fn instructions(&self) -> Option<&Content> {
match self {
Self::Noul(question) => question.instructions.as_ref(),
Self::Choice(question) => question.instructions.as_ref(),
Self::Score(question) => question.instructions.as_ref(),
}
}
#[must_use]
pub const fn extra(&self) -> &IndexMap<String, Value> {
match self {
Self::Noul(question) => &question.extra,
Self::Choice(question) => &question.extra,
Self::Score(question) => &question.extra,
}
}
}
impl From<Noul> for Question {
fn from(question: Noul) -> Self {
Self::Noul(question)
}
}
impl From<Choice> for Question {
fn from(question: Choice) -> Self {
Self::Choice(question)
}
}
impl From<Score> for Question {
fn from(question: Score) -> Self {
Self::Score(question)
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[schemars(extend("required" = ["instructions"]))]
#[non_exhaustive]
pub struct Noul {
#[serde(
default,
deserialize_with = "de::present",
skip_serializing_if = "Option::is_none"
)]
pub instructions: Option<Content>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub criteria: Option<NoulCriteria>,
#[serde(flatten)]
#[schemars(skip)]
pub extra: IndexMap<String, Value>,
}
impl Noul {
#[must_use]
pub fn new(instructions: impl Into<Content>) -> Self {
Self {
instructions: Some(instructions.into()),
..Self::default()
}
}
#[must_use]
pub fn with_criteria(mut self, criteria: NoulCriteria) -> Self {
self.criteria = Some(criteria);
self
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[schemars(
description = "What a yes and a no mean for a noul. Either side may be omitted.",
extend("additionalProperties" = false)
)]
#[non_exhaustive]
pub struct NoulCriteria {
#[serde(
rename = "true",
default,
deserialize_with = "de::present",
skip_serializing_if = "Option::is_none"
)]
pub when_true: Option<Content>,
#[serde(
rename = "false",
default,
deserialize_with = "de::present",
skip_serializing_if = "Option::is_none"
)]
pub when_false: Option<Content>,
#[serde(flatten)]
#[schemars(skip)]
pub extra: IndexMap<String, Value>,
}
impl NoulCriteria {
#[must_use]
pub fn new(when_true: impl Into<Content>, when_false: impl Into<Content>) -> Self {
Self {
when_true: Some(when_true.into()),
when_false: Some(when_false.into()),
extra: IndexMap::new(),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[schemars(extend("required" = ["instructions", "criteria"]))]
#[non_exhaustive]
pub struct Choice {
#[serde(
default,
deserialize_with = "de::present",
skip_serializing_if = "Option::is_none"
)]
pub instructions: Option<Content>,
#[serde(deserialize_with = "de::unique_map")]
#[schemars(extend("minProperties" = 1, "maxProperties" = MAX_CHOICE_OPTIONS))]
pub criteria: IndexMap<String, Content>,
#[serde(flatten)]
#[schemars(skip)]
pub extra: IndexMap<String, Value>,
}
impl Choice {
#[must_use]
pub fn new(instructions: impl Into<Content>) -> Self {
Self {
instructions: Some(instructions.into()),
..Self::default()
}
}
#[must_use]
pub fn option(mut self, name: impl Into<String>, description: impl Into<Content>) -> Self {
self.criteria.insert(name.into(), description.into());
self
}
#[must_use]
pub fn bare_option(self, name: impl Into<String>) -> Self {
self.option(name, Content::null())
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[schemars(extend("required" = ["instructions", "criteria"]))]
#[non_exhaustive]
pub struct Score {
#[serde(
default,
deserialize_with = "de::present",
skip_serializing_if = "Option::is_none"
)]
pub instructions: Option<Content>,
#[schemars(schema_with = "levels_schema")]
pub criteria: Vec<Content>,
#[serde(flatten)]
#[schemars(skip)]
pub extra: IndexMap<String, Value>,
}
impl Score {
#[must_use]
pub fn new(instructions: impl Into<Content>) -> Self {
Self {
instructions: Some(instructions.into()),
..Self::default()
}
}
#[must_use]
pub fn level(mut self, description: impl Into<Content>) -> Self {
self.criteria.push(description.into());
self
}
}
fn levels_schema(generator: &mut SchemaGenerator) -> Schema {
json_schema!({
"type": "array",
"items": non_null_schema(generator),
"minItems": MIN_SCORE_LEVELS,
"maxItems": MAX_SCORE_LEVELS
})
}
#[cfg(test)]
mod tests {
use serde_json::{Value, json};
use super::{Choice, Noul, NoulCriteria, Question, Score};
use crate::Content;
fn round_trip(json: &Value) -> Value {
let question: Question = serde_json::from_value(json.clone()).unwrap();
serde_json::to_value(&question).unwrap()
}
#[test]
fn builders_produce_the_documented_wire_shape() {
let noul = Noul::new("Does this convey urgency?").with_criteria(NoulCriteria::new(
"Explicitly time-sensitive",
"No urgency expressed",
));
let choice = Choice::new("Which team should handle this?")
.option("billing", "Payments, invoicing, refunds")
.bare_option("other");
let score = Score::new("How frustrated is the customer?")
.level("Calm")
.level("Angry");
assert_eq!(
serde_json::to_value(Question::from(noul)).unwrap(),
json!({
"type": "noul",
"instructions": "Does this convey urgency?",
"criteria": { "true": "Explicitly time-sensitive", "false": "No urgency expressed" }
})
);
assert_eq!(
serde_json::to_value(Question::from(choice)).unwrap(),
json!({
"type": "choice",
"instructions": "Which team should handle this?",
"criteria": { "billing": "Payments, invoicing, refunds", "other": null }
})
);
assert_eq!(
serde_json::to_value(Question::from(score)).unwrap(),
json!({
"type": "score",
"instructions": "How frustrated is the customer?",
"criteria": ["Calm", "Angry"]
})
);
}
#[test]
fn structured_instructions_and_criteria_round_trip() {
let json = json!({
"type": "score",
"instructions": { "question": "How risky is this change?", "focus": ["scope"] },
"criteria": ["Safe", { "what": "Risky", "signals": ["touches billing"] }, ["Dangerous"]]
});
assert_eq!(round_trip(&json), json);
}
#[test]
fn an_explicit_null_is_kept_distinct_from_an_absent_key() {
let explicit =
json!({ "type": "noul", "instructions": null, "criteria": { "true": null } });
let absent = json!({ "type": "noul", "criteria": {} });
assert_eq!(round_trip(&explicit), explicit);
assert_eq!(round_trip(&absent), absent);
let Question::Noul(noul) = serde_json::from_value(explicit).unwrap() else {
panic!("expected a noul");
};
assert_eq!(noul.instructions, Some(Content::null()));
let criteria = noul.criteria.unwrap();
assert_eq!(criteria.when_true, Some(Content::null()));
assert_eq!(criteria.when_false, None);
}
#[test]
fn choice_options_keep_the_order_they_were_written_in() {
let text = r#"{"type":"choice","instructions":"?","criteria":{"zebra":null,"apple":"a","mango":null}}"#;
let question: Question = serde_json::from_str(text).unwrap();
let Question::Choice(choice) = &question else {
panic!("expected a choice")
};
assert_eq!(
choice.criteria.keys().collect::<Vec<_>>(),
["zebra", "apple", "mango"]
);
assert_eq!(serde_json::to_string(&question).unwrap(), text);
}
#[test]
fn a_repeated_choice_option_is_a_parse_error() {
let text =
r#"{"type":"choice","instructions":"?","criteria":{"a":null,"b":null,"a":"again"}}"#;
let error = serde_json::from_str::<Question>(text)
.unwrap_err()
.to_string();
assert!(error.contains("duplicate key `a`"), "{error}");
}
#[test]
fn unknown_fields_are_kept_for_validation_and_sent_unchanged() {
let json = json!({
"type": "noul",
"instructions": "Is it urgent?",
"critera": { "true": "typo in the key above" },
"criteria": { "true": "yes", "maybe": "not a real side" }
});
let question: Question = serde_json::from_value(json.clone()).unwrap();
assert_eq!(question.extra().keys().collect::<Vec<_>>(), ["critera"]);
let Question::Noul(noul) = &question else {
panic!("expected a noul")
};
assert_eq!(
noul.criteria
.as_ref()
.unwrap()
.extra
.keys()
.collect::<Vec<_>>(),
["maybe"]
);
assert_eq!(serde_json::to_value(&question).unwrap(), json);
}
#[test]
fn a_missing_or_unknown_type_is_rejected() {
let missing = serde_json::from_value::<Question>(json!({ "instructions": "?" }));
let unknown = serde_json::from_value::<Question>(json!({ "type": "rank" }));
assert!(
missing
.unwrap_err()
.to_string()
.contains("missing field `type`")
);
assert!(
unknown
.unwrap_err()
.to_string()
.contains("unknown variant `rank`")
);
}
#[test]
fn accessors_report_the_type_and_instructions() {
let question = Question::from(Score::new("Rate it").level("low").level("high"));
assert_eq!(question.type_name(), "score");
assert_eq!(
question.instructions().and_then(Content::as_str),
Some("Rate it")
);
assert!(question.extra().is_empty());
}
}