typesafeai-sdk 0.2.0

Rust SDK for TypeSafe AI — typed judgments from System One models like Jev
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Request and response types for the TypeSafe SDK.
//!
//! Mirrors the Python SDK's `SystemOneRequest` / `SystemOneResponse` and the
//! JS SDK's `SystemOneRequest` / `SystemOneResult`.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::questions::Question;

// ---------------------------------------------------------------------------
// Request
// ---------------------------------------------------------------------------

/// The request body for `POST /v1/systemone`.
///
/// Fields:
/// - `state` — text, a JSON object, or an array to evaluate.
/// - `model` — the model name or alias (e.g. `"jev-latest"`).
/// - `questions` — non-empty map of question names to question objects.
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct SystemOneRequest {
    /// Text, a JSON object, or an array to evaluate.
    pub state: Value,
    /// The model name or alias (e.g. `"jev-latest"`).
    pub model: String,
    /// Non-empty map of question names to question objects.
    pub questions: HashMap<String, Question>,
    /// Extra fields to merge into the request body for forward compatibility.
    /// These are serialized at the top level alongside `state`, `model`,
    /// and `questions`. If a key collides with a known field, the known
    /// field takes precedence.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extra_body: Option<Value>,
}

// ---------------------------------------------------------------------------
// Response
// ---------------------------------------------------------------------------

/// Token usage for a request.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct Usage {
    /// Number of input tokens consumed.
    pub input_tokens: u64,
    /// Number of output tokens generated.
    pub output_tokens: u64,
}

/// A yes/no answer.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct NoulAnswer {
    /// Probability of a "yes" answer, from 0 to 1.
    pub noul: f64,
}

/// A choice answer.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ChoiceAnswer {
    /// The selected label.
    pub choice: String,
    /// Per-label probabilities.
    pub probabilities: HashMap<String, f64>,
    /// Confidence score in `[0, 1]`.
    pub confidence: f64,
}

/// A score answer.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ScoreAnswer {
    /// The assigned score (0-indexed). Returned as a float by the API
    /// (e.g. `0.0`); cast to `u32` if you need an integer index.
    pub score: f64,
    /// Rubric descriptions keyed by score.
    pub legend: HashMap<String, Value>,
    /// Per-score probabilities.
    pub probabilities: HashMap<String, f64>,
    /// Confidence score in `[0, 1]`.
    pub confidence: f64,
}

/// An answer to a single question, identified by its `type` field.
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "type")]
#[non_exhaustive]
pub enum Answer {
    /// A yes/no answer.
    #[serde(rename = "noul")]
    Noul(NoulAnswer),
    /// A multiple-choice answer.
    #[serde(rename = "choice")]
    Choice(ChoiceAnswer),
    /// A rubric-based score answer.
    #[serde(rename = "score")]
    Score(ScoreAnswer),
    /// An unknown answer type returned by a newer API version.
    /// This prevents deserialization failures when the server adds new
    /// primitives that this SDK version doesn't yet know about.
    #[serde(other)]
    Unknown,
}

impl Answer {
    /// Returns `true` if this is a noul answer.
    pub fn is_noul(&self) -> bool {
        matches!(self, Answer::Noul(_))
    }

    /// Returns `true` if this is a choice answer.
    pub fn is_choice(&self) -> bool {
        matches!(self, Answer::Choice(_))
    }

    /// Returns `true` if this is a score answer.
    pub fn is_score(&self) -> bool {
        matches!(self, Answer::Score(_))
    }

    /// Returns the noul answer if this is one.
    pub fn as_noul(&self) -> Option<&NoulAnswer> {
        if let Answer::Noul(n) = self {
            Some(n)
        } else {
            None
        }
    }

    /// Returns the choice answer if this is one.
    pub fn as_choice(&self) -> Option<&ChoiceAnswer> {
        if let Answer::Choice(c) = self {
            Some(c)
        } else {
            None
        }
    }

    /// Returns the score answer if this is one.
    pub fn as_score(&self) -> Option<&ScoreAnswer> {
        if let Answer::Score(s) = self {
            Some(s)
        } else {
            None
        }
    }
}

/// The response from `POST /v1/systemone`.
///
/// Answers are grouped by question name in the `answers` field. You can also
/// access them by type using the [`SystemOneResponse::nouls`],
/// [`SystemOneResponse::choices`], and [`SystemOneResponse::scores`] helper
/// methods, mirroring the Python SDK's grouped accessors.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SystemOneResponse {
    /// The model used to answer the request.
    pub model: String,
    /// All answers keyed by question name.
    pub answers: HashMap<String, Answer>,
    /// Token usage for the request.
    pub usage: Usage,
    /// The request ID returned by the server (from the
    /// `x-typesafe-request-id` response header), if present.
    #[serde(default)]
    pub request_id: Option<String>,
    /// The raw JSON body of the response, injected after deserialization.
    /// Useful for accessing fields the SDK doesn't yet model.
    #[serde(skip)]
    pub raw: Option<Value>,
}

impl SystemOneResponse {
    /// Returns all noul answers keyed by question name.
    pub fn nouls(&self) -> HashMap<&str, &NoulAnswer> {
        self.answers
            .iter()
            .filter_map(|(k, v)| v.as_noul().map(|n| (k.as_str(), n)))
            .collect()
    }

    /// Returns all choice answers keyed by question name.
    pub fn choices(&self) -> HashMap<&str, &ChoiceAnswer> {
        self.answers
            .iter()
            .filter_map(|(k, v)| v.as_choice().map(|c| (k.as_str(), c)))
            .collect()
    }

    /// Returns all score answers keyed by question name.
    pub fn scores(&self) -> HashMap<&str, &ScoreAnswer> {
        self.answers
            .iter()
            .filter_map(|(k, v)| v.as_score().map(|s| (k.as_str(), s)))
            .collect()
    }

    /// Returns the noul answer for the given question name, if it exists.
    pub fn noul(&self, name: &str) -> Option<&NoulAnswer> {
        self.answers.get(name).and_then(|a| a.as_noul())
    }

    /// Returns the choice answer for the given question name, if it exists.
    pub fn choice(&self, name: &str) -> Option<&ChoiceAnswer> {
        self.answers.get(name).and_then(|a| a.as_choice())
    }

    /// Returns the score answer for the given question name, if it exists.
    pub fn score(&self, name: &str) -> Option<&ScoreAnswer> {
        self.answers.get(name).and_then(|a| a.as_score())
    }

    /// Returns the request ID associated with this response, if the server
    /// provided one via the `x-typesafe-request-id` header.
    pub fn request_id(&self) -> Option<&str> {
        self.request_id.as_deref()
    }

    /// Returns the raw JSON body of the response as a [`serde_json::Value`],
    /// if it was captured. This gives access to fields the SDK doesn't yet
    /// model.
    pub fn raw(&self) -> Option<&Value> {
        self.raw.as_ref()
    }
}

// ---------------------------------------------------------------------------
// Models
// ---------------------------------------------------------------------------

/// Metadata for an available model.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ModelCard {
    /// The model name or alias.
    pub name: String,
    /// Human-readable description of the model.
    pub description: String,
    /// Release date of the model, if available.
    #[serde(default)]
    pub release_date: Option<String>,
}

/// The response from `GET /v1/models`.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ListModelsResponse {
    /// List of available models.
    pub models: Vec<ModelCard>,
    /// The request ID returned by the server (from the
    /// `x-typesafe-request-id` response header), if present.
    #[serde(default)]
    pub request_id: Option<String>,
    /// The raw JSON body of the response, injected after deserialization.
    #[serde(skip)]
    pub raw: Option<Value>,
}

impl ListModelsResponse {
    /// Returns the request ID associated with this response, if the server
    /// provided one via the `x-typesafe-request-id` header.
    pub fn request_id(&self) -> Option<&str> {
        self.request_id.as_deref()
    }

    /// Returns the raw JSON body of the response as a [`serde_json::Value`],
    /// if it was captured.
    pub fn raw(&self) -> Option<&Value> {
        self.raw.as_ref()
    }
}

// ---------------------------------------------------------------------------
// SetRequestId trait
// ---------------------------------------------------------------------------

/// Trait for response types that can carry a request ID captured from the
/// `x-typesafe-request-id` response header.
///
/// Implemented by [`SystemOneResponse`] and [`ListModelsResponse`]. The
/// client calls [`set_request_id`](Self::set_request_id) after deserializing
/// the response body, injecting the header value so callers can correlate
/// requests with server-side logs.
pub trait SetRequestId {
    /// Set the request ID on this response.
    fn set_request_id(&mut self, request_id: Option<String>);
}

/// Trait for response types that can carry the raw JSON body.
///
/// Implemented by [`SystemOneResponse`] and [`ListModelsResponse`]. The
/// client calls [`set_raw`](Self::set_raw) after deserializing, injecting
/// the raw JSON so callers can access fields the SDK doesn't yet model.
pub trait SetRawBody {
    /// Set the raw JSON body on this response.
    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());
    }
}