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