1use 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
93#[serde(rename_all = "snake_case")]
94#[non_exhaustive]
95pub enum Confirm {
96 #[default]
98 Off,
99 Model,
101}
102
103#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
105#[serde(rename_all = "snake_case")]
106#[non_exhaustive]
107pub enum Check {
108 #[default]
110 Sentences,
111 Numbers,
113}
114
115#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
117#[serde(rename_all = "snake_case")]
118#[non_exhaustive]
119pub enum OnFail {
120 #[default]
122 Fallback,
123 Output,
125 Error,
127}
128
129#[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#[derive(Clone, Debug, Deserialize)]
160#[serde(deny_unknown_fields)]
161#[non_exhaustive]
162pub struct GroundingConfig {
163 #[serde(default)]
165 pub facts: Vec<Selector>,
166 #[serde(default)]
168 pub customer: Vec<Selector>,
169 #[serde(default)]
171 pub fallback: Option<String>,
172 #[serde(default)]
173 pub confirm: Confirm,
174 #[serde(default)]
175 pub check: Check,
176 #[serde(default)]
178 pub numbers: Option<NumbersConfig>,
179 #[serde(default)]
181 pub attribution: Option<AttributionConfig>,
182 #[serde(default)]
183 pub on_fail: OnFail,
184}
185
186pub(super) struct NumbersReport {
188 pub grounded: bool,
189 pub unsupported: Value,
191}
192
193pub(super) struct Grounded {
195 pub text: String,
196 pub grounded: bool,
197 pub admits_unknown: bool,
199 pub unsupported: Value,
200 pub confirmed: Vec<String>,
202 pub usage: Option<Usage>,
204}
205
206impl GroundingConfig {
207 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 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 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 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 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 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 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 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 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 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
445const MOST_SENTENCES: usize = 8;
447
448async 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
505fn 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 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}