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
//! `attribution` of a `grounding` block (feature `grounding-attribution`): every figure must
//! stand next to an entity whose facts hold it ([`graphrt_core::grounding::entities`]).
//!
//! Entities come from run values, a scope per field says which entity a field is about, and each
//! 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 std::collections::BTreeMap;

use graphrt_core::grounding::entities::{AttributionRules, Entities};
use graphrt_core::grounding::figures::NumberRules;
use graphrt_core::template::Template;
use graphrt_core::value::Value;
use graphrt_core::{NodeError, Selector, VariablePool};
use serde::Deserialize;

/// `attribution` of a `grounding` block: every figure must stand next to an entity that holds it.
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AttributionConfig {
    /// Values holding the entities and their facts.
    entities: Vec<EntitySource>,
    /// Group words that name no entity of their own ("all stores").
    #[serde(default)]
    groups: Vec<String>,
    /// The entity each field is about, for sentences that name none.
    #[serde(default)]
    scopes: Option<Scopes>,
    #[serde(default)]
    skip: SkipConfig,
}

/// Where entities come from: a value of records labelled `entity` (or an object of facts per
/// label), or `{from, label}` for records labelled by another field.
#[derive(Clone, Debug, Deserialize)]
#[serde(untagged)]
enum EntitySource {
    Value(Selector),
    Labelled(LabelledSource),
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct LabelledSource {
    from: Selector,
    #[serde(default = "default_label_key")]
    label: String,
}

fn default_label_key() -> String {
    "entity".to_owned()
}

/// The entity of each field: a value computed by the workflow, or field patterns to label
/// templates.
#[derive(Clone, Debug, Deserialize)]
#[serde(untagged)]
enum Scopes {
    Value(Selector),
    Fields(BTreeMap<String, String>),
}

/// Figures the attribution check does not judge.
#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct SkipConfig {
    /// Numbers written with digits alone up to this value (counts such as "3 stores").
    #[serde(default = "default_integers_up_to")]
    integers_up_to: u32,
}

impl Default for SkipConfig {
    fn default() -> Self {
        Self { integers_up_to: default_integers_up_to() }
    }
}

fn default_integers_up_to() -> u32 {
    10
}

impl EntitySource {
    fn selector(&self) -> &Selector {
        match self {
            Self::Value(selector) | Self::Labelled(LabelledSource { from: selector, .. }) => selector,
        }
    }

    fn label_key(&self) -> &str {
        match self {
            Self::Value(_) => "entity",
            Self::Labelled(LabelledSource { label, .. }) => label,
        }
    }
}

/// What the attribution check reads at run time.
pub(super) struct Attribution {
    entities: Entities,
    /// Field patterns (`stores[*].note`) and the label of the entity each is about.
    scopes: Vec<(String, String)>,
    rules: AttributionRules,
}

impl AttributionConfig {
    /// What is wrong with the block, if anything.
    pub(super) fn problem(&self) -> Option<&'static str> {
        self.entities
            .is_empty()
            .then_some("`attribution` needs `entities`: the values that hold the entities and their facts")
    }

    /// The values the block reads.
    pub(super) fn selectors(&self) -> Vec<Selector> {
        let mut selectors: Vec<Selector> = self.entity_selectors().cloned().collect();
        match &self.scopes {
            Some(Scopes::Value(selector)) => selectors.push(selector.clone()),
            Some(Scopes::Fields(fields)) => {
                for label in fields.values() {
                    selectors.extend(Template::parse(label).selectors().cloned());
                }
            }
            None => {}
        }
        selectors
    }

    /// The values that hold the entities (their numbers are facts too).
    pub(super) fn entity_selectors(&self) -> impl Iterator<Item = &Selector> {
        self.entities.iter().map(EntitySource::selector)
    }

    /// The entities and scopes, read from the pool.
    pub(super) fn read(&self, pool: &VariablePool, numbers: NumberRules) -> Result<Attribution, NodeError> {
        let mut entities = Entities::new();
        for source in &self.entities {
            // A missing value is skipped, as missing facts are.
            let Some(value) = pool.get(source.selector()) else { continue };
            entities.add_json(&json_of(&value), source.label_key()).map_err(|problem| {
                grounding_error(format!("`attribution.entities` {}: {problem}", source.selector()))
            })?;
        }
        for group in &self.groups {
            entities.add_group(group);
        }
        let scopes = match &self.scopes {
            None => Vec::new(),
            Some(Scopes::Fields(fields)) => {
                fields.iter().map(|(field, label)| (field.clone(), Template::parse(label).render(pool))).collect()
            }
            Some(Scopes::Value(selector)) => match pool.get(selector).map(|value| json_of(&value)) {
                None | Some(serde_json::Value::Null) => Vec::new(),
                Some(serde_json::Value::Object(fields)) => fields
                    .into_iter()
                    .map(|(field, label)| match label {
                        serde_json::Value::String(label) => Ok((field, label)),
                        serde_json::Value::Null => Ok((field, String::new())),
                        _ => Err(grounding_error(format!(
                            "`attribution.scopes` {selector}: the scope of `{field}` must be an entity label (a string)"
                        ))),
                    })
                    .collect::<Result<_, _>>()?,
                Some(_) => {
                    return Err(grounding_error(format!(
                        "`attribution.scopes` {selector}: expected an object of field to entity label"
                    )));
                }
            },
        };
        let rules = AttributionRules { numbers, integers_up_to: f64::from(self.skip.integers_up_to) };
        Ok(Attribution { entities, scopes, rules })
    }
}

impl Attribution {
    /// Adds the misattributed figures of the field `field` (its text `text`) to `found`.
    pub(super) fn findings(&self, field: &str, text: &str, found: &mut Vec<Value>) {
        for wrong in self.entities.misattributed(text, self.scope_of(field), self.rules) {
            found.push(Value::object([
                ("field", Value::from(field)),
                ("number", Value::from(wrong.number)),
                ("sentence", Value::from(wrong.sentence)),
                ("reason", Value::from("attribution")),
                ("named", Value::from(wrong.named)),
                ("owners", Value::array(wrong.owners.into_iter().map(Value::from))),
            ]));
        }
    }
}

impl Attribution {
    /// The label of the entity `field` is about: the scope written for the field itself, else
    /// for the list or object it is in (`notes` for `notes[2]`). `[*]` stands for any index.
    fn scope_of(&self, field: &str) -> Option<&str> {
        let pattern = any_index(field);
        let mut best: Option<(usize, &str)> = None;
        for (key, label) in &self.scopes {
            let covers = |path: &str| {
                path == key
                    || path
                        .strip_prefix(key.as_str())
                        .is_some_and(|rest| rest.starts_with('[') || rest.starts_with('.'))
            };
            if (covers(field) || covers(&pattern)) && best.is_none_or(|(length, _)| key.len() > length) {
                best = Some((key.len(), label));
            }
        }
        best.map(|(_, label)| label)
    }
}

/// `field` with every index written `[*]`: `stores[2].note` is `stores[*].note`.
fn any_index(field: &str) -> String {
    let mut pattern = String::with_capacity(field.len());
    let mut rest = field;
    while let Some(open) = rest.find('[') {
        let (before, after) = rest.split_at(open);
        pattern.push_str(before);
        match after.find(']') {
            Some(close) if after.get(1..close).is_some_and(|index| index.chars().all(|c| c.is_ascii_digit())) => {
                pattern.push_str("[*]");
                rest = after.get(close + 1..).unwrap_or_default();
            }
            _ => {
                pattern.push('[');
                rest = after.get(1..).unwrap_or_default();
            }
        }
    }
    pattern.push_str(rest);
    pattern
}

/// The JSON of a value, reading a string as JSON when it is (a code node may return text).
fn json_of(value: &Value) -> serde_json::Value {
    match value {
        Value::String(text) => serde_json::from_str(text).unwrap_or_else(|_| value.to_json()),
        other => other.to_json(),
    }
}

fn grounding_error(message: String) -> NodeError {
    NodeError::fatal("grounding", message)
}