interplane.Get Omega
Read in your language

aien-protocols-mv

Canonical specifications, wire protocols, and schemas for the AIEN sovereign ecosystem

Brought by drakestapleton

branch main Branches Tags History

aien-protocols-mv / crates / aien-probe / src / lib.rs

385 lines · 11991 bytes Raw Blame History
1//! Sovereign native probe evaluation engine.
2//!
3//! This crate implements AIEN's native, non-generative evaluation primitive. A caller supplies
4//! a JSON state and a set of typed probes. Each probe asks one calibrated question about that
5//! state: a yes or no probability ([`Noul`]), a position on an ordered scale ([`Score`]), or one
6//! option out of a set ([`Choice`]). Every probe is evaluated against the same state, and the
7//! answers come back calibrated.
8//!
9//! The engine is backend driven:
10//!
11//! * [`DeterministicReferenceBackend`] runs entirely in process with no network and no model.
12//! It is the offline oracle for conformance tests and continuous integration.
13//! * [`HttpProbeBackend`] targets an AIEN inference service that taps logits at a single forward
14//! boundary on the local Grace Blackwell GB10.
15//!
16//! This is the sovereign path: no external service, no per token fee, and no state leaving the
17//! AIEN boundary. The engine plugs into the unified Evaluator protocol through
18//! [`ProbeEvaluator`].
19
20pub mod backend;
21pub mod evaluator;
22pub mod math;
23
24use serde::{Deserialize, Serialize};
25use serde_json::Value;
26use std::collections::BTreeMap;
27use std::time::Instant;
28
29pub use backend::{DeterministicReferenceBackend, HttpProbeBackend, ProbeBackend};
30pub use evaluator::{ProbeEvaluator, ProbeEvaluatorConfig, ProbeGate};
31
32/// Error type for probe evaluation.
33#[derive(thiserror::Error, Debug)]
34pub enum ProbeError {
35 #[error("probe serialization failed: {0}")]
36 Serialization(String),
37 #[error("probe backend transport failed: {0}")]
38 Transport(String),
39 #[error("probe backend returned status {status}: {body}")]
40 Status { status: u16, body: String },
41 #[error("probe backend returned a malformed response: {0}")]
42 Malformed(String),
43 #[error("probe evaluation failed: {0}")]
44 Evaluation(String),
45}
46
47/// A typed question about a JSON state.
48#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
49#[serde(tag = "type", rename_all = "lowercase")]
50pub enum Probe {
51 /// A yes or no question answered by a calibrated probability.
52 Noul(Noul),
53 /// A judgment on an ordered, described scale.
54 Score(Score),
55 /// A selection of one option out of a set.
56 Choice(Choice),
57}
58
59/// A yes or no question.
60#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
61pub struct Noul {
62 /// What the question asks.
63 pub instructions: String,
64 /// An optional description of what a yes means.
65 #[serde(default, skip_serializing_if = "Option::is_none")]
66 pub yes: Option<String>,
67 /// An optional description of what a no means.
68 #[serde(default, skip_serializing_if = "Option::is_none")]
69 pub no: Option<String>,
70}
71
72impl Noul {
73 /// A yes or no question with instructions only.
74 pub fn new(instructions: impl Into<String>) -> Self {
75 Self {
76 instructions: instructions.into(),
77 yes: None,
78 no: None,
79 }
80 }
81
82 /// Adds a description of what a yes means.
83 pub fn with_yes(mut self, yes: impl Into<String>) -> Self {
84 self.yes = Some(yes.into());
85 self
86 }
87
88 /// Adds a description of what a no means.
89 pub fn with_no(mut self, no: impl Into<String>) -> Self {
90 self.no = Some(no.into());
91 self
92 }
93}
94
95/// A judgment on an ordered scale, one criterion per level.
96#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
97pub struct Score {
98 /// What the question asks.
99 pub instructions: String,
100 /// The levels of the scale in order, lowest first.
101 pub criteria: Vec<String>,
102}
103
104impl Score {
105 /// A score question with an ordered list of criteria.
106 pub fn new<I, S>(instructions: impl Into<String>, criteria: I) -> Self
107 where
108 I: IntoIterator<Item = S>,
109 S: Into<String>,
110 {
111 Self {
112 instructions: instructions.into(),
113 criteria: criteria.into_iter().map(Into::into).collect(),
114 }
115 }
116}
117
118/// A selection of one option out of a set.
119#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
120pub struct Choice {
121 /// What the question asks.
122 pub instructions: String,
123 /// The options to choose from.
124 pub options: Vec<ChoiceOption>,
125}
126
127impl Choice {
128 /// A choice question over a list of options.
129 pub fn new<I>(instructions: impl Into<String>, options: I) -> Self
130 where
131 I: IntoIterator<Item = ChoiceOption>,
132 {
133 Self {
134 instructions: instructions.into(),
135 options: options.into_iter().collect(),
136 }
137 }
138}
139
140/// One option of a choice question.
141#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
142pub struct ChoiceOption {
143 /// The stable identifier of the option.
144 pub id: String,
145 /// An optional description of the option.
146 #[serde(default, skip_serializing_if = "Option::is_none")]
147 pub description: Option<String>,
148}
149
150impl ChoiceOption {
151 /// An option with an identifier only.
152 pub fn new(id: impl Into<String>) -> Self {
153 Self {
154 id: id.into(),
155 description: None,
156 }
157 }
158
159 /// Adds a description to the option.
160 pub fn with_description(mut self, description: impl Into<String>) -> Self {
161 self.description = Some(description.into());
162 self
163 }
164}
165
166/// The answer to one probe, of the type the probe had.
167#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
168#[serde(tag = "type", rename_all = "lowercase")]
169pub enum Answer {
170 /// The answer to a [`Noul`].
171 Noul(NoulAnswer),
172 /// The answer to a [`Score`].
173 Score(ScoreAnswer),
174 /// The answer to a [`Choice`].
175 Choice(ChoiceAnswer),
176}
177
178/// The answer to a yes or no question.
179#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
180pub struct NoulAnswer {
181 /// The calibrated probability that the answer is yes, from zero to one.
182 pub noul: f64,
183}
184
185/// The answer to a score question.
186#[derive(Clone, Debug, PartialEq, Serialize)]
187pub struct ScoreAnswer {
188 /// The probability weighted position on the scale.
189 pub score: f64,
190 /// How concentrated the distribution is, from zero to one.
191 pub confidence: f64,
192 /// Each level and the criterion the question gave it.
193 pub legend: BTreeMap<u32, String>,
194 /// Each level and its probability.
195 pub probabilities: BTreeMap<u32, f64>,
196}
197
198impl<'de> Deserialize<'de> for ScoreAnswer {
199 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
200 where
201 D: serde::Deserializer<'de>,
202 {
203 #[derive(Deserialize)]
204 struct Raw {
205 score: f64,
206 confidence: f64,
207 legend: BTreeMap<String, String>,
208 probabilities: BTreeMap<String, f64>,
209 }
210
211 fn by_level<T, E>(map: BTreeMap<String, T>, field: &str) -> Result<BTreeMap<u32, T>, E>
212 where
213 E: serde::de::Error,
214 {
215 map.into_iter()
216 .map(|(level, value)| match level.parse::<u32>() {
217 Ok(level) => Ok((level, value)),
218 Err(_) => Err(E::custom(format!(
219 "{field} has the key {level}, which is not a level number"
220 ))),
221 })
222 .collect()
223 }
224
225 let raw = Raw::deserialize(deserializer)?;
226 Ok(ScoreAnswer {
227 score: raw.score,
228 confidence: raw.confidence,
229 legend: by_level(raw.legend, "legend")?,
230 probabilities: by_level(raw.probabilities, "probabilities")?,
231 })
232 }
233}
234
235/// The answer to a choice question.
236#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
237pub struct ChoiceAnswer {
238 /// The option with the highest probability.
239 pub choice: String,
240 /// How concentrated the distribution is, from zero to one.
241 pub confidence: f64,
242 /// Every option and its probability.
243 pub probabilities: BTreeMap<String, f64>,
244}
245
246/// An ordered set of probes keyed by identifier.
247#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
248pub struct ProbeSet {
249 entries: Vec<(String, Probe)>,
250}
251
252impl ProbeSet {
253 /// An empty probe set.
254 pub fn new() -> Self {
255 Self {
256 entries: Vec::new(),
257 }
258 }
259
260 /// Adds a probe under an identifier, in builder style.
261 pub fn with(mut self, id: impl Into<String>, probe: Probe) -> Self {
262 self.entries.push((id.into(), probe));
263 self
264 }
265
266 /// Adds a probe under an identifier.
267 pub fn insert(&mut self, id: impl Into<String>, probe: Probe) {
268 self.entries.push((id.into(), probe));
269 }
270
271 /// The probe under an identifier.
272 pub fn get(&self, id: &str) -> Option<&Probe> {
273 self.entries
274 .iter()
275 .find(|(key, _)| key == id)
276 .map(|(_, probe)| probe)
277 }
278
279 /// The number of probes.
280 pub fn len(&self) -> usize {
281 self.entries.len()
282 }
283
284 /// Whether the set is empty.
285 pub fn is_empty(&self) -> bool {
286 self.entries.is_empty()
287 }
288
289 /// Iterates over the probes in insertion order.
290 pub fn iter(&self) -> impl Iterator<Item = (&String, &Probe)> {
291 self.entries.iter().map(|(key, probe)| (key, probe))
292 }
293}
294
295/// The answers to one probe request.
296#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
297pub struct ProbeResponse {
298 /// The model or backend that produced the answers.
299 pub model: String,
300 /// One answer per probe, in request order.
301 pub answers: Vec<(String, Answer)>,
302 /// Wall clock time the evaluation took, in microseconds.
303 #[serde(default)]
304 pub latency_micros: u64,
305}
306
307impl ProbeResponse {
308 /// The answer under an identifier.
309 pub fn answer(&self, id: &str) -> Option<&Answer> {
310 self.answers
311 .iter()
312 .find(|(key, _)| key == id)
313 .map(|(_, answer)| answer)
314 }
315
316 /// The answer under an identifier, if it answers a [`Noul`].
317 pub fn noul(&self, id: &str) -> Option<&NoulAnswer> {
318 match self.answer(id)? {
319 Answer::Noul(answer) => Some(answer),
320 _ => None,
321 }
322 }
323
324 /// The answer under an identifier, if it answers a [`Score`].
325 pub fn score(&self, id: &str) -> Option<&ScoreAnswer> {
326 match self.answer(id)? {
327 Answer::Score(answer) => Some(answer),
328 _ => None,
329 }
330 }
331
332 /// The answer under an identifier, if it answers a [`Choice`].
333 pub fn choice(&self, id: &str) -> Option<&ChoiceAnswer> {
334 match self.answer(id)? {
335 Answer::Choice(answer) => Some(answer),
336 _ => None,
337 }
338 }
339}
340
341/// Runs a [`ProbeBackend`] over a state and a probe set.
342pub struct ProbeEngine<B: ProbeBackend> {
343 backend: B,
344}
345
346impl<B: ProbeBackend> ProbeEngine<B> {
347 /// Builds an engine over a backend.
348 pub fn new(backend: B) -> Self {
349 Self { backend }
350 }
351
352 /// The backend the engine runs.
353 pub fn backend(&self) -> &B {
354 &self.backend
355 }
356
357 /// Evaluates every probe against the state and returns the calibrated answers.
358 pub async fn evaluate(
359 &self,
360 state: &Value,
361 probes: &ProbeSet,
362 ) -> Result<ProbeResponse, ProbeError> {
363 let started = Instant::now();
364 let mut response = self.backend.evaluate(state, probes).await?;
365 response.latency_micros = started.elapsed().as_micros() as u64;
366 Ok(response)
367 }
368}
369
370/// Recursively orders object keys so the serialized form of a state is byte stable.
371pub(crate) fn canonicalize(value: &Value) -> Value {
372 match value {
373 Value::Object(map) => {
374 let mut keys: Vec<&String> = map.keys().collect();
375 keys.sort();
376 let mut out = serde_json::Map::new();
377 for key in keys {
378 out.insert(key.clone(), canonicalize(&map[key]));
379 }
380 Value::Object(out)
381 }
382 Value::Array(items) => Value::Array(items.iter().map(canonicalize).collect()),
383 other => other.clone(),
384 }
385}