1use serde_json::{Value, json};
7use typesafe::{Answer, ModelMetadata};
8
9pub fn answer(state: &Value, name: &str, question: &Value) -> Option<Answer> {
11 let state = state.to_string();
12 let kind = question.get("type")?.as_str()?;
13 let instructions = question
14 .get("instructions")
15 .map(ToString::to_string)
16 .unwrap_or_default();
17 let seed = format!("{state}\u{1}{name}\u{1}{instructions}");
18 match kind {
19 "noul" => {
20 let p = round(0.04 + 0.92 * unit(&[&seed, "noul"]));
21 from_value(json!({ "noul": p }))
22 }
23 "choice" => {
24 let labels: Vec<String> = question
25 .get("criteria")?
26 .as_object()?
27 .keys()
28 .cloned()
29 .collect();
30 let probs = distribution(&seed, &state, &labels);
31 let (choice, _) = probs
32 .iter()
33 .cloned()
34 .max_by(|a, b| a.1.total_cmp(&b.1))
35 .unwrap_or_default();
36 let map: serde_json::Map<String, Value> =
37 probs.iter().map(|(l, p)| (l.clone(), json!(p))).collect();
38 let conf = confidence(probs.iter().map(|(_, p)| *p));
39 from_value(json!({"choice": choice, "probabilities": map, "confidence": conf}))
40 }
41 "score" => {
42 let levels = question.get("criteria")?.as_array()?;
43 let keys: Vec<String> = (0..levels.len()).map(|i| i.to_string()).collect();
44 let probs = distribution(&seed, &state, &keys);
45 let score = round(
46 probs
47 .iter()
48 .enumerate()
49 .map(|(i, (_, p))| i as f64 * p)
50 .sum(),
51 );
52 let legend: serde_json::Map<String, Value> = levels
53 .iter()
54 .enumerate()
55 .map(|(i, v)| (i.to_string(), v.clone()))
56 .collect();
57 let map: serde_json::Map<String, Value> =
58 probs.iter().map(|(k, p)| (k.clone(), json!(p))).collect();
59 let conf = confidence(probs.iter().map(|(_, p)| *p));
60 from_value(
61 json!({"score": score, "confidence": conf, "legend": legend, "probabilities": map}),
62 )
63 }
64 _ => None,
65 }
66}
67
68pub fn answer_json(answer: &Answer) -> Value {
71 match answer {
72 Answer::Noul(a) => json!({"type": "noul", "noul": a.noul}),
73 Answer::Choice(a) => json!({
74 "type": "choice", "choice": a.choice,
75 "probabilities": a.probabilities.iter()
76 .map(|(k, v)| (k.clone(), json!(v)))
77 .collect::<serde_json::Map<String, Value>>(),
78 "confidence": a.confidence,
79 }),
80 Answer::Score(a) => json!({
81 "type": "score", "score": a.score, "confidence": a.confidence,
82 "legend": a.legend.iter()
83 .map(|(k, v)| (k.to_string(), v.clone()))
84 .collect::<serde_json::Map<String, Value>>(),
85 "probabilities": a.probabilities.iter()
86 .map(|(k, v)| (k.to_string(), json!(v)))
87 .collect::<serde_json::Map<String, Value>>(),
88 }),
89 _ => Value::Null,
91 }
92}
93
94pub fn models() -> Vec<ModelMetadata> {
96 [
97 (
98 "jev-latest",
99 "Alias for the newest jev release",
100 "2026-05-01",
101 ),
102 ("jev-2", "Previous generation", "2025-11-12"),
103 ]
104 .into_iter()
105 .filter_map(|(name, description, release_date)| {
106 serde_json::from_value(json!({
107 "name": name, "description": description, "release_date": release_date
108 }))
109 .ok()
110 })
111 .collect()
112}
113
114fn from_value(v: Value) -> Option<Answer> {
115 if v.get("noul").is_some() {
118 return serde_json::from_value(v).ok().map(Answer::Noul);
119 }
120 if v.get("choice").is_some() {
121 return serde_json::from_value(v).ok().map(Answer::Choice);
122 }
123 serde_json::from_value(v).ok().map(Answer::Score)
124}
125
126fn distribution(seed: &str, state: &str, labels: &[String]) -> Vec<(String, f64)> {
128 let lower = state.to_lowercase();
129 let mut raw: Vec<(String, f64)> = labels
130 .iter()
131 .map(|label| {
132 let u = unit(&[seed, label]);
133 let mut w = 0.02 + u * u * u;
134 if label.len() > 3 && lower.contains(&label.to_lowercase()) {
135 w *= 4.0;
136 }
137 (label.clone(), w)
138 })
139 .collect();
140 let total: f64 = raw.iter().map(|(_, w)| w).sum();
141 if total <= 0.0 {
142 let even = round(1.0 / raw.len().max(1) as f64);
143 return raw.into_iter().map(|(l, _)| (l, even)).collect();
144 }
145 for (_, w) in &mut raw {
146 *w = round(*w / total);
147 }
148 let drift = 1.0 - raw.iter().map(|(_, w)| w).sum::<f64>();
150 if let Some(top) = raw
151 .iter_mut()
152 .max_by(|a, b| a.1.total_cmp(&b.1))
153 .filter(|_| drift.abs() > f64::EPSILON)
154 {
155 top.1 = round(top.1 + drift);
156 }
157 raw
158}
159
160fn confidence(probs: impl Iterator<Item = f64>) -> f64 {
162 let probs: Vec<f64> = probs.collect();
163 let n = probs.len();
164 if n < 2 {
165 return 1.0;
166 }
167 let max = probs.iter().copied().fold(0.0, f64::max);
168 let floor = 1.0 / n as f64;
169 round(((max - floor) / (1.0 - floor)).clamp(0.0, 1.0))
170}
171
172fn unit(parts: &[&str]) -> f64 {
173 (fnv(parts) % 100_000) as f64 / 100_000.0
174}
175
176fn fnv(parts: &[&str]) -> u64 {
177 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
178 for part in parts {
179 for b in part.as_bytes() {
180 h ^= *b as u64;
181 h = h.wrapping_mul(0x0000_0100_0000_01b3);
182 }
183 h ^= 0xff;
184 h = h.wrapping_mul(0x0000_0100_0000_01b3);
185 }
186 h
187}
188
189fn round(x: f64) -> f64 {
190 (x * 1000.0).round() / 1000.0
191}
192
193pub fn body(answers: &[(String, Option<Answer>)], model: &str) -> String {
195 let mut map = serde_json::Map::new();
196 for (name, answer) in answers {
197 let value = match answer {
198 Some(answer) => answer_json(answer),
199 None => Value::Null,
200 };
201 map.insert(name.clone(), value);
202 }
203 serde_json::to_string_pretty(&serde_json::json!({
204 "model": model,
205 "answers": map,
206 "usage": {"input_tokens": null, "output_tokens": null},
207 }))
208 .unwrap_or_default()
209}