graphrt-core 0.7.0

Executor-agnostic graph runtime for agentic AI workflows: graph model, variable pool, scheduler, events, snapshots and built-in control nodes.
Documentation
//! Numbers stay with what they belong to: "express 15k, regular 8k" holds 8k, but not
//! "express is 8k".
//!
//! Sources and replies are cut into clauses (at commas, full stops, colons (not one before its
//! value: "Express price: 15k" is one clause), brackets, line breaks and
//! words such as "and", "dan", "while", "sedangkan", "but", but not "45 and 30"). A number of
//! the sources belongs to the words of its clause. A reply's number is **misattributed** when
//! its clause names a word the sources give to another number **of the same kind** (a price, a
//! duration, a time of day, a count, a share) and never to this one: "express" is 15k's in
//! "prices are 8k per kg, express 15k per kg", so "express is 8k per kg" is left out. "Banner
//! 50k per meter, ready in 3 days" still holds "a banner takes 3 days": 50k is a price, 3 days a
//! duration.
//!
//! The check is cautious, so true answers are not refused: a reply clause with more than one
//! number ("brownies 50k cheesecake 120k", "9 to 20") is not judged, nor a number the customer
//! wrote, nor a word the sources give to the number as well.

use std::collections::HashSet;

use super::claims::{says_nothing, stems, words};
use super::numbers::{Kind, numbers, same};

/// Words that join two clauses.
const JOINERS: &[&str] = &["and", "dan", "while", "whereas", "but", "sedangkan", "tapi", "tetapi", "namun", "serta"];

/// `text` cut into clauses.
fn clauses(text: &str) -> Vec<String> {
    let characters: Vec<char> = text.chars().collect();
    let mut clauses = Vec::new();
    let mut clause = String::new();
    for (index, &character) in characters.iter().enumerate() {
        let between_digits = index > 0
            && characters.get(index - 1).is_some_and(char::is_ascii_digit)
            && characters.get(index + 1).is_some_and(char::is_ascii_digit);
        // A colon keeps a label with the value right after it ("Express price: 15.000/kg"),
        // but ends an introduction ("my laundry shop: prices are 8k").
        let labels_a_value = character == ':' && {
            let after: String =
                characters.iter().skip(index + 1).skip_while(|c| c.is_whitespace() || **c == '*').take(3).collect();
            let after = after.to_lowercase();
            after.starts_with(|c: char| c.is_ascii_digit() || "$€£¥₹₫฿₱₩₦₺₽".contains(c)) || after.starts_with("rp")
        };
        let ends = matches!(character, ',' | '.' | ';' | ':' | '!' | '?' | '(' | ')' | '\n')
            && !between_digits
            && !labels_a_value;
        if ends {
            clauses.push(std::mem::take(&mut clause));
        } else {
            clause.push(character);
        }
    }
    clauses.push(clause);
    clauses
        .into_iter()
        .flat_map(|clause| {
            let words: Vec<&str> = clause.split_whitespace().collect();
            let numeric = |word: Option<&&str>| word.is_some_and(|word| word.starts_with(|c: char| c.is_ascii_digit()));
            let mut parts = vec![String::new()];
            for (index, word) in words.iter().enumerate() {
                // "between 45 and 30 minutes" is one range, not two clauses.
                let range =
                    numeric(index.checked_sub(1).and_then(|before| words.get(before))) && numeric(words.get(index + 1));
                if JOINERS.contains(&word.to_lowercase().as_str()) && !range {
                    parts.push(String::new());
                } else if let Some(last) = parts.last_mut() {
                    last.push(' ');
                    last.push_str(word);
                }
            }
            parts
        })
        .map(|part| part.trim().to_owned())
        .filter(|part| !part.is_empty())
        .collect()
}

/// The stems of the words of `clause` that state something.
fn stems_of(clause: &str) -> HashSet<String> {
    words(clause).iter().filter(|word| !says_nothing(word)).flat_map(|word| stems(word)).collect()
}

/// The numbers of one clause of the sources (value and kind) and the stems of its words.
type Clause = (Vec<(f64, Kind)>, HashSet<String>);

/// The numbers of the sources, each with its kind and the words of its clause.
#[derive(Debug, Default)]
pub(super) struct Attributions {
    numbers: Vec<Clause>,
    customer: Vec<f64>,
}

impl Attributions {
    pub(super) fn of(facts: &str, customer: &str) -> Self {
        let mut numbers_of_clauses = Vec::new();
        for clause in clauses(facts) {
            let values: Vec<(f64, Kind)> = numbers(&clause)
                .into_iter()
                .flat_map(|number| number.values.into_iter().map(move |value| (value, number.kind)))
                .collect();
            if !values.is_empty() {
                numbers_of_clauses.push((values, stems_of(&clause)));
            }
        }
        let customer = numbers(customer).into_iter().flat_map(|number| number.values).collect();
        Self { numbers: numbers_of_clauses, customer }
    }

    /// The first number of `sentence` that stands with a word the sources give only to other
    /// numbers of its kind, as written, with that word.
    pub(super) fn first_misattributed(&self, sentence: &str) -> Option<(String, String)> {
        for clause in clauses(sentence) {
            let written: Vec<_> = numbers(&clause).into_iter().filter(|number| !number.is_a_word()).collect();
            let [number] = written.as_slice() else { continue };
            let is = |value: &f64| number.values.iter().any(|own| same(*own, *value));
            if self.customer.iter().any(is)
                || !self.numbers.iter().any(|(values, _)| values.iter().any(|(value, _)| is(value)))
            {
                continue;
            }
            for word in words(&clause).iter().filter(|word| !says_nothing(word)) {
                let word_stems = stems(word);
                let with_word =
                    self.numbers.iter().filter(|(_, clause)| word_stems.iter().any(|stem| clause.contains(stem)));
                let mut elsewhere = false;
                let mut here = false;
                for (values, _) in with_word {
                    for (value, kind) in values {
                        if is(value) {
                            here = true;
                        } else if *kind == number.kind {
                            elsewhere = true;
                        }
                    }
                }
                if elsewhere && !here {
                    return Some((number.written.clone(), word.clone()));
                }
            }
        }
        None
    }
}

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

    const LAUNDRY: &str =
        "A chatbot for my laundry shop: prices are 8k per kg, express 15k per kg, pickup between 9 and 18.";

    #[test]
    fn a_number_stays_with_what_it_belongs_to() {
        let known = Attributions::of(LAUNDRY, "How much is express?");
        assert_eq!(
            known.first_misattributed("Our current prices are 8k/kg for express laundry."),
            Some(("8k".into(), "express".into()))
        );
        assert_eq!(
            known.first_misattributed("Our prices are 8k/kg express and 15k/kg standard."),
            Some(("8k".into(), "express".into()))
        );
        assert_eq!(known.first_misattributed("Express laundry is 15k per kg."), None);
        assert_eq!(known.first_misattributed("**Express Price:** 8.000/kg"), Some(("8.000".into(), "express".into())));
        assert_eq!(known.first_misattributed("Laundry is 8k per kg, express 15k."), None);
        assert_eq!(known.first_misattributed("Regular is 8k and express is 15k."), None);
        // Several numbers in one clause, and the customer's numbers, are not judged.
        assert_eq!(known.first_misattributed("Express 8k 15k per kg"), None);
        assert_eq!(Attributions::of(LAUNDRY, "I have 8 kg express").first_misattributed("Express for 8 kg."), None);
    }

    #[test]
    fn numbers_of_another_kind_are_no_confusion() {
        let print =
            Attributions::of("Banner 50k per meter, ready in 3 days; A4 color 2k per sheet, ready in 1 day.", "");
        assert_eq!(print.first_misattributed("A banner is ready in 3 days."), None);
        assert_eq!(print.first_misattributed("A banner costs 2k per meter."), Some(("2k".into(), "banner".into())));
        let team = Attributions::of("Our team arrives between 45 and 30 minutes before the agreed meal time.", "");
        assert_eq!(team.first_misattributed("We arrive 45 minutes before the meal."), None);
    }

    #[test]
    fn clauses_end_at_punctuation_and_joining_words() {
        assert_eq!(
            clauses("brownies 50k, cheesecake 120k dan tumpeng 350k (min 20 boxes). Rp 25.000"),
            ["brownies 50k", "cheesecake 120k", "tumpeng 350k", "min 20 boxes", "Rp 25.000"]
        );
    }
}