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
//! `revise` of the `llm` node: the answer is checked, and while it has issues
//! the model is asked again, in the same conversation, with the issues listed,
//! up to `max_rounds` more times.
//!
//! ```yaml
//! grounding: { facts: [[figures, json]], check: numbers, on_fail: output }
//! revise:
//!   max_rounds: 2                       # default 1, at most 5
//!   checks:                             # the rules of the `text-check` node
//!     forbid: [{ text: ";", message: "split the sentence with a full stop" }]
//!     require: [prep, key_figures]
//!     paragraphs: { highlights: 2 }
//!   message: { file: ../prompts/revise.md }   # or { text: ... }; a default is built in
//! ```
//!
//! The issues are the `unsupported` items of a `check: numbers` grounding, the
//! issues of `checks` and, with structured output, an answer that is not JSON of
//! the schema. Each revision sends the answer back as the model's turn and a
//! user message: `message` followed by the issues, one per line.
//!
//! Cargo feature `revise` (with `graphrt-core/text-check`).

use graphrt_core::node::ConfigError;
use graphrt_core::pool::{Selector, VariablePool};
use graphrt_core::template::Template;
use graphrt_core::text_check::{self, Issue, RuleSources, RulesConfig, Texts};
use graphrt_core::value::Value;
use graphrt_core::{NodeError, dsl::NodeDoc};
use serde::Deserialize;

/// Most revisions one node asks for.
pub const MAX_ROUNDS: u32 = 5;

/// What the model is told before the issues when no `message` is given.
const DEFAULT_MESSAGE: &str = "Your answer has the issues listed below. Write the whole answer again in the same \
     format, fix every issue, and keep everything else as it was.";

/// `revise` as a workflow writes it.
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ReviseConfig {
    #[serde(default = "one")]
    max_rounds: u32,
    #[serde(default)]
    checks: Option<RulesConfig>,
    #[serde(default)]
    message: Option<Message>,
}

fn one() -> u32 {
    1
}

/// The revision message: `text`, or a `file` the host reads into `text` when it
/// loads the workflow (`graphrt_core::prompt_files`).
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct Message {
    #[serde(default)]
    text: Option<String>,
    #[serde(default)]
    file: Option<serde_json::Value>,
    /// Read with the `file` (`graphrt_core::prompt_files`).
    #[serde(default)]
    #[allow(dead_code)]
    required: Option<serde_json::Value>,
    #[serde(default)]
    #[allow(dead_code)]
    strip_comments: Option<serde_json::Value>,
}

/// The parsed `revise` block.
#[derive(Clone, Debug)]
pub(super) struct Revise {
    max_rounds: u32,
    rules: RuleSources,
    message: Template,
}

impl Revise {
    pub(super) fn parse(doc: &NodeDoc, value: &serde_json::Value) -> Result<Self, ConfigError> {
        let config: ReviseConfig = serde_json::from_value(value.clone())
            .map_err(|e| ConfigError::new(doc, format!("revise: {e}")).at_field("revise"))?;
        if !(1..=MAX_ROUNDS).contains(&config.max_rounds) {
            return Err(ConfigError::new(doc, format!("revise: `max_rounds` is 1 to {MAX_ROUNDS}"))
                .at_field("revise.max_rounds"));
        }
        let rules = match &config.checks {
            Some(checks) => RuleSources::parse(checks).map_err(|(field, error)| {
                ConfigError::new(doc, format!("revise.checks: {}", error.0)).at_field(format!("revise.checks.{field}"))
            })?,
            None => RuleSources::default(),
        };
        let message = config.message.unwrap_or_default();
        if let Some(file) = &message.file {
            let file = file.as_str().map_or_else(|| file.to_string(), str::to_owned);
            return Err(ConfigError::new(
                doc,
                format!("prompt file `{file}`: prompt files are read when the workflow is loaded from a file"),
            )
            .at_field("revise.message.file"));
        }
        let text = message.text.filter(|text| !text.trim().is_empty()).unwrap_or_else(|| DEFAULT_MESSAGE.to_owned());
        let message = Template::parse(&text);
        Ok(Self { max_rounds: config.max_rounds, rules, message })
    }

    pub(super) fn max_rounds(&self) -> u32 {
        self.max_rounds
    }

    pub(super) fn selectors(&self) -> Vec<Selector> {
        let mut out = self.rules.selectors();
        out.extend(self.message.selectors().cloned());
        out
    }

    /// The issues of `checks` in `answer` (the text, or the parsed structured output).
    pub(super) fn check(&self, pool: &VariablePool, answer: &Value) -> Result<Vec<Issue>, NodeError> {
        if self.rules.is_empty() {
            return Ok(Vec::new());
        }
        let rules = self.rules.resolve(pool)?;
        Ok(text_check::check(&Texts::of(answer, ""), &rules))
    }

    /// The user message of a revision.
    pub(super) fn message(&self, pool: &VariablePool, issues: &[Issue]) -> String {
        format!("{}\n\n{}", self.message.render(pool).trim_end(), text_check::notes(issues))
    }
}

/// An answer of the model, as the node reads it.
pub(super) struct Answered {
    pub text: String,
    pub reasoning: String,
    pub usage: graphrt_core::event::Usage,
    pub finish_reason: Value,
    /// The answer as a turn of the conversation (provider state included).
    pub turn: crate::types::Message,
}

/// What the revisions did.
pub(super) struct Revision {
    pub rounds: u32,
    /// The issues of the last answer.
    pub issues: Vec<Issue>,
}

/// The `unsupported` items of a numbers check as issues.
pub(super) fn grounding_issues(unsupported: &Value) -> Result<Vec<Issue>, NodeError> {
    text_check::issues_from(unsupported).map_err(|e| NodeError::fatal("grounding", e.0))
}

/// A structured answer that could not be read, as an issue the model can fix.
pub(super) fn unreadable(error: &NodeError) -> Issue {
    Issue {
        field: String::new(),
        rule: "structured_output".into(),
        message: format!("{}. Answer with one JSON value that matches the schema", error.message),
        found: None,
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    fn parse(value: serde_json::Value) -> Result<Revise, ConfigError> {
        let doc = NodeDoc::new("write", "llm", json!({}));
        Revise::parse(&doc, &value)
    }

    #[test]
    fn rounds_rules_and_message_are_read() {
        let revise = parse(json!({
            "max_rounds": 2,
            "checks": {"forbid": [{"text": ";", "message": "use a full stop"}], "require": "prep.required"},
            "message": {"text": "Fix these for {{#start.month#}}:"}
        }))
        .unwrap();
        assert_eq!(revise.max_rounds(), 2);
        assert_eq!(
            revise.selectors().iter().map(ToString::to_string).collect::<Vec<_>>(),
            vec!["prep.required", "start.month"]
        );
        let mut pool = VariablePool::new();
        pool.insert("start", "month", Value::from("May"));
        let issues = revise.check(&pool, &Value::from("One; two.")).unwrap();
        assert_eq!(revise.message(&pool, &issues), "Fix these for May:\n\n- text: use a full stop (\";\")");
        assert_eq!(parse(json!({})).unwrap().message(&pool, &[]), format!("{DEFAULT_MESSAGE}\n\n"));
    }

    #[test]
    fn wrong_blocks_are_refused() {
        for (value, says) in [
            (json!({"max_rounds": 0}), "`max_rounds` is 1 to 5"),
            (json!({"max_rounds": 6}), "`max_rounds` is 1 to 5"),
            (json!({"rounds": 2}), "unknown field"),
            (json!({"checks": {"forbid": [{"pattern": "("}]}}), "revise.checks: forbid pattern"),
            (json!({"message": {"file": "revise.md"}}), "prompt files are read when the workflow is loaded"),
        ] {
            let error = parse(value.clone()).err().unwrap_or_else(|| panic!("accepted {value}"));
            assert!(error.to_string().contains(says), "{value}: {error}");
        }
    }

    #[test]
    fn grounding_findings_and_broken_answers_read_as_issues() {
        let unsupported = Value::from_json(json!([{"field": "summary", "number": "31%", "reason": "value"}]));
        assert_eq!(grounding_issues(&unsupported).unwrap()[0].to_string(), "summary: 31% is not in the facts");
        let issue = unreadable(&NodeError::new("structured_output", "model output contains no JSON value"));
        assert!(issue.to_string().starts_with("model output contains no JSON value. Answer with one JSON value"));
    }
}