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
//! Grounding: a reply may only state what its sources hold.
//!
//! [`check`] reads a reply sentence by sentence against two kinds of sources:
//!
//! - **facts**: what the reply may state (the owner's own words, the knowledge passages the
//!   reply was written from, what lookups found);
//! - **the customer's words**: numbers the customer wrote may be repeated ("for your 5 kg"), but
//!   nothing else they wrote is a fact ("You deliver for free, right?" makes no free delivery).
//!
//! A sentence is **unsupported** when it states
//! - a number the sources do not hold (compared by value: `15k` = `15.000` = `15 ribu`),
//! - a day the facts do not open or close on ("open on Sunday"),
//! - a link, email address or `@handle` the facts do not write,
//! - a word the facts do not hold, other than function words and the words any business chat
//!   uses ("free delivery" for a laundry whose facts never mention delivery),
//! - a yes or a no and nothing the facts hold ("Yes, we do.").
//!
//! Unsupported sentences are left out. When no sentence the facts hold is left, the reply is
//! not sent ([`Checked::text`] is `None`): the caller says it does not know, or hands over. A
//! currency the sources never name is taken out of the sentences that stay ("$15k" -> "15k"),
//! as the round-5 template filter did.
//!
//! The words check is lexical, so a paraphrase can be left out although it is true. A caller
//! with a model at hand may ask it about those sentences ([`Review::to_verify`]) and keep the
//! ones it confirms ([`Review::confirm`]); numbers, days and addresses are never left to a model.

mod attribution;
mod claims;
mod numbers;
mod words;

use std::fmt;

use attribution::Attributions;
use claims::{KnownAddresses, KnownDays, KnownWords};
use numbers::KnownNumbers;

/// The round-5 `grounded` template filter: numbers and currencies only, the whole reply or `""`.
#[cfg(feature = "jinja")]
pub(crate) use numbers::grounded as grounded_numbers;

/// What a reply may draw on.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Sources {
    facts: Vec<String>,
    customer: Vec<String>,
}

impl Sources {
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a text the reply may state facts from.
    #[must_use]
    pub fn fact(mut self, text: impl Into<String>) -> Self {
        self.add_fact(text);
        self
    }

    /// Adds a text the customer wrote: its numbers may be repeated, nothing else counts.
    #[must_use]
    pub fn customer(mut self, text: impl Into<String>) -> Self {
        self.add_customer(text);
        self
    }

    pub fn add_fact(&mut self, text: impl Into<String>) {
        let text = text.into();
        if !text.trim().is_empty() {
            self.facts.push(text);
        }
    }

    pub fn add_customer(&mut self, text: impl Into<String>) {
        let text = text.into();
        if !text.trim().is_empty() {
            self.customer.push(text);
        }
    }

    /// The facts, one text.
    pub fn facts_text(&self) -> String {
        self.facts.join("\n")
    }

    /// The customer's words, one text.
    pub fn customer_text(&self) -> String {
        self.customer.join("\n")
    }
}

/// Why a sentence was left out.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Reason {
    /// A number the sources do not hold, as written (`20k`).
    Number(String),
    /// A number the sources hold, next to a word they give only to other numbers (`8k`,
    /// `express`: "express is 8k" for "regular 8k, express 15k").
    Attribution { number: String, word: String },
    /// A day the facts do not open or close on, as written.
    Day(String),
    /// A link, email address or `@handle` the facts do not write.
    Address(String),
    /// Words the facts do not hold.
    Words(Vec<String>),
    /// Words the facts do not hold that the customer wrote: the reply takes up the customer's
    /// premise ("Delivery is free, right?" -> "Yes, delivery is free").
    Premise(Vec<String>),
    /// A yes or a no with nothing the facts hold.
    Answer,
}

impl Reason {
    /// Whether a model may confirm the sentence after all: only words and answers, which a
    /// paraphrase or another language can miss. Numbers, days and addresses are exact.
    pub fn may_be_confirmed(&self) -> bool {
        matches!(self, Self::Words(_) | Self::Answer)
    }
}

impl fmt::Display for Reason {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Number(number) => write!(formatter, "the number {number} is not in the sources"),
            Self::Attribution { number, word } => {
                write!(formatter, "the sources give {number} to something else than {word}")
            }
            Self::Day(day) => write!(formatter, "the day {day} is not in the facts"),
            Self::Address(address) => write!(formatter, "{address} is not in the facts"),
            Self::Words(words) => write!(formatter, "not in the facts: {}", words.join(", ")),
            Self::Premise(words) => write!(formatter, "only the customer wrote: {}", words.join(", ")),
            Self::Answer => formatter.write_str("a yes or no the facts do not hold"),
        }
    }
}

/// What the check found in one sentence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict {
    /// It states something the facts hold, and nothing they do not.
    Supported,
    /// It states nothing (a greeting, thanks, an offer to help).
    NoClaim,
    /// It says the bot does not know what the customer asked ("I'm not sure about a vegan
    /// menu"), naming nothing the customer did not.
    Unknown,
    /// It states something the sources do not hold.
    Unsupported(Reason),
}

/// One sentence of a reply.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sentence {
    /// The sentence as written, without the space after it.
    pub text: String,
    /// What follows it up to the next sentence (spaces, a line break).
    gap: String,
    pub verdict: Verdict,
}

/// A sentence that was left out, and why.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unsupported {
    pub sentence: String,
    pub reason: Reason,
}

/// The result of a check.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Checked {
    /// The reply to send: the sentences the sources hold. `None` when none is left: say you do
    /// not know, or hand over.
    pub text: Option<String>,
    /// The sentences left out.
    pub unsupported: Vec<Unsupported>,
    /// The reply says it does not know something the customer asked (whether or not it also
    /// states facts): the owner should answer that part.
    pub admits_unknown: bool,
}

impl Checked {
    /// Whether the reply goes out as the model wrote it (apart from a currency taken out).
    pub fn is_whole(&self) -> bool {
        self.text.is_some() && self.unsupported.is_empty()
    }
}

/// A reply read sentence by sentence, before it is [finished](Review::finish).
#[derive(Debug)]
pub struct Review {
    sentences: Vec<Sentence>,
    numbers: KnownNumbers,
}

impl Review {
    /// Reads `reply` against `sources`.
    pub fn of(reply: &str, sources: &Sources) -> Self {
        let facts = sources.facts_text();
        let numbers = KnownNumbers::with_customer(&facts, &sources.customer_text());
        let known = Known {
            numbers: &numbers,
            attributions: Attributions::of(&facts, &sources.customer_text()),
            words: KnownWords::of(&facts),
            customer_words: KnownWords::of(&sources.customer_text()),
            days: KnownDays::of(&facts),
            addresses: KnownAddresses::of(&facts),
        };
        let sentences = split_sentences(reply)
            .into_iter()
            .map(|(text, gap)| {
                let verdict = known.verdict(&text);
                Sentence { text, gap, verdict }
            })
            .collect();
        Self { sentences, numbers }
    }

    pub fn sentences(&self) -> &[Sentence] {
        &self.sentences
    }

    /// The sentences a model may confirm ([`Reason::may_be_confirmed`]), by index.
    pub fn to_verify(&self) -> Vec<(usize, &str)> {
        self.sentences
            .iter()
            .enumerate()
            .filter(
                |(_, sentence)| matches!(&sentence.verdict, Verdict::Unsupported(reason) if reason.may_be_confirmed()),
            )
            .map(|(index, sentence)| (index, sentence.text.as_str()))
            .collect()
    }

    /// Keeps sentence `index` after all: a model found it in the facts. Sentences whose reason
    /// may not be confirmed stay out.
    pub fn confirm(&mut self, index: usize) {
        if let Some(sentence) = self.sentences.get_mut(index)
            && matches!(&sentence.verdict, Verdict::Unsupported(reason) if reason.may_be_confirmed())
        {
            sentence.verdict = Verdict::Supported;
        }
    }

    pub fn finish(self) -> Checked {
        let mut kept = String::new();
        let mut unsupported = Vec::new();
        let mut holds_a_fact = false;
        let mut admits_unknown = false;
        for sentence in self.sentences {
            match sentence.verdict {
                Verdict::Unsupported(reason) => unsupported.push(Unsupported { sentence: sentence.text, reason }),
                verdict => {
                    holds_a_fact |= verdict == Verdict::Supported;
                    admits_unknown |= verdict == Verdict::Unknown;
                    kept.push_str(&sentence.text);
                    kept.push_str(&sentence.gap);
                }
            }
        }
        // A reply that states nothing ("Hello! How can I help?") goes out as written. One whose
        // every fact was left out, or that only says it does not know, does not: the caller's
        // "I don't know yet" (and its hand-over) says that.
        let sendable = holds_a_fact || (unsupported.is_empty() && !admits_unknown);
        let text = self.numbers.without_unknown_currencies(kept.trim());
        Checked { text: (sendable && !text.is_empty()).then_some(text), unsupported, admits_unknown }
    }
}

/// The facts of `sources` cut into sentences, for a model to name the one that says a sentence
/// of the reply ([`shares_a_fact`] then checks what it named).
pub fn fact_sentences(sources: &Sources) -> Vec<String> {
    sources.facts.iter().flat_map(|fact| split_sentences(&unwrapped(fact))).map(|(text, _)| text).collect()
}

/// `text` with the line breaks inside a sentence (a PDF's wrapped lines) made spaces: a break
/// stays only after the end of a sentence, a colon, or before a line that starts a list item
/// or a capital.
fn unwrapped(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut lines = text.lines().peekable();
    while let Some(line) = lines.next() {
        out.push_str(line);
        let Some(next) = lines.peek() else { break };
        let ends = line.trim_end().ends_with(['.', '!', '?', ':', ';']) || line.trim().is_empty();
        let starts = next
            .trim_start()
            .starts_with(|c: char| c.is_uppercase() || c.is_ascii_digit() || matches!(c, '-' | '*' | '•'));
        out.push(if ends || starts { '\n' } else { ' ' });
    }
    out
}

/// Whether `sentence` and `fact` have a word (by stem), a number or an address in common: the
/// least a fact a model names for a sentence must show, in any language ("menu", "WhatsApp",
/// "45").
pub fn shares_a_fact(sentence: &str, fact: &str) -> bool {
    let words = KnownWords::of(fact);
    let (held, _) = words.sort(sentence);
    !held.is_empty() || KnownNumbers::of(fact).repeats_one(sentence)
}

/// Checks `reply` against `sources` (see the module docs).
pub fn check(reply: &str, sources: &Sources) -> Checked {
    Review::of(reply, sources).finish()
}

struct Known<'a> {
    numbers: &'a KnownNumbers,
    attributions: Attributions,
    words: KnownWords,
    /// The customer's words: a "not sure about X" may name only what they asked about.
    customer_words: KnownWords,
    days: KnownDays,
    addresses: KnownAddresses,
}

impl Known<'_> {
    fn verdict(&self, sentence: &str) -> Verdict {
        if let Some(address) = self.addresses.first_unknown(sentence) {
            return Verdict::Unsupported(Reason::Address(address));
        }
        if let Some(number) = self.numbers.first_unknown(sentence) {
            return Verdict::Unsupported(Reason::Number(number));
        }
        if let Some((number, word)) = self.attributions.first_misattributed(sentence) {
            return Verdict::Unsupported(Reason::Attribution { number, word });
        }
        let (unknown_day, repeats_a_day) = self.days.check(sentence);
        if let Some(day) = unknown_day {
            return Verdict::Unsupported(Reason::Day(day));
        }
        let (held, novel) = self.words.sort(sentence);
        let states_facts_only = novel.is_empty() && !held.is_empty();
        if !states_facts_only
            && claims::admits_unknown(sentence)
            && novel.iter().all(|word| self.customer_words.holds(word))
        {
            return Verdict::Unknown;
        }
        if !novel.is_empty() {
            let premise: Vec<String> = novel.iter().filter(|word| self.customer_words.holds(word)).cloned().collect();
            if !premise.is_empty() {
                return Verdict::Unsupported(Reason::Premise(premise));
            }
            return Verdict::Unsupported(Reason::Words(novel));
        }
        if !held.is_empty() || repeats_a_day || self.numbers.repeats_one(sentence) {
            return Verdict::Supported;
        }
        if claims::answers_yes_or_no(sentence) {
            return Verdict::Unsupported(Reason::Answer);
        }
        Verdict::NoClaim
    }
}

/// Words a dot follows without ending the sentence (`Rp. 25.000`, `Jl. Merdeka`).
const ABBREVIATIONS: &[&str] =
    &["rp", "no", "dr", "drg", "mr", "mrs", "ms", "jl", "st", "tel", "telp", "hp", "wa", "approx", "vs"];

/// `text` cut into sentences, each with the gap after it. A sentence ends at `.`, `!`, `?` or
/// `…` followed by a space or the end, and at a line break. `a.m.`, `e.g.` and `15.000` do not
/// end one.
fn split_sentences(text: &str) -> Vec<(String, String)> {
    let mut sentences = Vec::new();
    let mut sentence = String::new();
    let characters: Vec<char> = text.chars().collect();
    let mut index = 0;
    while let Some(&character) = characters.get(index) {
        let next = characters.get(index + 1).copied();
        let ends = match character {
            '\n' => true,
            '.' | '!' | '?' | '…' | '。' => {
                let at_a_break = next.is_none_or(char::is_whitespace);
                // `a.m.`, `e.g.`: one letter before the dot.
                let short = character == '.' && {
                    let word: String = sentence.chars().rev().take_while(|c| !c.is_whitespace()).collect();
                    let word: String = word.chars().rev().collect::<String>().to_lowercase();
                    let letters = word.chars().filter(|c| c.is_alphabetic()).count();
                    let only_letters = word.chars().all(|c| c.is_alphabetic() || c == '.');
                    (only_letters && (letters <= 1 || word.contains('.'))) || ABBREVIATIONS.contains(&word.as_str())
                };
                at_a_break && !short
            }
            _ => false,
        };
        if character != '\n' {
            sentence.push(character);
        }
        if ends {
            let mut gap = String::new();
            if character == '\n' {
                gap.push('\n');
            }
            while let Some(space) = characters.get(index + 1).copied().filter(|c| c.is_whitespace()) {
                gap.push(space);
                index += 1;
            }
            if !sentence.trim().is_empty() {
                sentences.push((sentence.trim_start().to_owned(), gap));
            } else if let Some((_, last_gap)) = sentences.last_mut() {
                last_gap.push_str(&gap);
            }
            sentence = String::new();
        }
        index += 1;
    }
    if !sentence.trim().is_empty() {
        sentences.push((sentence.trim_start().to_owned(), String::new()));
    }
    sentences
}

#[cfg(test)]
mod tests;