use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::questions::Question;
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct SystemOneRequest {
pub state: Value,
pub model: String,
pub questions: HashMap<String, Question>,
#[serde(skip_serializing_if = "Option::is_none")]
pub extra_body: Option<Value>,
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct Usage {
pub input_tokens: u64,
pub output_tokens: u64,
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct NoulAnswer {
pub noul: f64,
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ChoiceAnswer {
pub choice: String,
pub probabilities: HashMap<String, f64>,
pub confidence: f64,
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ScoreAnswer {
pub score: f64,
pub legend: HashMap<String, Value>,
pub probabilities: HashMap<String, f64>,
pub confidence: f64,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "type")]
#[non_exhaustive]
pub enum Answer {
#[serde(rename = "noul")]
Noul(NoulAnswer),
#[serde(rename = "choice")]
Choice(ChoiceAnswer),
#[serde(rename = "score")]
Score(ScoreAnswer),
#[serde(other)]
Unknown,
}
impl Answer {
pub fn is_noul(&self) -> bool {
matches!(self, Answer::Noul(_))
}
pub fn is_choice(&self) -> bool {
matches!(self, Answer::Choice(_))
}
pub fn is_score(&self) -> bool {
matches!(self, Answer::Score(_))
}
pub fn as_noul(&self) -> Option<&NoulAnswer> {
if let Answer::Noul(n) = self {
Some(n)
} else {
None
}
}
pub fn as_choice(&self) -> Option<&ChoiceAnswer> {
if let Answer::Choice(c) = self {
Some(c)
} else {
None
}
}
pub fn as_score(&self) -> Option<&ScoreAnswer> {
if let Answer::Score(s) = self {
Some(s)
} else {
None
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SystemOneResponse {
pub model: String,
pub answers: HashMap<String, Answer>,
pub usage: Usage,
#[serde(default)]
pub request_id: Option<String>,
#[serde(skip)]
pub raw: Option<Value>,
}
impl SystemOneResponse {
pub fn nouls(&self) -> HashMap<&str, &NoulAnswer> {
self.answers
.iter()
.filter_map(|(k, v)| v.as_noul().map(|n| (k.as_str(), n)))
.collect()
}
pub fn choices(&self) -> HashMap<&str, &ChoiceAnswer> {
self.answers
.iter()
.filter_map(|(k, v)| v.as_choice().map(|c| (k.as_str(), c)))
.collect()
}
pub fn scores(&self) -> HashMap<&str, &ScoreAnswer> {
self.answers
.iter()
.filter_map(|(k, v)| v.as_score().map(|s| (k.as_str(), s)))
.collect()
}
pub fn noul(&self, name: &str) -> Option<&NoulAnswer> {
self.answers.get(name).and_then(|a| a.as_noul())
}
pub fn choice(&self, name: &str) -> Option<&ChoiceAnswer> {
self.answers.get(name).and_then(|a| a.as_choice())
}
pub fn score(&self, name: &str) -> Option<&ScoreAnswer> {
self.answers.get(name).and_then(|a| a.as_score())
}
pub fn request_id(&self) -> Option<&str> {
self.request_id.as_deref()
}
pub fn raw(&self) -> Option<&Value> {
self.raw.as_ref()
}
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ModelCard {
pub name: String,
pub description: String,
#[serde(default)]
pub release_date: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ListModelsResponse {
pub models: Vec<ModelCard>,
#[serde(default)]
pub request_id: Option<String>,
#[serde(skip)]
pub raw: Option<Value>,
}
impl ListModelsResponse {
pub fn request_id(&self) -> Option<&str> {
self.request_id.as_deref()
}
pub fn raw(&self) -> Option<&Value> {
self.raw.as_ref()
}
}
pub trait SetRequestId {
fn set_request_id(&mut self, request_id: Option<String>);
}
pub trait SetRawBody {
fn set_raw(&mut self, raw: Option<Value>);
}
impl SetRequestId for SystemOneResponse {
fn set_request_id(&mut self, request_id: Option<String>) {
self.request_id = request_id;
}
}
impl SetRawBody for SystemOneResponse {
fn set_raw(&mut self, raw: Option<Value>) {
self.raw = raw;
}
}
impl SetRequestId for ListModelsResponse {
fn set_request_id(&mut self, request_id: Option<String>) {
self.request_id = request_id;
}
}
impl SetRawBody for ListModelsResponse {
fn set_raw(&mut self, raw: Option<Value>) {
self.raw = raw;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deserialize_noul_answer() {
let json = r#"{"type":"noul","noul":0.95}"#;
let answer: Answer = serde_json::from_str(json).unwrap();
match answer {
Answer::Noul(n) => assert!((n.noul - 0.95).abs() < 1e-9),
_ => panic!("expected noul answer"),
}
}
#[test]
fn deserialize_choice_answer() {
let json = r#"{"type":"choice","choice":"calm","probabilities":{"calm":0.9,"angry":0.1},"confidence":0.85}"#;
let answer: Answer = serde_json::from_str(json).unwrap();
match answer {
Answer::Choice(c) => {
assert_eq!(c.choice, "calm");
assert!((c.confidence - 0.85).abs() < 1e-9);
assert!((c.probabilities["calm"] - 0.9).abs() < 1e-9);
}
_ => panic!("expected choice answer"),
}
}
#[test]
fn deserialize_score_answer() {
let json = r#"{"type":"score","score":1,"legend":{"0":"low","1":"high"},"probabilities":{"0":0.3,"1":0.7},"confidence":0.8}"#;
let answer: Answer = serde_json::from_str(json).unwrap();
match answer {
Answer::Score(s) => {
assert!((s.score - 1.0).abs() < 1e-9);
assert!((s.confidence - 0.8).abs() < 1e-9);
}
_ => panic!("expected score answer"),
}
}
#[test]
fn deserialize_full_response() {
let json = r#"{
"model": "jev-latest",
"answers": {
"billing": {"type":"noul","noul":0.98},
"tone": {"type":"choice","choice":"calm","probabilities":{"calm":0.9,"angry":0.1},"confidence":0.85}
},
"usage": {"input_tokens":120,"output_tokens":12}
}"#;
let resp: SystemOneResponse = serde_json::from_str(json).unwrap();
assert_eq!(resp.model, "jev-latest");
assert_eq!(resp.usage.input_tokens, 120);
assert_eq!(resp.nouls().len(), 1);
assert_eq!(resp.choices().len(), 1);
assert!((resp.nouls()["billing"].noul - 0.98).abs() < 1e-9);
assert_eq!(resp.choices()["tone"].choice, "calm");
}
#[test]
fn deserialize_unknown_answer_type() {
let json = r#"{"type":"future_primitive","data":"something"}"#;
let answer: Answer = serde_json::from_str(json).unwrap();
assert!(matches!(answer, Answer::Unknown));
}
#[test]
fn safe_accessors_return_none_for_missing() {
let json = r#"{
"model": "jev-latest",
"answers": {
"billing": {"type":"noul","noul":0.98}
},
"usage": {"input_tokens":10,"output_tokens":2}
}"#;
let resp: SystemOneResponse = serde_json::from_str(json).unwrap();
assert!(resp.noul("billing").is_some());
assert!(resp.noul("nonexistent").is_none());
assert!(resp.choice("billing").is_none());
assert!(resp.score("billing").is_none());
}
}