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