Skip to main content

kaeso_kpp/
decision.rs

1use indexmap::IndexMap;
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4
5use crate::block::{Block, CacheTtl, Source};
6use crate::error::KppError;
7use crate::extras::Extras;
8use crate::raw::RawJson;
9use crate::request::Message;
10use crate::response::Usage;
11
12/// A decision request: typed questions about one input, answered with probabilities instead of
13/// generated text.
14#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
15#[non_exhaustive]
16pub struct DecideRequest {
17    pub model: String,
18    /// What every question is about: the state of System One, the input of OpenAI's and
19    /// Gemini's Decisions APIs.
20    pub input: DecisionInput,
21    /// The questions, in order; `answers[i]` of the reply answers `questions[i]`.
22    pub questions: Vec<Question>,
23    /// Media the input, instructions and descriptions reference by their key, written as a whole
24    /// string or inside a longer one (System One's `assets`).
25    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
26    pub assets: IndexMap<String, Asset>,
27    /// A stable identifier of the app's end user.
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub user: Option<String>,
30    /// How the provider should cache the request's prefix.
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub cache: Option<DecisionCache>,
33    #[serde(default, skip_serializing_if = "Extras::is_empty")]
34    pub extras: Extras,
35}
36
37impl DecideRequest {
38    pub fn new(model: impl Into<String>, input: DecisionInput) -> Self {
39        DecideRequest {
40            model: model.into(),
41            input,
42            questions: Vec::new(),
43            assets: IndexMap::new(),
44            user: None,
45            cache: None,
46            extras: Extras::default(),
47        }
48    }
49
50    #[must_use]
51    pub fn with_question(mut self, question: Question) -> Self {
52        self.questions.push(question);
53        self
54    }
55
56    #[must_use]
57    pub fn with_asset(mut self, reference: impl Into<String>, asset: Asset) -> Self {
58        self.assets.insert(reference.into(), asset);
59        self
60    }
61
62    /// Checks what every decision request needs, whatever its format: a model, at least one
63    /// question, options and levels to choose from, and assets that are referenced. Names may be
64    /// missing or repeated, as OpenAI's format allows; a format that keys questions by name
65    /// renames them. The limits of each format, such as at least two options, are the codecs'.
66    pub fn validate(&self) -> Result<(), KppError> {
67        if self.model.is_empty() {
68            return Err(invalid("`model` must not be empty.", "model"));
69        }
70        if self.questions.is_empty() {
71            return Err(invalid("Ask at least one question.", "questions"));
72        }
73        for (i, q) in self.questions.iter().enumerate() {
74            match &q.kind {
75                QuestionKind::Choice(c) if c.options.is_empty() => {
76                    return Err(invalid(
77                        "A choice question needs at least one option.",
78                        format!("questions[{i}]"),
79                    ));
80                }
81                QuestionKind::Score(s) if s.levels.is_empty() => {
82                    return Err(invalid(
83                        "A score question needs at least one level.",
84                        format!("questions[{i}]"),
85                    ));
86                }
87                _ => {}
88            }
89        }
90        if !self.assets.is_empty() {
91            let mut texts = Vec::new();
92            self.texts(&mut texts);
93            for reference in self.assets.keys() {
94                if reference.trim().is_empty() {
95                    return Err(invalid(
96                        "An asset reference must not be empty.",
97                        format!("assets.{reference}"),
98                    ));
99                }
100                if !texts.iter().any(|t| t.contains(reference.as_str())) {
101                    return Err(invalid(
102                        format!(
103                            "The asset `{reference}` is not referenced; write its reference where the image belongs."
104                        ),
105                        format!("assets.{reference}"),
106                    ));
107                }
108            }
109        }
110        Ok(())
111    }
112
113    /// What a model must be able to do to serve the request.
114    pub fn required_capabilities(&self) -> crate::Capabilities {
115        let mut caps = crate::Capabilities {
116            images: !self.assets.is_empty(),
117            cache_hints: self.cache.is_some(),
118            ..crate::Capabilities::default()
119        };
120        let mut note = |block: &Block| match block {
121            Block::Image(_) => caps.images = true,
122            Block::Audio(_) => caps.audio_input = true,
123            Block::Video(_) => caps.video_input = true,
124            Block::Document(doc) => match doc.source {
125                Source::Text(_) => caps.text_documents = true,
126                _ => caps.pdf = true,
127            },
128            _ => {}
129        };
130        if let DecisionInput::Messages(messages) = &self.input {
131            messages.iter().flat_map(|m| &m.blocks).for_each(&mut note);
132        }
133        for q in &self.questions {
134            if let Some(Instructions::Blocks(blocks)) = &q.instructions {
135                blocks.iter().for_each(&mut note);
136            }
137        }
138        caps.box_questions = self
139            .questions
140            .iter()
141            .any(|q| matches!(q.kind, QuestionKind::Box(_)));
142        caps
143    }
144
145    // Every string an asset reference may stand in: strings of the input, the instructions and
146    // the descriptions, without object keys, which are never replaced.
147    fn texts(&self, out: &mut Vec<String>) {
148        match &self.input {
149            DecisionInput::Text(t) => out.push(t.clone()),
150            DecisionInput::Json(raw) => strings_of(raw, out),
151            DecisionInput::Messages(messages) => {
152                for block in messages.iter().flat_map(|m| &m.blocks) {
153                    block_texts(block, out);
154                }
155            }
156        }
157        for q in &self.questions {
158            match &q.instructions {
159                Some(Instructions::Text(t)) => out.push(t.clone()),
160                Some(Instructions::Json(raw)) => strings_of(raw, out),
161                Some(Instructions::Blocks(blocks)) => {
162                    blocks.iter().for_each(|b| block_texts(b, out));
163                }
164                None => {}
165            }
166            let mut description = |d: &Option<Description>| match d {
167                Some(Description::Text(t)) => out.push(t.clone()),
168                Some(Description::Json(raw)) => strings_of(raw, out),
169                None => {}
170            };
171            match &q.kind {
172                QuestionKind::Predicate(p) => {
173                    description(&p.when_true);
174                    description(&p.when_false);
175                }
176                QuestionKind::Choice(c) => {
177                    c.options.iter().for_each(|o| description(&o.description))
178                }
179                QuestionKind::Score(s) => s.levels.iter().for_each(|l| description(&l.description)),
180                QuestionKind::Box(_) => {}
181            }
182        }
183    }
184}
185
186fn block_texts(block: &Block, out: &mut Vec<String>) {
187    match block {
188        Block::Text(t) => out.push(t.text.clone()),
189        Block::Json(j) => strings_of(&j.data, out),
190        _ => {}
191    }
192}
193
194fn strings_of(raw: &RawJson, out: &mut Vec<String>) {
195    fn walk(v: Value, out: &mut Vec<String>) {
196        match v {
197            Value::String(s) => out.push(s),
198            Value::Array(items) => items.into_iter().for_each(|i| walk(i, out)),
199            Value::Object(map) => map.into_iter().for_each(|(_, v)| walk(v, out)),
200            _ => {}
201        }
202    }
203    if let Ok(v) = raw.to_value() {
204        walk(v, out);
205    }
206}
207
208fn invalid(message: impl Into<String>, param: impl Into<String>) -> KppError {
209    KppError::invalid_request(message).with_param(param)
210}
211
212/// What a decision request's questions are about.
213#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
214#[serde(rename_all = "snake_case")]
215#[non_exhaustive]
216pub enum DecisionInput {
217    /// Plain text.
218    Text(String),
219    /// Structured data, written as the app wrote it.
220    Json(RawJson),
221    /// Messages with text, images, audio, video, documents and JSON parts, as OpenAI's and
222    /// Gemini's formats send them, or a System One state of text and image parts.
223    Messages(Vec<Message>),
224}
225
226/// An image a decision request references by its key.
227#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
228#[non_exhaustive]
229pub struct Asset {
230    pub source: Source,
231    #[serde(default, skip_serializing_if = "Extras::is_empty")]
232    pub extras: Extras,
233}
234
235impl Asset {
236    pub fn new(source: Source) -> Self {
237        Asset {
238            source,
239            extras: Extras::default(),
240        }
241    }
242}
243
244/// One question of a decision request.
245#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
246#[non_exhaustive]
247pub struct Question {
248    /// The name the app gave the question: System One's and Gemini's map key, OpenAI's optional
249    /// `name`.
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub name: Option<String>,
252    #[serde(default, skip_serializing_if = "Option::is_none")]
253    pub instructions: Option<Instructions>,
254    pub kind: QuestionKind,
255    #[serde(default, skip_serializing_if = "Extras::is_empty")]
256    pub extras: Extras,
257}
258
259impl Question {
260    pub fn new(name: Option<String>, kind: QuestionKind) -> Self {
261        Question {
262            name,
263            instructions: None,
264            kind,
265            extras: Extras::default(),
266        }
267    }
268
269    #[must_use]
270    pub fn with_instructions(mut self, instructions: Instructions) -> Self {
271        self.instructions = Some(instructions);
272        self
273    }
274
275    /// The question type's KPP name: `predicate`, `choice`, `score` or `box`.
276    pub fn type_name(&self) -> &'static str {
277        self.kind.as_str()
278    }
279}
280
281/// What a question asks.
282#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
283#[serde(rename_all = "snake_case")]
284#[non_exhaustive]
285pub enum Instructions {
286    Text(String),
287    Json(RawJson),
288    /// Text, image and JSON parts in order.
289    Blocks(Vec<Block>),
290}
291
292/// The type of a question and what it chooses from.
293#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
294#[serde(rename_all = "snake_case")]
295#[non_exhaustive]
296pub enum QuestionKind {
297    /// A yes/no question (System One's and Gemini's `noul`, OpenAI's `predicate`), answered with
298    /// the probability of yes.
299    Predicate(Predicate),
300    /// One of several options.
301    Choice(Choice),
302    /// A position on an ordered scale of levels, lowest first.
303    Score(Score),
304    /// Where in an image something is.
305    Box(BoxQuestion),
306}
307
308impl QuestionKind {
309    pub const fn as_str(&self) -> &'static str {
310        match self {
311            QuestionKind::Predicate(_) => "predicate",
312            QuestionKind::Choice(_) => "choice",
313            QuestionKind::Score(_) => "score",
314            QuestionKind::Box(_) => "box",
315        }
316    }
317}
318
319/// A yes/no question, with what counts as yes and as no.
320#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
321#[non_exhaustive]
322pub struct Predicate {
323    #[serde(default, skip_serializing_if = "Option::is_none")]
324    pub when_true: Option<Description>,
325    #[serde(default, skip_serializing_if = "Option::is_none")]
326    pub when_false: Option<Description>,
327    #[serde(default, skip_serializing_if = "Extras::is_empty")]
328    pub extras: Extras,
329}
330
331impl Predicate {
332    pub fn new(when_true: Option<Description>, when_false: Option<Description>) -> Self {
333        Predicate {
334            when_true,
335            when_false,
336            extras: Extras::default(),
337        }
338    }
339}
340
341/// A question that picks one option.
342#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
343#[non_exhaustive]
344pub struct Choice {
345    pub options: Vec<ChoiceOption>,
346}
347
348impl Choice {
349    pub fn new(options: Vec<ChoiceOption>) -> Self {
350        Choice { options }
351    }
352}
353
354/// One option of a choice question.
355#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
356#[non_exhaustive]
357pub struct ChoiceOption {
358    pub value: ChoiceValue,
359    #[serde(default, skip_serializing_if = "Option::is_none")]
360    pub description: Option<Description>,
361    #[serde(default, skip_serializing_if = "Extras::is_empty")]
362    pub extras: Extras,
363}
364
365impl ChoiceOption {
366    pub fn new(value: ChoiceValue, description: Option<Description>) -> Self {
367        ChoiceOption {
368            value,
369            description,
370            extras: Extras::default(),
371        }
372    }
373}
374
375/// An option's value: a key or text, or OpenAI's `true` and `false`.
376#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
377#[serde(rename_all = "snake_case")]
378#[non_exhaustive]
379pub enum ChoiceValue {
380    Text(String),
381    Bool(bool),
382}
383
384/// What an option, level or answer means: text, or structured data as written.
385#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
386#[serde(rename_all = "snake_case")]
387#[non_exhaustive]
388pub enum Description {
389    Text(String),
390    Json(RawJson),
391}
392
393/// A question that rates on ordered levels.
394#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
395#[non_exhaustive]
396pub struct Score {
397    /// The levels, lowest first; level `i` scores `i`.
398    pub levels: Vec<Level>,
399}
400
401impl Score {
402    pub fn new(levels: Vec<Level>) -> Self {
403        Score { levels }
404    }
405}
406
407/// One level of a score question.
408#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
409#[non_exhaustive]
410pub struct Level {
411    /// A short name, as OpenAI's `label`.
412    #[serde(default, skip_serializing_if = "Option::is_none")]
413    pub label: Option<String>,
414    #[serde(default, skip_serializing_if = "Option::is_none")]
415    pub description: Option<Description>,
416    #[serde(default, skip_serializing_if = "Extras::is_empty")]
417    pub extras: Extras,
418}
419
420impl Level {
421    pub fn new(label: Option<String>, description: Option<Description>) -> Self {
422        Level {
423            label,
424            description,
425            extras: Extras::default(),
426        }
427    }
428}
429
430/// A question that locates what its instructions describe in an image.
431#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
432#[non_exhaustive]
433pub struct BoxQuestion {}
434
435impl BoxQuestion {
436    pub fn new() -> Self {
437        BoxQuestion {}
438    }
439}
440
441/// How the provider caches a decision request's prefix (OpenAI's `prompt_cache_key` and
442/// `prompt_cache_options`).
443#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
444#[non_exhaustive]
445pub struct DecisionCache {
446    #[serde(default, skip_serializing_if = "Option::is_none")]
447    pub key: Option<String>,
448    #[serde(default, skip_serializing_if = "Option::is_none")]
449    pub mode: Option<String>,
450    #[serde(default, skip_serializing_if = "Option::is_none")]
451    pub ttl: Option<CacheTtl>,
452}
453
454impl DecisionCache {
455    pub fn new(key: Option<String>) -> Self {
456        DecisionCache {
457            key,
458            mode: None,
459            ttl: None,
460        }
461    }
462}
463
464/// The answers to a decision request, one per question in question order.
465#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
466#[non_exhaustive]
467pub struct DecideResponse {
468    pub model: String,
469    pub answers: Vec<Answer>,
470    pub usage: Usage,
471    #[serde(default, skip_serializing_if = "Extras::is_empty")]
472    pub extras: Extras,
473}
474
475impl DecideResponse {
476    pub fn new(model: impl Into<String>, answers: Vec<Answer>) -> Self {
477        DecideResponse {
478            model: model.into(),
479            answers,
480            ..DecideResponse::default()
481        }
482    }
483}
484
485/// The answer to one question.
486#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
487#[non_exhaustive]
488pub struct Answer {
489    pub value: AnswerValue,
490    /// The provider's confidence, from 0 to 1. What it measures differs between formats; a
491    /// reply that crosses formats recomputes it from the probabilities by the app's format.
492    #[serde(default, skip_serializing_if = "Option::is_none")]
493    pub confidence: Option<f64>,
494    #[serde(default, skip_serializing_if = "Extras::is_empty")]
495    pub extras: Extras,
496}
497
498impl Answer {
499    pub fn new(value: AnswerValue) -> Self {
500        Answer {
501            value,
502            confidence: None,
503            extras: Extras::default(),
504        }
505    }
506
507    #[must_use]
508    pub fn with_confidence(mut self, confidence: Option<f64>) -> Self {
509        self.confidence = confidence;
510        self
511    }
512}
513
514/// What a question was answered with.
515#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
516#[serde(rename_all = "snake_case")]
517#[non_exhaustive]
518pub enum AnswerValue {
519    Predicate(PredicateAnswer),
520    Choice(ChoiceAnswer),
521    Score(ScoreAnswer),
522    Box(BoxAnswer),
523    /// The model declined to answer this question.
524    Refusal(Refusal),
525}
526
527impl AnswerValue {
528    /// The answer type's KPP name: `predicate`, `choice`, `score`, `box` or `refusal`.
529    pub const fn as_str(&self) -> &'static str {
530        match self {
531            AnswerValue::Predicate(_) => "predicate",
532            AnswerValue::Choice(_) => "choice",
533            AnswerValue::Score(_) => "score",
534            AnswerValue::Box(_) => "box",
535            AnswerValue::Refusal(_) => "refusal",
536        }
537    }
538}
539
540/// The probability that the answer to a yes/no question is yes.
541#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
542#[non_exhaustive]
543pub struct PredicateAnswer {
544    pub probability: f64,
545}
546
547impl PredicateAnswer {
548    pub fn new(probability: f64) -> Self {
549        PredicateAnswer { probability }
550    }
551}
552
553/// The chosen option and a probability per option.
554#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
555#[non_exhaustive]
556pub struct ChoiceAnswer {
557    /// The index of the chosen option in the question's options.
558    pub option: usize,
559    /// The probability of each option, by index; `None` where the provider gave none.
560    pub probabilities: Vec<Option<f64>>,
561}
562
563impl ChoiceAnswer {
564    pub fn new(option: usize, probabilities: Vec<Option<f64>>) -> Self {
565        ChoiceAnswer {
566            option,
567            probabilities,
568        }
569    }
570}
571
572/// The expected level, `Σ i·p_i` over the levels numbered from 0, and a probability per level.
573#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
574#[non_exhaustive]
575pub struct ScoreAnswer {
576    pub score: f64,
577    /// The probability of each level, by index; `None` where the provider gave none.
578    pub probabilities: Vec<Option<f64>>,
579}
580
581impl ScoreAnswer {
582    pub fn new(score: f64, probabilities: Vec<Option<f64>>) -> Self {
583        ScoreAnswer {
584            score,
585            probabilities,
586        }
587    }
588}
589
590/// A box's edges as fractions of the image's height (`top`, `bottom`, from the top) and width
591/// (`left`, `right`, from the left).
592#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
593#[non_exhaustive]
594pub struct BoxAnswer {
595    pub top: f64,
596    pub bottom: f64,
597    pub left: f64,
598    pub right: f64,
599}
600
601impl BoxAnswer {
602    pub fn new(top: f64, bottom: f64, left: f64, right: f64) -> Self {
603        BoxAnswer {
604            top,
605            bottom,
606            left,
607            right,
608        }
609    }
610}
611
612/// A question the model declined to answer.
613#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
614#[non_exhaustive]
615pub struct Refusal {}
616
617impl Refusal {
618    pub fn new() -> Self {
619        Refusal {}
620    }
621}