graphrt-core 0.7.0

Executor-agnostic graph runtime for agentic AI workflows: graph model, variable pool, scheduler, events, snapshots and built-in control nodes.
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Numbers and currencies in a reply, compared by value with the ones its sources hold.
//!
//! Numbers are compared by value: `15k`, `15.000`, `15,000`, `15 ribu` and `15rb` are all
//! 15000, `1.5 jt` is 1500000. A clock time counts as its hour either way (`8pm` matches `20`,
//! `20:00` matches `8 pm`). The numbers 0, 1 and 2 without a currency count as words ("1 box",
//! "2 options"), not as facts.

/// Currencies by what a reply writes for them; the first name is the one compared.
const CURRENCIES: &[&[&str]] = &[
    &["usd", "$", "us$", "dollar", "dollars"],
    &["idr", "rp", "rupiah"],
    &["eur", "€", "euro", "euros"],
    &["gbp", "£"],
    &["jpy", "¥", "yen"],
    &["kes", "ksh"],
    &["sgd", "s$"],
    &["myr", "ringgit"],
    &["inr", "₹", "rupee", "rupees"],
    &["aud", "a$"],
    &["vnd", "₫", "dong"],
    &["thb", "฿", "baht"],
    &["php", "₱", "peso", "pesos"],
    &["cny", "rmb", "yuan"],
    &["krw", "₩", "won"],
    &["hkd", "hk$"],
    &["cad", "c$"],
    &["nzd", "nz$"],
    &["chf"],
    &["brl", "r$"],
    &["zar"],
    &["ngn", "₦", "naira"],
    &["aed", "dirham", "dirhams"],
    &["sar", "riyal", "riyals"],
    &["try", "₺", "lira"],
    &["mxn"],
    &["rub", "₽", "ruble", "rubles"],
    &["pkr"],
    &["bdt", "৳", "taka"],
    &["egp"],
    &["ghs", "cedi", "cedis"],
    &["ugx"],
    &["tzs"],
];

/// Multipliers a number may be written with, in the words that follow it.
const MULTIPLIERS: &[(&str, f64)] = &[
    ("k", 1_000.0),
    ("rb", 1_000.0),
    ("ribu", 1_000.0),
    ("thousand", 1_000.0),
    ("jt", 1_000_000.0),
    ("juta", 1_000_000.0),
    ("million", 1_000_000.0),
];

/// The numbers and currencies some texts hold.
#[derive(Debug, Default)]
pub(super) struct KnownNumbers {
    values: Vec<f64>,
    /// Numbers the customer wrote: what they have or want ("my 5 kg", "for 50 people"), which a
    /// reply may repeat. A price, a duration, a time or a share they wrote is their question
    /// ("ready in 2 hours, right?"), never the business's fact.
    customer: Vec<f64>,
    currencies: Vec<&'static str>,
}

impl KnownNumbers {
    pub(super) fn of(text: &str) -> Self {
        Self::with_customer(text, "")
    }

    pub(super) fn with_customer(facts: &str, customer: &str) -> Self {
        Self {
            values: numbers(facts).iter().flat_map(|number| number.values.clone()).collect(),
            customer: numbers(customer)
                .into_iter()
                .filter(|number| matches!(number.kind, Kind::Plain | Kind::Count))
                .flat_map(|number| number.values)
                .collect(),
            currencies: currencies_in(&format!("{facts}\n{customer}")),
        }
    }

    fn holds(&self, number: &Written) -> bool {
        let among = |known: &[f64]| number.values.iter().any(|value| known.iter().any(|known| same(*known, *value)));
        among(&self.values) || (matches!(number.kind, Kind::Plain | Kind::Count) && among(&self.customer))
    }

    /// The first number `text` states that is not known, as written (`20k`).
    pub(super) fn first_unknown(&self, text: &str) -> Option<String> {
        numbers(text).into_iter().find(|number| !number.is_a_word() && !self.holds(number)).map(|number| number.written)
    }

    /// Whether `text` states a number that is known (a fact it repeats).
    pub(super) fn repeats_one(&self, text: &str) -> bool {
        numbers(text).iter().any(|number| !number.is_a_word() && self.holds(number))
    }

    /// `text` without the currency words and signs of currencies not known.
    pub(super) fn without_unknown_currencies(&self, text: &str) -> String {
        without_unknown_currencies(text, &self.currencies)
    }
}

/// The `grounded` template filter of round 5: `text` with currencies `sources` do not name taken
/// out, or `""` when it states a number they do not hold.
#[cfg(any(feature = "jinja", test))]
pub(crate) fn grounded(text: &str, sources: &[String]) -> String {
    let known = KnownNumbers::of(&sources.join("\n"));
    if known.first_unknown(text).is_some() {
        return String::new();
    }
    known.without_unknown_currencies(text)
}

pub(super) fn same(left: f64, right: f64) -> bool {
    (left - right).abs() < 1e-6
}

/// What a number measures: two numbers of one kind can be confused ("8k" and "15k"), a
/// price and a duration cannot.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Kind {
    Money,
    Duration,
    Clock,
    Count,
    Share,
    Plain,
}

/// Words after a number that make it a length of time.
const TIME_UNITS: &[&str] = &[
    "hour", "hours", "hr", "hrs", "jam", "minute", "minutes", "min", "mins", "menit", "day", "days", "hari", "week",
    "weeks", "minggu", "pekan", "month", "months", "bulan", "year", "years", "tahun",
];

fn kind_of(value: f64, before: Option<&str>, next: Option<&str>, money: bool, clock: bool) -> Kind {
    if money || value >= 1000.0 {
        Kind::Money
    } else if clock || matches!(before, Some("jam" | "pukul" | "at")) {
        Kind::Clock
    } else if next.is_some_and(|next| TIME_UNITS.contains(&next)) {
        Kind::Duration
    } else if matches!(next, Some("percent" | "persen")) {
        Kind::Share
    } else if next.is_some_and(|next| COUNTED.contains(&next)) {
        Kind::Count
    } else {
        Kind::Plain
    }
}

/// One number written in a text: the values it may mean, and whether it was written with a
/// currency, a multiplier or a fraction.
#[derive(Debug)]
pub(super) struct Written {
    /// What the number measures, as far as the words around it tell.
    pub(super) kind: Kind,
    /// The number as the text writes it, with its multiplier (`15k`, `8 pm`).
    pub(super) written: String,
    pub(super) values: Vec<f64>,
    plain_small: bool,
}

impl Written {
    pub(super) fn is_a_word(&self) -> bool {
        self.plain_small
    }
}

/// Lowercase words of `text` (letters, digits and currency signs), in order.
pub(super) fn tokens(text: &str) -> Vec<String> {
    let mut tokens = Vec::new();
    let mut word = String::new();
    let flush = |word: &mut String, tokens: &mut Vec<String>| {
        if !word.is_empty() {
            tokens.push(std::mem::take(word));
        }
    };
    let characters: Vec<char> = text.chars().collect();
    for (index, character) in characters.iter().enumerate() {
        let between_digits = |at: usize| {
            at > 0
                && characters.get(at - 1).is_some_and(char::is_ascii_digit)
                && characters.get(at + 1).is_some_and(char::is_ascii_digit)
        };
        match character {
            c if c.is_alphanumeric() => {
                // `15k`, `8pm`: a number and the letters after it are separate words.
                let switches = word.chars().last().is_some_and(|last| last.is_ascii_digit() != c.is_ascii_digit());
                if switches && !word.ends_with([':', '.', ',']) {
                    flush(&mut word, &mut tokens);
                }
                word.extend(c.to_lowercase());
            }
            '.' | ',' | ':' if between_digits(index) => word.push(*character),
            '$' | '€' | '£' | '¥' | '₹' | '₫' | '฿' | '₱' | '₩' | '₦' | '₺' | '₽' | '৳' => {
                // `US$`, `S$`, `A$`: the letters before belong to the sign.
                if !matches!(word.as_str(), "us" | "s" | "a" | "hk" | "c" | "nz" | "r") {
                    flush(&mut word, &mut tokens);
                }
                word.push(*character);
                flush(&mut word, &mut tokens);
            }
            _ => flush(&mut word, &mut tokens),
        }
    }
    flush(&mut word, &mut tokens);
    tokens
}

/// Words after a number that make even a small one a fact: a duration, a share, a time of day
/// ("2 hours", "1 hari", "dua minggu", "0%").
const DURATIONS: &[&str] = &[
    "hour", "hours", "hr", "hrs", "jam", "minute", "minutes", "min", "mins", "menit", "day", "days", "hari", "week",
    "weeks", "minggu", "pekan", "month", "months", "bulan", "year", "years", "tahun", "percent", "persen", "times",
    "kali", "am", "pm",
];

/// Words that count things: a number of 3 or more written as a word is a fact before one
/// ("tiga kotak", "fifty guests").
const COUNTED: &[&str] = &[
    "box",
    "boxes",
    "kotak",
    "porsi",
    "portion",
    "portions",
    "pcs",
    "piece",
    "pieces",
    "kg",
    "kilo",
    "kilogram",
    "kilograms",
    "gram",
    "grams",
    "liter",
    "liters",
    "orang",
    "people",
    "persons",
    "tamu",
    "guest",
    "guests",
    "km",
    "meter",
    "meters",
    "tumpeng",
    "buah",
];

/// Number words, English and Indonesian, with their value.
const NUMBER_WORDS: &[(&str, f64)] = &[
    ("zero", 0.0),
    ("nol", 0.0),
    ("one", 1.0),
    ("satu", 1.0),
    ("two", 2.0),
    ("dua", 2.0),
    ("three", 3.0),
    ("tiga", 3.0),
    ("four", 4.0),
    ("empat", 4.0),
    ("five", 5.0),
    ("lima", 5.0),
    ("six", 6.0),
    ("enam", 6.0),
    ("seven", 7.0),
    ("tujuh", 7.0),
    ("eight", 8.0),
    ("delapan", 8.0),
    ("nine", 9.0),
    ("sembilan", 9.0),
    ("ten", 10.0),
    ("sepuluh", 10.0),
    ("eleven", 11.0),
    ("sebelas", 11.0),
    ("twelve", 12.0),
    ("thirteen", 13.0),
    ("fourteen", 14.0),
    ("fifteen", 15.0),
    ("sixteen", 16.0),
    ("seventeen", 17.0),
    ("eighteen", 18.0),
    ("nineteen", 19.0),
    ("twenty", 20.0),
    ("thirty", 30.0),
    ("forty", 40.0),
    ("fifty", 50.0),
    ("sixty", 60.0),
    ("seventy", 70.0),
    ("eighty", 80.0),
    ("ninety", 90.0),
    ("seratus", 100.0),
    ("seribu", 1000.0),
];

/// Whether `word` is (part of) a number written as a word ("dua", "fourteen", "belas").
pub(super) fn is_number_word(word: &str) -> bool {
    NUMBER_WORDS.iter().any(|(name, _)| *name == word) || matches!(word, "belas" | "puluh" | "ratus" | "hundred")
}

/// The value of the number words `tokens` start with ("empat belas", "lima puluh dua",
/// "one hundred twenty") and how many words it takes, or `None`.
fn word_number(tokens: &[String]) -> Option<(f64, usize)> {
    let mut value = 0.0;
    let mut last = 0.0;
    let mut used = 0;
    for token in tokens {
        let word = token.as_str();
        if let Some((_, number)) = NUMBER_WORDS.iter().find(|(name, _)| *name == word) {
            value += number;
            last = *number;
        } else if used > 0 && word == "belas" && last < 10.0 {
            value += 10.0;
            last = 0.0;
        } else if used > 0 && word == "puluh" && last < 10.0 {
            value += last * 9.0;
            last = 0.0;
        } else if used > 0 && word == "ratus" && last < 10.0 {
            value += last * 99.0;
            last = 0.0;
        } else if used > 0 && word == "hundred" {
            value = if value == 0.0 { 100.0 } else { value * 100.0 };
            last = 0.0;
        } else {
            break;
        }
        used += 1;
    }
    (used > 0).then_some((value, used))
}

pub(super) fn numbers(text: &str) -> Vec<Written> {
    let tokens = tokens(text);
    let mut found = Vec::new();
    let mut index = 0;
    while let Some(token) = tokens.get(index) {
        let starts_with_digit = token.starts_with(|c: char| c.is_ascii_digit());
        let spelled = if starts_with_digit { None } else { word_number(tokens.get(index..).unwrap_or_default()) };
        if !starts_with_digit && spelled.is_none() {
            index += 1;
            continue;
        }
        let width = spelled.map_or(1, |(_, used)| used);
        let next = tokens.get(index + width).map(String::as_str);
        let before = index.checked_sub(1).and_then(|before| tokens.get(before)).map(String::as_str);
        let with_currency = [before, next, tokens.get(index + width + 1).map(String::as_str)]
            .into_iter()
            .flatten()
            .any(|word| currency_of(word).is_some());
        let multiplier = next.and_then(|next| MULTIPLIERS.iter().find(|(word, _)| *word == next)).map(|(_, by)| *by);
        let of_a_duration = next.is_some_and(|next| DURATIONS.contains(&next));
        if let Some((value, used)) = spelled {
            let value = value * multiplier.unwrap_or(1.0);
            let counts = value >= 3.0 && next.is_some_and(|next| COUNTED.contains(&next));
            // A number word is a fact only with a duration, a currency, a multiplier or what it
            // counts: "one of our cakes" and "two options" are words.
            let a_word = multiplier.is_none() && !with_currency && !of_a_duration && !counts;
            let written = tokens.get(index..index + used).map(|words| words.join(" ")).unwrap_or_default();
            let kind = kind_of(value, before, next, multiplier.is_some() || with_currency, false);
            found.push(Written { written, kind, values: vec![value], plain_small: a_word });
            index += used;
            continue;
        }
        let mut values = Vec::new();
        if let Some((hour, minutes)) = token.split_once(':') {
            values.extend(hour.parse::<f64>().ok());
            if let Ok(minutes) = minutes.parse::<f64>()
                && minutes > 0.0
            {
                found.push(Written {
                    written: token.clone(),
                    kind: Kind::Clock,
                    values: vec![minutes],
                    plain_small: false,
                });
            }
        } else if let Some(value) = parse_number(token) {
            values.push(value * multiplier.unwrap_or(1.0));
            // 0, 1 and 2 count as words ("1 kg", "2 options"), unless a duration or a share
            // follows ("2 hours", "1 hari").
            let plain_small =
                multiplier.is_none() && !with_currency && !of_a_duration && !token.contains(['.', ',']) && value <= 2.0;
            if plain_small {
                found.push(Written { written: token.clone(), kind: Kind::Plain, values, plain_small });
                index += 1;
                continue;
            }
        }
        // A clock time: its hour on the other half of the day too.
        let clock = matches!(next, Some("am" | "pm" | "pagi" | "sore" | "malam")) || token.contains(':');
        let first_value = values.first().copied().unwrap_or_default();
        let kind = kind_of(first_value, before, next, multiplier.is_some() || with_currency, clock);
        if clock {
            let hours: Vec<f64> = values.iter().filter(|hour| **hour < 24.0).map(|hour| (hour + 12.0) % 24.0).collect();
            values.extend(hours);
        }
        if !values.is_empty() {
            let written = match next {
                Some(word) if MULTIPLIERS.iter().any(|(multiplier, _)| *multiplier == word) => format!("{token}{word}"),
                Some(word @ ("am" | "pm")) => format!("{token} {word}"),
                _ => token.clone(),
            };
            found.push(Written { written, kind, values, plain_small: false });
        }
        index += 1;
    }
    found
}

/// `15.000` and `15,000` as fifteen thousand, `1.5` and `1,5` as one and a half.
fn parse_number(token: &str) -> Option<f64> {
    let groups: Vec<&str> = token.split(['.', ',']).collect();
    let thousands = groups.len() > 1 && groups.iter().skip(1).all(|group| group.len() == 3);
    if thousands {
        return groups.concat().parse().ok();
    }
    match groups.as_slice() {
        [whole] => whole.parse().ok(),
        [whole, fraction] => format!("{whole}.{fraction}").parse().ok(),
        _ => None,
    }
}

/// Whether `word` names a currency or multiplies a number (`k`, `ribu`, `rp`).
pub(super) fn is_currency_or_multiplier(word: &str) -> bool {
    currency_of(word).is_some() || MULTIPLIERS.iter().any(|(multiplier, _)| *multiplier == word)
}

fn currency_of(word: &str) -> Option<&'static str> {
    CURRENCIES.iter().find(|names| names.contains(&word)).and_then(|names| names.first().copied())
}

fn currencies_in(text: &str) -> Vec<&'static str> {
    tokens(text).iter().filter_map(|word| currency_of(word)).collect()
}

/// `text` without the currency words and signs of currencies `known` does not hold.
fn without_unknown_currencies(text: &str, known: &[&str]) -> String {
    let mut kept = String::with_capacity(text.len());
    let mut rest = text;
    while !rest.is_empty() {
        let Some((start, length)) = next_currency_mark(rest, known) else {
            kept.push_str(rest);
            break;
        };
        kept.push_str(&rest[..start]);
        rest = &rest[start + length..];
        // One space is enough where the mark was: "costs $15k" stays "costs 15k".
        if kept.ends_with(' ') && rest.starts_with(' ') {
            rest = &rest[1..];
        }
    }
    let kept = kept.replace(" .", ".").replace(" ,", ",");
    kept.trim().to_owned()
}

/// Where the next mark of an unknown currency is in `text` (byte offset and length).
fn next_currency_mark(text: &str, known: &[&str]) -> Option<(usize, usize)> {
    let mut best: Option<(usize, usize)> = None;
    for names in CURRENCIES {
        if names.first().is_some_and(|name| known.contains(name)) {
            continue;
        }
        for name in names.iter() {
            let is_sign = !name.chars().all(char::is_alphabetic);
            let lower = text.to_lowercase();
            // Lowercasing keeps byte offsets for the ASCII and sign characters searched here.
            if lower.len() != text.len() {
                continue;
            }
            let mut from = 0;
            while let Some(found) = lower[from..].find(name) {
                let start = from + found;
                let end = start + name.len();
                // A currency's name or code only next to a number: "try again" is no lira.
                let whole_word = is_sign
                    || (!lower[..start].chars().last().is_some_and(char::is_alphanumeric)
                        && !lower[end..].chars().next().is_some_and(char::is_alphabetic)
                        && next_to_a_number(&lower[..start], &lower[end..]));
                if whole_word && best.is_none_or(|(at, _)| start < at) {
                    best = Some((start, name.len()));
                }
                from = end;
            }
        }
    }
    best
}

/// Whether a word between `before` and `after` stands next to a number (`120k VND`, `IDR 25.000`).
fn next_to_a_number(before: &str, after: &str) -> bool {
    let before = before.trim_end();
    let before = MULTIPLIERS
        .iter()
        .find_map(|(word, _)| {
            before.strip_suffix(word).filter(|rest| rest.ends_with(|c: char| c.is_ascii_digit() || c == ' '))
        })
        .unwrap_or(before)
        .trim_end();
    before.ends_with(|c: char| c.is_ascii_digit()) || after.trim_start().starts_with(|c: char| c.is_ascii_digit())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sources(texts: &[&str]) -> Vec<String> {
        texts.iter().map(|text| (*text).to_owned()).collect()
    }

    const LAUNDRY: &str =
        "A chatbot for my laundry shop: prices are 8k per kg, express 15k per kg, pickup between 9 and 18.";

    #[test]
    fn a_currency_the_facts_never_name_is_taken_out() {
        let facts = sources(&[LAUNDRY, "How much is express laundry?"]);
        assert_eq!(grounded("$15k per kg.", &facts), "15k per kg.");
        assert_eq!(
            grounded("Our express laundry service costs $15,000 per kilogram.", &facts),
            "Our express laundry service costs 15,000 per kilogram."
        );
        assert_eq!(grounded("Cheesecakes are 120k KES.", &sources(&["cheesecake 120k"])), "Cheesecakes are 120k.");
        assert_eq!(
            grounded("Our cheesecakes are priced at 120k VND.", &sources(&["cheesecake 120k"])),
            "Our cheesecakes are priced at 120k."
        );
        assert_eq!(grounded("Price: ₱120k.", &sources(&["cheesecake 120k"])), "Price: 120k.");
        // A currency's word away from a number is a word.
        assert_eq!(
            grounded("Please try again, we won a prize.", &sources(&["x"])),
            "Please try again, we won a prize."
        );
        assert_eq!(
            grounded("Harga nasi box Rp 25.000 per box.", &sources(&["nasi box 25k"])),
            "Harga nasi box 25.000 per box."
        );
        // A currency the facts name stays.
        assert_eq!(grounded("Nasi box Rp 25.000.", &sources(&["nasi box Rp25.000"])), "Nasi box Rp 25.000.");
        assert_eq!(grounded("It costs 25,000 IDR.", &sources(&["25 ribu rupiah"])), "It costs 25,000 IDR.");
    }

    #[test]
    fn a_number_the_sources_do_not_hold_empties_the_reply() {
        let facts = sources(&[LAUNDRY, "How much is express laundry?"]);
        assert_eq!(grounded("Express costs 20k per kg.", &facts), "");
        assert_eq!(grounded("We open at 7am.", &facts), "");
        // The same value written another way is the same number.
        assert_eq!(
            grounded("Express is 15.000 per kg, regular 8 ribu.", &facts),
            "Express is 15.000 per kg, regular 8 ribu."
        );
        assert_eq!(grounded("Pickup is from 9am to 6pm.", &facts), "Pickup is from 9am to 6pm.");
        assert_eq!(grounded("Pickup until 18:00.", &facts), "Pickup until 18:00.");
        // Numbers the customer wrote may be repeated, small counting words are words.
        let asked = sources(&[LAUNDRY, "I have 5 kg, how much?"]);
        assert_eq!(
            grounded("For 5 kg that is 2 options: 8k or 15k per kg.", &asked),
            "For 5 kg that is 2 options: 8k or 15k per kg."
        );
        assert_eq!(grounded("Yes, 1 kg is fine.", &facts), "Yes, 1 kg is fine.");
        assert_eq!(grounded("That is $2.", &facts), "");
    }

    #[test]
    fn numbers_are_read_in_the_ways_people_write_them() {
        let values = |text: &str| numbers(text).into_iter().flat_map(|number| number.values).collect::<Vec<_>>();
        assert_eq!(values("15k"), [15_000.0]);
        assert_eq!(values("Rp 1.500.000"), [1_500_000.0]);
        assert_eq!(values("1,5 jt"), [1_500_000.0]);
        assert_eq!(values("120k"), [120_000.0]);
        assert_eq!(values("8pm"), [8.0, 20.0]);
        assert_eq!(values("9-20"), [9.0, 20.0]);
        assert!(values("Monday to Saturday").is_empty());
        assert_eq!(grounded("", &sources(&["x"])), "");
        assert_eq!(grounded("Open Monday to Saturday.", &sources(&["closed Sunday"])), "Open Monday to Saturday.");
    }
}