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;
pub const MAX_ROUNDS: u32 = 5;
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.";
#[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
}
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct Message {
#[serde(default)]
text: Option<String>,
#[serde(default)]
file: Option<serde_json::Value>,
#[serde(default)]
#[allow(dead_code)]
required: Option<serde_json::Value>,
#[serde(default)]
#[allow(dead_code)]
strip_comments: Option<serde_json::Value>,
}
#[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
}
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))
}
pub(super) fn message(&self, pool: &VariablePool, issues: &[Issue]) -> String {
format!("{}\n\n{}", self.message.render(pool).trim_end(), text_check::notes(issues))
}
}
pub(super) struct Answered {
pub text: String,
pub reasoning: String,
pub usage: graphrt_core::event::Usage,
pub finish_reason: Value,
pub turn: crate::types::Message,
}
pub(super) struct Revision {
pub rounds: u32,
pub issues: Vec<Issue>,
}
pub(super) fn grounding_issues(unsupported: &Value) -> Result<Vec<Issue>, NodeError> {
text_check::issues_from(unsupported).map_err(|e| NodeError::fatal("grounding", e.0))
}
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"));
}
}