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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
15#[non_exhaustive]
16pub struct DecideRequest {
17 pub model: String,
18 pub input: DecisionInput,
21 pub questions: Vec<Question>,
23 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
26 pub assets: IndexMap<String, Asset>,
27 #[serde(default, skip_serializing_if = "Option::is_none")]
29 pub user: Option<String>,
30 #[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 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 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 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
214#[serde(rename_all = "snake_case")]
215#[non_exhaustive]
216pub enum DecisionInput {
217 Text(String),
219 Json(RawJson),
221 Messages(Vec<Message>),
224}
225
226#[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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
246#[non_exhaustive]
247pub struct Question {
248 #[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 pub fn type_name(&self) -> &'static str {
277 self.kind.as_str()
278 }
279}
280
281#[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 Blocks(Vec<Block>),
290}
291
292#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
294#[serde(rename_all = "snake_case")]
295#[non_exhaustive]
296pub enum QuestionKind {
297 Predicate(Predicate),
300 Choice(Choice),
302 Score(Score),
304 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#[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#[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#[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#[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#[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#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
395#[non_exhaustive]
396pub struct Score {
397 pub levels: Vec<Level>,
399}
400
401impl Score {
402 pub fn new(levels: Vec<Level>) -> Self {
403 Score { levels }
404 }
405}
406
407#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
409#[non_exhaustive]
410pub struct Level {
411 #[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#[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#[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#[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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
487#[non_exhaustive]
488pub struct Answer {
489 pub value: AnswerValue,
490 #[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#[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 Refusal(Refusal),
525}
526
527impl AnswerValue {
528 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#[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#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
555#[non_exhaustive]
556pub struct ChoiceAnswer {
557 pub option: usize,
559 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#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
574#[non_exhaustive]
575pub struct ScoreAnswer {
576 pub score: f64,
577 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#[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#[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}