Skip to main content

graphrt_llm/nodes/
grounding.rs

1//! `grounding` of the `llm` node: the answer is checked against its sources before it leaves.
2//!
3//! ```yaml
4//! - id: write_reply
5//!   type: llm
6//!   context: { enabled: true, variable_selector: [retrieve, result] }
7//!   grounding:
8//!     facts: [[sys, chatbot_facts], [lookup, body]]   # what the answer may state
9//!     customer: [[start, message]]                     # whose numbers it may repeat
10//!     fallback: "Sorry, I don't have that information yet."
11//!     confirm: model                                   # optional, see below
12//! ```
13//!
14//! The facts are the listed values (missing ones are skipped) and the node's own `context`
15//! (the knowledge passages it answers from). The prompt is not a source: a builder model may
16//! have written it, and a made-up fact in a prompt is still made up.
17//!
18//! The answer is checked by [`graphrt_core::grounding`]: sentences that state a number, a
19//! day, an address or words the sources do not hold are left out; when no sentence the facts
20//! hold is left, `text` is the `fallback` (a template) and `grounded` is `false`, for the
21//! workflow (or its host) to hand over. Answers are not streamed while grounding is on: only
22//! the checked text may reach anyone.
23//!
24//! `confirm: model` asks the node's model once more, and only when the words check left out a
25//! sentence (a paraphrase or another language can miss a true one): one short call, at
26//! temperature 0, that names the sentences the facts hold. Numbers, days and addresses are
27//! never left to it. Its usage is the node's.
28//!
29//! Outputs: `text`, `grounded` (bool), `unknown` (bool: the answer says it does not know
30//! something the customer asked, "I'm not sure about a vegan menu"; with nothing else it is the
31//! fallback too), `draft` (the model's answer as written),
32//! `unsupported` (`[{sentence, reason}]`), and with a confirming call `confirmed` (the sentences
33//! the model kept) and `check_usage` (its tokens).
34//!
35//! # Numbers only (`check: numbers`)
36//!
37//! A report may word its figures freely, but every figure must be one of the facts:
38//!
39//! ```yaml
40//! grounding:
41//!   facts: [[figures, json]]
42//!   check: numbers
43//!   numbers: { tolerance: rounding, ratios_as_percent: true }
44//!   on_fail: output                 # keep the draft and report, or `fallback` (the default)
45//! ```
46//!
47//! Every number of the answer is compared with the numbers of the facts by
48//! [`graphrt_core::grounding::figures`] (rounding, percentages and ratios, notations). With
49//! structured output every string of `structured_output` is checked, and each unsupported
50//! number is reported with the path of its field. Outputs: `grounded` (bool) and `unsupported`
51//! (`[{field, number, sentence}]`). With `on_fail: fallback` a text answer with an unsupported
52//! number becomes the `fallback` and `draft` keeps it; `on_fail: output` changes nothing.
53
54use graphrt_core::event::Usage;
55use graphrt_core::grounding::figures::{Figures, NumberRules, Tolerance};
56use graphrt_core::grounding::{Checked, Review, Sources, fact_sentences, shares_a_fact};
57use graphrt_core::template::Template;
58use graphrt_core::value::Value;
59use graphrt_core::{NodeContext, NodeError, Selector, VariablePool};
60use serde::Deserialize;
61
62use super::common::{ModelConfig, StreamMode, context_text, invoke};
63use crate::types::{ChatModel, Message};
64
65/// Whether a model may confirm sentences the words check left out.
66#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
67#[serde(rename_all = "snake_case")]
68#[non_exhaustive]
69pub enum Confirm {
70    /// The checks decide alone (no model call).
71    #[default]
72    Off,
73    /// The node's model is asked about the sentences the words check left out.
74    Model,
75}
76
77/// What the check reads.
78#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
79#[serde(rename_all = "snake_case")]
80#[non_exhaustive]
81pub enum Check {
82    /// A chat answer, sentence by sentence: numbers, days, addresses, words.
83    #[default]
84    Sentences,
85    /// Numbers only, in a text or in every string of a structured output.
86    Numbers,
87}
88
89/// What happens to an answer the check does not pass.
90#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
91#[serde(rename_all = "snake_case")]
92#[non_exhaustive]
93pub enum OnFail {
94    /// `text` is the `fallback` (with `check: sentences`, only when nothing the facts hold is left).
95    #[default]
96    Fallback,
97    /// The answer is kept as written: `grounded` and `unsupported` say what was found.
98    Output,
99}
100
101/// `numbers` of a `grounding` block: how numbers are compared.
102#[derive(Clone, Copy, Debug, Default, Deserialize)]
103#[serde(deny_unknown_fields)]
104pub struct NumbersConfig {
105    #[serde(default)]
106    tolerance: ToleranceConfig,
107    #[serde(default)]
108    ratios_as_percent: bool,
109}
110
111#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
112#[serde(rename_all = "snake_case")]
113enum ToleranceConfig {
114    #[default]
115    Rounding,
116    Exact,
117}
118
119impl NumbersConfig {
120    fn rules(self) -> NumberRules {
121        let tolerance = match self.tolerance {
122            ToleranceConfig::Rounding => Tolerance::Rounding,
123            ToleranceConfig::Exact => Tolerance::Exact,
124        };
125        NumberRules { tolerance, ratios_as_percent: self.ratios_as_percent }
126    }
127}
128
129/// The `grounding` block of an `llm` node.
130#[derive(Clone, Debug, Deserialize)]
131#[serde(deny_unknown_fields)]
132pub struct GroundingConfig {
133    /// Values the answer may state facts from.
134    #[serde(default)]
135    pub facts: Vec<Selector>,
136    /// Values the customer wrote: their numbers may be repeated, nothing else counts.
137    #[serde(default)]
138    pub customer: Vec<Selector>,
139    /// Template sent instead when nothing the facts hold is left (`on_fail: fallback`).
140    #[serde(default)]
141    pub fallback: Option<String>,
142    #[serde(default)]
143    pub confirm: Confirm,
144    #[serde(default)]
145    pub check: Check,
146    /// How numbers are compared (`check: numbers`).
147    #[serde(default)]
148    pub numbers: Option<NumbersConfig>,
149    #[serde(default)]
150    pub on_fail: OnFail,
151}
152
153/// What the numbers check found.
154pub(super) struct NumbersReport {
155    pub grounded: bool,
156    /// `[{field, number, sentence}]`.
157    pub unsupported: Value,
158}
159
160/// What the check made of an answer.
161pub(super) struct Grounded {
162    pub text: String,
163    pub grounded: bool,
164    /// The answer says it does not know something the customer asked.
165    pub admits_unknown: bool,
166    pub unsupported: Value,
167    /// The sentences the model confirmed (`confirm: model`).
168    pub confirmed: Vec<String>,
169    /// Tokens the confirming call spent, `None` without one.
170    pub usage: Option<Usage>,
171}
172
173impl GroundingConfig {
174    /// What is wrong with the block for a node with or without structured output.
175    pub(super) fn problem(&self, structured: bool) -> Option<&'static str> {
176        match (self.check, self.on_fail) {
177            (Check::Sentences, _) if structured => Some(
178                "`grounding` with `check: sentences` checks a text answer; with structured output use \
179                 `check: numbers` and `on_fail: output`",
180            ),
181            (Check::Sentences, OnFail::Output) => Some("`on_fail: output` goes with `check: numbers`"),
182            (Check::Numbers, OnFail::Fallback) if structured => {
183                Some("with structured output, `grounding` reports what it found: set `on_fail: output`")
184            }
185            _ if self.numbers.is_some() && self.check != Check::Numbers => Some("`numbers` goes with `check: numbers`"),
186            (_, OnFail::Fallback) if self.fallback.is_none() => Some(
187                "`grounding` needs a `fallback` (the text sent instead), or `check: numbers` with `on_fail: output`",
188            ),
189            (Check::Numbers, _) if self.confirm != Confirm::Off => Some("`confirm` goes with `check: sentences`"),
190            _ => None,
191        }
192    }
193
194    /// Whether the answer may stream: only when nothing the check finds can change it.
195    pub(super) fn keeps_the_answer(&self) -> bool {
196        self.on_fail == OnFail::Output
197    }
198
199    pub(super) fn checks_numbers(&self) -> bool {
200        self.check == Check::Numbers
201    }
202
203    pub(super) fn selectors(&self) -> Vec<Selector> {
204        let mut selectors: Vec<Selector> = self.facts.iter().chain(&self.customer).cloned().collect();
205        if let Some(fallback) = &self.fallback {
206            selectors.extend(Template::parse(fallback).selectors().cloned());
207        }
208        selectors
209    }
210
211    /// The numbers the facts (the listed values, the node's `context`) and the customer hold.
212    fn figures(&self, pool: &VariablePool, context: Option<&str>) -> Figures {
213        let mut figures = Figures::new();
214        for selector in self.facts.iter().chain(&self.customer) {
215            match pool.get(selector) {
216                Some(Value::String(text)) => figures.add_text(&text),
217                Some(value) => figures.add_json(&value.to_json()),
218                None => {}
219            }
220        }
221        if let Some(context) = context {
222            figures.add_text(context);
223        }
224        figures
225    }
226
227    /// The numbers check of `text` (`check: numbers`), reported under the field `text`.
228    pub(super) fn check_numbers_text(&self, pool: &VariablePool, context: Option<&str>, text: &str) -> NumbersReport {
229        let figures = self.figures(pool, context);
230        let mut found = Vec::new();
231        self.check_field(&figures, "text", text, &mut found);
232        NumbersReport { grounded: found.is_empty(), unsupported: Value::array(found) }
233    }
234
235    /// The numbers check of every string of a structured output, each reported by its path
236    /// (`summary`, `stores[2].note`).
237    pub(super) fn check_numbers_fields(
238        &self,
239        pool: &VariablePool,
240        context: Option<&str>,
241        output: &serde_json::Value,
242    ) -> NumbersReport {
243        let figures = self.figures(pool, context);
244        let mut found = Vec::new();
245        self.walk(&figures, String::new(), output, &mut found);
246        NumbersReport { grounded: found.is_empty(), unsupported: Value::array(found) }
247    }
248
249    fn walk(&self, figures: &Figures, path: String, value: &serde_json::Value, found: &mut Vec<Value>) {
250        match value {
251            serde_json::Value::String(text) => self.check_field(figures, &path, text, found),
252            serde_json::Value::Array(items) => {
253                for (index, item) in items.iter().enumerate() {
254                    self.walk(figures, format!("{path}[{index}]"), item, found);
255                }
256            }
257            serde_json::Value::Object(fields) => {
258                for (name, item) in fields {
259                    let path = if path.is_empty() { name.clone() } else { format!("{path}.{name}") };
260                    self.walk(figures, path, item, found);
261                }
262            }
263            _ => {}
264        }
265    }
266
267    fn check_field(&self, figures: &Figures, field: &str, text: &str, found: &mut Vec<Value>) {
268        let rules = self.numbers.unwrap_or_default().rules();
269        for unsupported in figures.unsupported(text, rules) {
270            found.push(Value::object([
271                ("field", Value::from(field)),
272                ("number", Value::from(unsupported.number)),
273                ("sentence", Value::from(unsupported.sentence)),
274            ]));
275        }
276    }
277
278    /// The `fallback`, rendered.
279    pub(super) fn fallback_text(&self, pool: &VariablePool) -> String {
280        self.fallback.as_deref().map(|fallback| Template::parse(fallback).render(pool)).unwrap_or_default()
281    }
282
283    fn sources(&self, pool: &VariablePool, context: Option<&str>) -> Sources {
284        let mut sources = Sources::new();
285        for selector in &self.facts {
286            if let Some(value) = pool.get(selector) {
287                sources.add_fact(context_text(&value));
288            }
289        }
290        if let Some(context) = context {
291            sources.add_fact(context);
292        }
293        for selector in &self.customer {
294            if let Some(value) = pool.get(selector) {
295                sources.add_customer(value.to_text());
296            }
297        }
298        sources
299    }
300
301    /// Checks `answer`; with `confirm: model`, asks `model` about the sentences the words
302    /// check left out.
303    pub(super) async fn check(
304        &self,
305        ctx: &NodeContext,
306        model: &dyn ChatModel,
307        model_config: &ModelConfig,
308        answer: &str,
309        context: Option<&str>,
310    ) -> Result<Grounded, NodeError> {
311        let sources = self.sources(&ctx.pool, context);
312        let mut review = Review::of(answer, &sources);
313        let mut usage = None;
314        let mut confirmed_sentences = Vec::new();
315        if self.confirm == Confirm::Model {
316            let to_verify: Vec<(usize, String)> =
317                review.to_verify().into_iter().map(|(index, sentence)| (index, sentence.to_owned())).collect();
318            if !to_verify.is_empty() {
319                let (confirmed, spent) = confirm(ctx, model, model_config, &sources, &to_verify).await?;
320                usage = Some(spent);
321                for index in confirmed {
322                    if let Some((_, sentence)) = to_verify.iter().find(|(asked, _)| *asked == index) {
323                        confirmed_sentences.push(sentence.clone());
324                    }
325                    review.confirm(index);
326                }
327            }
328        }
329        let Checked { text, unsupported, admits_unknown } = review.finish();
330        let unsupported = Value::array(unsupported.into_iter().map(|left_out| {
331            Value::object([
332                ("sentence", Value::from(left_out.sentence)),
333                ("reason", Value::from(left_out.reason.to_string())),
334            ])
335        }));
336        Ok(match text {
337            Some(text) => {
338                Grounded { text, grounded: true, admits_unknown, unsupported, confirmed: confirmed_sentences, usage }
339            }
340            None => {
341                let fallback = self.fallback_text(&ctx.pool);
342                Grounded {
343                    text: fallback,
344                    grounded: false,
345                    admits_unknown,
346                    unsupported,
347                    confirmed: confirmed_sentences,
348                    usage,
349                }
350            }
351        })
352    }
353}
354
355/// Most sentences one confirming call is asked about.
356const MOST_SENTENCES: usize = 8;
357
358/// Asks `model` which of `sentences` the facts hold. Returns their indexes and the usage.
359///
360/// The facts go to the model numbered, one sentence each, and it names the facts that say each
361/// sentence of the reply and whether they say ALL of it or only PART (`2. [5] ALL`), or `NONE`.
362/// A sentence counts as confirmed only when the facts say all of it and one of them shares a
363/// word, a number or an address with it ([`shares_a_fact`]): a "yes" is cheap for a small model
364/// to give, a fact that says the same thing in another language still shares a name, a number
365/// or a word ("menu", "WhatsApp", "45"). Naming numbers is shorter than quoting, and models
366/// translate quotes; asking for ALL or PART keeps a made-up detail next to a true one out
367/// ("Scaling is 300k and generally painless").
368async fn confirm(
369    ctx: &NodeContext,
370    model: &dyn ChatModel,
371    model_config: &ModelConfig,
372    sources: &Sources,
373    sentences: &[(usize, String)],
374) -> Result<(Vec<usize>, Usage), NodeError> {
375    let sentences = sentences.get(..MOST_SENTENCES).unwrap_or(sentences);
376    let facts = fact_sentences(sources);
377    let numbered_facts: Vec<String> =
378        facts.iter().enumerate().map(|(number, fact)| format!("[{}] {fact}", number + 1)).collect();
379    let numbered: Vec<String> =
380        sentences.iter().enumerate().map(|(number, (_, sentence))| format!("{}. {sentence}", number + 1)).collect();
381    let messages = vec![
382        Message::system(
383            "You check a chatbot's reply against the business's numbered facts. For each numbered sentence of \
384             the reply, name the facts that say what it says (in any language), then write ALL when they say \
385             everything the sentence states, or PART when the sentence also states something no fact says. Write \
386             NONE when no fact says it. What the customer wrote is not a fact. One line per sentence. \
387             Example:\n1. [4] ALL\n2. [2] PART\n3. NONE",
388        ),
389        Message::user(format!(
390            "Facts:\n{}\n\nThe customer wrote:\n{}\n\nSentences of the reply:\n{}",
391            numbered_facts.join("\n"),
392            sources.customer_text(),
393            numbered.join("\n")
394        )),
395    ];
396    let mut request = model_config.request(messages, &ctx.pool)?;
397    request.temperature = Some(0.0);
398    request.max_tokens = Some(u32::try_from(14 * sentences.len() + 16).unwrap_or(128));
399    request.response_format = None;
400    super::common::fit_budget(ctx, model_config, &mut request, false)?;
401    let response = invoke(ctx, model, request, StreamMode::Off).await?;
402    super::common::charge_model(ctx, &super::common::answered_by(model_config, &response), &response.usage)?;
403    let confirmed = named_facts(&response.text, sentences.len())
404        .into_iter()
405        .filter(|(number, named)| {
406            sentences.get(*number).is_some_and(|(_, sentence)| {
407                named.iter().filter_map(|fact| facts.get(*fact)).any(|fact| shares_a_fact(sentence, fact))
408            })
409        })
410        .filter_map(|(number, _)| sentences.get(number).map(|(index, _)| *index))
411        .collect();
412    Ok((confirmed, response.usage))
413}
414
415/// The facts (numbers from 0) an answer like "1. [3] ALL\n2. NONE\n3. [1], [4] ALL" says all of
416/// each sentence (numbers from 0, at most `count`). A line it cannot read, `NONE` or `PART`
417/// names none.
418fn named_facts(answer: &str, count: usize) -> Vec<(usize, Vec<usize>)> {
419    let mut named: Vec<(usize, Vec<usize>)> = Vec::new();
420    for line in answer.lines() {
421        let line = line.trim().trim_start_matches(['-', '*', ' ']);
422        let digits: String = line.chars().take_while(char::is_ascii_digit).collect();
423        let Ok(number) = digits.parse::<usize>() else { continue };
424        if !(1..=count).contains(&number) || named.iter().any(|(sentence, _)| *sentence == number - 1) {
425            continue;
426        }
427        let rest = line.get(digits.len()..).unwrap_or_default().to_lowercase();
428        let says_all = rest.split(|c: char| !c.is_alphabetic()).any(|word| word == "all");
429        if rest.contains("none") || rest.contains("part") || !says_all {
430            continue;
431        }
432        let facts: Vec<usize> = rest
433            .split(|c: char| !c.is_ascii_digit())
434            .filter_map(|digits| digits.parse::<usize>().ok())
435            .filter(|fact| *fact >= 1)
436            .map(|fact| fact - 1)
437            .collect();
438        if !facts.is_empty() {
439            named.push((number - 1, facts));
440        }
441    }
442    named
443}
444
445#[cfg(test)]
446mod tests {
447    use super::*;
448
449    #[test]
450    fn a_sentence_names_the_facts_that_say_it() {
451        assert_eq!(
452            named_facts("1. [3] ALL\n2. NONE\n3: [1], [4] all\n9. [2] ALL\n1. [5] ALL", 3),
453            [(0, vec![2]), (2, vec![0, 3])]
454        );
455        // Part of a sentence, or no word about it, confirms nothing.
456        assert!(named_facts("1. [2] PART\n2. [3]", 2).is_empty());
457        assert!(named_facts("I think all of the first one", 1).is_empty());
458    }
459}