Skip to main content

graphrt_core/grounding/
mod.rs

1//! Grounding: a reply may only state what its sources hold.
2//!
3//! [`check`] reads a reply sentence by sentence against two kinds of sources:
4//!
5//! - **facts**: what the reply may state (the owner's own words, the knowledge passages the
6//!   reply was written from, what lookups found);
7//! - **the customer's words**: numbers the customer wrote may be repeated ("for your 5 kg"), but
8//!   nothing else they wrote is a fact ("You deliver for free, right?" makes no free delivery).
9//!
10//! A sentence is **unsupported** when it states
11//! - a number the sources do not hold (compared by value: `15k` = `15.000` = `15 ribu`),
12//! - a day the facts do not open or close on ("open on Sunday"),
13//! - a link, email address or `@handle` the facts do not write,
14//! - a word the facts do not hold, other than function words and the words any business chat
15//!   uses ("free delivery" for a laundry whose facts never mention delivery),
16//! - a yes or a no and nothing the facts hold ("Yes, we do.").
17//!
18//! Unsupported sentences are left out. When no sentence the facts hold is left, the reply is
19//! not sent ([`Checked::text`] is `None`): the caller says it does not know, or hands over. A
20//! currency the sources never name is taken out of the sentences that stay ("$15k" -> "15k"),
21//! as the round-5 template filter did.
22//!
23//! The words check is lexical, so a paraphrase can be left out although it is true. A caller
24//! with a model at hand may ask it about those sentences ([`Review::to_verify`]) and keep the
25//! ones it confirms ([`Review::confirm`]); numbers, days and addresses are never left to a model.
26
27mod attribution;
28mod claims;
29#[cfg(feature = "compare-numbers")]
30mod compare;
31pub mod entities;
32pub mod figures;
33mod numbers;
34mod words;
35
36use std::fmt;
37
38use attribution::Attributions;
39use claims::{KnownAddresses, KnownDays, KnownWords};
40use numbers::KnownNumbers;
41
42/// The numbers of a text compared with those of a reference text (`compare-numbers` feature).
43#[cfg(feature = "compare-numbers")]
44pub use compare::{NumberComparison, compare_numbers};
45
46/// The round-5 `grounded` template filter: numbers and currencies only, the whole reply or `""`.
47#[cfg(feature = "jinja")]
48pub(crate) use numbers::grounded as grounded_numbers;
49
50/// What a reply may draw on.
51#[derive(Debug, Clone, Default, PartialEq, Eq)]
52pub struct Sources {
53    facts: Vec<String>,
54    customer: Vec<String>,
55}
56
57impl Sources {
58    pub fn new() -> Self {
59        Self::default()
60    }
61
62    /// Adds a text the reply may state facts from.
63    #[must_use]
64    pub fn fact(mut self, text: impl Into<String>) -> Self {
65        self.add_fact(text);
66        self
67    }
68
69    /// Adds a text the customer wrote: its numbers may be repeated, nothing else counts.
70    #[must_use]
71    pub fn customer(mut self, text: impl Into<String>) -> Self {
72        self.add_customer(text);
73        self
74    }
75
76    pub fn add_fact(&mut self, text: impl Into<String>) {
77        let text = text.into();
78        if !text.trim().is_empty() {
79            self.facts.push(text);
80        }
81    }
82
83    pub fn add_customer(&mut self, text: impl Into<String>) {
84        let text = text.into();
85        if !text.trim().is_empty() {
86            self.customer.push(text);
87        }
88    }
89
90    /// The facts, one text.
91    pub fn facts_text(&self) -> String {
92        self.facts.join("\n")
93    }
94
95    /// The customer's words, one text.
96    pub fn customer_text(&self) -> String {
97        self.customer.join("\n")
98    }
99}
100
101/// Why a sentence was left out.
102#[derive(Debug, Clone, PartialEq, Eq)]
103#[non_exhaustive]
104pub enum Reason {
105    /// A number the sources do not hold, as written (`20k`).
106    Number(String),
107    /// A number the sources hold, next to a word they give only to other numbers (`8k`,
108    /// `express`: "express is 8k" for "regular 8k, express 15k").
109    Attribution { number: String, word: String },
110    /// A day the facts do not open or close on, as written.
111    Day(String),
112    /// A link, email address or `@handle` the facts do not write.
113    Address(String),
114    /// Words the facts do not hold.
115    Words(Vec<String>),
116    /// Words the facts do not hold that the customer wrote: the reply takes up the customer's
117    /// premise ("Delivery is free, right?" -> "Yes, delivery is free").
118    Premise(Vec<String>),
119    /// A yes or a no with nothing the facts hold.
120    Answer,
121}
122
123impl Reason {
124    /// Whether a model may confirm the sentence after all: only words and answers, which a
125    /// paraphrase or another language can miss. Numbers, days and addresses are exact.
126    pub fn may_be_confirmed(&self) -> bool {
127        matches!(self, Self::Words(_) | Self::Answer)
128    }
129}
130
131impl fmt::Display for Reason {
132    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
133        match self {
134            Self::Number(number) => write!(formatter, "the number {number} is not in the sources"),
135            Self::Attribution { number, word } => {
136                write!(formatter, "the sources give {number} to something else than {word}")
137            }
138            Self::Day(day) => write!(formatter, "the day {day} is not in the facts"),
139            Self::Address(address) => write!(formatter, "{address} is not in the facts"),
140            Self::Words(words) => write!(formatter, "not in the facts: {}", words.join(", ")),
141            Self::Premise(words) => write!(formatter, "only the customer wrote: {}", words.join(", ")),
142            Self::Answer => formatter.write_str("a yes or no the facts do not hold"),
143        }
144    }
145}
146
147/// What the check found in one sentence.
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub enum Verdict {
150    /// It states something the facts hold, and nothing they do not.
151    Supported,
152    /// It states nothing (a greeting, thanks, an offer to help).
153    NoClaim,
154    /// It says the bot does not know what the customer asked ("I'm not sure about a vegan
155    /// menu"), naming nothing the customer did not.
156    Unknown,
157    /// It states something the sources do not hold.
158    Unsupported(Reason),
159}
160
161/// One sentence of a reply.
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub struct Sentence {
164    /// The sentence as written, without the space after it.
165    pub text: String,
166    /// What follows it up to the next sentence (spaces, a line break).
167    gap: String,
168    pub verdict: Verdict,
169}
170
171/// A sentence that was left out, and why.
172#[derive(Debug, Clone, PartialEq, Eq)]
173pub struct Unsupported {
174    pub sentence: String,
175    pub reason: Reason,
176}
177
178/// The result of a check.
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct Checked {
181    /// The reply to send: the sentences the sources hold. `None` when none is left: say you do
182    /// not know, or hand over.
183    pub text: Option<String>,
184    /// The sentences left out.
185    pub unsupported: Vec<Unsupported>,
186    /// The reply says it does not know something the customer asked (whether or not it also
187    /// states facts): the owner should answer that part.
188    pub admits_unknown: bool,
189}
190
191impl Checked {
192    /// Whether the reply goes out as the model wrote it (apart from a currency taken out).
193    pub fn is_whole(&self) -> bool {
194        self.text.is_some() && self.unsupported.is_empty()
195    }
196}
197
198/// A reply read sentence by sentence, before it is [finished](Review::finish).
199#[derive(Debug)]
200pub struct Review {
201    sentences: Vec<Sentence>,
202    numbers: KnownNumbers,
203}
204
205impl Review {
206    /// Reads `reply` against `sources`.
207    pub fn of(reply: &str, sources: &Sources) -> Self {
208        let facts = sources.facts_text();
209        let numbers = KnownNumbers::with_customer(&facts, &sources.customer_text());
210        let known = Known {
211            numbers: &numbers,
212            attributions: Attributions::of(&facts, &sources.customer_text()),
213            words: KnownWords::of(&facts),
214            customer_words: KnownWords::of(&sources.customer_text()),
215            days: KnownDays::of(&facts),
216            addresses: KnownAddresses::of(&facts),
217        };
218        let sentences = split_sentences(reply)
219            .into_iter()
220            .map(|(text, gap)| {
221                let verdict = known.verdict(&text);
222                Sentence { text, gap, verdict }
223            })
224            .collect();
225        Self { sentences, numbers }
226    }
227
228    pub fn sentences(&self) -> &[Sentence] {
229        &self.sentences
230    }
231
232    /// The sentences a model may confirm ([`Reason::may_be_confirmed`]), by index.
233    pub fn to_verify(&self) -> Vec<(usize, &str)> {
234        self.sentences
235            .iter()
236            .enumerate()
237            .filter(
238                |(_, sentence)| matches!(&sentence.verdict, Verdict::Unsupported(reason) if reason.may_be_confirmed()),
239            )
240            .map(|(index, sentence)| (index, sentence.text.as_str()))
241            .collect()
242    }
243
244    /// Keeps sentence `index` after all: a model found it in the facts. Sentences whose reason
245    /// may not be confirmed stay out.
246    pub fn confirm(&mut self, index: usize) {
247        if let Some(sentence) = self.sentences.get_mut(index)
248            && matches!(&sentence.verdict, Verdict::Unsupported(reason) if reason.may_be_confirmed())
249        {
250            sentence.verdict = Verdict::Supported;
251        }
252    }
253
254    pub fn finish(self) -> Checked {
255        let mut kept = String::new();
256        let mut unsupported = Vec::new();
257        let mut holds_a_fact = false;
258        let mut admits_unknown = false;
259        for sentence in self.sentences {
260            match sentence.verdict {
261                Verdict::Unsupported(reason) => unsupported.push(Unsupported { sentence: sentence.text, reason }),
262                verdict => {
263                    holds_a_fact |= verdict == Verdict::Supported;
264                    admits_unknown |= verdict == Verdict::Unknown;
265                    kept.push_str(&sentence.text);
266                    kept.push_str(&sentence.gap);
267                }
268            }
269        }
270        // A reply that states nothing ("Hello! How can I help?") goes out as written. One whose
271        // every fact was left out, or that only says it does not know, does not: the caller's
272        // "I don't know yet" (and its hand-over) says that.
273        let sendable = holds_a_fact || (unsupported.is_empty() && !admits_unknown);
274        let text = self.numbers.without_unknown_currencies(kept.trim());
275        Checked { text: (sendable && !text.is_empty()).then_some(text), unsupported, admits_unknown }
276    }
277}
278
279/// The facts of `sources` cut into sentences, for a model to name the one that says a sentence
280/// of the reply ([`shares_a_fact`] then checks what it named).
281pub fn fact_sentences(sources: &Sources) -> Vec<String> {
282    sources.facts.iter().flat_map(|fact| split_sentences(&unwrapped(fact))).map(|(text, _)| text).collect()
283}
284
285/// `text` with the line breaks inside a sentence (a PDF's wrapped lines) made spaces: a break
286/// stays only after the end of a sentence, a colon, or before a line that starts a list item
287/// or a capital.
288fn unwrapped(text: &str) -> String {
289    let mut out = String::with_capacity(text.len());
290    let mut lines = text.lines().peekable();
291    while let Some(line) = lines.next() {
292        out.push_str(line);
293        let Some(next) = lines.peek() else { break };
294        let ends = line.trim_end().ends_with(['.', '!', '?', ':', ';']) || line.trim().is_empty();
295        let starts = next
296            .trim_start()
297            .starts_with(|c: char| c.is_uppercase() || c.is_ascii_digit() || matches!(c, '-' | '*' | '•'));
298        out.push(if ends || starts { '\n' } else { ' ' });
299    }
300    out
301}
302
303/// Whether `sentence` and `fact` have a word (by stem), a number or an address in common: the
304/// least a fact a model names for a sentence must show, in any language ("menu", "WhatsApp",
305/// "45").
306pub fn shares_a_fact(sentence: &str, fact: &str) -> bool {
307    let words = KnownWords::of(fact);
308    let (held, _) = words.sort(sentence);
309    !held.is_empty() || KnownNumbers::of(fact).repeats_one(sentence)
310}
311
312/// Checks `reply` against `sources` (see the module docs).
313pub fn check(reply: &str, sources: &Sources) -> Checked {
314    Review::of(reply, sources).finish()
315}
316
317struct Known<'a> {
318    numbers: &'a KnownNumbers,
319    attributions: Attributions,
320    words: KnownWords,
321    /// The customer's words: a "not sure about X" may name only what they asked about.
322    customer_words: KnownWords,
323    days: KnownDays,
324    addresses: KnownAddresses,
325}
326
327impl Known<'_> {
328    fn verdict(&self, sentence: &str) -> Verdict {
329        if let Some(address) = self.addresses.first_unknown(sentence) {
330            return Verdict::Unsupported(Reason::Address(address));
331        }
332        if let Some(number) = self.numbers.first_unknown(sentence) {
333            return Verdict::Unsupported(Reason::Number(number));
334        }
335        if let Some((number, word)) = self.attributions.first_misattributed(sentence) {
336            return Verdict::Unsupported(Reason::Attribution { number, word });
337        }
338        let (unknown_day, repeats_a_day) = self.days.check(sentence);
339        if let Some(day) = unknown_day {
340            return Verdict::Unsupported(Reason::Day(day));
341        }
342        let (held, novel) = self.words.sort(sentence);
343        let states_facts_only = novel.is_empty() && !held.is_empty();
344        if !states_facts_only
345            && claims::admits_unknown(sentence)
346            && novel.iter().all(|word| self.customer_words.holds(word))
347        {
348            return Verdict::Unknown;
349        }
350        if !novel.is_empty() {
351            let premise: Vec<String> = novel.iter().filter(|word| self.customer_words.holds(word)).cloned().collect();
352            if !premise.is_empty() {
353                return Verdict::Unsupported(Reason::Premise(premise));
354            }
355            return Verdict::Unsupported(Reason::Words(novel));
356        }
357        if !held.is_empty() || repeats_a_day || self.numbers.repeats_one(sentence) {
358            return Verdict::Supported;
359        }
360        if claims::answers_yes_or_no(sentence) {
361            return Verdict::Unsupported(Reason::Answer);
362        }
363        Verdict::NoClaim
364    }
365}
366
367/// Words a dot follows without ending the sentence (`Rp. 25.000`, `Jl. Merdeka`).
368const ABBREVIATIONS: &[&str] =
369    &["rp", "no", "dr", "drg", "mr", "mrs", "ms", "jl", "st", "tel", "telp", "hp", "wa", "approx", "vs"];
370
371/// `text` cut into sentences, each with the gap after it. A sentence ends at `.`, `!`, `?` or
372/// `…` followed by a space or the end, and at a line break. `a.m.`, `e.g.` and `15.000` do not
373/// end one.
374fn split_sentences(text: &str) -> Vec<(String, String)> {
375    let mut sentences = Vec::new();
376    let mut sentence = String::new();
377    let characters: Vec<char> = text.chars().collect();
378    let mut index = 0;
379    while let Some(&character) = characters.get(index) {
380        let next = characters.get(index + 1).copied();
381        let ends = match character {
382            '\n' => true,
383            '.' | '!' | '?' | '…' | '。' => {
384                let at_a_break = next.is_none_or(char::is_whitespace);
385                // `a.m.`, `e.g.`: one letter before the dot.
386                let short = character == '.' && {
387                    let word: String = sentence.chars().rev().take_while(|c| !c.is_whitespace()).collect();
388                    let word: String = word.chars().rev().collect::<String>().to_lowercase();
389                    let letters = word.chars().filter(|c| c.is_alphabetic()).count();
390                    let only_letters = word.chars().all(|c| c.is_alphabetic() || c == '.');
391                    (only_letters && (letters <= 1 || word.contains('.'))) || ABBREVIATIONS.contains(&word.as_str())
392                };
393                at_a_break && !short
394            }
395            _ => false,
396        };
397        if character != '\n' {
398            sentence.push(character);
399        }
400        if ends {
401            let mut gap = String::new();
402            if character == '\n' {
403                gap.push('\n');
404            }
405            while let Some(space) = characters.get(index + 1).copied().filter(|c| c.is_whitespace()) {
406                gap.push(space);
407                index += 1;
408            }
409            if !sentence.trim().is_empty() {
410                sentences.push((sentence.trim_start().to_owned(), gap));
411            } else if let Some((_, last_gap)) = sentences.last_mut() {
412                last_gap.push_str(&gap);
413            }
414            sentence = String::new();
415        }
416        index += 1;
417    }
418    if !sentence.trim().is_empty() {
419        sentences.push((sentence.trim_start().to_owned(), String::new()));
420    }
421    sentences
422}
423
424#[cfg(test)]
425mod tests;