graphrt-llm 0.9.0

Model providers (OpenAI-compatible, Anthropic, Gemini, AWS Bedrock, TypeSafe Jev) and LLM, classifier, extractor and agent nodes for the graphrt workflow runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//! `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).
//!
//! # Numbers only (`check: numbers`)
//!
//! A report may word its figures freely, but every figure must be one of the facts:
//!
//! ```yaml
//! grounding:
//!   facts: [[figures, json]]
//!   check: numbers
//!   numbers: { tolerance: rounding, ratios_as_percent: true }
//!   on_fail: output                 # keep the draft and report, or `fallback` (the default)
//! ```
//!
//! Every number of the answer is compared with the numbers of the facts by
//! [`graphrt_core::grounding::figures`] (rounding, percentages and ratios, notations). With
//! structured output every string of `structured_output` is checked, and each unsupported
//! number is reported with the path of its field. Outputs: `grounded` (bool) and `unsupported`
//! (`[{field, number, sentence, reason}]`). With `on_fail: fallback` a text answer with an
//! unsupported number becomes the `fallback` and `draft` keeps it; `on_fail: output` changes
//! nothing; `on_fail: error` fails the node (for an `on_error` branch).
//!
//! # Attribution (`attribution`)
//!
//! A true number can still stand next to the wrong entity. With `attribution`, the facts are
//! also grouped by entity, and every figure must stand next to an entity that holds it
//! ([`graphrt_core::grounding::entities`]):
//!
//! ```yaml
//! grounding:
//!   facts: [[figures, json]]
//!   check: numbers
//!   attribution:
//!     entities: [[prep, categories], { from: [figures, json, stores], label: name }]
//!     groups: [all categories]            # group words that name no entity
//!     scopes: { "stores[*].note": "{{#prep.top_store#}}" }   # or [prep, scopes]
//!     skip: { integers_up_to: 10 }
//!   on_fail: output
//! ```
//!
//! A misattributed figure is reported in `unsupported` with `reason: attribution`, the entity
//! the text gives it to (`named`) and the entities whose facts hold it (`owners`).

use graphrt_core::event::Usage;
use graphrt_core::grounding::figures::{Figures, NumberRules, Tolerance};
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};
#[cfg(feature = "grounding-attribution")]
use super::grounding_attribution::{Attribution, AttributionConfig};
#[cfg(not(feature = "grounding-attribution"))]
use super::grounding_attribution_off::{Attribution, AttributionConfig};
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,
}

/// What the check reads.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Check {
    /// A chat answer, sentence by sentence: numbers, days, addresses, words.
    #[default]
    Sentences,
    /// Numbers only, in a text or in every string of a structured output.
    Numbers,
}

/// What happens to an answer the check does not pass.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum OnFail {
    /// `text` is the `fallback` (with `check: sentences`, only when nothing the facts hold is left).
    #[default]
    Fallback,
    /// The answer is kept as written: `grounded` and `unsupported` say what was found.
    Output,
    /// The node fails with the unsupported numbers (`check: numbers`), for an `on_error` branch.
    Error,
}

/// `numbers` of a `grounding` block: how numbers are compared.
#[derive(Clone, Copy, Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct NumbersConfig {
    #[serde(default)]
    tolerance: ToleranceConfig,
    #[serde(default)]
    ratios_as_percent: bool,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
enum ToleranceConfig {
    #[default]
    Rounding,
    Exact,
}

impl NumbersConfig {
    fn rules(self) -> NumberRules {
        let tolerance = match self.tolerance {
            ToleranceConfig::Rounding => Tolerance::Rounding,
            ToleranceConfig::Exact => Tolerance::Exact,
        };
        NumberRules { tolerance, ratios_as_percent: self.ratios_as_percent }
    }
}

/// The `grounding` block of an `llm` node.
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
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 (`on_fail: fallback`).
    #[serde(default)]
    pub fallback: Option<String>,
    #[serde(default)]
    pub confirm: Confirm,
    #[serde(default)]
    pub check: Check,
    /// How numbers are compared (`check: numbers`).
    #[serde(default)]
    pub numbers: Option<NumbersConfig>,
    /// Every figure must stand next to an entity that holds it (`check: numbers`).
    #[serde(default)]
    pub attribution: Option<AttributionConfig>,
    #[serde(default)]
    pub on_fail: OnFail,
}

/// What the numbers check found.
pub(super) struct NumbersReport {
    pub grounded: bool,
    /// `[{field, number, sentence, reason}]`, and `named` and `owners` for `reason: attribution`.
    pub unsupported: Value,
}

/// 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 {
    /// What is wrong with the block for a node with or without structured output.
    pub(super) fn problem(&self, structured: bool) -> Option<&'static str> {
        match (self.check, self.on_fail) {
            (Check::Sentences, _) if structured => Some(
                "`grounding` with `check: sentences` checks a text answer; with structured output use \
                 `check: numbers` and `on_fail: output`",
            ),
            (Check::Sentences, OnFail::Output) => Some("`on_fail: output` goes with `check: numbers`"),
            (Check::Sentences, OnFail::Error) => Some("`on_fail: error` goes with `check: numbers`"),
            (Check::Numbers, OnFail::Fallback) if structured => {
                Some("with structured output, `grounding` reports what it found: set `on_fail: output` (or `error`)")
            }
            _ if self.numbers.is_some() && self.check != Check::Numbers => Some("`numbers` goes with `check: numbers`"),
            _ if self.attribution.is_some() && self.check != Check::Numbers => {
                Some("`attribution` goes with `check: numbers`")
            }
            _ if self.attribution.as_ref().and_then(AttributionConfig::problem).is_some() => {
                self.attribution.as_ref().and_then(AttributionConfig::problem)
            }
            (_, OnFail::Fallback) if self.fallback.is_none() => Some(
                "`grounding` needs a `fallback` (the text sent instead), or `check: numbers` with `on_fail: output`",
            ),
            (Check::Numbers, _) if self.confirm != Confirm::Off => Some("`confirm` goes with `check: sentences`"),
            _ => None,
        }
    }

    /// Whether the answer may stream: only when nothing the check finds can change it.
    pub(super) fn keeps_the_answer(&self) -> bool {
        self.on_fail == OnFail::Output
    }

    pub(super) fn checks_numbers(&self) -> bool {
        self.check == Check::Numbers
    }

    /// Whether an answer the check does not pass fails the node.
    pub(super) fn fails_the_node(&self) -> bool {
        self.on_fail == OnFail::Error
    }

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

    /// The entities and scopes of `attribution`, read from the pool.
    fn attribution(&self, pool: &VariablePool) -> Result<Option<Attribution>, NodeError> {
        let Some(config) = &self.attribution else { return Ok(None) };
        config.read(pool, self.numbers.unwrap_or_default().rules()).map(Some)
    }

    /// The numbers the facts (the listed values, the entities of `attribution`, the node's
    /// `context`) and the customer hold.
    fn figures(&self, pool: &VariablePool, context: Option<&str>) -> Figures {
        let mut figures = Figures::new();
        let entities = self.attribution.iter().flat_map(AttributionConfig::entity_selectors);
        for selector in self.facts.iter().chain(&self.customer).chain(entities) {
            match pool.get(selector) {
                Some(Value::String(text)) => figures.add_text(&text),
                Some(value) => figures.add_json(&value.to_json()),
                None => {}
            }
        }
        if let Some(context) = context {
            figures.add_text(context);
        }
        figures
    }

    /// The numbers check of `text` (`check: numbers`), reported under the field `text`.
    pub(super) fn check_numbers_text(
        &self,
        pool: &VariablePool,
        context: Option<&str>,
        text: &str,
    ) -> Result<NumbersReport, NodeError> {
        let figures = self.figures(pool, context);
        let attribution = self.attribution(pool)?;
        let mut found = Vec::new();
        self.check_field(&figures, attribution.as_ref(), "text", text, &mut found);
        Ok(NumbersReport { grounded: found.is_empty(), unsupported: Value::array(found) })
    }

    /// The numbers check of every string of a structured output, each reported by its path
    /// (`summary`, `stores[2].note`).
    pub(super) fn check_numbers_fields(
        &self,
        pool: &VariablePool,
        context: Option<&str>,
        output: &serde_json::Value,
    ) -> Result<NumbersReport, NodeError> {
        let figures = self.figures(pool, context);
        let attribution = self.attribution(pool)?;
        let mut found = Vec::new();
        self.walk(&figures, attribution.as_ref(), String::new(), output, &mut found);
        Ok(NumbersReport { grounded: found.is_empty(), unsupported: Value::array(found) })
    }

    fn walk(
        &self,
        figures: &Figures,
        attribution: Option<&Attribution>,
        path: String,
        value: &serde_json::Value,
        found: &mut Vec<Value>,
    ) {
        match value {
            serde_json::Value::String(text) => self.check_field(figures, attribution, &path, text, found),
            serde_json::Value::Array(items) => {
                for (index, item) in items.iter().enumerate() {
                    self.walk(figures, attribution, format!("{path}[{index}]"), item, found);
                }
            }
            serde_json::Value::Object(fields) => {
                for (name, item) in fields {
                    let path = if path.is_empty() { name.clone() } else { format!("{path}.{name}") };
                    self.walk(figures, attribution, path, item, found);
                }
            }
            _ => {}
        }
    }

    fn check_field(
        &self,
        figures: &Figures,
        attribution: Option<&Attribution>,
        field: &str,
        text: &str,
        found: &mut Vec<Value>,
    ) {
        let rules = self.numbers.unwrap_or_default().rules();
        for unsupported in figures.unsupported(text, rules) {
            found.push(Value::object([
                ("field", Value::from(field)),
                ("number", Value::from(unsupported.number)),
                ("sentence", Value::from(unsupported.sentence)),
                ("reason", Value::from("value")),
            ]));
        }
        if let Some(attribution) = attribution {
            attribution.findings(field, text, found);
        }
    }

    /// The error of a node whose answer the numbers check did not pass (`on_fail: error`): the
    /// `unsupported` items, as JSON.
    pub(super) fn failure(report: &NumbersReport) -> NodeError {
        NodeError::new(
            "ungrounded",
            format!("the answer states numbers the facts do not support: {}", report.unsupported.to_json()),
        )
    }

    /// The `fallback`, rendered.
    pub(super) fn fallback_text(&self, pool: &VariablePool) -> String {
        self.fallback.as_deref().map(|fallback| Template::parse(fallback).render(pool)).unwrap_or_default()
    }

    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 = self.fallback_text(&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, &super::common::answered_by(model_config, &response), &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());
    }
}