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, reason}]`). With `on_fail: fallback` a text answer with an
52//! unsupported number becomes the `fallback` and `draft` keeps it; `on_fail: output` changes
53//! nothing; `on_fail: error` fails the node (for an `on_error` branch).
54//!
55//! # Attribution (`attribution`)
56//!
57//! A true number can still stand next to the wrong entity. With `attribution`, the facts are
58//! also grouped by entity, and every figure must stand next to an entity that holds it
59//! ([`graphrt_core::grounding::entities`]):
60//!
61//! ```yaml
62//! grounding:
63//!   facts: [[figures, json]]
64//!   check: numbers
65//!   attribution:
66//!     entities: [[prep, categories], { from: [figures, json, stores], label: name }]
67//!     groups: [all categories]            # group words that name no entity
68//!     scopes: { "stores[*].note": "{{#prep.top_store#}}" }   # or [prep, scopes]
69//!     skip: { integers_up_to: 10 }
70//!   on_fail: output
71//! ```
72//!
73//! A misattributed figure is reported in `unsupported` with `reason: attribution`, the entity
74//! the text gives it to (`named`) and the entities whose facts hold it (`owners`).
75
76use graphrt_core::event::Usage;
77use graphrt_core::grounding::figures::{Figures, NumberRules, Tolerance};
78use graphrt_core::grounding::{Checked, Review, Sources, fact_sentences, shares_a_fact};
79use graphrt_core::template::Template;
80use graphrt_core::value::Value;
81use graphrt_core::{NodeContext, NodeError, Selector, VariablePool};
82use serde::Deserialize;
83
84use super::common::{ModelConfig, StreamMode, context_text, invoke};
85#[cfg(feature = "grounding-attribution")]
86use super::grounding_attribution::{Attribution, AttributionConfig};
87#[cfg(not(feature = "grounding-attribution"))]
88use super::grounding_attribution_off::{Attribution, AttributionConfig};
89use crate::types::{ChatModel, Message};
90
91/// Whether a model may confirm sentences the words check left out.
92#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
93#[serde(rename_all = "snake_case")]
94#[non_exhaustive]
95pub enum Confirm {
96    /// The checks decide alone (no model call).
97    #[default]
98    Off,
99    /// The node's model is asked about the sentences the words check left out.
100    Model,
101}
102
103/// What the check reads.
104#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
105#[serde(rename_all = "snake_case")]
106#[non_exhaustive]
107pub enum Check {
108    /// A chat answer, sentence by sentence: numbers, days, addresses, words.
109    #[default]
110    Sentences,
111    /// Numbers only, in a text or in every string of a structured output.
112    Numbers,
113}
114
115/// What happens to an answer the check does not pass.
116#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
117#[serde(rename_all = "snake_case")]
118#[non_exhaustive]
119pub enum OnFail {
120    /// `text` is the `fallback` (with `check: sentences`, only when nothing the facts hold is left).
121    #[default]
122    Fallback,
123    /// The answer is kept as written: `grounded` and `unsupported` say what was found.
124    Output,
125    /// The node fails with the unsupported numbers (`check: numbers`), for an `on_error` branch.
126    Error,
127}
128
129/// `numbers` of a `grounding` block: how numbers are compared.
130#[derive(Clone, Copy, Debug, Default, Deserialize)]
131#[serde(deny_unknown_fields)]
132#[non_exhaustive]
133pub struct NumbersConfig {
134    #[serde(default)]
135    tolerance: ToleranceConfig,
136    #[serde(default)]
137    ratios_as_percent: bool,
138}
139
140#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
141#[serde(rename_all = "snake_case")]
142enum ToleranceConfig {
143    #[default]
144    Rounding,
145    Exact,
146}
147
148impl NumbersConfig {
149    fn rules(self) -> NumberRules {
150        let tolerance = match self.tolerance {
151            ToleranceConfig::Rounding => Tolerance::Rounding,
152            ToleranceConfig::Exact => Tolerance::Exact,
153        };
154        NumberRules { tolerance, ratios_as_percent: self.ratios_as_percent }
155    }
156}
157
158/// The `grounding` block of an `llm` node.
159#[derive(Clone, Debug, Deserialize)]
160#[serde(deny_unknown_fields)]
161#[non_exhaustive]
162pub struct GroundingConfig {
163    /// Values the answer may state facts from.
164    #[serde(default)]
165    pub facts: Vec<Selector>,
166    /// Values the customer wrote: their numbers may be repeated, nothing else counts.
167    #[serde(default)]
168    pub customer: Vec<Selector>,
169    /// Template sent instead when nothing the facts hold is left (`on_fail: fallback`).
170    #[serde(default)]
171    pub fallback: Option<String>,
172    #[serde(default)]
173    pub confirm: Confirm,
174    #[serde(default)]
175    pub check: Check,
176    /// How numbers are compared (`check: numbers`).
177    #[serde(default)]
178    pub numbers: Option<NumbersConfig>,
179    /// Every figure must stand next to an entity that holds it (`check: numbers`).
180    #[serde(default)]
181    pub attribution: Option<AttributionConfig>,
182    #[serde(default)]
183    pub on_fail: OnFail,
184}
185
186/// What the numbers check found.
187pub(super) struct NumbersReport {
188    pub grounded: bool,
189    /// `[{field, number, sentence, reason}]`, and `named` and `owners` for `reason: attribution`.
190    pub unsupported: Value,
191}
192
193/// What the check made of an answer.
194pub(super) struct Grounded {
195    pub text: String,
196    pub grounded: bool,
197    /// The answer says it does not know something the customer asked.
198    pub admits_unknown: bool,
199    pub unsupported: Value,
200    /// The sentences the model confirmed (`confirm: model`).
201    pub confirmed: Vec<String>,
202    /// Tokens the confirming call spent, `None` without one.
203    pub usage: Option<Usage>,
204}
205
206impl GroundingConfig {
207    /// What is wrong with the block for a node with or without structured output.
208    pub(super) fn problem(&self, structured: bool) -> Option<&'static str> {
209        match (self.check, self.on_fail) {
210            (Check::Sentences, _) if structured => Some(
211                "`grounding` with `check: sentences` checks a text answer; with structured output use \
212                 `check: numbers` and `on_fail: output`",
213            ),
214            (Check::Sentences, OnFail::Output) => Some("`on_fail: output` goes with `check: numbers`"),
215            (Check::Sentences, OnFail::Error) => Some("`on_fail: error` goes with `check: numbers`"),
216            (Check::Numbers, OnFail::Fallback) if structured => {
217                Some("with structured output, `grounding` reports what it found: set `on_fail: output` (or `error`)")
218            }
219            _ if self.numbers.is_some() && self.check != Check::Numbers => Some("`numbers` goes with `check: numbers`"),
220            _ if self.attribution.is_some() && self.check != Check::Numbers => {
221                Some("`attribution` goes with `check: numbers`")
222            }
223            _ if self.attribution.as_ref().and_then(AttributionConfig::problem).is_some() => {
224                self.attribution.as_ref().and_then(AttributionConfig::problem)
225            }
226            (_, OnFail::Fallback) if self.fallback.is_none() => Some(
227                "`grounding` needs a `fallback` (the text sent instead), or `check: numbers` with `on_fail: output`",
228            ),
229            (Check::Numbers, _) if self.confirm != Confirm::Off => Some("`confirm` goes with `check: sentences`"),
230            _ => None,
231        }
232    }
233
234    /// Whether the answer may stream: only when nothing the check finds can change it.
235    pub(super) fn keeps_the_answer(&self) -> bool {
236        self.on_fail == OnFail::Output
237    }
238
239    pub(super) fn checks_numbers(&self) -> bool {
240        self.check == Check::Numbers
241    }
242
243    /// Whether an answer the check does not pass fails the node.
244    pub(super) fn fails_the_node(&self) -> bool {
245        self.on_fail == OnFail::Error
246    }
247
248    pub(super) fn selectors(&self) -> Vec<Selector> {
249        let mut selectors: Vec<Selector> = self.facts.iter().chain(&self.customer).cloned().collect();
250        if let Some(fallback) = &self.fallback {
251            selectors.extend(Template::parse(fallback).selectors().cloned());
252        }
253        if let Some(attribution) = &self.attribution {
254            selectors.extend(attribution.selectors());
255        }
256        selectors
257    }
258
259    /// The entities and scopes of `attribution`, read from the pool.
260    fn attribution(&self, pool: &VariablePool) -> Result<Option<Attribution>, NodeError> {
261        let Some(config) = &self.attribution else { return Ok(None) };
262        config.read(pool, self.numbers.unwrap_or_default().rules()).map(Some)
263    }
264
265    /// The numbers the facts (the listed values, the entities of `attribution`, the node's
266    /// `context`) and the customer hold.
267    fn figures(&self, pool: &VariablePool, context: Option<&str>) -> Figures {
268        let mut figures = Figures::new();
269        let entities = self.attribution.iter().flat_map(AttributionConfig::entity_selectors);
270        for selector in self.facts.iter().chain(&self.customer).chain(entities) {
271            match pool.get(selector) {
272                Some(Value::String(text)) => figures.add_text(&text),
273                Some(value) => figures.add_json(&value.to_json()),
274                None => {}
275            }
276        }
277        if let Some(context) = context {
278            figures.add_text(context);
279        }
280        figures
281    }
282
283    /// The numbers check of `text` (`check: numbers`), reported under the field `text`.
284    pub(super) fn check_numbers_text(
285        &self,
286        pool: &VariablePool,
287        context: Option<&str>,
288        text: &str,
289    ) -> Result<NumbersReport, NodeError> {
290        let figures = self.figures(pool, context);
291        let attribution = self.attribution(pool)?;
292        let mut found = Vec::new();
293        self.check_field(&figures, attribution.as_ref(), "text", text, &mut found);
294        Ok(NumbersReport { grounded: found.is_empty(), unsupported: Value::array(found) })
295    }
296
297    /// The numbers check of every string of a structured output, each reported by its path
298    /// (`summary`, `stores[2].note`).
299    pub(super) fn check_numbers_fields(
300        &self,
301        pool: &VariablePool,
302        context: Option<&str>,
303        output: &serde_json::Value,
304    ) -> Result<NumbersReport, NodeError> {
305        let figures = self.figures(pool, context);
306        let attribution = self.attribution(pool)?;
307        let mut found = Vec::new();
308        self.walk(&figures, attribution.as_ref(), String::new(), output, &mut found);
309        Ok(NumbersReport { grounded: found.is_empty(), unsupported: Value::array(found) })
310    }
311
312    fn walk(
313        &self,
314        figures: &Figures,
315        attribution: Option<&Attribution>,
316        path: String,
317        value: &serde_json::Value,
318        found: &mut Vec<Value>,
319    ) {
320        match value {
321            serde_json::Value::String(text) => self.check_field(figures, attribution, &path, text, found),
322            serde_json::Value::Array(items) => {
323                for (index, item) in items.iter().enumerate() {
324                    self.walk(figures, attribution, format!("{path}[{index}]"), item, found);
325                }
326            }
327            serde_json::Value::Object(fields) => {
328                for (name, item) in fields {
329                    let path = if path.is_empty() { name.clone() } else { format!("{path}.{name}") };
330                    self.walk(figures, attribution, path, item, found);
331                }
332            }
333            _ => {}
334        }
335    }
336
337    fn check_field(
338        &self,
339        figures: &Figures,
340        attribution: Option<&Attribution>,
341        field: &str,
342        text: &str,
343        found: &mut Vec<Value>,
344    ) {
345        let rules = self.numbers.unwrap_or_default().rules();
346        for unsupported in figures.unsupported(text, rules) {
347            found.push(Value::object([
348                ("field", Value::from(field)),
349                ("number", Value::from(unsupported.number)),
350                ("sentence", Value::from(unsupported.sentence)),
351                ("reason", Value::from("value")),
352            ]));
353        }
354        if let Some(attribution) = attribution {
355            attribution.findings(field, text, found);
356        }
357    }
358
359    /// The error of a node whose answer the numbers check did not pass (`on_fail: error`): the
360    /// `unsupported` items, as JSON.
361    pub(super) fn failure(report: &NumbersReport) -> NodeError {
362        NodeError::new(
363            "ungrounded",
364            format!("the answer states numbers the facts do not support: {}", report.unsupported.to_json()),
365        )
366    }
367
368    /// The `fallback`, rendered.
369    pub(super) fn fallback_text(&self, pool: &VariablePool) -> String {
370        self.fallback.as_deref().map(|fallback| Template::parse(fallback).render(pool)).unwrap_or_default()
371    }
372
373    fn sources(&self, pool: &VariablePool, context: Option<&str>) -> Sources {
374        let mut sources = Sources::new();
375        for selector in &self.facts {
376            if let Some(value) = pool.get(selector) {
377                sources.add_fact(context_text(&value));
378            }
379        }
380        if let Some(context) = context {
381            sources.add_fact(context);
382        }
383        for selector in &self.customer {
384            if let Some(value) = pool.get(selector) {
385                sources.add_customer(value.to_text());
386            }
387        }
388        sources
389    }
390
391    /// Checks `answer`; with `confirm: model`, asks `model` about the sentences the words
392    /// check left out.
393    pub(super) async fn check(
394        &self,
395        ctx: &NodeContext,
396        model: &dyn ChatModel,
397        model_config: &ModelConfig,
398        answer: &str,
399        context: Option<&str>,
400    ) -> Result<Grounded, NodeError> {
401        let sources = self.sources(&ctx.pool, context);
402        let mut review = Review::of(answer, &sources);
403        let mut usage = None;
404        let mut confirmed_sentences = Vec::new();
405        if self.confirm == Confirm::Model {
406            let to_verify: Vec<(usize, String)> =
407                review.to_verify().into_iter().map(|(index, sentence)| (index, sentence.to_owned())).collect();
408            if !to_verify.is_empty() {
409                let (confirmed, spent) = confirm(ctx, model, model_config, &sources, &to_verify).await?;
410                usage = Some(spent);
411                for index in confirmed {
412                    if let Some((_, sentence)) = to_verify.iter().find(|(asked, _)| *asked == index) {
413                        confirmed_sentences.push(sentence.clone());
414                    }
415                    review.confirm(index);
416                }
417            }
418        }
419        let Checked { text, unsupported, admits_unknown } = review.finish();
420        let unsupported = Value::array(unsupported.into_iter().map(|left_out| {
421            Value::object([
422                ("sentence", Value::from(left_out.sentence)),
423                ("reason", Value::from(left_out.reason.to_string())),
424            ])
425        }));
426        Ok(match text {
427            Some(text) => {
428                Grounded { text, grounded: true, admits_unknown, unsupported, confirmed: confirmed_sentences, usage }
429            }
430            None => {
431                let fallback = self.fallback_text(&ctx.pool);
432                Grounded {
433                    text: fallback,
434                    grounded: false,
435                    admits_unknown,
436                    unsupported,
437                    confirmed: confirmed_sentences,
438                    usage,
439                }
440            }
441        })
442    }
443}
444
445/// Most sentences one confirming call is asked about.
446const MOST_SENTENCES: usize = 8;
447
448/// Asks `model` which of `sentences` the facts hold. Returns their indexes and the usage.
449///
450/// The facts go to the model numbered, one sentence each, and it names the facts that say each
451/// sentence of the reply and whether they say ALL of it or only PART (`2. [5] ALL`), or `NONE`.
452/// A sentence counts as confirmed only when the facts say all of it and one of them shares a
453/// word, a number or an address with it ([`shares_a_fact`]): a "yes" is cheap for a small model
454/// to give, a fact that says the same thing in another language still shares a name, a number
455/// or a word ("menu", "WhatsApp", "45"). Naming numbers is shorter than quoting, and models
456/// translate quotes; asking for ALL or PART keeps a made-up detail next to a true one out
457/// ("Scaling is 300k and generally painless").
458async fn confirm(
459    ctx: &NodeContext,
460    model: &dyn ChatModel,
461    model_config: &ModelConfig,
462    sources: &Sources,
463    sentences: &[(usize, String)],
464) -> Result<(Vec<usize>, Usage), NodeError> {
465    let sentences = sentences.get(..MOST_SENTENCES).unwrap_or(sentences);
466    let facts = fact_sentences(sources);
467    let numbered_facts: Vec<String> =
468        facts.iter().enumerate().map(|(number, fact)| format!("[{}] {fact}", number + 1)).collect();
469    let numbered: Vec<String> =
470        sentences.iter().enumerate().map(|(number, (_, sentence))| format!("{}. {sentence}", number + 1)).collect();
471    let messages = vec![
472        Message::system(
473            "You check a chatbot's reply against the business's numbered facts. For each numbered sentence of \
474             the reply, name the facts that say what it says (in any language), then write ALL when they say \
475             everything the sentence states, or PART when the sentence also states something no fact says. Write \
476             NONE when no fact says it. What the customer wrote is not a fact. One line per sentence. \
477             Example:\n1. [4] ALL\n2. [2] PART\n3. NONE",
478        ),
479        Message::user(format!(
480            "Facts:\n{}\n\nThe customer wrote:\n{}\n\nSentences of the reply:\n{}",
481            numbered_facts.join("\n"),
482            sources.customer_text(),
483            numbered.join("\n")
484        )),
485    ];
486    let mut request = model_config.request(messages, &ctx.pool)?;
487    request.temperature = Some(0.0);
488    request.max_tokens = Some(u32::try_from(14 * sentences.len() + 16).unwrap_or(128));
489    request.response_format = None;
490    super::common::fit_budget(ctx, model_config, &mut request, false)?;
491    let response = invoke(ctx, model, request, StreamMode::Off).await?;
492    super::common::charge_model(ctx, &super::common::answered_by(model_config, &response), &response.usage)?;
493    let confirmed = named_facts(&response.text, sentences.len())
494        .into_iter()
495        .filter(|(number, named)| {
496            sentences.get(*number).is_some_and(|(_, sentence)| {
497                named.iter().filter_map(|fact| facts.get(*fact)).any(|fact| shares_a_fact(sentence, fact))
498            })
499        })
500        .filter_map(|(number, _)| sentences.get(number).map(|(index, _)| *index))
501        .collect();
502    Ok((confirmed, response.usage))
503}
504
505/// The facts (numbers from 0) an answer like "1. [3] ALL\n2. NONE\n3. [1], [4] ALL" says all of
506/// each sentence (numbers from 0, at most `count`). A line it cannot read, `NONE` or `PART`
507/// names none.
508fn named_facts(answer: &str, count: usize) -> Vec<(usize, Vec<usize>)> {
509    let mut named: Vec<(usize, Vec<usize>)> = Vec::new();
510    for line in answer.lines() {
511        let line = line.trim().trim_start_matches(['-', '*', ' ']);
512        let digits: String = line.chars().take_while(char::is_ascii_digit).collect();
513        let Ok(number) = digits.parse::<usize>() else { continue };
514        if !(1..=count).contains(&number) || named.iter().any(|(sentence, _)| *sentence == number - 1) {
515            continue;
516        }
517        let rest = line.get(digits.len()..).unwrap_or_default().to_lowercase();
518        let says_all = rest.split(|c: char| !c.is_alphabetic()).any(|word| word == "all");
519        if rest.contains("none") || rest.contains("part") || !says_all {
520            continue;
521        }
522        let facts: Vec<usize> = rest
523            .split(|c: char| !c.is_ascii_digit())
524            .filter_map(|digits| digits.parse::<usize>().ok())
525            .filter(|fact| *fact >= 1)
526            .map(|fact| fact - 1)
527            .collect();
528        if !facts.is_empty() {
529            named.push((number - 1, facts));
530        }
531    }
532    named
533}
534
535#[cfg(test)]
536mod tests {
537    use super::*;
538
539    #[test]
540    fn a_sentence_names_the_facts_that_say_it() {
541        assert_eq!(
542            named_facts("1. [3] ALL\n2. NONE\n3: [1], [4] all\n9. [2] ALL\n1. [5] ALL", 3),
543            [(0, vec![2]), (2, vec![0, 3])]
544        );
545        // Part of a sentence, or no word about it, confirms nothing.
546        assert!(named_facts("1. [2] PART\n2. [3]", 2).is_empty());
547        assert!(named_facts("I think all of the first one", 1).is_empty());
548    }
549}