Skip to main content

typesafe/
question.rs

1//! Typed questions: [`Noul`], [`Choice`], [`Score`] and [`BoxQuestion`].
2//!
3//! Instructions, option descriptions and score levels accept any JSON value (`&str`, `String`,
4//! or `serde_json::json!({...})` for structured rubrics), per the API's "advanced structure" support.
5
6use indexmap::IndexMap;
7use serde::{Serialize, Serializer};
8use serde_json::Value;
9
10use crate::error::{Error, Result};
11
12/// A yes/no question; the answer is the probability of "yes".
13#[derive(Debug, Clone, Default, PartialEq, Serialize)]
14#[non_exhaustive]
15#[serde(tag = "type", rename = "noul")]
16pub struct Noul {
17    /// The question to evaluate.
18    #[serde(skip_serializing_if = "Option::is_none")]
19    pub instructions: Option<Value>,
20    /// Optional descriptions of what yes and no mean.
21    #[serde(skip_serializing_if = "Option::is_none")]
22    pub criteria: Option<NoulCriteria>,
23}
24
25/// Descriptions of the yes (`true`) and no (`false`) outcomes of a [`Noul`].
26#[derive(Debug, Clone, Default, PartialEq, Serialize)]
27#[non_exhaustive]
28pub struct NoulCriteria {
29    /// What a yes (value near 1) means.
30    #[serde(rename = "true", skip_serializing_if = "Option::is_none")]
31    pub yes: Option<Value>,
32    /// What a no (value near 0) means.
33    #[serde(rename = "false", skip_serializing_if = "Option::is_none")]
34    pub no: Option<Value>,
35}
36
37impl Noul {
38    /// A yes/no question with the given instructions.
39    pub fn new(instructions: impl Into<Value>) -> Self {
40        Self {
41            instructions: Some(instructions.into()),
42            criteria: None,
43        }
44    }
45
46    /// Describe what a yes means.
47    #[must_use]
48    pub fn when_true(mut self, description: impl Into<Value>) -> Self {
49        self.criteria.get_or_insert_with(Default::default).yes = Some(description.into());
50        self
51    }
52
53    /// Describe what a no means.
54    #[must_use]
55    pub fn when_false(mut self, description: impl Into<Value>) -> Self {
56        self.criteria.get_or_insert_with(Default::default).no = Some(description.into());
57        self
58    }
59}
60
61/// Pick one option from a set you define.
62#[derive(Debug, Clone, Default, PartialEq, Serialize)]
63#[non_exhaustive]
64#[serde(tag = "type", rename = "choice")]
65pub struct Choice {
66    /// What the model should decide.
67    #[serde(skip_serializing_if = "Option::is_none")]
68    pub instructions: Option<Value>,
69    /// Option label → description (`None` is sent as `null`: an undescribed option).
70    pub criteria: IndexMap<String, Option<Value>>,
71}
72
73impl Choice {
74    /// A choice with instructions and no options yet; add them with [`Choice::option`].
75    pub fn new(instructions: impl Into<Value>) -> Self {
76        Self {
77            instructions: Some(instructions.into()),
78            criteria: IndexMap::new(),
79        }
80    }
81
82    /// A choice between undescribed labels.
83    pub fn from_labels<I, S>(instructions: impl Into<Value>, labels: I) -> Self
84    where
85        I: IntoIterator<Item = S>,
86        S: Into<String>,
87    {
88        let mut c = Self::new(instructions);
89        c.criteria
90            .extend(labels.into_iter().map(|l| (l.into(), None)));
91        c
92    }
93
94    /// Add an option with a description.
95    #[must_use]
96    pub fn option(mut self, label: impl Into<String>, description: impl Into<Value>) -> Self {
97        self.criteria.insert(label.into(), Some(description.into()));
98        self
99    }
100
101    /// Add an option without a description.
102    #[must_use]
103    pub fn label(mut self, label: impl Into<String>) -> Self {
104        self.criteria.insert(label.into(), None);
105        self
106    }
107}
108
109/// Rate the state along ordered levels; the answer is a probability-weighted level index.
110#[derive(Debug, Clone, Default, PartialEq, Serialize)]
111#[non_exhaustive]
112#[serde(tag = "type", rename = "score")]
113pub struct Score {
114    /// What the model should rate.
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub instructions: Option<Value>,
117    /// Ordered level descriptions; level `i` is index `i`.
118    pub criteria: Vec<Value>,
119}
120
121impl Score {
122    /// A score with instructions and ordered level descriptions.
123    pub fn new<I, V>(instructions: impl Into<Value>, levels: I) -> Self
124    where
125        I: IntoIterator<Item = V>,
126        V: Into<Value>,
127    {
128        Self {
129            instructions: Some(instructions.into()),
130            criteria: levels.into_iter().map(Into::into).collect(),
131        }
132    }
133
134    /// Append a level.
135    #[must_use]
136    pub fn level(mut self, description: impl Into<Value>) -> Self {
137        self.criteria.push(description.into());
138        self
139    }
140}
141
142/// Locate one thing in an image; the answer is a [`BoxAnswer`](crate::BoxAnswer).
143///
144/// Jev 1.14 (`jev-1.14.0`, `jev-preview`) and later only, and experimental: a request that asks
145/// one is sent with `TypeSafe-Danger-Zone-Images: true`. The image goes in the request's assets
146/// (see [`Image`](crate::Image)); a box question has instructions and no criteria.
147#[derive(Debug, Clone, Default, PartialEq, Serialize)]
148#[non_exhaustive]
149#[serde(tag = "type", rename = "box")]
150pub struct BoxQuestion {
151    /// What to find, naming the image by its reference.
152    #[serde(skip_serializing_if = "Option::is_none")]
153    pub instructions: Option<Value>,
154}
155
156impl BoxQuestion {
157    /// Where in the image `instructions` points.
158    pub fn new(instructions: impl Into<Value>) -> Self {
159        Self {
160            instructions: Some(instructions.into()),
161        }
162    }
163}
164
165/// Any question. `Raw` passes a hand-built JSON object through (after light validation), which is
166/// useful for fields this SDK version does not model yet.
167#[derive(Debug, Clone, PartialEq)]
168#[non_exhaustive]
169pub enum Question {
170    /// See [`Noul`].
171    Noul(Noul),
172    /// See [`Choice`].
173    Choice(Choice),
174    /// See [`Score`].
175    Score(Score),
176    /// See [`BoxQuestion`].
177    Box(BoxQuestion),
178    /// A JSON object with a non-empty string `type`.
179    Raw(Value),
180}
181
182impl Serialize for Question {
183    fn serialize<S: Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
184        match self {
185            Question::Noul(q) => q.serialize(s),
186            Question::Choice(q) => q.serialize(s),
187            Question::Score(q) => q.serialize(s),
188            Question::Box(q) => q.serialize(s),
189            Question::Raw(v) => v.serialize(s),
190        }
191    }
192}
193
194impl From<Noul> for Question {
195    fn from(q: Noul) -> Self {
196        Question::Noul(q)
197    }
198}
199impl From<Choice> for Question {
200    fn from(q: Choice) -> Self {
201        Question::Choice(q)
202    }
203}
204impl From<Score> for Question {
205    fn from(q: Score) -> Self {
206        Question::Score(q)
207    }
208}
209impl From<BoxQuestion> for Question {
210    fn from(q: BoxQuestion) -> Self {
211        Question::Box(q)
212    }
213}
214impl From<Value> for Question {
215    fn from(v: Value) -> Self {
216        Question::Raw(v)
217    }
218}
219
220/// Ordered map of question name → question. Answers come back under the same names.
221#[derive(Debug, Clone, Default, PartialEq, Serialize)]
222#[serde(transparent)]
223pub struct Questions(IndexMap<String, Question>);
224
225impl Questions {
226    /// An empty set.
227    pub fn new() -> Self {
228        Self::default()
229    }
230
231    /// Add (or replace) a question, builder-style.
232    #[must_use]
233    pub fn with(mut self, name: impl Into<String>, question: impl Into<Question>) -> Self {
234        self.insert(name, question);
235        self
236    }
237
238    /// Add a question, or replace the one of the same name (keeping its position). Returns the
239    /// question it replaced, as `HashMap::insert` does.
240    pub fn insert(
241        &mut self,
242        name: impl Into<String>,
243        question: impl Into<Question>,
244    ) -> Option<Question> {
245        self.0.insert(name.into(), question.into())
246    }
247
248    /// The question named `name`.
249    pub fn get(&self, name: &str) -> Option<&Question> {
250        self.0.get(name)
251    }
252
253    /// Number of questions.
254    pub fn len(&self) -> usize {
255        self.0.len()
256    }
257
258    /// Whether there are no questions.
259    pub fn is_empty(&self) -> bool {
260        self.0.is_empty()
261    }
262
263    /// Iterate in insertion order.
264    pub fn iter(&self) -> impl Iterator<Item = (&str, &Question)> {
265        self.0.iter().map(|(k, v)| (k.as_str(), v))
266    }
267
268    /// Whether any question is a box, which only the images opt-in may ask.
269    pub(crate) fn asks_box(&self) -> bool {
270        self.0.values().any(|q| match q {
271            Question::Box(_) => true,
272            Question::Raw(v) => v.get("type").and_then(Value::as_str) == Some("box"),
273            _ => false,
274        })
275    }
276
277    /// Reject what the Python SDK rejects locally; everything else is left to server validation.
278    pub(crate) fn validate(&self) -> Result<()> {
279        if self.0.is_empty() {
280            return Err(Error::invalid_request("at least one question is required"));
281        }
282        for (name, q) in &self.0 {
283            match q {
284                Question::Score(s) if s.criteria.is_empty() => return Err(empty_score(name)),
285                Question::Choice(c) if c.criteria.is_empty() => return Err(empty_choice(name)),
286                Question::Raw(v) => validate_raw(name, v)?,
287                _ => {}
288            }
289        }
290        Ok(())
291    }
292}
293
294fn empty_score(name: &str) -> Error {
295    Error::invalid_request(format!(
296        "score question \"{name}\" has no criteria; at least one score is required"
297    ))
298}
299
300fn empty_choice(name: &str) -> Error {
301    Error::invalid_request(format!(
302        "choice question \"{name}\" has no criteria; at least one option is required"
303    ))
304}
305
306fn validate_raw(name: &str, v: &Value) -> Result<()> {
307    let ty = v
308        .as_object()
309        .and_then(|o| o.get("type"))
310        .and_then(Value::as_str)
311        .filter(|t| !t.is_empty())
312        .ok_or_else(|| {
313            Error::invalid_request(format!(
314                "question \"{name}\" must be a question object or a JSON object with a nonempty string \"type\""
315            ))
316        })?;
317    if matches!(ty, "choice" | "score") {
318        let criteria = v.get("criteria").ok_or_else(|| {
319            Error::invalid_request(format!("question \"{name}\" requires \"criteria\""))
320        })?;
321        let empty = match criteria {
322            Value::Null => true,
323            Value::Bool(b) => !b,
324            Value::String(s) => s.is_empty(),
325            Value::Array(a) => a.is_empty(),
326            Value::Object(o) => o.is_empty(),
327            Value::Number(n) => n.as_f64() == Some(0.0),
328        };
329        if empty {
330            return Err(if ty == "score" {
331                empty_score(name)
332            } else {
333                empty_choice(name)
334            });
335        }
336    }
337    Ok(())
338}
339
340impl<K: Into<String>, Q: Into<Question>> FromIterator<(K, Q)> for Questions {
341    fn from_iter<T: IntoIterator<Item = (K, Q)>>(iter: T) -> Self {
342        Self(
343            iter.into_iter()
344                .map(|(k, q)| (k.into(), q.into()))
345                .collect(),
346        )
347    }
348}
349
350impl<K: Into<String>, Q: Into<Question>> Extend<(K, Q)> for Questions {
351    /// Add (or replace) each question, as [`Questions::insert`] does.
352    fn extend<T: IntoIterator<Item = (K, Q)>>(&mut self, iter: T) {
353        self.0
354            .extend(iter.into_iter().map(|(k, q)| (k.into(), q.into())));
355    }
356}
357
358/// Name and question, in insertion order.
359impl IntoIterator for Questions {
360    type Item = (String, Question);
361    type IntoIter = indexmap::map::IntoIter<String, Question>;
362
363    fn into_iter(self) -> Self::IntoIter {
364        self.0.into_iter()
365    }
366}
367
368/// The same items as [`Questions::iter`].
369impl<'a> IntoIterator for &'a Questions {
370    type Item = (&'a str, &'a Question);
371    type IntoIter = std::iter::Map<
372        indexmap::map::Iter<'a, String, Question>,
373        fn((&'a String, &'a Question)) -> (&'a str, &'a Question),
374    >;
375
376    fn into_iter(self) -> Self::IntoIter {
377        self.0.iter().map(|(k, v)| (k.as_str(), v))
378    }
379}
380
381impl<K: Into<String>, Q: Into<Question>, const N: usize> From<[(K, Q); N]> for Questions {
382    fn from(arr: [(K, Q); N]) -> Self {
383        arr.into_iter().collect()
384    }
385}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390    use serde_json::json;
391
392    #[test]
393    fn serializes_like_the_api_reference() {
394        let q = Questions::new()
395            .with(
396                "department",
397                Choice::new("Which team should handle this")
398                    .option("billing", "Payment or subscription issues")
399                    .label("other"),
400            )
401            .with(
402                "frustration",
403                Score::new("How frustrated", ["Calm", "Angry"]),
404            )
405            .with(
406                "is_urgent",
407                Noul::new("Urgent?").when_true("Explicitly time-sensitive"),
408            )
409            .with("bare", Noul::default());
410        assert_eq!(
411            serde_json::to_value(&q).unwrap(),
412            json!({
413                "department": {"type": "choice", "instructions": "Which team should handle this",
414                    "criteria": {"billing": "Payment or subscription issues", "other": null}},
415                "frustration": {"type": "score", "instructions": "How frustrated", "criteria": ["Calm", "Angry"]},
416                "is_urgent": {"type": "noul", "instructions": "Urgent?", "criteria": {"true": "Explicitly time-sensitive"}},
417                "bare": {"type": "noul"}
418            })
419        );
420        // insertion order is preserved on the wire
421        let keys: Vec<_> = q.iter().map(|(k, _)| k).collect();
422        assert_eq!(keys, ["department", "frustration", "is_urgent", "bare"]);
423    }
424
425    #[test]
426    fn lookup_iteration_and_extend() {
427        let mut q: Questions = [("a", Noul::new("a"))].into_iter().collect();
428        q.extend([("b", Question::from(Noul::new("b")))]);
429        q.extend(vec![(String::from("a"), Score::new("a", ["lo", "hi"]))]);
430        assert_eq!(q.len(), 2);
431        assert!(matches!(q.get("a"), Some(Question::Score(_))));
432        assert_eq!(q.get("b"), Some(&Question::Noul(Noul::new("b"))));
433        assert_eq!(q.get("c"), None);
434
435        let borrowed: Vec<&str> = (&q).into_iter().map(|(k, _)| k).collect();
436        assert_eq!(borrowed, ["a", "b"]);
437        let mut names = Vec::new();
438        for (name, _) in &q {
439            names.push(name);
440        }
441        assert_eq!(names, borrowed);
442        let owned: Vec<String> = q.clone().into_iter().map(|(k, _)| k).collect();
443        assert_eq!(owned, ["a", "b"]);
444        // Round-trips through the owned iterator without losing order or content.
445        assert_eq!(q.clone().into_iter().collect::<Questions>(), q);
446
447        // `insert` hands back what it replaced.
448        let mut r = Questions::new();
449        assert_eq!(r.insert("c", Noul::new("c")), None);
450        assert_eq!(r.insert("c", Noul::new("d")), Some(Noul::new("c").into()));
451        assert_eq!(r.get("c"), Some(&Question::Noul(Noul::new("d"))));
452    }
453
454    #[test]
455    fn box_questions() {
456        let q = Questions::new()
457            .with("door", BoxQuestion::new("the front door in photo"))
458            .with("n", Noul::new("x"));
459        assert_eq!(
460            serde_json::to_value(&q).unwrap(),
461            json!({
462                "door": {"type": "box", "instructions": "the front door in photo"},
463                "n": {"type": "noul", "instructions": "x"}
464            })
465        );
466        assert!(q.validate().is_ok());
467        assert!(q.asks_box());
468        assert!(Questions::from([("r", json!({"type": "box"}))]).asks_box());
469        assert!(!Questions::from([("n", Noul::new("x"))]).asks_box());
470    }
471
472    #[test]
473    fn structured_instructions() {
474        let q = Score::new(
475            json!({"task": "rate", "focus": ["tone"]}),
476            [json!({"level": "low"}), json!("high")],
477        );
478        assert_eq!(
479            serde_json::to_value(Question::from(q)).unwrap(),
480            json!({"type": "score", "instructions": {"task": "rate", "focus": ["tone"]},
481                   "criteria": [{"level": "low"}, "high"]})
482        );
483    }
484
485    #[test]
486    fn validation() {
487        assert!(Questions::new().validate().is_err());
488        assert!(
489            Questions::from([("s", Score::new("x", Vec::<Value>::new()))])
490                .validate()
491                .is_err()
492        );
493        assert!(
494            Questions::from([("r", json!({"instructions": "x"}))])
495                .validate()
496                .is_err()
497        );
498        assert!(
499            Questions::from([("r", json!({"type": ""}))])
500                .validate()
501                .is_err()
502        );
503        assert!(
504            Questions::from([("c", Choice::new("x"))])
505                .validate()
506                .is_err()
507        );
508        assert!(
509            Questions::from([("r", json!({"type": "choice"}))])
510                .validate()
511                .is_err()
512        );
513        assert!(
514            Questions::from([("r", json!({"type": "choice", "criteria": {}}))])
515                .validate()
516                .is_err()
517        );
518        assert!(
519            Questions::from([("r", json!({"type": "score", "criteria": []}))])
520                .validate()
521                .is_err()
522        );
523        assert!(
524            Questions::from([("r", json!({"type": "noul", "future_field": 1}))])
525                .validate()
526                .is_ok()
527        );
528        assert!(
529            Questions::from([("r", json!({"type": "choice", "criteria": {"a": null}}))])
530                .validate()
531                .is_ok()
532        );
533    }
534}