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