graphrt-llm 0.7.0

Model providers (OpenAI-compatible, Anthropic, Gemini, AWS Bedrock, TypeSafe Jev) and LLM, classifier, extractor and agent nodes for the graphrt workflow runtime.
Documentation
//! `grounding` of the `llm` node: the answer is checked against its sources before it leaves.
//!
//! ```yaml
//! - id: write_reply
//!   type: llm
//!   context: { enabled: true, variable_selector: [retrieve, result] }
//!   grounding:
//!     facts: [[sys, chatbot_facts], [lookup, body]]   # what the answer may state
//!     customer: [[start, message]]                     # whose numbers it may repeat
//!     fallback: "Sorry, I don't have that information yet."
//!     confirm: model                                   # optional, see below
//! ```
//!
//! The facts are the listed values (missing ones are skipped) and the node's own `context`
//! (the knowledge passages it answers from). The prompt is not a source: a builder model may
//! have written it, and a made-up fact in a prompt is still made up.
//!
//! The answer is checked by [`graphrt_core::grounding`]: sentences that state a number, a
//! day, an address or words the sources do not hold are left out; when no sentence the facts
//! hold is left, `text` is the `fallback` (a template) and `grounded` is `false`, for the
//! workflow (or its host) to hand over. Answers are not streamed while grounding is on: only
//! the checked text may reach anyone.
//!
//! `confirm: model` asks the node's model once more, and only when the words check left out a
//! sentence (a paraphrase or another language can miss a true one): one short call, at
//! temperature 0, that names the sentences the facts hold. Numbers, days and addresses are
//! never left to it. Its usage is the node's.
//!
//! Outputs: `text`, `grounded` (bool), `unknown` (bool: the answer says it does not know
//! something the customer asked, "I'm not sure about a vegan menu"; with nothing else it is the
//! fallback too), `draft` (the model's answer as written),
//! `unsupported` (`[{sentence, reason}]`), and with a confirming call `confirmed` (the sentences
//! the model kept) and `check_usage` (its tokens).

use graphrt_core::event::Usage;
use graphrt_core::grounding::{Checked, Review, Sources, fact_sentences, shares_a_fact};
use graphrt_core::template::Template;
use graphrt_core::value::Value;
use graphrt_core::{NodeContext, NodeError, Selector, VariablePool};
use serde::Deserialize;

use super::common::{ModelConfig, StreamMode, context_text, invoke};
use crate::types::{ChatModel, Message};

/// Whether a model may confirm sentences the words check left out.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Confirm {
    /// The checks decide alone (no model call).
    #[default]
    Off,
    /// The node's model is asked about the sentences the words check left out.
    Model,
}

/// The `grounding` block of an `llm` node.
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GroundingConfig {
    /// Values the answer may state facts from.
    #[serde(default)]
    pub facts: Vec<Selector>,
    /// Values the customer wrote: their numbers may be repeated, nothing else counts.
    #[serde(default)]
    pub customer: Vec<Selector>,
    /// Template sent instead when nothing the facts hold is left.
    pub fallback: String,
    #[serde(default)]
    pub confirm: Confirm,
}

/// What the check made of an answer.
pub(super) struct Grounded {
    pub text: String,
    pub grounded: bool,
    /// The answer says it does not know something the customer asked.
    pub admits_unknown: bool,
    pub unsupported: Value,
    /// The sentences the model confirmed (`confirm: model`).
    pub confirmed: Vec<String>,
    /// Tokens the confirming call spent, `None` without one.
    pub usage: Option<Usage>,
}

impl GroundingConfig {
    pub(super) fn selectors(&self) -> Vec<Selector> {
        let mut selectors: Vec<Selector> = self.facts.iter().chain(&self.customer).cloned().collect();
        selectors.extend(Template::parse(&self.fallback).selectors().cloned());
        selectors
    }

    fn sources(&self, pool: &VariablePool, context: Option<&str>) -> Sources {
        let mut sources = Sources::new();
        for selector in &self.facts {
            if let Some(value) = pool.get(selector) {
                sources.add_fact(context_text(&value));
            }
        }
        if let Some(context) = context {
            sources.add_fact(context);
        }
        for selector in &self.customer {
            if let Some(value) = pool.get(selector) {
                sources.add_customer(value.to_text());
            }
        }
        sources
    }

    /// Checks `answer`; with `confirm: model`, asks `model` about the sentences the words
    /// check left out.
    pub(super) async fn check(
        &self,
        ctx: &NodeContext,
        model: &dyn ChatModel,
        model_config: &ModelConfig,
        answer: &str,
        context: Option<&str>,
    ) -> Result<Grounded, NodeError> {
        let sources = self.sources(&ctx.pool, context);
        let mut review = Review::of(answer, &sources);
        let mut usage = None;
        let mut confirmed_sentences = Vec::new();
        if self.confirm == Confirm::Model {
            let to_verify: Vec<(usize, String)> =
                review.to_verify().into_iter().map(|(index, sentence)| (index, sentence.to_owned())).collect();
            if !to_verify.is_empty() {
                let (confirmed, spent) = confirm(ctx, model, model_config, &sources, &to_verify).await?;
                usage = Some(spent);
                for index in confirmed {
                    if let Some((_, sentence)) = to_verify.iter().find(|(asked, _)| *asked == index) {
                        confirmed_sentences.push(sentence.clone());
                    }
                    review.confirm(index);
                }
            }
        }
        let Checked { text, unsupported, admits_unknown } = review.finish();
        let unsupported = Value::array(unsupported.into_iter().map(|left_out| {
            Value::object([
                ("sentence", Value::from(left_out.sentence)),
                ("reason", Value::from(left_out.reason.to_string())),
            ])
        }));
        Ok(match text {
            Some(text) => {
                Grounded { text, grounded: true, admits_unknown, unsupported, confirmed: confirmed_sentences, usage }
            }
            None => {
                let fallback = Template::parse(&self.fallback).render(&ctx.pool);
                Grounded {
                    text: fallback,
                    grounded: false,
                    admits_unknown,
                    unsupported,
                    confirmed: confirmed_sentences,
                    usage,
                }
            }
        })
    }
}

/// Most sentences one confirming call is asked about.
const MOST_SENTENCES: usize = 8;

/// Asks `model` which of `sentences` the facts hold. Returns their indexes and the usage.
///
/// The facts go to the model numbered, one sentence each, and it names the facts that say each
/// sentence of the reply and whether they say ALL of it or only PART (`2. [5] ALL`), or `NONE`.
/// A sentence counts as confirmed only when the facts say all of it and one of them shares a
/// word, a number or an address with it ([`shares_a_fact`]): a "yes" is cheap for a small model
/// to give, a fact that says the same thing in another language still shares a name, a number
/// or a word ("menu", "WhatsApp", "45"). Naming numbers is shorter than quoting, and models
/// translate quotes; asking for ALL or PART keeps a made-up detail next to a true one out
/// ("Scaling is 300k and generally painless").
async fn confirm(
    ctx: &NodeContext,
    model: &dyn ChatModel,
    model_config: &ModelConfig,
    sources: &Sources,
    sentences: &[(usize, String)],
) -> Result<(Vec<usize>, Usage), NodeError> {
    let sentences = sentences.get(..MOST_SENTENCES).unwrap_or(sentences);
    let facts = fact_sentences(sources);
    let numbered_facts: Vec<String> =
        facts.iter().enumerate().map(|(number, fact)| format!("[{}] {fact}", number + 1)).collect();
    let numbered: Vec<String> =
        sentences.iter().enumerate().map(|(number, (_, sentence))| format!("{}. {sentence}", number + 1)).collect();
    let messages = vec![
        Message::system(
            "You check a chatbot's reply against the business's numbered facts. For each numbered sentence of \
             the reply, name the facts that say what it says (in any language), then write ALL when they say \
             everything the sentence states, or PART when the sentence also states something no fact says. Write \
             NONE when no fact says it. What the customer wrote is not a fact. One line per sentence. \
             Example:\n1. [4] ALL\n2. [2] PART\n3. NONE",
        ),
        Message::user(format!(
            "Facts:\n{}\n\nThe customer wrote:\n{}\n\nSentences of the reply:\n{}",
            numbered_facts.join("\n"),
            sources.customer_text(),
            numbered.join("\n")
        )),
    ];
    let mut request = model_config.request(messages, &ctx.pool)?;
    request.temperature = Some(0.0);
    request.max_tokens = Some(u32::try_from(14 * sentences.len() + 16).unwrap_or(128));
    request.response_format = None;
    super::common::fit_budget(ctx, model_config, &mut request, false)?;
    let response = invoke(ctx, model, request, StreamMode::Off).await?;
    super::common::charge_model(ctx, model_config, &response.usage)?;
    let confirmed = named_facts(&response.text, sentences.len())
        .into_iter()
        .filter(|(number, named)| {
            sentences.get(*number).is_some_and(|(_, sentence)| {
                named.iter().filter_map(|fact| facts.get(*fact)).any(|fact| shares_a_fact(sentence, fact))
            })
        })
        .filter_map(|(number, _)| sentences.get(number).map(|(index, _)| *index))
        .collect();
    Ok((confirmed, response.usage))
}

/// The facts (numbers from 0) an answer like "1. [3] ALL\n2. NONE\n3. [1], [4] ALL" says all of
/// each sentence (numbers from 0, at most `count`). A line it cannot read, `NONE` or `PART`
/// names none.
fn named_facts(answer: &str, count: usize) -> Vec<(usize, Vec<usize>)> {
    let mut named: Vec<(usize, Vec<usize>)> = Vec::new();
    for line in answer.lines() {
        let line = line.trim().trim_start_matches(['-', '*', ' ']);
        let digits: String = line.chars().take_while(char::is_ascii_digit).collect();
        let Ok(number) = digits.parse::<usize>() else { continue };
        if !(1..=count).contains(&number) || named.iter().any(|(sentence, _)| *sentence == number - 1) {
            continue;
        }
        let rest = line.get(digits.len()..).unwrap_or_default().to_lowercase();
        let says_all = rest.split(|c: char| !c.is_alphabetic()).any(|word| word == "all");
        if rest.contains("none") || rest.contains("part") || !says_all {
            continue;
        }
        let facts: Vec<usize> = rest
            .split(|c: char| !c.is_ascii_digit())
            .filter_map(|digits| digits.parse::<usize>().ok())
            .filter(|fact| *fact >= 1)
            .map(|fact| fact - 1)
            .collect();
        if !facts.is_empty() {
            named.push((number - 1, facts));
        }
    }
    named
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_sentence_names_the_facts_that_say_it() {
        assert_eq!(
            named_facts("1. [3] ALL\n2. NONE\n3: [1], [4] all\n9. [2] ALL\n1. [5] ALL", 3),
            [(0, vec![2]), (2, vec![0, 3])]
        );
        // Part of a sentence, or no word about it, confirms nothing.
        assert!(named_facts("1. [2] PART\n2. [3]", 2).is_empty());
        assert!(named_facts("I think all of the first one", 1).is_empty());
    }
}