use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::block::{Block, CacheTtl, Source};
use crate::error::KppError;
use crate::extras::Extras;
use crate::raw::RawJson;
use crate::request::Message;
use crate::response::Usage;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DecideRequest {
pub model: String,
pub input: DecisionInput,
pub questions: Vec<Question>,
#[serde(default, skip_serializing_if = "IndexMap::is_empty")]
pub assets: IndexMap<String, Asset>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub user: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cache: Option<DecisionCache>,
#[serde(default, skip_serializing_if = "Extras::is_empty")]
pub extras: Extras,
}
impl DecideRequest {
pub fn new(model: impl Into<String>, input: DecisionInput) -> Self {
DecideRequest {
model: model.into(),
input,
questions: Vec::new(),
assets: IndexMap::new(),
user: None,
cache: None,
extras: Extras::default(),
}
}
#[must_use]
pub fn with_question(mut self, question: Question) -> Self {
self.questions.push(question);
self
}
#[must_use]
pub fn with_asset(mut self, reference: impl Into<String>, asset: Asset) -> Self {
self.assets.insert(reference.into(), asset);
self
}
pub fn validate(&self) -> Result<(), KppError> {
if self.model.is_empty() {
return Err(invalid("`model` must not be empty.", "model"));
}
if self.questions.is_empty() {
return Err(invalid("Ask at least one question.", "questions"));
}
for (i, q) in self.questions.iter().enumerate() {
match &q.kind {
QuestionKind::Choice(c) if c.options.is_empty() => {
return Err(invalid(
"A choice question needs at least one option.",
format!("questions[{i}]"),
));
}
QuestionKind::Score(s) if s.levels.is_empty() => {
return Err(invalid(
"A score question needs at least one level.",
format!("questions[{i}]"),
));
}
_ => {}
}
}
if !self.assets.is_empty() {
let mut texts = Vec::new();
self.texts(&mut texts);
for reference in self.assets.keys() {
if reference.trim().is_empty() {
return Err(invalid(
"An asset reference must not be empty.",
format!("assets.{reference}"),
));
}
if !texts.iter().any(|t| t.contains(reference.as_str())) {
return Err(invalid(
format!(
"The asset `{reference}` is not referenced; write its reference where the image belongs."
),
format!("assets.{reference}"),
));
}
}
}
Ok(())
}
pub fn required_capabilities(&self) -> crate::Capabilities {
let mut caps = crate::Capabilities {
images: !self.assets.is_empty(),
cache_hints: self.cache.is_some(),
..crate::Capabilities::default()
};
let mut note = |block: &Block| match block {
Block::Image(_) => caps.images = true,
Block::Audio(_) => caps.audio_input = true,
Block::Video(_) => caps.video_input = true,
Block::Document(doc) => match doc.source {
Source::Text(_) => caps.text_documents = true,
_ => caps.pdf = true,
},
_ => {}
};
if let DecisionInput::Messages(messages) = &self.input {
messages.iter().flat_map(|m| &m.blocks).for_each(&mut note);
}
for q in &self.questions {
if let Some(Instructions::Blocks(blocks)) = &q.instructions {
blocks.iter().for_each(&mut note);
}
}
caps.box_questions = self
.questions
.iter()
.any(|q| matches!(q.kind, QuestionKind::Box(_)));
caps
}
fn texts(&self, out: &mut Vec<String>) {
match &self.input {
DecisionInput::Text(t) => out.push(t.clone()),
DecisionInput::Json(raw) => strings_of(raw, out),
DecisionInput::Messages(messages) => {
for block in messages.iter().flat_map(|m| &m.blocks) {
block_texts(block, out);
}
}
}
for q in &self.questions {
match &q.instructions {
Some(Instructions::Text(t)) => out.push(t.clone()),
Some(Instructions::Json(raw)) => strings_of(raw, out),
Some(Instructions::Blocks(blocks)) => {
blocks.iter().for_each(|b| block_texts(b, out));
}
None => {}
}
let mut description = |d: &Option<Description>| match d {
Some(Description::Text(t)) => out.push(t.clone()),
Some(Description::Json(raw)) => strings_of(raw, out),
None => {}
};
match &q.kind {
QuestionKind::Predicate(p) => {
description(&p.when_true);
description(&p.when_false);
}
QuestionKind::Choice(c) => {
c.options.iter().for_each(|o| description(&o.description))
}
QuestionKind::Score(s) => s.levels.iter().for_each(|l| description(&l.description)),
QuestionKind::Box(_) => {}
}
}
}
}
fn block_texts(block: &Block, out: &mut Vec<String>) {
match block {
Block::Text(t) => out.push(t.text.clone()),
Block::Json(j) => strings_of(&j.data, out),
_ => {}
}
}
fn strings_of(raw: &RawJson, out: &mut Vec<String>) {
fn walk(v: Value, out: &mut Vec<String>) {
match v {
Value::String(s) => out.push(s),
Value::Array(items) => items.into_iter().for_each(|i| walk(i, out)),
Value::Object(map) => map.into_iter().for_each(|(_, v)| walk(v, out)),
_ => {}
}
}
if let Ok(v) = raw.to_value() {
walk(v, out);
}
}
fn invalid(message: impl Into<String>, param: impl Into<String>) -> KppError {
KppError::invalid_request(message).with_param(param)
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DecisionInput {
Text(String),
Json(RawJson),
Messages(Vec<Message>),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Asset {
pub source: Source,
#[serde(default, skip_serializing_if = "Extras::is_empty")]
pub extras: Extras,
}
impl Asset {
pub fn new(source: Source) -> Self {
Asset {
source,
extras: Extras::default(),
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Question {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub instructions: Option<Instructions>,
pub kind: QuestionKind,
#[serde(default, skip_serializing_if = "Extras::is_empty")]
pub extras: Extras,
}
impl Question {
pub fn new(name: Option<String>, kind: QuestionKind) -> Self {
Question {
name,
instructions: None,
kind,
extras: Extras::default(),
}
}
#[must_use]
pub fn with_instructions(mut self, instructions: Instructions) -> Self {
self.instructions = Some(instructions);
self
}
pub fn type_name(&self) -> &'static str {
self.kind.as_str()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Instructions {
Text(String),
Json(RawJson),
Blocks(Vec<Block>),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum QuestionKind {
Predicate(Predicate),
Choice(Choice),
Score(Score),
Box(BoxQuestion),
}
impl QuestionKind {
pub const fn as_str(&self) -> &'static str {
match self {
QuestionKind::Predicate(_) => "predicate",
QuestionKind::Choice(_) => "choice",
QuestionKind::Score(_) => "score",
QuestionKind::Box(_) => "box",
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Predicate {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub when_true: Option<Description>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub when_false: Option<Description>,
#[serde(default, skip_serializing_if = "Extras::is_empty")]
pub extras: Extras,
}
impl Predicate {
pub fn new(when_true: Option<Description>, when_false: Option<Description>) -> Self {
Predicate {
when_true,
when_false,
extras: Extras::default(),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Choice {
pub options: Vec<ChoiceOption>,
}
impl Choice {
pub fn new(options: Vec<ChoiceOption>) -> Self {
Choice { options }
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ChoiceOption {
pub value: ChoiceValue,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<Description>,
#[serde(default, skip_serializing_if = "Extras::is_empty")]
pub extras: Extras,
}
impl ChoiceOption {
pub fn new(value: ChoiceValue, description: Option<Description>) -> Self {
ChoiceOption {
value,
description,
extras: Extras::default(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ChoiceValue {
Text(String),
Bool(bool),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Description {
Text(String),
Json(RawJson),
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Score {
pub levels: Vec<Level>,
}
impl Score {
pub fn new(levels: Vec<Level>) -> Self {
Score { levels }
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Level {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<Description>,
#[serde(default, skip_serializing_if = "Extras::is_empty")]
pub extras: Extras,
}
impl Level {
pub fn new(label: Option<String>, description: Option<Description>) -> Self {
Level {
label,
description,
extras: Extras::default(),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct BoxQuestion {}
impl BoxQuestion {
pub fn new() -> Self {
BoxQuestion {}
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DecisionCache {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mode: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ttl: Option<CacheTtl>,
}
impl DecisionCache {
pub fn new(key: Option<String>) -> Self {
DecisionCache {
key,
mode: None,
ttl: None,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DecideResponse {
pub model: String,
pub answers: Vec<Answer>,
pub usage: Usage,
#[serde(default, skip_serializing_if = "Extras::is_empty")]
pub extras: Extras,
}
impl DecideResponse {
pub fn new(model: impl Into<String>, answers: Vec<Answer>) -> Self {
DecideResponse {
model: model.into(),
answers,
..DecideResponse::default()
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Answer {
pub value: AnswerValue,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub confidence: Option<f64>,
#[serde(default, skip_serializing_if = "Extras::is_empty")]
pub extras: Extras,
}
impl Answer {
pub fn new(value: AnswerValue) -> Self {
Answer {
value,
confidence: None,
extras: Extras::default(),
}
}
#[must_use]
pub fn with_confidence(mut self, confidence: Option<f64>) -> Self {
self.confidence = confidence;
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AnswerValue {
Predicate(PredicateAnswer),
Choice(ChoiceAnswer),
Score(ScoreAnswer),
Box(BoxAnswer),
Refusal(Refusal),
}
impl AnswerValue {
pub const fn as_str(&self) -> &'static str {
match self {
AnswerValue::Predicate(_) => "predicate",
AnswerValue::Choice(_) => "choice",
AnswerValue::Score(_) => "score",
AnswerValue::Box(_) => "box",
AnswerValue::Refusal(_) => "refusal",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct PredicateAnswer {
pub probability: f64,
}
impl PredicateAnswer {
pub fn new(probability: f64) -> Self {
PredicateAnswer { probability }
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ChoiceAnswer {
pub option: usize,
pub probabilities: Vec<Option<f64>>,
}
impl ChoiceAnswer {
pub fn new(option: usize, probabilities: Vec<Option<f64>>) -> Self {
ChoiceAnswer {
option,
probabilities,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ScoreAnswer {
pub score: f64,
pub probabilities: Vec<Option<f64>>,
}
impl ScoreAnswer {
pub fn new(score: f64, probabilities: Vec<Option<f64>>) -> Self {
ScoreAnswer {
score,
probabilities,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct BoxAnswer {
pub top: f64,
pub bottom: f64,
pub left: f64,
pub right: f64,
}
impl BoxAnswer {
pub fn new(top: f64, bottom: f64, left: f64, right: f64) -> Self {
BoxAnswer {
top,
bottom,
left,
right,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Refusal {}
impl Refusal {
pub fn new() -> Self {
Refusal {}
}
}