1use indexmap::IndexMap;
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7
8use crate::content::Content;
9
10#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
27#[serde(tag = "type", rename_all = "lowercase")]
28#[schemars(
29 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."
30)]
31#[non_exhaustive]
32pub enum Answer {
33 Noul(NoulAnswer),
35 Choice(ChoiceAnswer),
37 Score(ScoreAnswer),
39 #[serde(untagged)]
41 Unknown(Value),
42}
43
44impl Answer {
45 #[must_use]
50 pub fn type_name(&self) -> Option<&str> {
51 match self {
52 Self::Noul(_) => Some("noul"),
53 Self::Choice(_) => Some("choice"),
54 Self::Score(_) => Some("score"),
55 Self::Unknown(raw) => raw.get("type").and_then(Value::as_str),
56 }
57 }
58
59 #[must_use]
61 pub const fn as_noul(&self) -> Option<&NoulAnswer> {
62 match self {
63 Self::Noul(answer) => Some(answer),
64 _ => None,
65 }
66 }
67
68 #[must_use]
70 pub const fn as_choice(&self) -> Option<&ChoiceAnswer> {
71 match self {
72 Self::Choice(answer) => Some(answer),
73 _ => None,
74 }
75 }
76
77 #[must_use]
79 pub const fn as_score(&self) -> Option<&ScoreAnswer> {
80 match self {
81 Self::Score(answer) => Some(answer),
82 _ => None,
83 }
84 }
85}
86
87impl From<NoulAnswer> for Answer {
88 fn from(answer: NoulAnswer) -> Self {
89 Self::Noul(answer)
90 }
91}
92
93impl From<ChoiceAnswer> for Answer {
94 fn from(answer: ChoiceAnswer) -> Self {
95 Self::Choice(answer)
96 }
97}
98
99impl From<ScoreAnswer> for Answer {
100 fn from(answer: ScoreAnswer) -> Self {
101 Self::Score(answer)
102 }
103}
104
105#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
107#[schemars(
108 description = "The answer to a noul. It has no `confidence`: the probability is the signal."
109)]
110#[non_exhaustive]
111pub struct NoulAnswer {
112 pub noul: f64,
114}
115
116impl NoulAnswer {
117 #[must_use]
119 pub const fn new(noul: f64) -> Self {
120 Self { noul }
121 }
122}
123
124#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
126#[schemars(description = "The answer to a choice.")]
127#[non_exhaustive]
128pub struct ChoiceAnswer {
129 pub choice: String,
131
132 pub probabilities: IndexMap<String, f64>,
136
137 pub confidence: f64,
139}
140
141impl ChoiceAnswer {
142 #[must_use]
144 pub fn new(
145 choice: impl Into<String>,
146 probabilities: IndexMap<String, f64>,
147 confidence: f64,
148 ) -> Self {
149 Self {
150 choice: choice.into(),
151 probabilities,
152 confidence,
153 }
154 }
155}
156
157#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
159#[schemars(description = "The answer to a score.")]
160#[non_exhaustive]
161pub struct ScoreAnswer {
162 pub score: f64,
164
165 pub legend: IndexMap<String, Content>,
170
171 pub probabilities: IndexMap<String, f64>,
173
174 pub confidence: f64,
176}
177
178impl ScoreAnswer {
179 #[must_use]
181 pub const fn new(
182 score: f64,
183 legend: IndexMap<String, Content>,
184 probabilities: IndexMap<String, f64>,
185 confidence: f64,
186 ) -> Self {
187 Self {
188 score,
189 legend,
190 probabilities,
191 confidence,
192 }
193 }
194}
195
196#[cfg(test)]
197mod tests {
198 use indexmap::IndexMap;
199 use serde_json::{Value, json};
200
201 use super::{Answer, ChoiceAnswer, NoulAnswer, ScoreAnswer};
202 use crate::Content;
203
204 fn parse(json: &Value) -> Answer {
205 serde_json::from_value(json.clone()).unwrap()
206 }
207
208 #[test]
209 fn known_answers_parse_into_their_variant() {
210 let choice = parse(&json!({
211 "type": "choice",
212 "choice": "technical",
213 "probabilities": { "billing": 0.08, "technical": 0.85, "sales": 0.07 },
214 "confidence": 0.82
215 }));
216
217 let choice = choice.as_choice().unwrap();
218 assert_eq!(choice.choice, "technical");
219 assert_eq!(choice.probabilities.get("technical"), Some(&0.85));
220 assert_eq!(
221 parse(&json!({ "type": "noul", "noul": 1 })),
222 Answer::from(NoulAnswer::new(1.0)),
223 "an integer probability is read as a float"
224 );
225 }
226
227 #[test]
228 fn score_levels_are_keyed_by_string_and_the_legend_may_be_structured() {
229 let json = json!({
230 "type": "score",
231 "score": 1.2,
232 "confidence": 0.68,
233 "legend": { "0": "Calm", "1": { "what": "Frustrated" }, "2": ["Very angry"] },
234 "probabilities": { "0": 0.01, "1": 0.78, "2": 0.21 }
235 });
236
237 let answer = parse(&json);
238
239 let score = answer.as_score().unwrap();
240 assert_eq!(
241 score.probabilities.keys().collect::<Vec<_>>(),
242 ["0", "1", "2"]
243 );
244 assert_eq!(
245 score.legend.get("0").and_then(Content::as_str),
246 Some("Calm")
247 );
248 assert_eq!(
249 score.legend.get("1").unwrap().as_value(),
250 &json!({ "what": "Frustrated" })
251 );
252 }
253
254 #[test]
255 fn an_unknown_type_keeps_its_raw_json() {
256 let json = json!({ "type": "rank", "order": ["b", "a"], "confidence": 0.5 });
257
258 let answer = parse(&json);
259
260 assert_eq!(answer, Answer::Unknown(json.clone()));
261 assert_eq!(answer.type_name(), Some("rank"));
262 assert_eq!(serde_json::to_value(&answer).unwrap(), json);
263 }
264
265 #[test]
266 fn a_known_type_with_a_changed_shape_degrades_to_unknown_instead_of_failing() {
267 let json = json!({ "type": "noul", "probability": 0.9 });
268
269 let answer = parse(&json);
270
271 assert_eq!(answer, Answer::Unknown(json));
272 assert_eq!(answer.type_name(), Some("noul"));
273 assert!(answer.as_noul().is_none());
274 }
275
276 #[test]
277 fn an_answer_without_a_type_is_still_kept() {
278 for json in [json!({ "noul": 0.5 }), json!("surprise"), json!(null)] {
279 let answer = parse(&json);
280
281 assert_eq!(answer, Answer::Unknown(json));
282 assert_eq!(answer.type_name(), None);
283 }
284 }
285
286 #[test]
287 fn extra_fields_on_a_known_answer_are_ignored() {
288 let answer = parse(&json!({ "type": "noul", "noul": 0.4, "confidence": 0.2 }));
289
290 assert_eq!(answer, Answer::from(NoulAnswer::new(0.4)));
291 }
292
293 #[test]
294 fn constructed_answers_serialise_with_their_type_tag() {
295 let probabilities = IndexMap::from([("a".to_owned(), 0.75), ("b".to_owned(), 0.25)]);
296 let choice = Answer::from(ChoiceAnswer::new("a", probabilities.clone(), 0.6));
297 let legend = IndexMap::from([("0".to_owned(), Content::from("low"))]);
298 let score = Answer::from(ScoreAnswer::new(0.0, legend, IndexMap::new(), 1.0));
299
300 assert_eq!(
301 serde_json::to_value(&choice).unwrap(),
302 json!({ "type": "choice", "choice": "a", "probabilities": probabilities, "confidence": 0.6 })
303 );
304 assert_eq!(score.type_name(), Some("score"));
305 assert_eq!(
306 serde_json::to_value(&score).unwrap()["legend"],
307 json!({ "0": "low" })
308 );
309 }
310}