jev-client 0.2.0

Unofficial Rust client for TypeSafe AI's Jev model: typed requests, offline validation, retries and typed errors
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! Lints: advice that does not stop a request, but usually improves its answers.

use serde_json::Value;

use super::document::child_pointer;
use super::finding::{Finding, Rule};
use super::rules::{QuestionView, RequestView};

/// An array longer than this is one the model miscounts into. Measured against the live API: every
/// index into 20 items was read correctly, while 10 of 60 were wrong.
const LONG_ARRAY_ITEMS: usize = 20;

// The escape-option lint compares normalised names (see `normalise`) word by word, so that
// `Not enough information`, `nobody-not-stated` and `other_team` all count, while look-alikes such
// as `another`, `otherwise`, `nonessential` or `not_urgent` do not. A false positive teaches people
// to ignore the lint, but a missed escape option costs answer quality, so the lists stay specific.

/// Words that make an option a way out wherever they appear in its name.
const ESCAPE_WORDS: [&str; 21] = [
    "other",
    "others",
    "else",
    "none",
    "neither",
    "nobody",
    "noone",
    "unknown",
    "unclear",
    "unsure",
    "uncertain",
    "ambiguous",
    "undetermined",
    "indeterminate",
    "unspecified",
    "unstated",
    "unanswerable",
    "inapplicable",
    "irrelevant",
    "idk",
    "unmatched",
];

/// Runs of whole words that make an option a way out wherever they appear in its name.
const ESCAPE_PHRASES: [&str; 33] = [
    "n_a",
    "no_one",
    "no_match",
    "no_fit",
    "no_answer",
    "off_topic",
    "does_not_apply",
    "doesn_t_apply",
    "not_stated",
    "not_specified",
    "not_mentioned",
    "not_given",
    "not_provided",
    "not_listed",
    "not_applicable",
    "not_relevant",
    "not_sure",
    "not_clear",
    "not_known",
    "not_determined",
    "cannot_tell",
    "can_t_tell",
    "cant_tell",
    "cannot_say",
    "can_t_say",
    "cannot_determine",
    "can_t_determine",
    "unable_to_tell",
    "unable_to_determine",
    "don_t_know",
    "dont_know",
    "do_not_know",
    "hard_to_say",
];

/// A way out when one of these comes right before one of `INFORMATION_WORDS`: `not_enough_data`,
/// `insufficient_context`. Alone they are ordinary categories (`insufficient_funds`).
const LACKING_PHRASES: [&str; 5] = ["not_enough", "insufficient", "no", "missing", "lacking"];

const INFORMATION_WORDS: [&str; 7] = [
    "info",
    "information",
    "data",
    "context",
    "detail",
    "details",
    "evidence",
];

const YES_NO_PAIRS: [[&str; 2]; 3] = [["yes", "no"], ["true", "false"], ["y", "n"]];

pub(super) fn check(request: &RequestView<'_>, findings: &mut Vec<Finding>) {
    for question in &request.questions {
        let criteria_pointer = child_pointer(&question.pointer, "criteria");
        match (question.kind, question.fields.get("criteria")) {
            (Some("choice"), Some(Value::Object(options))) if !options.is_empty() => {
                let names: Vec<String> = options.keys().map(|name| normalise(name)).collect();
                check_escape_option(question, &criteria_pointer, &names, findings);
                check_yes_no(question, &criteria_pointer, &names, findings);
                let described = options
                    .iter()
                    .map(|(name, description)| (name.clone(), description));
                check_duplicate_descriptions(
                    question,
                    &criteria_pointer,
                    "options",
                    described,
                    findings,
                );
            }
            (Some("score"), Some(Value::Array(levels))) => {
                let described = levels
                    .iter()
                    .enumerate()
                    .map(|(index, level)| (index.to_string(), level));
                check_duplicate_descriptions(
                    question,
                    &criteria_pointer,
                    "levels",
                    described,
                    findings,
                );
            }
            _ => {}
        }
        if let Some(state) = request.state {
            check_indexed_paths(question, state, findings);
        }
    }
}

/// Lower-case, with every run of other characters collapsed to one underscore.
fn normalise(name: &str) -> String {
    let mut normalised = String::with_capacity(name.len());
    for character in name.trim().chars() {
        if character.is_alphanumeric() {
            normalised.extend(character.to_lowercase());
        } else if !normalised.ends_with('_') {
            normalised.push('_');
        }
    }
    normalised.trim_matches('_').to_owned()
}

/// Whether a name, already passed through `normalise`, gives the model a way out.
fn is_escape_option(normalised: &str) -> bool {
    // `na` alone is "n/a"; as one word of many it is more likely a region (`na_east`).
    if normalised == "na"
        || normalised
            .split('_')
            .any(|word| ESCAPE_WORDS.contains(&word))
    {
        return true;
    }
    // Padding with underscores makes `contains` match whole words only.
    let padded = format!("_{normalised}_");
    let has_phrase = |phrase: &str| padded.contains(&format!("_{phrase}_"));
    ESCAPE_PHRASES.iter().any(|phrase| has_phrase(phrase))
        || LACKING_PHRASES.iter().any(|lacking| {
            INFORMATION_WORDS
                .iter()
                .any(|information| has_phrase(&format!("{lacking}_{information}")))
        })
}

fn check_escape_option(
    question: &QuestionView<'_>,
    pointer: &str,
    names: &[String],
    findings: &mut Vec<Finding>,
) {
    if names.iter().any(|name| is_escape_option(name)) {
        return;
    }
    findings.push(
        Finding::warning(
            Rule::ChoiceNoEscapeOption,
            pointer,
            format!(
                "choice `{}` has no way out; the model must pick one of its options even when none fits",
                question.id
            ),
        )
        .in_question(question.id)
        .suggest("add an option such as `other`, `none_of_the_above` or `not_stated`"),
    );
}

fn check_yes_no(
    question: &QuestionView<'_>,
    pointer: &str,
    names: &[String],
    findings: &mut Vec<Finding>,
) {
    let [first, second] = names else { return };
    let is_pair = YES_NO_PAIRS
        .iter()
        .any(|[yes, no]| (first == yes && second == no) || (first == no && second == yes));
    if !is_pair {
        return;
    }
    findings.push(
        Finding::warning(
            Rule::ChoiceYesNo,
            pointer,
            format!("choice `{}` is a yes/no question", question.id),
        )
        .in_question(question.id)
        .suggest(
            "use a noul: it returns the probability of yes, which a threshold can be tuned against",
        ),
    );
}

fn check_duplicate_descriptions<'a>(
    question: &QuestionView<'_>,
    pointer: &str,
    what: &str,
    described: impl Iterator<Item = (String, &'a Value)>,
    findings: &mut Vec<Finding>,
) {
    let mut seen: Vec<(String, &Value)> = Vec::new();
    for (name, description) in described {
        if description.is_null()
            || description
                .as_str()
                .is_some_and(|text| text.trim().is_empty())
        {
            continue;
        }
        if let Some((earlier, _)) = seen
            .iter()
            .find(|(_, other)| same_description(other, description))
        {
            findings.push(
                Finding::warning(
                    Rule::DuplicateDescription,
                    child_pointer(pointer, &name),
                    format!(
                        "{what} `{earlier}` and `{name}` of `{}` have the same description",
                        question.id
                    ),
                )
                .in_question(question.id)
                .suggest("say what tells them apart, or merge them"),
            );
        } else {
            seen.push((name, description));
        }
    }
}

fn same_description(left: &Value, right: &Value) -> bool {
    match (left.as_str(), right.as_str()) {
        (Some(left), Some(right)) => left.trim().eq_ignore_ascii_case(right.trim()),
        _ => left == right,
    }
}

/// Warns about backticked paths such as `` `items[47].name` `` that index into a long array.
fn check_indexed_paths(question: &QuestionView<'_>, state: &Value, findings: &mut Vec<Finding>) {
    let mut reported: Vec<String> = Vec::new();
    for field in ["instructions", "criteria"] {
        let Some(content) = question.fields.get(field) else {
            continue;
        };
        let field_pointer = child_pointer(&question.pointer, field);
        visit_strings(content, &field_pointer, &mut |text, pointer| {
            for path in backticked(text) {
                let Some(length) = longest_indexed_array(state, path) else {
                    continue;
                };
                if length <= LONG_ARRAY_ITEMS || reported.iter().any(|seen| seen == path) {
                    continue;
                }
                reported.push(path.to_owned());
                findings.push(
                    Finding::warning(
                        Rule::PathIndexLongArray,
                        pointer,
                        format!(
                            "`{path}` indexes into an array of {length} items; the model miscounts positions in arrays longer than {LONG_ARRAY_ITEMS}"
                        ),
                    )
                    .in_question(question.id)
                    .suggest("put the value itself in the instructions, or key the items by a short id instead of a position"),
                );
            }
        });
    }
}

/// Calls `visit` with every string inside `value`, and the JSON Pointer to it.
fn visit_strings(value: &Value, pointer: &str, visit: &mut impl FnMut(&str, &str)) {
    match value {
        Value::String(text) => visit(text, pointer),
        Value::Array(items) => {
            for (index, item) in items.iter().enumerate() {
                visit_strings(item, &child_pointer(pointer, &index.to_string()), visit);
            }
        }
        Value::Object(map) => {
            for (key, item) in map {
                visit_strings(item, &child_pointer(pointer, key), visit);
            }
        }
        _ => {}
    }
}

/// The segments of `text` that are wrapped in single backticks.
fn backticked(text: &str) -> impl Iterator<Item = &str> {
    text.split('`')
        .skip(1)
        .step_by(2)
        .map(str::trim)
        .filter(|segment| !segment.is_empty())
}

/// One step of a path: a key, or an index into an array.
enum Step<'a> {
    Key(&'a str),
    Index(usize),
}

/// Parses `a.b[3].c` into steps. Returns `None` for text that is not a path with an index in it.
fn parse_path(path: &str) -> Option<Vec<Step<'_>>> {
    let mut steps = Vec::new();
    let mut has_index = false;
    for part in path.split('.') {
        let (key, mut rest) = part
            .split_once('[')
            .map_or((part, ""), |(key, rest)| (key, rest));
        if !key.is_empty() {
            if !key
                .chars()
                .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
            {
                return None;
            }
            steps.push(Step::Key(key));
        } else if rest.is_empty() {
            return None;
        }
        while !rest.is_empty() {
            let (index, after) = rest.split_once(']')?;
            steps.push(Step::Index(index.trim().parse().ok()?));
            has_index = true;
            rest = match after.strip_prefix('[') {
                Some(next) => next,
                None if after.is_empty() => "",
                None => return None,
            };
        }
    }
    has_index.then_some(steps)
}

/// Follows `path` through `state` and returns the length of the longest array it indexes into.
/// A path that does not lead anywhere in `state` yields `None`: it may not be a path at all.
fn longest_indexed_array(state: &Value, path: &str) -> Option<usize> {
    let steps = parse_path(path)?;
    // People write both `items[3]` and `state.items[3]`.
    let skip = usize::from(
        matches!(steps.first(), Some(Step::Key("state"))) && state.get("state").is_none(),
    );

    let mut current = state;
    let mut longest = None;
    for step in steps.iter().skip(skip) {
        current = match step {
            Step::Key(key) => current.get(key)?,
            Step::Index(index) => {
                let items = current.as_array()?;
                longest = longest.max(Some(items.len()));
                // An index past the end still points into this array, so its length still counts.
                match items.get(*index) {
                    Some(item) => item,
                    None => return longest,
                }
            }
        };
    }
    longest
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::{backticked, is_escape_option, longest_indexed_array, normalise};

    #[test]
    fn option_names_are_compared_without_case_or_punctuation() {
        assert_eq!(normalise(" None of the Above "), "none_of_the_above");
        assert_eq!(normalise("N/A"), "n_a");
        assert_eq!(normalise("not-stated"), "not_stated");
        assert_eq!(normalise("__Other__"), "other");
    }

    #[test]
    fn recognises_the_usual_ways_out() {
        for name in [
            "other",
            "none_of_the_above",
            "not_stated",
            "N/A",
            "na",
            "unknown",
            "other_reason",
            "none_of_these_teams",
            "billing_or_other",
            "something-else",
            "Not enough information",
            "not_enough_data",
            "insufficient_information",
            "insufficient context",
            "no_info",
            "missing-details",
            "nobody_not_stated",
            "Nobody",
            "no one",
            "UNKNOWN_SENDER",
            "unclear",
            "cannot tell",
            "can't determine",
            "don't know",
            "does not apply",
            "Not applicable",
            "not_listed",
            "off-topic",
            "irrelevant",
            "no_match",
            "neither",
            "IDK",
        ] {
            assert!(is_escape_option(&normalise(name)), "{name}");
        }
        for name in [
            "billing",
            "not_urgent",
            "another",
            "nonessential",
            "no",
            "otherwise",
            "known_issue",
            "insufficient_funds",
            "not_enough_stock",
            "missing_item",
            "na_east",
            "banana",
            "enough_information",
            "detailed",
            "unknowns_resolved",
        ] {
            assert!(!is_escape_option(&normalise(name)), "{name}");
        }
    }

    #[test]
    fn finds_backticked_segments() {
        let found: Vec<&str> =
            backticked("Compare `a[0]` with ` b.c[12] ` and `` and plain text").collect();

        assert_eq!(found, ["a[0]", "b.c[12]"]);
        assert_eq!(backticked("no code here").count(), 0);
        assert_eq!(
            backticked("an `unclosed segment").collect::<Vec<_>>(),
            ["unclosed segment"]
        );
    }

    #[test]
    fn follows_indexed_paths_through_the_state() {
        let state = json!({
            "items": (0..30).map(|n| json!({ "tags": ["a", "b"], "n": n })).collect::<Vec<_>>(),
            "few": [1, 2, 3],
            "grid": [[1, 2], [3, 4]]
        });

        assert_eq!(longest_indexed_array(&state, "items[3]"), Some(30));
        assert_eq!(longest_indexed_array(&state, "state.items[3].n"), Some(30));
        assert_eq!(
            longest_indexed_array(&state, "items[3].tags[1]"),
            Some(30),
            "the longest one counts"
        );
        assert_eq!(
            longest_indexed_array(&state, "items[99]"),
            Some(30),
            "past the end still indexes it"
        );
        assert_eq!(longest_indexed_array(&state, "few[0]"), Some(3));
        assert_eq!(longest_indexed_array(&state, "grid[1][0]"), Some(2));
    }

    #[test]
    fn ignores_backticks_that_are_not_indexed_paths_into_the_state() {
        let state = json!({ "items": [1, 2, 3], "name": "x" });

        for not_a_path in [
            "items",
            "name",
            "missing[0]",
            "items[x]",
            "items[0",
            "name[0]",
            "f(x)[0]",
            "a b[0]",
            "[",
            "",
        ] {
            assert_eq!(
                longest_indexed_array(&state, not_a_path),
                None,
                "{not_a_path:?}"
            );
        }
        assert_eq!(
            longest_indexed_array(&json!("plain text state"), "items[0]"),
            None
        );
        assert_eq!(
            longest_indexed_array(&json!([[1, 2, 3]]), "[0][1]"),
            Some(3),
            "a root array"
        );
    }
}