Skip to main content

graphrt_llm/nodes/
llm.rs

1//! `llm` node: a single (streaming) model call.
2//!
3//! Outputs: `text`, `reasoning` (when present), `usage`, `finish_reason` and,
4//! with structured output enabled, `structured_output`. Answer tokens stream
5//! as chunks on field `text`, reasoning on field `reasoning`. With
6//! `reasoning_format: separated`, `<think>` sections are streamed on
7//! `reasoning` too, so the streamed text always equals the `text` output.
8//!
9//! `context_window` keeps the request inside the model's context window (see
10//! [`crate::context`], cargo feature `context`): when the provider refuses it
11//! for its size, the oldest history turns are removed and it is sent once
12//! more. Only the history (`memory`) is ever removed: the messages of the
13//! prompt template always stay.
14//!
15//! `revise` (cargo feature `revise`, see [`super::revise`]) checks the answer
16//! and asks the model again, in the same conversation, while it has issues.
17//!
18//! Structured output is parsed from the answer and checked against the schema
19//! (top-level type, required properties, property types); a mismatch is a
20//! retryable `structured_output` error.
21
22use std::sync::Arc;
23
24use futures::future::BoxFuture;
25use graphrt_core::dsl::NodeDoc;
26use graphrt_core::node::{ConfigError, NodeResult, parse_config};
27use graphrt_core::value::Value;
28use graphrt_core::{Node, NodeContext, NodeError, NodeOutput, Selector};
29use serde::Deserialize;
30use serde_json::Value as Json;
31
32use super::common::{
33    ContextConfig, FinishCheck, MemoryConfig, ModelConfig, PromptTemplate, StreamMode, VisionConfig, build_messages,
34    check_finish, extract_json_where, finish_reason_value, invoke, model_for, report_request_messages,
35    split_think_tags, usage_value,
36};
37use super::schema;
38use crate::types::{ChatResponse, ResponseFormat};
39
40/// How `<think>` tags inside the answer are treated.
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
42#[serde(rename_all = "snake_case")]
43#[non_exhaustive]
44pub enum ReasoningFormat {
45    /// Keep tags in `text` as produced.
46    #[default]
47    Tagged,
48    /// Move tagged reasoning into `reasoning`.
49    Separated,
50}
51
52#[derive(Clone, Debug, Default, Deserialize)]
53struct StructuredOutput {
54    #[serde(default)]
55    enabled: Option<bool>,
56    #[serde(default)]
57    schema: Option<Json>,
58}
59
60/// Configuration of the `llm` node.
61#[derive(Clone, Debug, Deserialize)]
62pub struct LlmConfig {
63    pub model: ModelConfig,
64    #[serde(default)]
65    pub prompt_template: PromptTemplate,
66    #[serde(default)]
67    pub context: ContextConfig,
68    #[serde(default)]
69    pub vision: VisionConfig,
70    #[serde(default)]
71    pub memory: Option<MemoryConfig>,
72    #[serde(default)]
73    structured_output: Option<StructuredOutput>,
74    #[serde(default, alias = "structured_output_switch_on")]
75    structured_output_enabled: Option<bool>,
76    #[serde(default)]
77    pub reasoning_format: ReasoningFormat,
78    /// What happens when the request outgrows the model's context window:
79    /// `auto` (the default), `summarize`, `off` or a mapping (see
80    /// [`crate::context`]). Needs the cargo feature `context`.
81    #[serde(default)]
82    pub context_window: Option<Json>,
83    /// Checks the answer against its sources before it leaves the node (see
84    /// [`super::grounding`]). Answers are not streamed while it is on.
85    #[serde(default)]
86    pub grounding: Option<super::grounding::GroundingConfig>,
87    /// Asks the model again while the answer has issues (see [`super::revise`],
88    /// cargo feature `revise`; builds without it report the key as unknown).
89    #[cfg(feature = "revise")]
90    #[serde(default)]
91    pub revise: Option<Json>,
92}
93
94impl LlmConfig {
95    /// JSON Schema for structured output, when enabled.
96    fn output_schema(&self) -> Option<Json> {
97        let so = self.structured_output.as_ref()?;
98        let enabled = self.structured_output_enabled.or(so.enabled).unwrap_or(true);
99        if !enabled {
100            return None;
101        }
102        let schema = so.schema.clone()?;
103        // Accept both `{schema: {...}}` and a bare schema.
104        match schema.get("schema") {
105            Some(inner) if inner.is_object() => Some(inner.clone()),
106            _ => Some(schema),
107        }
108    }
109}
110
111/// The `llm` node.
112#[derive(Debug)]
113pub struct LlmNode {
114    config: LlmConfig,
115    schema: Option<Json>,
116    /// `model` and `provider` metadata, built once instead of per run.
117    model_name: Value,
118    provider: Value,
119    /// Parsed `context_window`.
120    #[cfg(feature = "context")]
121    context: crate::context::ContextWindow,
122    /// Parsed `revise`.
123    #[cfg(feature = "revise")]
124    revise: Option<super::revise::Revise>,
125}
126
127impl LlmNode {
128    pub fn from_doc(doc: &NodeDoc) -> Result<Self, ConfigError> {
129        let config: LlmConfig = parse_config(doc)?;
130        if config.prompt_template.messages().is_empty() && config.memory.is_none() {
131            return Err(ConfigError::new(doc, "prompt_template must contain at least one message"));
132        }
133        if let Some(file) = config.prompt_template.unread_file() {
134            return Err(ConfigError::new(
135                doc,
136                format!("prompt file `{file}`: prompt files are read when the workflow is loaded from a file"),
137            ));
138        }
139        let schema = config.output_schema();
140        if let Some(problem) = config.grounding.as_ref().and_then(|grounding| grounding.problem(schema.is_some())) {
141            return Err(ConfigError::new(doc, problem));
142        }
143        let model_name = Value::from(config.model.name.as_str());
144        let provider = Value::from(config.model.provider.as_str());
145        #[cfg(not(feature = "context"))]
146        if super::agent::asks_for_context_guard(config.context_window.as_ref()) {
147            return Err(ConfigError::new(
148                doc,
149                "`context_window` needs a build with the context guard (cargo feature `context`)",
150            ));
151        }
152        #[cfg(feature = "context")]
153        let context = crate::context::ContextWindow::parse(doc, config.context_window.as_ref())?;
154        #[cfg(feature = "revise")]
155        if config.revise.is_some() && config.grounding.as_ref().is_some_and(|grounding| !grounding.checks_numbers()) {
156            return Err(ConfigError::new(doc, "`revise` goes with `grounding` of `check: numbers`").at_field("revise"));
157        }
158        #[cfg(feature = "revise")]
159        let revise = config.revise.as_ref().map(|value| super::revise::Revise::parse(doc, value)).transpose()?;
160        Ok(Self {
161            config,
162            schema,
163            model_name,
164            provider,
165            #[cfg(feature = "context")]
166            context,
167            #[cfg(feature = "revise")]
168            revise,
169        })
170    }
171
172    async fn execute(&self, ctx: NodeContext) -> NodeResult {
173        let cfg = &self.config;
174        let pool = &ctx.pool;
175        let context = cfg.context.resolve(pool);
176        #[cfg(feature = "vision-preparer")]
177        let images = cfg.vision.prepared_image_parts(&ctx).await?;
178        #[cfg(not(feature = "vision-preparer"))]
179        let images = cfg.vision.image_parts(pool)?;
180        let messages = build_messages(&cfg.prompt_template, pool, context.as_deref(), cfg.memory.as_ref(), images)?;
181        if messages.is_empty() {
182            return Err(NodeError::invalid_input("prompt rendered to no messages"));
183        }
184        // Whether the budget limited the call's output below the node's own limit.
185        let capped = std::sync::atomic::AtomicBool::new(false);
186        let request = |messages: Vec<crate::types::Message>| -> Result<crate::types::ChatRequest, NodeError> {
187            let mut request = cfg.model.request(messages, pool)?;
188            if let Some(schema) = &self.schema {
189                request.response_format = Some(ResponseFormat::JsonSchema {
190                    name: "structured_output".into(),
191                    schema: schema.clone(),
192                    strict: false,
193                });
194            }
195            if ctx.captures_content() {
196                report_request_messages(&ctx, &request.messages);
197            }
198            capped.store(
199                crate::nodes::common::fit_budget(&ctx, &cfg.model, &mut request, false)?,
200                std::sync::atomic::Ordering::Relaxed,
201            );
202            Ok(request)
203        };
204
205        let model = model_for(&ctx, &cfg.model)?;
206        let mode = match cfg.reasoning_format {
207            // Only the checked answer may reach anyone, unless the check changes nothing.
208            _ if cfg.grounding.as_ref().is_some_and(|grounding| !grounding.keeps_the_answer()) => StreamMode::Off,
209            // Only the last revision may reach anyone.
210            #[cfg(feature = "revise")]
211            _ if self.revise.is_some() => StreamMode::Off,
212            ReasoningFormat::Tagged => StreamMode::Raw,
213            ReasoningFormat::Separated => StreamMode::SeparateThink,
214        };
215        // The conversation a revision continues.
216        #[cfg(feature = "revise")]
217        let conversation = self.revise.as_ref().map(|_| messages.clone());
218        #[cfg(not(feature = "context"))]
219        let response = invoke(&ctx, model.as_ref(), request(messages)?, mode).await?;
220        #[cfg(feature = "context")]
221        let (response, trimmed) = {
222            let mut messages = messages;
223            // Only the history may be removed: the messages of the prompt
224            // template are the owner's, wherever they stand.
225            // `build_messages` puts the history right after the leading system
226            // messages of the template (the history may start with system items of its own).
227            let template = cfg.prompt_template.messages();
228            let leading = template.iter().take_while(|m| m.role == crate::types::Role::System).count();
229            let history = match &cfg.memory {
230                Some(memory) if self.context.is_on() => memory.history(pool)?.len(),
231                _ => 0,
232            };
233            let scope = crate::context::Scope { pinned: &[], tail: messages.len().saturating_sub(leading + history) };
234            let mut guard = self.context.session(&ctx, model.as_ref(), &cfg.model, scope);
235            let mut state = crate::context::ContextState::default();
236            // Tokens of a summary the guard asked a model for.
237            let mut spent = graphrt_core::event::Usage::default();
238            let outcome: Result<ChatResponse, NodeError> = 'call: loop {
239                if let Err(error) = guard.fit(&mut state, &mut messages, &[], &mut spent).await {
240                    break 'call Err(error);
241                }
242                let built = match request(state.request_messages(&messages)) {
243                    Ok(built) => built,
244                    Err(error) => break 'call Err(error),
245                };
246                match invoke(&ctx, model.as_ref(), built, mode).await {
247                    Ok(response) => break 'call Ok(response),
248                    // A request the provider refused for its size is trimmed and sent
249                    // once more. Any other error, and a second refusal, fail the node.
250                    Err(error) => {
251                        if let Err(error) = guard.refused(&mut state, &mut messages, &[], error, &mut spent).await {
252                            break 'call Err(error);
253                        }
254                    }
255                }
256            };
257            let mut response = match outcome {
258                Ok(response) => response,
259                Err(error) => {
260                    // A summary made for the call was paid for, even when the call failed.
261                    if !spent.is_zero() {
262                        // Past a limit the budget stops the run itself: the call's own error is the answer.
263                        let _limit_reached = crate::nodes::common::charge_model(&ctx, &cfg.model, &spent).is_err();
264                    }
265                    return Err(error);
266                }
267            };
268            response.usage.add(&spent);
269            (response, state.report())
270        };
271        // Paid for whatever comes next, a broken answer too.
272        crate::nodes::common::charge_model(
273            &ctx,
274            &crate::nodes::common::answered_by(&cfg.model, &response),
275            &response.usage,
276        )?;
277        let finish = check_finish(&response)?;
278        let cut_short = response.finish_reason == Some(crate::types::FinishReason::Length);
279        let finish_reason = finish_reason_value(response.finish_reason.as_ref());
280        #[cfg(feature = "revise")]
281        let turn = response.to_message();
282        let ChatResponse { text: answer, reasoning: model_reasoning, usage, warnings, .. } = response;
283
284        let (text, mut reasoning) = match cfg.reasoning_format {
285            ReasoningFormat::Tagged => (answer, String::new()),
286            ReasoningFormat::Separated => split_think_tags(&answer),
287        };
288        if !model_reasoning.is_empty() {
289            reasoning = if reasoning.is_empty() { model_reasoning } else { format!("{model_reasoning}\n{reasoning}") };
290        }
291        #[cfg(feature = "revise")]
292        let (text, reasoning, usage, finish_reason, revision) = match (&self.revise, conversation) {
293            (Some(revise), Some(conversation)) => {
294                let first = super::revise::Answered { text, reasoning, usage, finish_reason, turn };
295                let (last, revision) = self
296                    .revised(&ctx, model.as_ref(), &request, conversation, first, revise, context.as_deref())
297                    .await?;
298                (last.text, last.reasoning, last.usage, last.finish_reason, Some(revision))
299            }
300            _ => (text, reasoning, usage, finish_reason, None),
301        };
302
303        let (text, usage, grounding_outputs) = match &cfg.grounding {
304            // With structured output, the fields are checked once they are parsed (below).
305            Some(grounding) if grounding.checks_numbers() && self.schema.is_some() => (text, usage, None),
306            Some(grounding) if grounding.checks_numbers() => {
307                let report = grounding.check_numbers_text(&ctx.pool, context.as_deref(), &text)?;
308                if !report.grounded && grounding.fails_the_node() {
309                    return Err(super::grounding::GroundingConfig::failure(&report));
310                }
311                let mut outputs = vec![("grounded", Value::from(report.grounded)), ("unsupported", report.unsupported)];
312                let text = if report.grounded || grounding.keeps_the_answer() {
313                    text
314                } else {
315                    outputs.push(("draft", Value::from(text.as_str())));
316                    grounding.fallback_text(&ctx.pool)
317                };
318                (text, usage, Some(outputs))
319            }
320            Some(grounding) => {
321                let checked = grounding.check(&ctx, model.as_ref(), &cfg.model, &text, context.as_deref()).await?;
322                let mut usage = usage;
323                let mut outputs = vec![
324                    ("grounded", Value::from(checked.grounded)),
325                    ("unknown", Value::from(checked.admits_unknown)),
326                    ("draft", Value::from(text.as_str())),
327                    ("unsupported", checked.unsupported),
328                ];
329                if let Some(spent) = &checked.usage {
330                    usage.add(spent);
331                    outputs.push(("confirmed", Value::array(checked.confirmed.into_iter().map(Value::from))));
332                    outputs.push(("check_usage", usage_value(spent)));
333                }
334                (checked.text, usage, Some(outputs))
335            }
336            None => (text, usage, None),
337        };
338        let mut output = NodeOutput::new()
339            .with("text", text.as_str())
340            .with("usage", usage_value(&usage))
341            .with("finish_reason", finish_reason)
342            .usage(usage)
343            .meta("model", self.model_name.clone())
344            .meta("provider", self.provider.clone());
345        if !reasoning.is_empty() {
346            output = output.with("reasoning", reasoning);
347        }
348        for (name, value) in grounding_outputs.into_iter().flatten() {
349            output = output.with(name, value);
350        }
351        #[cfg(feature = "revise")]
352        if let Some(revision) = &revision {
353            output = output
354                .with("revisions", Value::Int(i64::from(revision.rounds)))
355                .with("issues", Value::array(revision.issues.iter().map(graphrt_core::text_check::Issue::to_value)));
356        }
357        let mut warnings: Vec<Value> = warnings.into_iter().map(Value::from).collect();
358        if let FinishCheck::Unknown(reason) = &finish {
359            warnings.push(Value::from(format!("unrecognized finish reason `{reason}`")));
360        }
361        if capped.load(std::sync::atomic::Ordering::Relaxed) && cut_short {
362            warnings.push(Value::from("the answer was cut at the output the run's budget left"));
363        }
364        #[cfg(feature = "context")]
365        if let Some(report) = trimmed {
366            warnings.push(Value::from(format!("the conversation was trimmed to fit the context window: {report}")));
367        }
368        if !warnings.is_empty() {
369            output = output.meta("warnings", Value::from(warnings));
370        }
371        if let Some(schema) = &self.schema {
372            let parsed = extract_json_where(&text, |v| schema::matches_top_level_type(v, schema)).ok_or_else(|| {
373                NodeError::new("structured_output", "model output contains no JSON value of the requested type")
374            })?;
375            schema::validate(&parsed, schema).map_err(|problem| {
376                NodeError::new("structured_output", format!("model output does not match the schema: {problem}"))
377            })?;
378            if let Some(grounding) = cfg.grounding.as_ref().filter(|grounding| grounding.checks_numbers()) {
379                let report = grounding.check_numbers_fields(&ctx.pool, context.as_deref(), &parsed)?;
380                if !report.grounded && grounding.fails_the_node() {
381                    return Err(super::grounding::GroundingConfig::failure(&report));
382                }
383                output = output.with("grounded", report.grounded).with("unsupported", report.unsupported);
384            }
385            output = output.with("structured_output", Value::from_json(parsed));
386        }
387        Ok(output.into())
388    }
389
390    /// Asks again, with the issues of the answer, until it has none or the rounds are spent.
391    /// A revision continues the conversation as it was sent: the context guard of the
392    /// first call does not trim it again.
393    #[cfg(feature = "revise")]
394    #[allow(clippy::too_many_arguments)]
395    async fn revised(
396        &self,
397        ctx: &NodeContext,
398        model: &dyn crate::types::ChatModel,
399        request: &(dyn Fn(Vec<crate::types::Message>) -> Result<crate::types::ChatRequest, NodeError> + Sync),
400        mut conversation: Vec<crate::types::Message>,
401        mut answer: super::revise::Answered,
402        revise: &super::revise::Revise,
403        context: Option<&str>,
404    ) -> Result<(super::revise::Answered, super::revise::Revision), NodeError> {
405        let cfg = &self.config;
406        let mut rounds = 0;
407        loop {
408            let issues = self.issues_of(&ctx.pool, context, &answer.text, revise)?;
409            if issues.is_empty() || rounds >= revise.max_rounds() {
410                return Ok((answer, super::revise::Revision { rounds, issues }));
411            }
412            ctx.progress(
413                "revise",
414                Value::object([
415                    ("round", Value::Int(i64::from(rounds + 1))),
416                    ("issues", Value::Int(i64::try_from(issues.len()).unwrap_or(i64::MAX))),
417                ]),
418            );
419            conversation.push(answer.turn.clone());
420            conversation.push(crate::types::Message::user(revise.message(&ctx.pool, &issues)));
421            let response = invoke(ctx, model, request(conversation.clone())?, StreamMode::Off).await?;
422            crate::nodes::common::charge_model(
423                ctx,
424                &crate::nodes::common::answered_by(&cfg.model, &response),
425                &response.usage,
426            )?;
427            check_finish(&response)?;
428            let finish_reason = finish_reason_value(response.finish_reason.as_ref());
429            let turn = response.to_message();
430            let ChatResponse { text: raw, reasoning: model_reasoning, usage, .. } = response;
431            let (text, mut reasoning) = match cfg.reasoning_format {
432                ReasoningFormat::Tagged => (raw, String::new()),
433                ReasoningFormat::Separated => split_think_tags(&raw),
434            };
435            if !model_reasoning.is_empty() {
436                reasoning =
437                    if reasoning.is_empty() { model_reasoning } else { format!("{model_reasoning}\n{reasoning}") };
438            }
439            let mut total = answer.usage;
440            total.add(&usage);
441            answer = super::revise::Answered { text, reasoning, usage: total, finish_reason, turn };
442            rounds += 1;
443        }
444    }
445
446    /// The issues of an answer: the numbers `grounding` finds, an unreadable
447    /// structured output and the `checks` of `revise`.
448    #[cfg(feature = "revise")]
449    fn issues_of(
450        &self,
451        pool: &graphrt_core::pool::VariablePool,
452        context: Option<&str>,
453        text: &str,
454        revise: &super::revise::Revise,
455    ) -> Result<Vec<graphrt_core::text_check::Issue>, NodeError> {
456        let grounding = self.config.grounding.as_ref().filter(|grounding| grounding.checks_numbers());
457        let mut issues = Vec::new();
458        let answer = match &self.schema {
459            Some(schema) => match structured(text, schema) {
460                Ok(parsed) => {
461                    if let Some(grounding) = grounding {
462                        let report = grounding.check_numbers_fields(pool, context, &parsed)?;
463                        issues.extend(super::revise::grounding_issues(&report.unsupported)?);
464                    }
465                    Value::from_json(parsed)
466                }
467                Err(error) => return Ok(vec![super::revise::unreadable(&error)]),
468            },
469            None => {
470                if let Some(grounding) = grounding {
471                    let report = grounding.check_numbers_text(pool, context, text)?;
472                    issues.extend(super::revise::grounding_issues(&report.unsupported)?);
473                }
474                Value::from(text)
475            }
476        };
477        issues.extend(revise.check(pool, &answer)?);
478        issues.truncate(graphrt_core::text_check::MAX_ISSUES);
479        Ok(issues)
480    }
481}
482
483/// The structured output of `text`: its JSON value of the schema's type, checked against the schema.
484#[cfg(feature = "revise")]
485fn structured(text: &str, schema: &Json) -> Result<Json, NodeError> {
486    let parsed = extract_json_where(text, |v| schema::matches_top_level_type(v, schema)).ok_or_else(|| {
487        NodeError::new("structured_output", "model output contains no JSON value of the requested type")
488    })?;
489    schema::validate(&parsed, schema).map_err(|problem| {
490        NodeError::new("structured_output", format!("model output does not match the schema: {problem}"))
491    })?;
492    Ok(parsed)
493}
494
495impl Node for LlmNode {
496    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
497        Box::pin(self.execute(ctx))
498    }
499
500    /// Each model response is charged with its cost as it arrives.
501    fn tracks_turns(&self) -> bool {
502        true
503    }
504
505    fn inputs(&self) -> Vec<Selector> {
506        let cfg = &self.config;
507        let mut out = cfg.prompt_template.selectors();
508        out.extend(cfg.context.selectors());
509        out.extend(cfg.vision.selectors());
510        if let Some(memory) = &cfg.memory {
511            out.extend(memory.selectors());
512        }
513        out.extend(cfg.model.selectors());
514        if let Some(grounding) = &cfg.grounding {
515            out.extend(grounding.selectors());
516        }
517        #[cfg(feature = "revise")]
518        if let Some(revise) = &self.revise {
519            out.extend(revise.selectors());
520        }
521        #[cfg(feature = "context")]
522        out.extend(self.context.selectors());
523        out
524    }
525}
526
527/// Factory for the node registry.
528pub fn factory(doc: &NodeDoc) -> Result<Arc<dyn Node>, ConfigError> {
529    Ok(Arc::new(LlmNode::from_doc(doc)?))
530}
531
532#[cfg(test)]
533mod tests {
534    use super::*;
535    use crate::mock::MockModel;
536    use crate::registry::ModelRegistry;
537    use crate::types::{ChatDelta, ContentPart, Role};
538    use graphrt_core::event::Event;
539    use graphrt_core::{NodeOutcome, Services, VariablePool};
540    use std::sync::Mutex;
541
542    fn doc(config: Json) -> NodeDoc {
543        NodeDoc::new("llm", "llm", config)
544    }
545
546    fn ctx_with(model: Arc<MockModel>, pool: VariablePool) -> (NodeContext, Arc<Mutex<Vec<Event>>>) {
547        let services = Services::new().with(ModelRegistry::new().with("openai", model));
548        let events = Arc::new(Mutex::new(Vec::new()));
549        let sink_events = Arc::clone(&events);
550        let ctx = NodeContext::for_test("llm", pool)
551            .with_services(Arc::new(services))
552            .with_sink(Arc::new(move |e| sink_events.lock().unwrap().push(e)));
553        (ctx, events)
554    }
555
556    fn completed(r: NodeResult) -> NodeOutput {
557        match r.unwrap() {
558            NodeOutcome::Completed(o) => o,
559            NodeOutcome::Paused(p) => panic!("unexpected pause {p:?}"),
560        }
561    }
562
563    /// A pool with `turns` history turns of `chars` characters each and a query.
564    #[cfg(feature = "context")]
565    fn pool_with_history(turns: usize, chars: usize) -> VariablePool {
566        let history: Vec<Json> = (0..turns)
567            .flat_map(|n| {
568                [
569                    serde_json::json!({"role": "user", "content": format!("question {n} {}", "q".repeat(chars))}),
570                    serde_json::json!({"role": "assistant", "content": format!("answer {n} {}", "a".repeat(chars))}),
571                ]
572            })
573            .collect();
574        let mut pool = VariablePool::new();
575        pool.insert("sys", "history", Value::from_json(Json::Array(history)));
576        pool.insert("sys", "query", Value::from("the newest question"));
577        pool
578    }
579
580    #[cfg(feature = "context")]
581    fn chat_node(extra: Json) -> LlmNode {
582        let mut config = serde_json::json!({
583            "model": {"provider": "openai", "name": "m"},
584            "prompt_template": [{"role": "system", "text": "Be brief."}],
585            "memory": {},
586        });
587        if let (Some(config), Json::Object(extra)) = (config.as_object_mut(), extra) {
588            config.extend(extra);
589        }
590        LlmNode::from_doc(&doc(config)).unwrap()
591    }
592
593    #[cfg(feature = "context")]
594    fn too_long() -> crate::LlmError {
595        crate::LlmError::ContextLength("prompt is too long: 30100 tokens > 16000 maximum".into())
596    }
597
598    #[cfg(feature = "context")]
599    #[tokio::test]
600    async fn a_request_refused_for_its_size_loses_its_oldest_history_and_is_sent_again() {
601        let model = Arc::new(MockModel::default());
602        model.push_error(too_long());
603        model.push(MockModel::text("short answer"));
604        let (ctx, events) = ctx_with(Arc::clone(&model), pool_with_history(10, 5_000));
605        let out = completed(chat_node(serde_json::json!({})).run(ctx).await);
606        assert_eq!(out.outputs["text"], Value::from("short answer"));
607        let requests = model.requests();
608        assert_eq!(requests.len(), 2);
609        let (refused, retried) = (&requests[0], &requests[1]);
610        assert_eq!(refused.messages.len(), 22);
611        assert!(retried.messages.len() < 12, "{}", retried.messages.len());
612        assert_eq!(retried.messages[0].text(), "Be brief.");
613        let last = retried.messages.last().unwrap();
614        assert_eq!((last.role, last.text().as_str()), (Role::User, "the newest question"));
615        // Whole turns were removed: what is left still alternates and starts with a user message.
616        let roles: Vec<Role> = retried.messages.iter().skip(1).map(|m| m.role).collect();
617        assert!(roles.chunks(2).all(|pair| pair[0] == Role::User), "{roles:?}");
618        assert!(retried.messages[1].text().starts_with("[Context note, written by the runtime."));
619        // The newest history is what stays.
620        assert!(retried.messages.iter().any(|m| m.text().starts_with("answer 9 ")));
621        assert!(!retried.messages.iter().any(|m| m.text().contains("question 0 ")));
622        let trimmed = events.lock().unwrap().iter().any(
623            |event| matches!(event, Event::NodeProgress { name, data, .. } if name == "context_trimmed" && data.get_path(&["reason"]) == Some(Value::from("provider_limit"))),
624        );
625        assert!(trimmed);
626    }
627
628    #[cfg(feature = "context")]
629    #[tokio::test]
630    async fn the_messages_of_the_prompt_template_are_never_removed() {
631        // A template with a document and an example before the question, and no history.
632        let config = serde_json::json!({
633            "model": {"provider": "openai", "name": "m"},
634            "prompt_template": [
635                {"role": "system", "text": "Be brief."},
636                {"role": "user", "text": "Document: {{#start.doc#}}"},
637                {"role": "assistant", "text": "I have read it."},
638                {"role": "user", "text": "Example question"},
639                {"role": "assistant", "text": "Example answer"},
640                {"role": "user", "text": "{{#sys.query#}}"},
641            ],
642        });
643        let node = LlmNode::from_doc(&doc(config.clone())).unwrap();
644        let model = Arc::new(MockModel::default());
645        model.push_error(too_long());
646        model.push(MockModel::text("never reached"));
647        let mut pool = VariablePool::new();
648        pool.insert("start", "doc", Value::from("d".repeat(90_000)));
649        pool.insert("sys", "query", Value::from("the newest question"));
650        let (ctx, _) = ctx_with(Arc::clone(&model), pool);
651        // Nothing here is history, so nothing may go: the node fails as it did before the guard.
652        let error = node.run(ctx).await.unwrap_err();
653        assert_eq!(error.kind, "model_context_length");
654        assert!(error.message.contains("nothing left to remove"), "{}", error.message);
655        assert_eq!(model.requests().len(), 1);
656
657        // The same when the template has no system message and the history starts with one.
658        let no_system = serde_json::json!({
659            "model": {"provider": "openai", "name": "m"},
660            "prompt_template": [
661                {"role": "user", "text": "Document: {{#start.doc#}}"},
662                {"role": "user", "text": "{{#sys.query#}}"},
663            ],
664            "memory": {},
665        });
666        let node = LlmNode::from_doc(&doc(no_system)).unwrap();
667        let model = Arc::new(MockModel::default());
668        model.push_error(too_long());
669        model.push(MockModel::text("short answer"));
670        let mut pool = pool_with_history(10, 5_000);
671        let mut history = vec![serde_json::json!({"role": "system", "content": "A summary the host keeps."})];
672        history.extend(
673            pool.get(&graphrt_core::Selector::of("sys", "history"))
674                .unwrap()
675                .to_json()
676                .as_array()
677                .unwrap()
678                .iter()
679                .cloned(),
680        );
681        pool.insert("sys", "history", Value::from_json(Json::Array(history)));
682        pool.insert("start", "doc", Value::from("the document"));
683        let (ctx, _) = ctx_with(Arc::clone(&model), pool);
684        completed(node.run(ctx).await);
685        let retried = model.requests().pop().unwrap();
686        assert!(retried.messages.iter().any(|m| m.text().ends_with("Document: the document")), "the template stays");
687        assert!(retried.messages.len() < 23);
688
689        // With history in front of the same template, only history goes.
690        let mut with_memory = config;
691        with_memory["memory"] = serde_json::json!({});
692        let node = LlmNode::from_doc(&doc(with_memory)).unwrap();
693        let model = Arc::new(MockModel::default());
694        model.push_error(too_long());
695        model.push(MockModel::text("short answer"));
696        let mut pool = pool_with_history(10, 5_000);
697        pool.insert("start", "doc", Value::from("the document"));
698        let (ctx, _) = ctx_with(Arc::clone(&model), pool);
699        let out = completed(node.run(ctx).await);
700        let retried = model.requests().pop().unwrap();
701        let texts: Vec<String> = retried.messages.iter().map(crate::types::Message::text).collect();
702        for kept in ["Be brief.", "Document: the document", "I have read it.", "Example question", "Example answer"] {
703            assert!(texts.iter().any(|text| text.ends_with(kept)), "`{kept}` was removed: {}", texts.len());
704        }
705        assert!(texts.len() < 27, "{}", texts.len());
706        // The node says in its warnings that the model was not sent everything.
707        let warnings = out.metadata["warnings"].to_json().to_string();
708        assert!(warnings.contains("trimmed to fit the context window"), "{warnings}");
709    }
710
711    #[cfg(feature = "context")]
712    #[tokio::test]
713    async fn a_second_refusal_and_off_fail_with_the_context_length_kind() {
714        let model = Arc::new(MockModel::default());
715        model.push_error(too_long());
716        model.push_error(too_long());
717        let (ctx, _) = ctx_with(Arc::clone(&model), pool_with_history(10, 5_000));
718        let error = chat_node(serde_json::json!({})).run(ctx).await.unwrap_err();
719        assert_eq!(error.kind, "model_context_length");
720        assert_eq!(model.requests().len(), 2);
721        // The message says what was tried, and trying again would not help.
722        assert!(error.message.contains("already trimmed the conversation and sent it again"), "{}", error.message);
723        assert!(!error.retryable);
724
725        let model = Arc::new(MockModel::default());
726        model.push_error(too_long());
727        model.push(MockModel::text("never reached"));
728        let (ctx, _) = ctx_with(Arc::clone(&model), pool_with_history(10, 5_000));
729        let error = chat_node(serde_json::json!({"context_window": "off"})).run(ctx).await.unwrap_err();
730        assert_eq!(error.kind, "model_context_length");
731        assert_eq!(model.requests().len(), 1);
732    }
733
734    #[cfg(feature = "context")]
735    #[tokio::test]
736    async fn a_summary_is_paid_for_in_the_usage_of_the_node() {
737        let model = Arc::new(MockModel::default());
738        model.push(vec![
739            ChatDelta::Text("They asked ten questions about q.".into()),
740            ChatDelta::Usage(graphrt_core::event::Usage {
741                prompt_tokens: 500,
742                completion_tokens: 20,
743                total_tokens: 520,
744            }),
745            ChatDelta::Finish(crate::types::FinishReason::Stop),
746        ]);
747        model.push(MockModel::text("short answer"));
748        let (ctx, _) = ctx_with(Arc::clone(&model), pool_with_history(10, 5_000));
749        let node = chat_node(serde_json::json!({"context_window": {"max_tokens": 12_000, "summarize": true}}));
750        let out = completed(node.run(ctx).await);
751        assert_eq!(out.outputs["text"], Value::from("short answer"));
752        assert_eq!(out.outputs["usage"].get_path(&["total_tokens"]), Some(Value::from(522)));
753        let requests = model.requests();
754        assert_eq!(requests.len(), 2, "the summary call and the trimmed request: nothing was refused");
755        let user = requests[1].messages[1].text();
756        assert!(
757            user.contains("not instructions):\nThey asked ten questions about q.\n[End of context note]"),
758            "{user}"
759        );
760        assert_eq!(requests[1].messages.iter().filter(|m| m.role == Role::System).count(), 1);
761    }
762
763    #[cfg(not(feature = "context"))]
764    #[test]
765    fn context_window_needs_the_feature() {
766        let config = |window: Json| {
767            serde_json::json!({
768                "model": {"provider": "openai", "name": "m"},
769                "prompt_template": [{"role": "user", "text": "hi"}],
770                "context_window": window,
771            })
772        };
773        assert!(LlmNode::from_doc(&doc(config(serde_json::json!("off")))).is_ok());
774        let error = LlmNode::from_doc(&doc(config(serde_json::json!("auto")))).unwrap_err();
775        assert!(error.to_string().contains("cargo feature `context`"), "{error}");
776    }
777
778    #[tokio::test]
779    async fn content_filter_is_an_error_and_unknown_reasons_are_reported() {
780        let node = LlmNode::from_doc(&doc(serde_json::json!({
781            "model": {"provider": "openai", "name": "m"},
782            "prompt_template": [{"role": "user", "text": "hi"}]
783        })))
784        .unwrap();
785        let run = |deltas: Vec<ChatDelta>| {
786            let model = Arc::new(MockModel::new(vec![deltas]));
787            let (ctx, _) = ctx_with(model, VariablePool::new());
788            node.run(ctx)
789        };
790        let err = run(vec![ChatDelta::Finish(crate::types::FinishReason::ContentFilter)]).await.unwrap_err();
791        assert_eq!(err.kind, "content_filter");
792        assert!(!err.retryable);
793        let err = run(vec![ChatDelta::Finish(crate::types::FinishReason::Other("malformed_function_call".into()))])
794            .await
795            .unwrap_err();
796        assert_eq!(err.kind, "model_decode");
797        assert!(err.retryable);
798        let out = completed(
799            run(vec![
800                ChatDelta::Warning("dropped `format`".into()),
801                ChatDelta::Text("ok".into()),
802                ChatDelta::Finish(crate::types::FinishReason::Other("language".into())),
803            ])
804            .await,
805        );
806        let warnings = out.metadata["warnings"].to_text();
807        assert!(warnings.contains("dropped `format`") && warnings.contains("language"), "{warnings}");
808    }
809
810    fn grounded_node(confirm: &str) -> LlmNode {
811        LlmNode::from_doc(&doc(serde_json::json!({
812            "model": {"provider": "langgenius/openai/openai", "name": "gpt"},
813            "prompt_template": [
814                {"role": "system", "text": "Our express laundry is 99k with free delivery."},
815                {"role": "user", "text": "{{#start.message#}}"}
816            ],
817            "grounding": {
818                "facts": [["sys", "chatbot_facts"], ["missing", "value"]],
819                "customer": [["start", "message"]],
820                "fallback": "Sorry, I don't know {{#start.message#}} yet.",
821                "confirm": confirm
822            }
823        })))
824        .unwrap()
825    }
826
827    fn laundry_pool(message: &str) -> VariablePool {
828        let mut pool = VariablePool::new();
829        pool.insert("sys", "chatbot_facts", Value::from("Laundry: 8k per kg, express 15k per kg."));
830        pool.insert("start", "message", Value::from(message));
831        pool
832    }
833
834    fn answer(text: &str) -> Vec<ChatDelta> {
835        vec![ChatDelta::Text(text.into()), ChatDelta::Finish(crate::types::FinishReason::Stop)]
836    }
837
838    #[tokio::test]
839    async fn a_grounded_answer_keeps_what_the_facts_hold_and_is_not_streamed() {
840        let model = Arc::new(MockModel::new(vec![answer("Express is $15k per kg. We also offer free delivery.")]));
841        let (ctx, events) = ctx_with(Arc::clone(&model), laundry_pool("How much is express?"));
842        let out = completed(grounded_node("off").run(ctx).await);
843        assert_eq!(out.outputs["text"], Value::from("Express is 15k per kg."));
844        assert_eq!(out.outputs["grounded"], Value::from(true));
845        assert_eq!(out.outputs["draft"], Value::from("Express is $15k per kg. We also offer free delivery."));
846        let unsupported = out.outputs["unsupported"].to_json();
847        assert_eq!(unsupported[0]["sentence"], "We also offer free delivery.");
848        assert!(events.lock().unwrap().iter().all(|event| !matches!(event, Event::NodeChunk { .. })));
849    }
850
851    #[tokio::test]
852    async fn the_prompt_is_no_source_and_the_fallback_is_a_template() {
853        // The prompt says 99k and free delivery: a builder model wrote it, the facts do not say so.
854        let model = Arc::new(MockModel::new(vec![answer("Express is 99k, with free delivery.")]));
855        let (ctx, _) = ctx_with(Arc::clone(&model), laundry_pool("express?"));
856        let out = completed(grounded_node("off").run(ctx).await);
857        assert_eq!(out.outputs["text"], Value::from("Sorry, I don't know express? yet."));
858        assert_eq!(out.outputs["grounded"], Value::from(false));
859        assert_eq!(model.requests().len(), 1);
860    }
861
862    #[tokio::test]
863    async fn a_model_confirms_words_the_check_missed_but_never_numbers() {
864        let model = Arc::new(MockModel::new(vec![
865            answer("Yes, the express service washes your clothes within a day. It costs 20k."),
866            answer("1. [1] ALL\n2. [1] ALL"),
867        ]));
868        let (ctx, _) = ctx_with(Arc::clone(&model), laundry_pool("Is express fast?"));
869        let out = completed(grounded_node("model").run(ctx).await);
870        assert_eq!(out.outputs["text"], Value::from("Yes, the express service washes your clothes within a day."));
871        assert_eq!(out.outputs["confirmed"].to_json()[0], "Yes, the express service washes your clothes within a day.");
872        assert!(out.outputs.get("check_usage").is_some());
873        let requests = model.requests();
874        assert_eq!(requests.len(), 2);
875        assert_eq!(requests[1].temperature, Some(0.0));
876        let asked = requests[1].messages[1].text();
877        assert!(asked.contains("1. Yes, the express service") && !asked.contains("20k"), "{asked}");
878    }
879
880    fn report_node(structured: bool, on_fail: &str) -> Result<LlmNode, ConfigError> {
881        let mut config = serde_json::json!({
882            "model": {"provider": "openai", "name": "gpt"},
883            "prompt_template": [{"role": "user", "text": "Write the report."}],
884            "grounding": {
885                "facts": [["figures", "json"]],
886                "check": "numbers",
887                "numbers": {"tolerance": "rounding", "ratios_as_percent": true},
888                "on_fail": on_fail,
889                "fallback": "The report is not ready."
890            }
891        });
892        if structured {
893            config["structured_output"] = serde_json::json!({"schema": {"type": "object", "properties": {
894                "summary": {"type": "string"},
895                "stores": {"type": "array", "items": {"type": "object", "properties": {"note": {"type": "string"}}}}
896            }}});
897        }
898        LlmNode::from_doc(&doc(config))
899    }
900
901    fn figures_pool() -> VariablePool {
902        let mut pool = VariablePool::new();
903        pool.insert(
904            "figures",
905            "json",
906            Value::from_json(serde_json::json!({"sales": 1_234_567, "growth": 0.1319, "stores": [{"orders": 1520}]})),
907        );
908        pool
909    }
910
911    #[tokio::test]
912    async fn a_structured_report_lists_the_unsupported_numbers_per_field() {
913        let report = r#"{"summary": "Sales reached 1.2 million, up 13.2%.",
914            "stores": [{"note": "North took 1,520 orders."}, {"note": "South grew 17%. It had 2 new staff."}]}"#;
915        let model = Arc::new(MockModel::new(vec![answer(report)]));
916        let (ctx, events) = ctx_with(Arc::clone(&model), figures_pool());
917        let out = completed(report_node(true, "output").unwrap().run(ctx).await);
918        assert_eq!(out.outputs["grounded"], Value::from(false));
919        assert_eq!(
920            out.outputs["unsupported"].to_json(),
921            serde_json::json!([
922                {"field": "stores[1].note", "number": "17%", "sentence": "South grew 17%.", "reason": "value"}
923            ])
924        );
925        // The draft is kept as written, and streamed: the check changes nothing.
926        assert_eq!(
927            out.outputs["structured_output"].to_json()["stores"][1]["note"],
928            "South grew 17%. It had 2 new staff."
929        );
930        assert!(events.lock().unwrap().iter().any(|event| matches!(event, Event::NodeChunk { .. })));
931    }
932
933    #[tokio::test]
934    async fn a_text_report_falls_back_or_keeps_its_draft() {
935        let model = Arc::new(MockModel::new(vec![
936            answer("Sales were 1,234,567 and growth 13.19%."),
937            answer("Growth was 15%."),
938        ]));
939        let (ctx, _) = ctx_with(Arc::clone(&model), figures_pool());
940        let out = completed(report_node(false, "fallback").unwrap().run(ctx).await);
941        assert_eq!(out.outputs["grounded"], Value::from(true));
942        assert_eq!(out.outputs["text"], Value::from("Sales were 1,234,567 and growth 13.19%."));
943        let (ctx, _) = ctx_with(Arc::clone(&model), figures_pool());
944        let out = completed(report_node(false, "fallback").unwrap().run(ctx).await);
945        assert_eq!(out.outputs["text"], Value::from("The report is not ready."));
946        assert_eq!(out.outputs["draft"], Value::from("Growth was 15%."));
947        assert_eq!(out.outputs["unsupported"].to_json()[0]["field"], "text");
948    }
949
950    #[cfg(feature = "grounding-attribution")]
951    /// A report about a shop's product categories, checked for attribution.
952    fn attributed_node(on_fail: &str, scopes: serde_json::Value) -> Result<LlmNode, ConfigError> {
953        LlmNode::from_doc(&doc(serde_json::json!({
954            "model": {"provider": "openai", "name": "gpt"},
955            "prompt_template": [{"role": "user", "text": "Write the report."}],
956            "structured_output": {"schema": {"type": "object", "properties": {
957                "summary": {"type": "string"},
958                "highlights": {"type": "array", "items": {"type": "string"}}
959            }}},
960            "grounding": {
961                "facts": [["shop", "facts"]],
962                "check": "numbers",
963                "numbers": {"ratios_as_percent": true},
964                "attribution": {
965                    "entities": [["shop", "categories"], {"from": ["shop", "facts", "stores"], "label": "name"}],
966                    "groups": ["all categories"],
967                    "scopes": scopes
968                },
969                "on_fail": on_fail
970            }
971        })))
972    }
973
974    #[cfg(feature = "grounding-attribution")]
975    fn shop_pool() -> VariablePool {
976        let mut pool = VariablePool::new();
977        pool.insert(
978            "shop",
979            "facts",
980            Value::from_json(serde_json::json!({
981                "total_revenue": 85_450,
982                "stores": [{"name": "Harbor Street", "visits": 3_120}, {"name": "Old Mill", "visits": 2_045}]
983            })),
984        );
985        pool.insert(
986            "shop",
987            "categories",
988            Value::from_json(serde_json::json!([
989                {"entity": "Electronics", "aliases": ["gadgets"], "revenue": 48_200, "share": 0.564},
990                {"entity": "Garden Tools", "revenue": 21_900, "share": 0.256},
991                {"entity": "Toys", "revenue": 15_350, "share": 0.18}
992            ])),
993        );
994        pool.insert("prep", "top", Value::from("Electronics"));
995        pool
996    }
997
998    #[cfg(feature = "grounding-attribution")]
999    async fn attributed(on_fail: &str, scopes: serde_json::Value, report: &str) -> NodeResult {
1000        let model = Arc::new(MockModel::new(vec![answer(report)]));
1001        let (ctx, _) = ctx_with(Arc::clone(&model), shop_pool());
1002        attributed_node(on_fail, scopes).unwrap().run(ctx).await
1003    }
1004
1005    #[cfg(feature = "grounding-attribution")]
1006    #[tokio::test]
1007    async fn a_figure_of_another_entity_is_reported_with_its_owner() {
1008        let report = r#"{"summary": "Gadgets took 56.4% of revenue, Garden Tools 25.6% and Toys 15,350.",
1009            "highlights": ["Harbor Street had 3,120 visits.", "Toys reached 48,200 in revenue.", "Revenue grew to 21,900."]}"#;
1010        let scopes = serde_json::json!({"highlights[*]": "{{#prep.top#}}"});
1011        let out = completed(attributed("output", scopes, report).await);
1012        assert_eq!(out.outputs["grounded"], Value::from(false));
1013        assert_eq!(
1014            out.outputs["unsupported"].to_json(),
1015            serde_json::json!([
1016                {"field": "highlights[1]", "number": "48,200", "sentence": "Toys reached 48,200 in revenue.",
1017                 "reason": "attribution", "named": "Toys", "owners": ["Electronics"]},
1018                {"field": "highlights[2]", "number": "21,900", "sentence": "Revenue grew to 21,900.",
1019                 "reason": "attribution", "named": "Electronics", "owners": ["Garden Tools"]}
1020            ])
1021        );
1022    }
1023
1024    #[cfg(feature = "grounding-attribution")]
1025    #[tokio::test]
1026    async fn a_true_report_passes_and_scopes_come_from_a_value() {
1027        let report = r#"{"summary": "Across all categories, Electronics led with 48.2k (56%), ahead of Garden Tools at 21,900.",
1028            "highlights": ["Revenue reached 15,350.", "Old Mill had 2,045 visits."]}"#;
1029        let model = Arc::new(MockModel::new(vec![answer(report)]));
1030        let mut pool = shop_pool();
1031        pool.insert("prep", "scopes", Value::from_json(serde_json::json!({"highlights[0]": "Toys", "summary": null})));
1032        let (ctx, _) = ctx_with(Arc::clone(&model), pool);
1033        let out = completed(attributed_node("output", serde_json::json!(["prep", "scopes"])).unwrap().run(ctx).await);
1034        assert_eq!(out.outputs["unsupported"].to_json(), serde_json::json!([]));
1035        assert_eq!(out.outputs["grounded"], Value::from(true));
1036    }
1037
1038    #[cfg(feature = "grounding-attribution")]
1039    #[tokio::test]
1040    async fn on_fail_error_fails_the_node_with_what_was_found() {
1041        let error = attributed("error", serde_json::json!({}), r#"{"summary": "Toys took 56.4% of revenue."}"#)
1042            .await
1043            .unwrap_err();
1044        assert_eq!(error.kind, "ungrounded");
1045        let message = error.to_string();
1046        assert!(message.contains(r#""named":"Toys""#) && message.contains(r#""owners":["Electronics"]"#), "{message}");
1047        let passed = attributed("error", serde_json::json!({}), r#"{"summary": "Toys took 18% of revenue."}"#).await;
1048        assert_eq!(completed(passed).outputs["grounded"], Value::from(true));
1049    }
1050
1051    #[cfg(feature = "grounding-attribution")]
1052    #[tokio::test]
1053    async fn malformed_entities_fail_the_node() {
1054        let model = Arc::new(MockModel::new(vec![answer(r#"{"summary": "ok"}"#)]));
1055        let mut pool = shop_pool();
1056        pool.insert("shop", "categories", Value::from("not entities"));
1057        let (ctx, _) = ctx_with(Arc::clone(&model), pool);
1058        let error = attributed_node("output", serde_json::json!({})).unwrap().run(ctx).await.unwrap_err();
1059        assert!(error.to_string().contains("attribution.entities"), "{error}");
1060    }
1061
1062    #[cfg(not(feature = "grounding-attribution"))]
1063    #[test]
1064    fn attribution_needs_its_feature() {
1065        let error = LlmNode::from_doc(&doc(serde_json::json!({
1066            "model": {"provider": "openai", "name": "gpt"},
1067            "prompt_template": [{"role": "user", "text": "hi"}],
1068            "grounding": {"check": "numbers", "on_fail": "output", "attribution": {"entities": [["a", "b"]]}}
1069        })))
1070        .unwrap_err();
1071        assert!(error.to_string().contains("`grounding-attribution` feature"), "{error}");
1072    }
1073
1074    #[cfg(feature = "grounding-attribution")]
1075    #[test]
1076    fn attribution_is_checked_for_what_it_can_do() {
1077        let sentences = LlmNode::from_doc(&doc(serde_json::json!({
1078            "model": {"provider": "openai", "name": "gpt"},
1079            "prompt_template": [{"role": "user", "text": "hi"}],
1080            "grounding": {"fallback": "?", "attribution": {"entities": [["a", "b"]]}}
1081        })));
1082        assert!(sentences.err().unwrap().to_string().contains("`attribution` goes with `check: numbers`"));
1083        let no_entities = LlmNode::from_doc(&doc(serde_json::json!({
1084            "model": {"provider": "openai", "name": "gpt"},
1085            "prompt_template": [{"role": "user", "text": "hi"}],
1086            "grounding": {"check": "numbers", "on_fail": "output", "attribution": {"entities": []}}
1087        })));
1088        assert!(no_entities.err().unwrap().to_string().contains("needs `entities`"));
1089        let error_with_sentences = LlmNode::from_doc(&doc(serde_json::json!({
1090            "model": {"provider": "openai", "name": "gpt"},
1091            "prompt_template": [{"role": "user", "text": "hi"}],
1092            "grounding": {"on_fail": "error"}
1093        })));
1094        assert!(error_with_sentences.err().unwrap().to_string().contains("`on_fail: error`"));
1095        assert!(report_node(true, "error").is_ok());
1096    }
1097
1098    #[test]
1099    fn numbers_grounding_is_checked_for_what_it_can_do() {
1100        let error = report_node(true, "fallback").err().unwrap();
1101        assert!(error.to_string().contains("on_fail: output"), "{error}");
1102        assert!(report_node(false, "output").is_ok());
1103        let sentences_output = LlmNode::from_doc(&doc(serde_json::json!({
1104            "model": {"provider": "openai", "name": "gpt"},
1105            "prompt_template": [{"role": "user", "text": "hi"}],
1106            "grounding": {"on_fail": "output"}
1107        })));
1108        assert!(sentences_output.err().unwrap().to_string().contains("check: numbers"));
1109        let no_fallback = LlmNode::from_doc(&doc(serde_json::json!({
1110            "model": {"provider": "openai", "name": "gpt"},
1111            "prompt_template": [{"role": "user", "text": "hi"}],
1112            "grounding": {"facts": []}
1113        })));
1114        assert!(no_fallback.err().unwrap().to_string().contains("fallback"));
1115    }
1116
1117    #[test]
1118    fn grounding_does_not_go_with_structured_output() {
1119        let error = LlmNode::from_doc(&doc(serde_json::json!({
1120            "model": {"provider": "openai", "name": "gpt"},
1121            "prompt_template": [{"role": "user", "text": "hi"}],
1122            "structured_output": {"schema": {"type": "object"}},
1123            "grounding": {"fallback": "?"}
1124        })))
1125        .unwrap_err();
1126        assert!(error.to_string().contains("structured output"), "{error}");
1127    }
1128
1129    #[tokio::test]
1130    async fn streams_and_outputs() {
1131        let model = Arc::new(MockModel::new(vec![vec![
1132            ChatDelta::Reasoning("why".into()),
1133            ChatDelta::Text("Hel".into()),
1134            ChatDelta::Text("lo".into()),
1135            ChatDelta::Finish(crate::types::FinishReason::Stop),
1136        ]]));
1137        let mut pool = VariablePool::new();
1138        pool.insert("sys", "query", Value::from("hi there"));
1139        let node = LlmNode::from_doc(&doc(serde_json::json!({
1140            "model": {"provider": "langgenius/openai/openai", "name": "gpt", "completion_params": {"temperature": 0.2}},
1141            "prompt_template": [{"role": "system", "text": "be nice"}, {"role": "user", "text": "{{#sys.query#}}"}]
1142        })))
1143        .unwrap();
1144        let (ctx, events) = ctx_with(Arc::clone(&model), pool);
1145        let out = completed(node.run(ctx).await);
1146        assert_eq!(out.outputs["text"], Value::from("Hello"));
1147        assert_eq!(out.outputs["reasoning"], Value::from("why"));
1148        assert_eq!(out.outputs["finish_reason"], Value::from("stop"));
1149        let chunks: Vec<(String, String)> = events
1150            .lock()
1151            .unwrap()
1152            .iter()
1153            .filter_map(|e| match e {
1154                Event::NodeChunk { field, chunk, .. } => Some((field.to_string(), chunk.clone())),
1155                _ => None,
1156            })
1157            .collect();
1158        assert_eq!(chunks.len(), 3);
1159        assert_eq!(chunks[0].0, "reasoning");
1160        let req = &model.requests()[0];
1161        assert_eq!(req.model, "gpt");
1162        assert_eq!(req.temperature, Some(0.2));
1163        assert_eq!(req.messages[0].role, Role::System);
1164        assert!(matches!(&req.messages[1].content[0], ContentPart::Text { text } if text == "hi there"));
1165    }
1166
1167    #[tokio::test]
1168    async fn rendered_messages_are_reported_only_when_the_host_captures_content() {
1169        let node = LlmNode::from_doc(&doc(serde_json::json!({
1170            "model": {"provider": "openai", "name": "gpt"},
1171            "prompt_template": [{"role": "system", "text": "key {{#env.KEY#}}"}, {"role": "user", "text": "hi"}]
1172        })))
1173        .unwrap();
1174        let mut pool = VariablePool::new();
1175        pool.insert("env", "KEY", Value::Secret(Arc::from("sk-live-1")));
1176        let requests = |events: &Arc<Mutex<Vec<Event>>>| -> Vec<Value> {
1177            let events = events.lock().unwrap();
1178            let found = events.iter().filter_map(|e| match e {
1179                Event::NodeProgress { name, data, .. } if name == "model_request" => Some(data.clone()),
1180                _ => None,
1181            });
1182            found.collect()
1183        };
1184
1185        let model = Arc::new(MockModel::new(vec![MockModel::text("ok")]));
1186        let (ctx, events) = ctx_with(Arc::clone(&model), pool.clone());
1187        completed(node.run(ctx).await);
1188        assert!(requests(&events).is_empty());
1189
1190        let model = Arc::new(MockModel::new(vec![MockModel::text("ok")]));
1191        let (ctx, events) = ctx_with(model, pool);
1192        let services = (*ctx.services).clone().with(graphrt_core::node::CaptureContent);
1193        completed(node.run(ctx.with_services(Arc::new(services))).await);
1194        let reported = requests(&events);
1195        assert_eq!(reported.len(), 1);
1196        let json = reported[0].to_json();
1197        assert_eq!(json["messages"][0]["role"], "system");
1198        assert_eq!(json["messages"][0]["content"][0]["text"], "key ******");
1199        assert_eq!(json["messages"][1]["content"][0]["text"], "hi");
1200    }
1201
1202    #[tokio::test]
1203    async fn structured_output_and_separated_reasoning() {
1204        let model = Arc::new(MockModel::new(vec![MockModel::text("<think>plan</think>{\"n\": 3}")]));
1205        let node = LlmNode::from_doc(&doc(serde_json::json!({
1206            "model": {"provider": "openai", "name": "gpt"},
1207            "prompt_template": [{"role": "user", "text": "give n"}],
1208            "structured_output_switch_on": true,
1209            "structured_output": {"schema": {"type": "object", "properties": {"n": {"type": "integer"}}}},
1210            "reasoning_format": "separated"
1211        })))
1212        .unwrap();
1213        let (ctx, _) = ctx_with(Arc::clone(&model), VariablePool::new());
1214        let out = completed(node.run(ctx).await);
1215        assert_eq!(out.outputs["structured_output"].get_path(&["n"]), Some(Value::Int(3)));
1216        assert_eq!(out.outputs["reasoning"], Value::from("plan"));
1217        assert!(matches!(model.requests()[0].response_format, Some(ResponseFormat::JsonSchema { .. })));
1218    }
1219
1220    #[tokio::test]
1221    async fn separated_reasoning_streams_without_think_tags() {
1222        let model = Arc::new(MockModel::new(vec![vec![
1223            ChatDelta::Text("<thi".into()),
1224            ChatDelta::Text("nk>plan</th".into()),
1225            ChatDelta::Text("ink>\nHel".into()),
1226            ChatDelta::Text("lo".into()),
1227            ChatDelta::Finish(crate::types::FinishReason::Stop),
1228        ]]));
1229        let node = LlmNode::from_doc(&doc(serde_json::json!({
1230            "model": {"provider": "openai", "name": "gpt"},
1231            "prompt_template": [{"role": "user", "text": "hi"}],
1232            "reasoning_format": "separated"
1233        })))
1234        .unwrap();
1235        let (ctx, events) = ctx_with(model, VariablePool::new());
1236        let out = completed(node.run(ctx).await);
1237        let mut streamed = String::new();
1238        let mut reasoning = String::new();
1239        for e in events.lock().unwrap().iter() {
1240            if let Event::NodeChunk { field, chunk, .. } = e {
1241                match field.as_ref() {
1242                    "text" => streamed.push_str(chunk),
1243                    _ => reasoning.push_str(chunk),
1244                }
1245            }
1246        }
1247        assert_eq!(streamed, "Hello");
1248        assert_eq!(out.outputs["text"], Value::from(streamed.as_str()));
1249        assert_eq!(reasoning, "plan");
1250    }
1251
1252    #[tokio::test]
1253    async fn structured_output_is_validated() {
1254        let model = Arc::new(MockModel::new(vec![MockModel::text("see [1] and {\"m\": 1}")]));
1255        let node = LlmNode::from_doc(&doc(serde_json::json!({
1256            "model": {"provider": "openai", "name": "gpt"},
1257            "prompt_template": [{"role": "user", "text": "give n"}],
1258            "structured_output": {"schema": {"type": "object", "required": ["n"], "properties": {"n": {"type": "integer"}}}}
1259        })))
1260        .unwrap();
1261        let (ctx, _) = ctx_with(model, VariablePool::new());
1262        let err = node.run(ctx).await.unwrap_err();
1263        assert_eq!(err.kind, "structured_output");
1264        assert!(err.message.contains("`n`"), "{}", err.message);
1265        assert!(err.retryable);
1266    }
1267
1268    #[tokio::test]
1269    async fn invalid_completion_params_fail_the_node() {
1270        let model = Arc::new(MockModel::new(vec![MockModel::text("x")]));
1271        let node = LlmNode::from_doc(&doc(serde_json::json!({
1272            "model": {"provider": "openai", "name": "gpt", "completion_params": {"temperature": "abc"}},
1273            "prompt_template": [{"role": "user", "text": "hi"}]
1274        })))
1275        .unwrap();
1276        let (ctx, _) = ctx_with(Arc::clone(&model), VariablePool::new());
1277        let err = node.run(ctx).await.unwrap_err();
1278        assert_eq!(err.kind, "invalid_input");
1279        assert!(err.message.contains("temperature"));
1280        assert!(model.requests().is_empty());
1281    }
1282
1283    #[test]
1284    fn inputs_cover_every_reference() {
1285        let node = LlmNode::from_doc(&doc(serde_json::json!({
1286            "model": {"provider": "openai", "name": "gpt", "completion_params": {"temperature": "{{#cfg.t#}}"}},
1287            "prompt_template": [{"role": "user", "text": "{{#start.q#}}"}],
1288            "context": {"enabled": true, "variable_selector": ["kb", "result"]},
1289            "vision": {"enabled": true, "configs": {"variable_selector": ["start", "files"]}},
1290            "memory": {"window": {"enabled": false}}
1291        })))
1292        .unwrap();
1293        let inputs: Vec<String> = node.inputs().iter().map(ToString::to_string).collect();
1294        for expected in ["start.q", "kb.result", "start.files", "sys.history", "sys.query", "cfg.t"] {
1295            assert!(inputs.iter().any(|i| i == expected), "missing {expected} in {inputs:?}");
1296        }
1297    }
1298
1299    #[tokio::test]
1300    async fn model_errors_map_to_node_errors() {
1301        let model = Arc::new(MockModel::new(vec![]));
1302        model.push_error(crate::error::LlmError::Server { status: 503, message: "down".into() });
1303        let node = LlmNode::from_doc(&doc(serde_json::json!({
1304            "model": {"provider": "openai", "name": "gpt"},
1305            "prompt_template": {"text": "completion style"}
1306        })))
1307        .unwrap();
1308        let (ctx, _) = ctx_with(model, VariablePool::new());
1309        let err = node.run(ctx).await.unwrap_err();
1310        assert!(err.retryable);
1311        assert_eq!(err.kind, "model_server");
1312    }
1313
1314    #[tokio::test]
1315    async fn missing_registry_is_a_fatal_error() {
1316        let node = LlmNode::from_doc(&doc(serde_json::json!({
1317            "model": {"provider": "openai", "name": "gpt"},
1318            "prompt_template": [{"role": "user", "text": "x"}]
1319        })))
1320        .unwrap();
1321        let err = node.run(NodeContext::for_test("llm", VariablePool::new())).await.unwrap_err();
1322        assert!(!err.retryable);
1323    }
1324
1325    #[test]
1326    fn rejects_empty_prompt() {
1327        let err = LlmNode::from_doc(&doc(serde_json::json!({"model": {"provider": "p", "name": "m"}}))).unwrap_err();
1328        assert!(err.message.contains("prompt_template"));
1329    }
1330
1331    /// A structured report with a numbers check and `revise`.
1332    #[cfg(feature = "revise")]
1333    fn revising_node(revise: serde_json::Value) -> Result<LlmNode, ConfigError> {
1334        let mut config = serde_json::json!({
1335            "model": {"provider": "openai", "name": "gpt"},
1336            "prompt_template": [{"role": "user", "text": "Write the report."}],
1337            "structured_output": {"schema": {"type": "object", "required": ["summary", "notes"], "properties": {
1338                "summary": {"type": "string"},
1339                "notes": {"type": "array", "items": {"type": "string"}}
1340            }}},
1341            "grounding": {"facts": [["figures", "json"]], "check": "numbers",
1342                "numbers": {"ratios_as_percent": true}, "on_fail": "output"}
1343        });
1344        config["revise"] = revise;
1345        LlmNode::from_doc(&doc(config))
1346    }
1347
1348    #[cfg(feature = "revise")]
1349    fn scored(text: &str) -> Vec<ChatDelta> {
1350        vec![
1351            ChatDelta::Text(text.into()),
1352            ChatDelta::Usage(graphrt_core::event::Usage { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 }),
1353            ChatDelta::Finish(crate::types::FinishReason::Stop),
1354        ]
1355    }
1356
1357    #[cfg(feature = "revise")]
1358    #[tokio::test]
1359    async fn a_report_with_issues_is_revised_in_the_same_conversation() {
1360        let model = Arc::new(MockModel::new(vec![
1361            scored(r#"{"summary": "Sales reached 1.2 million; growth was 17%.", "notes": ["One note."]}"#),
1362            scored(r#"{"summary": "Sales reached 1.2 million. Growth was 13.2%.", "notes": ["First.", "Second."]}"#),
1363        ]));
1364        let (ctx, events) = ctx_with(Arc::clone(&model), figures_pool());
1365        let node = revising_node(serde_json::json!({
1366            "max_rounds": 2,
1367            "checks": {"forbid": [{"name": "semicolon", "text": ";", "message": "split the sentence with a full stop"}],
1368                       "paragraphs": {"notes": 2}},
1369            "message": {"text": "Fix these issues:"}
1370        }))
1371        .unwrap();
1372        let out = completed(node.run(ctx).await);
1373        assert_eq!(out.outputs["revisions"], Value::Int(1));
1374        assert_eq!(out.outputs["issues"].to_json(), serde_json::json!([]));
1375        assert_eq!(out.outputs["grounded"], Value::from(true));
1376        assert_eq!(
1377            out.outputs["structured_output"].to_json()["summary"],
1378            "Sales reached 1.2 million. Growth was 13.2%."
1379        );
1380        assert_eq!(out.outputs["usage"].to_json()["total_tokens"], 30);
1381        let requests = model.requests();
1382        assert_eq!(requests.len(), 2);
1383        let messages = &requests[1].messages;
1384        assert_eq!(messages.len(), 3);
1385        assert_eq!(messages[1].role, Role::Assistant);
1386        assert!(messages[1].text().contains("growth was 17%"));
1387        assert_eq!(
1388            messages[2].text(),
1389            "Fix these issues:\n\n- summary: 17% is not in the facts (\"Sales reached 1.2 million; growth was 17%.\")\n\
1390             - summary: split the sentence with a full stop (\";\")\n- notes: write exactly 2 paragraphs, not 1"
1391        );
1392        // Only the last answer may reach anyone: nothing is streamed.
1393        assert!(!events.lock().unwrap().iter().any(|event| matches!(event, Event::NodeChunk { .. })));
1394    }
1395
1396    #[cfg(feature = "revise")]
1397    #[tokio::test]
1398    async fn the_rounds_end_with_the_issues_the_last_answer_still_has() {
1399        let model = Arc::new(MockModel::new(vec![
1400            answer("Here is the report."),
1401            answer(r#"{"summary": "Growth was 17%.", "notes": []}"#),
1402        ]));
1403        let (ctx, _) = ctx_with(Arc::clone(&model), figures_pool());
1404        let out = completed(revising_node(serde_json::json!({})).unwrap().run(ctx).await);
1405        assert_eq!(out.outputs["revisions"], Value::Int(1));
1406        assert_eq!(out.outputs["grounded"], Value::from(false));
1407        assert_eq!(out.outputs["issues"].to_json()[0]["message"], "17% is not in the facts");
1408        // The first answer was not JSON: the model was told so.
1409        let asked = model.requests()[1].messages[2].text();
1410        assert!(asked.contains("model output contains no JSON value"), "{asked}");
1411        assert!(asked.contains("Answer with one JSON value that matches the schema"), "{asked}");
1412    }
1413
1414    #[cfg(feature = "revise")]
1415    #[tokio::test]
1416    async fn a_clean_first_answer_is_not_revised() {
1417        let model = Arc::new(MockModel::new(vec![answer(r#"{"summary": "Growth was 13.2%.", "notes": ["a"]}"#)]));
1418        let (ctx, _) = ctx_with(Arc::clone(&model), figures_pool());
1419        let out = completed(revising_node(serde_json::json!({"max_rounds": 3})).unwrap().run(ctx).await);
1420        assert_eq!(out.outputs["revisions"], Value::Int(0));
1421        assert_eq!(model.requests().len(), 1);
1422    }
1423
1424    #[cfg(feature = "revise")]
1425    #[test]
1426    fn revise_goes_with_a_numbers_check() {
1427        let error = LlmNode::from_doc(&doc(serde_json::json!({
1428            "model": {"provider": "openai", "name": "gpt"},
1429            "prompt_template": [{"role": "user", "text": "Hi"}],
1430            "grounding": {"facts": [["a", "b"]], "fallback": "?"},
1431            "revise": {}
1432        })))
1433        .unwrap_err();
1434        assert!(error.to_string().contains("`revise` goes with `grounding` of `check: numbers`"), "{error}");
1435        let error = revising_node(serde_json::json!({"max_rounds": 9})).unwrap_err();
1436        assert!(error.to_string().contains("`max_rounds` is 1 to 5"), "{error}");
1437        // Without grounding, the checks alone decide.
1438        let node = LlmNode::from_doc(&doc(serde_json::json!({
1439            "model": {"provider": "openai", "name": "gpt"},
1440            "prompt_template": [{"role": "user", "text": "Hi"}],
1441            "revise": {"checks": {"forbid": [{"text": ";"}]}}
1442        })));
1443        assert!(node.is_ok());
1444    }
1445
1446    #[test]
1447    fn revise_is_in_the_schema_only_with_its_feature() {
1448        let descriptor = crate::nodes::descriptors::llm();
1449        let has = descriptor.config_schema["properties"].get("revise").is_some();
1450        assert_eq!(has, cfg!(feature = "revise"));
1451        assert_eq!(descriptor.outputs.iter().any(|o| o.name == "revisions"), cfg!(feature = "revise"));
1452    }
1453}