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
35use graphrt_core::event::Usage;
36use graphrt_core::grounding::{Checked, Review, Sources, fact_sentences, shares_a_fact};
37use graphrt_core::template::Template;
38use graphrt_core::value::Value;
39use graphrt_core::{NodeContext, NodeError, Selector, VariablePool};
40use serde::Deserialize;
41
42use super::common::{ModelConfig, StreamMode, context_text, invoke};
43use crate::types::{ChatModel, Message};
44
45/// Whether a model may confirm sentences the words check left out.
46#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
47#[serde(rename_all = "snake_case")]
48#[non_exhaustive]
49pub enum Confirm {
50    /// The checks decide alone (no model call).
51    #[default]
52    Off,
53    /// The node's model is asked about the sentences the words check left out.
54    Model,
55}
56
57/// The `grounding` block of an `llm` node.
58#[derive(Clone, Debug, Deserialize)]
59#[serde(deny_unknown_fields)]
60pub struct GroundingConfig {
61    /// Values the answer may state facts from.
62    #[serde(default)]
63    pub facts: Vec<Selector>,
64    /// Values the customer wrote: their numbers may be repeated, nothing else counts.
65    #[serde(default)]
66    pub customer: Vec<Selector>,
67    /// Template sent instead when nothing the facts hold is left.
68    pub fallback: String,
69    #[serde(default)]
70    pub confirm: Confirm,
71}
72
73/// What the check made of an answer.
74pub(super) struct Grounded {
75    pub text: String,
76    pub grounded: bool,
77    /// The answer says it does not know something the customer asked.
78    pub admits_unknown: bool,
79    pub unsupported: Value,
80    /// The sentences the model confirmed (`confirm: model`).
81    pub confirmed: Vec<String>,
82    /// Tokens the confirming call spent, `None` without one.
83    pub usage: Option<Usage>,
84}
85
86impl GroundingConfig {
87    pub(super) fn selectors(&self) -> Vec<Selector> {
88        let mut selectors: Vec<Selector> = self.facts.iter().chain(&self.customer).cloned().collect();
89        selectors.extend(Template::parse(&self.fallback).selectors().cloned());
90        selectors
91    }
92
93    fn sources(&self, pool: &VariablePool, context: Option<&str>) -> Sources {
94        let mut sources = Sources::new();
95        for selector in &self.facts {
96            if let Some(value) = pool.get(selector) {
97                sources.add_fact(context_text(&value));
98            }
99        }
100        if let Some(context) = context {
101            sources.add_fact(context);
102        }
103        for selector in &self.customer {
104            if let Some(value) = pool.get(selector) {
105                sources.add_customer(value.to_text());
106            }
107        }
108        sources
109    }
110
111    /// Checks `answer`; with `confirm: model`, asks `model` about the sentences the words
112    /// check left out.
113    pub(super) async fn check(
114        &self,
115        ctx: &NodeContext,
116        model: &dyn ChatModel,
117        model_config: &ModelConfig,
118        answer: &str,
119        context: Option<&str>,
120    ) -> Result<Grounded, NodeError> {
121        let sources = self.sources(&ctx.pool, context);
122        let mut review = Review::of(answer, &sources);
123        let mut usage = None;
124        let mut confirmed_sentences = Vec::new();
125        if self.confirm == Confirm::Model {
126            let to_verify: Vec<(usize, String)> =
127                review.to_verify().into_iter().map(|(index, sentence)| (index, sentence.to_owned())).collect();
128            if !to_verify.is_empty() {
129                let (confirmed, spent) = confirm(ctx, model, model_config, &sources, &to_verify).await?;
130                usage = Some(spent);
131                for index in confirmed {
132                    if let Some((_, sentence)) = to_verify.iter().find(|(asked, _)| *asked == index) {
133                        confirmed_sentences.push(sentence.clone());
134                    }
135                    review.confirm(index);
136                }
137            }
138        }
139        let Checked { text, unsupported, admits_unknown } = review.finish();
140        let unsupported = Value::array(unsupported.into_iter().map(|left_out| {
141            Value::object([
142                ("sentence", Value::from(left_out.sentence)),
143                ("reason", Value::from(left_out.reason.to_string())),
144            ])
145        }));
146        Ok(match text {
147            Some(text) => {
148                Grounded { text, grounded: true, admits_unknown, unsupported, confirmed: confirmed_sentences, usage }
149            }
150            None => {
151                let fallback = Template::parse(&self.fallback).render(&ctx.pool);
152                Grounded {
153                    text: fallback,
154                    grounded: false,
155                    admits_unknown,
156                    unsupported,
157                    confirmed: confirmed_sentences,
158                    usage,
159                }
160            }
161        })
162    }
163}
164
165/// Most sentences one confirming call is asked about.
166const MOST_SENTENCES: usize = 8;
167
168/// Asks `model` which of `sentences` the facts hold. Returns their indexes and the usage.
169///
170/// The facts go to the model numbered, one sentence each, and it names the facts that say each
171/// sentence of the reply and whether they say ALL of it or only PART (`2. [5] ALL`), or `NONE`.
172/// A sentence counts as confirmed only when the facts say all of it and one of them shares a
173/// word, a number or an address with it ([`shares_a_fact`]): a "yes" is cheap for a small model
174/// to give, a fact that says the same thing in another language still shares a name, a number
175/// or a word ("menu", "WhatsApp", "45"). Naming numbers is shorter than quoting, and models
176/// translate quotes; asking for ALL or PART keeps a made-up detail next to a true one out
177/// ("Scaling is 300k and generally painless").
178async fn confirm(
179    ctx: &NodeContext,
180    model: &dyn ChatModel,
181    model_config: &ModelConfig,
182    sources: &Sources,
183    sentences: &[(usize, String)],
184) -> Result<(Vec<usize>, Usage), NodeError> {
185    let sentences = sentences.get(..MOST_SENTENCES).unwrap_or(sentences);
186    let facts = fact_sentences(sources);
187    let numbered_facts: Vec<String> =
188        facts.iter().enumerate().map(|(number, fact)| format!("[{}] {fact}", number + 1)).collect();
189    let numbered: Vec<String> =
190        sentences.iter().enumerate().map(|(number, (_, sentence))| format!("{}. {sentence}", number + 1)).collect();
191    let messages = vec![
192        Message::system(
193            "You check a chatbot's reply against the business's numbered facts. For each numbered sentence of \
194             the reply, name the facts that say what it says (in any language), then write ALL when they say \
195             everything the sentence states, or PART when the sentence also states something no fact says. Write \
196             NONE when no fact says it. What the customer wrote is not a fact. One line per sentence. \
197             Example:\n1. [4] ALL\n2. [2] PART\n3. NONE",
198        ),
199        Message::user(format!(
200            "Facts:\n{}\n\nThe customer wrote:\n{}\n\nSentences of the reply:\n{}",
201            numbered_facts.join("\n"),
202            sources.customer_text(),
203            numbered.join("\n")
204        )),
205    ];
206    let mut request = model_config.request(messages, &ctx.pool)?;
207    request.temperature = Some(0.0);
208    request.max_tokens = Some(u32::try_from(14 * sentences.len() + 16).unwrap_or(128));
209    request.response_format = None;
210    super::common::fit_budget(ctx, model_config, &mut request, false)?;
211    let response = invoke(ctx, model, request, StreamMode::Off).await?;
212    super::common::charge_model(ctx, model_config, &response.usage)?;
213    let confirmed = named_facts(&response.text, sentences.len())
214        .into_iter()
215        .filter(|(number, named)| {
216            sentences.get(*number).is_some_and(|(_, sentence)| {
217                named.iter().filter_map(|fact| facts.get(*fact)).any(|fact| shares_a_fact(sentence, fact))
218            })
219        })
220        .filter_map(|(number, _)| sentences.get(number).map(|(index, _)| *index))
221        .collect();
222    Ok((confirmed, response.usage))
223}
224
225/// The facts (numbers from 0) an answer like "1. [3] ALL\n2. NONE\n3. [1], [4] ALL" says all of
226/// each sentence (numbers from 0, at most `count`). A line it cannot read, `NONE` or `PART`
227/// names none.
228fn named_facts(answer: &str, count: usize) -> Vec<(usize, Vec<usize>)> {
229    let mut named: Vec<(usize, Vec<usize>)> = Vec::new();
230    for line in answer.lines() {
231        let line = line.trim().trim_start_matches(['-', '*', ' ']);
232        let digits: String = line.chars().take_while(char::is_ascii_digit).collect();
233        let Ok(number) = digits.parse::<usize>() else { continue };
234        if !(1..=count).contains(&number) || named.iter().any(|(sentence, _)| *sentence == number - 1) {
235            continue;
236        }
237        let rest = line.get(digits.len()..).unwrap_or_default().to_lowercase();
238        let says_all = rest.split(|c: char| !c.is_alphabetic()).any(|word| word == "all");
239        if rest.contains("none") || rest.contains("part") || !says_all {
240            continue;
241        }
242        let facts: Vec<usize> = rest
243            .split(|c: char| !c.is_ascii_digit())
244            .filter_map(|digits| digits.parse::<usize>().ok())
245            .filter(|fact| *fact >= 1)
246            .map(|fact| fact - 1)
247            .collect();
248        if !facts.is_empty() {
249            named.push((number - 1, facts));
250        }
251    }
252    named
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258
259    #[test]
260    fn a_sentence_names_the_facts_that_say_it() {
261        assert_eq!(
262            named_facts("1. [3] ALL\n2. NONE\n3: [1], [4] all\n9. [2] ALL\n1. [5] ALL", 3),
263            [(0, vec![2]), (2, vec![0, 3])]
264        );
265        // Part of a sentence, or no word about it, confirms nothing.
266        assert!(named_facts("1. [2] PART\n2. [3]", 2).is_empty());
267        assert!(named_facts("I think all of the first one", 1).is_empty());
268    }
269}