use indexmap::IndexMap;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::content::Content;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "lowercase")]
#[schemars(
description = "The answer to one question. The `type` field mirrors the question's type. An answer of a type this version does not understand is passed through as the raw JSON received."
)]
#[non_exhaustive]
pub enum Answer {
Noul(NoulAnswer),
Choice(ChoiceAnswer),
Score(ScoreAnswer),
#[serde(untagged)]
Unknown(Value),
}
impl Answer {
#[must_use]
pub fn type_name(&self) -> Option<&str> {
match self {
Self::Noul(_) => Some("noul"),
Self::Choice(_) => Some("choice"),
Self::Score(_) => Some("score"),
Self::Unknown(raw) => raw.get("type").and_then(Value::as_str),
}
}
#[must_use]
pub const fn as_noul(&self) -> Option<&NoulAnswer> {
match self {
Self::Noul(answer) => Some(answer),
_ => None,
}
}
#[must_use]
pub const fn as_choice(&self) -> Option<&ChoiceAnswer> {
match self {
Self::Choice(answer) => Some(answer),
_ => None,
}
}
#[must_use]
pub const fn as_score(&self) -> Option<&ScoreAnswer> {
match self {
Self::Score(answer) => Some(answer),
_ => None,
}
}
}
impl From<NoulAnswer> for Answer {
fn from(answer: NoulAnswer) -> Self {
Self::Noul(answer)
}
}
impl From<ChoiceAnswer> for Answer {
fn from(answer: ChoiceAnswer) -> Self {
Self::Choice(answer)
}
}
impl From<ScoreAnswer> for Answer {
fn from(answer: ScoreAnswer) -> Self {
Self::Score(answer)
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[schemars(
description = "The answer to a noul. It has no `confidence`: the probability is the signal."
)]
#[non_exhaustive]
pub struct NoulAnswer {
pub noul: f64,
}
impl NoulAnswer {
#[must_use]
pub const fn new(noul: f64) -> Self {
Self { noul }
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[schemars(description = "The answer to a choice.")]
#[non_exhaustive]
pub struct ChoiceAnswer {
pub choice: String,
pub probabilities: IndexMap<String, f64>,
pub confidence: f64,
}
impl ChoiceAnswer {
#[must_use]
pub fn new(
choice: impl Into<String>,
probabilities: IndexMap<String, f64>,
confidence: f64,
) -> Self {
Self {
choice: choice.into(),
probabilities,
confidence,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[schemars(description = "The answer to a score.")]
#[non_exhaustive]
pub struct ScoreAnswer {
pub score: f64,
pub legend: IndexMap<String, Content>,
pub probabilities: IndexMap<String, f64>,
pub confidence: f64,
}
impl ScoreAnswer {
#[must_use]
pub const fn new(
score: f64,
legend: IndexMap<String, Content>,
probabilities: IndexMap<String, f64>,
confidence: f64,
) -> Self {
Self {
score,
legend,
probabilities,
confidence,
}
}
}
#[cfg(test)]
mod tests {
use indexmap::IndexMap;
use serde_json::{Value, json};
use super::{Answer, ChoiceAnswer, NoulAnswer, ScoreAnswer};
use crate::Content;
fn parse(json: &Value) -> Answer {
serde_json::from_value(json.clone()).unwrap()
}
#[test]
fn known_answers_parse_into_their_variant() {
let choice = parse(&json!({
"type": "choice",
"choice": "technical",
"probabilities": { "billing": 0.08, "technical": 0.85, "sales": 0.07 },
"confidence": 0.82
}));
let choice = choice.as_choice().unwrap();
assert_eq!(choice.choice, "technical");
assert_eq!(choice.probabilities.get("technical"), Some(&0.85));
assert_eq!(
parse(&json!({ "type": "noul", "noul": 1 })),
Answer::from(NoulAnswer::new(1.0)),
"an integer probability is read as a float"
);
}
#[test]
fn score_levels_are_keyed_by_string_and_the_legend_may_be_structured() {
let json = json!({
"type": "score",
"score": 1.2,
"confidence": 0.68,
"legend": { "0": "Calm", "1": { "what": "Frustrated" }, "2": ["Very angry"] },
"probabilities": { "0": 0.01, "1": 0.78, "2": 0.21 }
});
let answer = parse(&json);
let score = answer.as_score().unwrap();
assert_eq!(
score.probabilities.keys().collect::<Vec<_>>(),
["0", "1", "2"]
);
assert_eq!(
score.legend.get("0").and_then(Content::as_str),
Some("Calm")
);
assert_eq!(
score.legend.get("1").unwrap().as_value(),
&json!({ "what": "Frustrated" })
);
}
#[test]
fn an_unknown_type_keeps_its_raw_json() {
let json = json!({ "type": "rank", "order": ["b", "a"], "confidence": 0.5 });
let answer = parse(&json);
assert_eq!(answer, Answer::Unknown(json.clone()));
assert_eq!(answer.type_name(), Some("rank"));
assert_eq!(serde_json::to_value(&answer).unwrap(), json);
}
#[test]
fn a_known_type_with_a_changed_shape_degrades_to_unknown_instead_of_failing() {
let json = json!({ "type": "noul", "probability": 0.9 });
let answer = parse(&json);
assert_eq!(answer, Answer::Unknown(json));
assert_eq!(answer.type_name(), Some("noul"));
assert!(answer.as_noul().is_none());
}
#[test]
fn an_answer_without_a_type_is_still_kept() {
for json in [json!({ "noul": 0.5 }), json!("surprise"), json!(null)] {
let answer = parse(&json);
assert_eq!(answer, Answer::Unknown(json));
assert_eq!(answer.type_name(), None);
}
}
#[test]
fn extra_fields_on_a_known_answer_are_ignored() {
let answer = parse(&json!({ "type": "noul", "noul": 0.4, "confidence": 0.2 }));
assert_eq!(answer, Answer::from(NoulAnswer::new(0.4)));
}
#[test]
fn constructed_answers_serialise_with_their_type_tag() {
let probabilities = IndexMap::from([("a".to_owned(), 0.75), ("b".to_owned(), 0.25)]);
let choice = Answer::from(ChoiceAnswer::new("a", probabilities.clone(), 0.6));
let legend = IndexMap::from([("0".to_owned(), Content::from("low"))]);
let score = Answer::from(ScoreAnswer::new(0.0, legend, IndexMap::new(), 1.0));
assert_eq!(
serde_json::to_value(&choice).unwrap(),
json!({ "type": "choice", "choice": "a", "probabilities": probabilities, "confidence": 0.6 })
);
assert_eq!(score.type_name(), Some("score"));
assert_eq!(
serde_json::to_value(&score).unwrap()["legend"],
json!({ "0": "low" })
);
}
}