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//! Structured output is parsed from the answer and checked against the schema
16//! (top-level type, required properties, property types); a mismatch is a
17//! retryable `structured_output` error.
18
19use std::sync::Arc;
20
21use futures::future::BoxFuture;
22use graphrt_core::dsl::NodeDoc;
23use graphrt_core::node::{ConfigError, NodeResult, parse_config};
24use graphrt_core::value::Value;
25use graphrt_core::{Node, NodeContext, NodeError, NodeOutput, Selector};
26use serde::Deserialize;
27use serde_json::Value as Json;
28
29use super::common::{
30    ContextConfig, FinishCheck, MemoryConfig, ModelConfig, PromptTemplate, StreamMode, VisionConfig, build_messages,
31    check_finish, extract_json_where, finish_reason_value, invoke, model_for, report_request_messages,
32    split_think_tags, usage_value,
33};
34use super::schema;
35use crate::types::{ChatResponse, ResponseFormat};
36
37/// How `<think>` tags inside the answer are treated.
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
39#[serde(rename_all = "snake_case")]
40#[non_exhaustive]
41pub enum ReasoningFormat {
42    /// Keep tags in `text` as produced.
43    #[default]
44    Tagged,
45    /// Move tagged reasoning into `reasoning`.
46    Separated,
47}
48
49#[derive(Clone, Debug, Default, Deserialize)]
50struct StructuredOutput {
51    #[serde(default)]
52    enabled: Option<bool>,
53    #[serde(default)]
54    schema: Option<Json>,
55}
56
57/// Configuration of the `llm` node.
58#[derive(Clone, Debug, Deserialize)]
59pub struct LlmConfig {
60    pub model: ModelConfig,
61    #[serde(default)]
62    pub prompt_template: PromptTemplate,
63    #[serde(default)]
64    pub context: ContextConfig,
65    #[serde(default)]
66    pub vision: VisionConfig,
67    #[serde(default)]
68    pub memory: Option<MemoryConfig>,
69    #[serde(default)]
70    structured_output: Option<StructuredOutput>,
71    #[serde(default, alias = "structured_output_switch_on")]
72    structured_output_enabled: Option<bool>,
73    #[serde(default)]
74    pub reasoning_format: ReasoningFormat,
75    /// What happens when the request outgrows the model's context window:
76    /// `auto` (the default), `summarize`, `off` or a mapping (see
77    /// [`crate::context`]). Needs the cargo feature `context`.
78    #[serde(default)]
79    pub context_window: Option<Json>,
80    /// Checks the answer against its sources before it leaves the node (see
81    /// [`super::grounding`]). Answers are not streamed while it is on.
82    #[serde(default)]
83    pub grounding: Option<super::grounding::GroundingConfig>,
84}
85
86impl LlmConfig {
87    /// JSON Schema for structured output, when enabled.
88    fn output_schema(&self) -> Option<Json> {
89        let so = self.structured_output.as_ref()?;
90        let enabled = self.structured_output_enabled.or(so.enabled).unwrap_or(true);
91        if !enabled {
92            return None;
93        }
94        let schema = so.schema.clone()?;
95        // Accept both `{schema: {...}}` and a bare schema.
96        match schema.get("schema") {
97            Some(inner) if inner.is_object() => Some(inner.clone()),
98            _ => Some(schema),
99        }
100    }
101}
102
103/// The `llm` node.
104#[derive(Debug)]
105pub struct LlmNode {
106    config: LlmConfig,
107    schema: Option<Json>,
108    /// `model` and `provider` metadata, built once instead of per run.
109    model_name: Value,
110    provider: Value,
111    /// Parsed `context_window`.
112    #[cfg(feature = "context")]
113    context: crate::context::ContextWindow,
114}
115
116impl LlmNode {
117    pub fn from_doc(doc: &NodeDoc) -> Result<Self, ConfigError> {
118        let config: LlmConfig = parse_config(doc)?;
119        if config.prompt_template.messages().is_empty() && config.memory.is_none() {
120            return Err(ConfigError::new(doc, "prompt_template must contain at least one message"));
121        }
122        if let Some(file) = config.prompt_template.unread_file() {
123            return Err(ConfigError::new(
124                doc,
125                format!("prompt file `{file}`: prompt files are read when the workflow is loaded from a file"),
126            ));
127        }
128        let schema = config.output_schema();
129        if let Some(problem) = config.grounding.as_ref().and_then(|grounding| grounding.problem(schema.is_some())) {
130            return Err(ConfigError::new(doc, problem));
131        }
132        let model_name = Value::from(config.model.name.as_str());
133        let provider = Value::from(config.model.provider.as_str());
134        #[cfg(not(feature = "context"))]
135        if super::agent::asks_for_context_guard(config.context_window.as_ref()) {
136            return Err(ConfigError::new(
137                doc,
138                "`context_window` needs a build with the context guard (cargo feature `context`)",
139            ));
140        }
141        #[cfg(feature = "context")]
142        let context = crate::context::ContextWindow::parse(doc, config.context_window.as_ref())?;
143        Ok(Self {
144            config,
145            schema,
146            model_name,
147            provider,
148            #[cfg(feature = "context")]
149            context,
150        })
151    }
152
153    async fn execute(&self, ctx: NodeContext) -> NodeResult {
154        let cfg = &self.config;
155        let pool = &ctx.pool;
156        let context = cfg.context.resolve(pool);
157        #[cfg(feature = "vision-preparer")]
158        let images = cfg.vision.prepared_image_parts(&ctx).await?;
159        #[cfg(not(feature = "vision-preparer"))]
160        let images = cfg.vision.image_parts(pool)?;
161        let messages = build_messages(&cfg.prompt_template, pool, context.as_deref(), cfg.memory.as_ref(), images)?;
162        if messages.is_empty() {
163            return Err(NodeError::invalid_input("prompt rendered to no messages"));
164        }
165        // Whether the budget limited the call's output below the node's own limit.
166        let capped = std::sync::atomic::AtomicBool::new(false);
167        let request = |messages: Vec<crate::types::Message>| -> Result<crate::types::ChatRequest, NodeError> {
168            let mut request = cfg.model.request(messages, pool)?;
169            if let Some(schema) = &self.schema {
170                request.response_format = Some(ResponseFormat::JsonSchema {
171                    name: "structured_output".into(),
172                    schema: schema.clone(),
173                    strict: false,
174                });
175            }
176            if ctx.captures_content() {
177                report_request_messages(&ctx, &request.messages);
178            }
179            capped.store(
180                crate::nodes::common::fit_budget(&ctx, &cfg.model, &mut request, false)?,
181                std::sync::atomic::Ordering::Relaxed,
182            );
183            Ok(request)
184        };
185
186        let model = model_for(&ctx, &cfg.model)?;
187        let mode = match cfg.reasoning_format {
188            // Only the checked answer may reach anyone, unless the check changes nothing.
189            _ if cfg.grounding.as_ref().is_some_and(|grounding| !grounding.keeps_the_answer()) => StreamMode::Off,
190            ReasoningFormat::Tagged => StreamMode::Raw,
191            ReasoningFormat::Separated => StreamMode::SeparateThink,
192        };
193        #[cfg(not(feature = "context"))]
194        let response = invoke(&ctx, model.as_ref(), request(messages)?, mode).await?;
195        #[cfg(feature = "context")]
196        let (response, trimmed) = {
197            let mut messages = messages;
198            // Only the history may be removed: the messages of the prompt
199            // template are the owner's, wherever they stand.
200            // `build_messages` puts the history right after the leading system
201            // messages of the template (the history may start with system items of its own).
202            let template = cfg.prompt_template.messages();
203            let leading = template.iter().take_while(|m| m.role == crate::types::Role::System).count();
204            let history = match &cfg.memory {
205                Some(memory) if self.context.is_on() => memory.history(pool)?.len(),
206                _ => 0,
207            };
208            let scope = crate::context::Scope { pinned: &[], tail: messages.len().saturating_sub(leading + history) };
209            let mut guard = self.context.session(&ctx, model.as_ref(), &cfg.model, scope);
210            let mut state = crate::context::ContextState::default();
211            // Tokens of a summary the guard asked a model for.
212            let mut spent = graphrt_core::event::Usage::default();
213            let outcome: Result<ChatResponse, NodeError> = 'call: loop {
214                if let Err(error) = guard.fit(&mut state, &mut messages, &[], &mut spent).await {
215                    break 'call Err(error);
216                }
217                let built = match request(state.request_messages(&messages)) {
218                    Ok(built) => built,
219                    Err(error) => break 'call Err(error),
220                };
221                match invoke(&ctx, model.as_ref(), built, mode).await {
222                    Ok(response) => break 'call Ok(response),
223                    // A request the provider refused for its size is trimmed and sent
224                    // once more. Any other error, and a second refusal, fail the node.
225                    Err(error) => {
226                        if let Err(error) = guard.refused(&mut state, &mut messages, &[], error, &mut spent).await {
227                            break 'call Err(error);
228                        }
229                    }
230                }
231            };
232            let mut response = match outcome {
233                Ok(response) => response,
234                Err(error) => {
235                    // A summary made for the call was paid for, even when the call failed.
236                    if !spent.is_zero() {
237                        // Past a limit the budget stops the run itself: the call's own error is the answer.
238                        let _limit_reached = crate::nodes::common::charge_model(&ctx, &cfg.model, &spent).is_err();
239                    }
240                    return Err(error);
241                }
242            };
243            response.usage.add(&spent);
244            (response, state.report())
245        };
246        // Paid for whatever comes next, a broken answer too.
247        crate::nodes::common::charge_model(
248            &ctx,
249            &crate::nodes::common::answered_by(&cfg.model, &response),
250            &response.usage,
251        )?;
252        let finish = check_finish(&response)?;
253        let cut_short = response.finish_reason == Some(crate::types::FinishReason::Length);
254        let finish_reason = finish_reason_value(response.finish_reason.as_ref());
255        let ChatResponse { text: answer, reasoning: model_reasoning, usage, warnings, .. } = response;
256
257        let (text, mut reasoning) = match cfg.reasoning_format {
258            ReasoningFormat::Tagged => (answer, String::new()),
259            ReasoningFormat::Separated => split_think_tags(&answer),
260        };
261        if !model_reasoning.is_empty() {
262            reasoning = if reasoning.is_empty() { model_reasoning } else { format!("{model_reasoning}\n{reasoning}") };
263        }
264
265        let (text, usage, grounding_outputs) = match &cfg.grounding {
266            // With structured output, the fields are checked once they are parsed (below).
267            Some(grounding) if grounding.checks_numbers() && self.schema.is_some() => (text, usage, None),
268            Some(grounding) if grounding.checks_numbers() => {
269                let report = grounding.check_numbers_text(&ctx.pool, context.as_deref(), &text);
270                let mut outputs = vec![("grounded", Value::from(report.grounded)), ("unsupported", report.unsupported)];
271                let text = if report.grounded || grounding.keeps_the_answer() {
272                    text
273                } else {
274                    outputs.push(("draft", Value::from(text.as_str())));
275                    grounding.fallback_text(&ctx.pool)
276                };
277                (text, usage, Some(outputs))
278            }
279            Some(grounding) => {
280                let checked = grounding.check(&ctx, model.as_ref(), &cfg.model, &text, context.as_deref()).await?;
281                let mut usage = usage;
282                let mut outputs = vec![
283                    ("grounded", Value::from(checked.grounded)),
284                    ("unknown", Value::from(checked.admits_unknown)),
285                    ("draft", Value::from(text.as_str())),
286                    ("unsupported", checked.unsupported),
287                ];
288                if let Some(spent) = &checked.usage {
289                    usage.add(spent);
290                    outputs.push(("confirmed", Value::array(checked.confirmed.into_iter().map(Value::from))));
291                    outputs.push(("check_usage", usage_value(spent)));
292                }
293                (checked.text, usage, Some(outputs))
294            }
295            None => (text, usage, None),
296        };
297        let mut output = NodeOutput::new()
298            .with("text", text.as_str())
299            .with("usage", usage_value(&usage))
300            .with("finish_reason", finish_reason)
301            .usage(usage)
302            .meta("model", self.model_name.clone())
303            .meta("provider", self.provider.clone());
304        if !reasoning.is_empty() {
305            output = output.with("reasoning", reasoning);
306        }
307        for (name, value) in grounding_outputs.into_iter().flatten() {
308            output = output.with(name, value);
309        }
310        let mut warnings: Vec<Value> = warnings.into_iter().map(Value::from).collect();
311        if let FinishCheck::Unknown(reason) = &finish {
312            warnings.push(Value::from(format!("unrecognized finish reason `{reason}`")));
313        }
314        if capped.load(std::sync::atomic::Ordering::Relaxed) && cut_short {
315            warnings.push(Value::from("the answer was cut at the output the run's budget left"));
316        }
317        #[cfg(feature = "context")]
318        if let Some(report) = trimmed {
319            warnings.push(Value::from(format!("the conversation was trimmed to fit the context window: {report}")));
320        }
321        if !warnings.is_empty() {
322            output = output.meta("warnings", Value::from(warnings));
323        }
324        if let Some(schema) = &self.schema {
325            let parsed = extract_json_where(&text, |v| schema::matches_top_level_type(v, schema)).ok_or_else(|| {
326                NodeError::new("structured_output", "model output contains no JSON value of the requested type")
327            })?;
328            schema::validate(&parsed, schema).map_err(|problem| {
329                NodeError::new("structured_output", format!("model output does not match the schema: {problem}"))
330            })?;
331            if let Some(grounding) = cfg.grounding.as_ref().filter(|grounding| grounding.checks_numbers()) {
332                let report = grounding.check_numbers_fields(&ctx.pool, context.as_deref(), &parsed);
333                output = output.with("grounded", report.grounded).with("unsupported", report.unsupported);
334            }
335            output = output.with("structured_output", Value::from_json(parsed));
336        }
337        Ok(output.into())
338    }
339}
340
341impl Node for LlmNode {
342    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
343        Box::pin(self.execute(ctx))
344    }
345
346    /// Each model response is charged with its cost as it arrives.
347    fn tracks_turns(&self) -> bool {
348        true
349    }
350
351    fn inputs(&self) -> Vec<Selector> {
352        let cfg = &self.config;
353        let mut out = cfg.prompt_template.selectors();
354        out.extend(cfg.context.selectors());
355        out.extend(cfg.vision.selectors());
356        if let Some(memory) = &cfg.memory {
357            out.extend(memory.selectors());
358        }
359        out.extend(cfg.model.selectors());
360        if let Some(grounding) = &cfg.grounding {
361            out.extend(grounding.selectors());
362        }
363        #[cfg(feature = "context")]
364        out.extend(self.context.selectors());
365        out
366    }
367}
368
369/// Factory for the node registry.
370pub fn factory(doc: &NodeDoc) -> Result<Arc<dyn Node>, ConfigError> {
371    Ok(Arc::new(LlmNode::from_doc(doc)?))
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377    use crate::mock::MockModel;
378    use crate::registry::ModelRegistry;
379    use crate::types::{ChatDelta, ContentPart, Role};
380    use graphrt_core::event::Event;
381    use graphrt_core::{NodeOutcome, Services, VariablePool};
382    use std::sync::Mutex;
383
384    fn doc(config: Json) -> NodeDoc {
385        NodeDoc::new("llm", "llm", config)
386    }
387
388    fn ctx_with(model: Arc<MockModel>, pool: VariablePool) -> (NodeContext, Arc<Mutex<Vec<Event>>>) {
389        let services = Services::new().with(ModelRegistry::new().with("openai", model));
390        let events = Arc::new(Mutex::new(Vec::new()));
391        let sink_events = Arc::clone(&events);
392        let ctx = NodeContext::for_test("llm", pool)
393            .with_services(Arc::new(services))
394            .with_sink(Arc::new(move |e| sink_events.lock().unwrap().push(e)));
395        (ctx, events)
396    }
397
398    fn completed(r: NodeResult) -> NodeOutput {
399        match r.unwrap() {
400            NodeOutcome::Completed(o) => o,
401            NodeOutcome::Paused(p) => panic!("unexpected pause {p:?}"),
402        }
403    }
404
405    /// A pool with `turns` history turns of `chars` characters each and a query.
406    #[cfg(feature = "context")]
407    fn pool_with_history(turns: usize, chars: usize) -> VariablePool {
408        let history: Vec<Json> = (0..turns)
409            .flat_map(|n| {
410                [
411                    serde_json::json!({"role": "user", "content": format!("question {n} {}", "q".repeat(chars))}),
412                    serde_json::json!({"role": "assistant", "content": format!("answer {n} {}", "a".repeat(chars))}),
413                ]
414            })
415            .collect();
416        let mut pool = VariablePool::new();
417        pool.insert("sys", "history", Value::from_json(Json::Array(history)));
418        pool.insert("sys", "query", Value::from("the newest question"));
419        pool
420    }
421
422    #[cfg(feature = "context")]
423    fn chat_node(extra: Json) -> LlmNode {
424        let mut config = serde_json::json!({
425            "model": {"provider": "openai", "name": "m"},
426            "prompt_template": [{"role": "system", "text": "Be brief."}],
427            "memory": {},
428        });
429        if let (Some(config), Json::Object(extra)) = (config.as_object_mut(), extra) {
430            config.extend(extra);
431        }
432        LlmNode::from_doc(&doc(config)).unwrap()
433    }
434
435    #[cfg(feature = "context")]
436    fn too_long() -> crate::LlmError {
437        crate::LlmError::ContextLength("prompt is too long: 30100 tokens > 16000 maximum".into())
438    }
439
440    #[cfg(feature = "context")]
441    #[tokio::test]
442    async fn a_request_refused_for_its_size_loses_its_oldest_history_and_is_sent_again() {
443        let model = Arc::new(MockModel::default());
444        model.push_error(too_long());
445        model.push(MockModel::text("short answer"));
446        let (ctx, events) = ctx_with(Arc::clone(&model), pool_with_history(10, 5_000));
447        let out = completed(chat_node(serde_json::json!({})).run(ctx).await);
448        assert_eq!(out.outputs["text"], Value::from("short answer"));
449        let requests = model.requests();
450        assert_eq!(requests.len(), 2);
451        let (refused, retried) = (&requests[0], &requests[1]);
452        assert_eq!(refused.messages.len(), 22);
453        assert!(retried.messages.len() < 12, "{}", retried.messages.len());
454        assert_eq!(retried.messages[0].text(), "Be brief.");
455        let last = retried.messages.last().unwrap();
456        assert_eq!((last.role, last.text().as_str()), (Role::User, "the newest question"));
457        // Whole turns were removed: what is left still alternates and starts with a user message.
458        let roles: Vec<Role> = retried.messages.iter().skip(1).map(|m| m.role).collect();
459        assert!(roles.chunks(2).all(|pair| pair[0] == Role::User), "{roles:?}");
460        assert!(retried.messages[1].text().starts_with("[Context note, written by the runtime."));
461        // The newest history is what stays.
462        assert!(retried.messages.iter().any(|m| m.text().starts_with("answer 9 ")));
463        assert!(!retried.messages.iter().any(|m| m.text().contains("question 0 ")));
464        let trimmed = events.lock().unwrap().iter().any(
465            |event| matches!(event, Event::NodeProgress { name, data, .. } if name == "context_trimmed" && data.get_path(&["reason"]) == Some(Value::from("provider_limit"))),
466        );
467        assert!(trimmed);
468    }
469
470    #[cfg(feature = "context")]
471    #[tokio::test]
472    async fn the_messages_of_the_prompt_template_are_never_removed() {
473        // A template with a document and an example before the question, and no history.
474        let config = serde_json::json!({
475            "model": {"provider": "openai", "name": "m"},
476            "prompt_template": [
477                {"role": "system", "text": "Be brief."},
478                {"role": "user", "text": "Document: {{#start.doc#}}"},
479                {"role": "assistant", "text": "I have read it."},
480                {"role": "user", "text": "Example question"},
481                {"role": "assistant", "text": "Example answer"},
482                {"role": "user", "text": "{{#sys.query#}}"},
483            ],
484        });
485        let node = LlmNode::from_doc(&doc(config.clone())).unwrap();
486        let model = Arc::new(MockModel::default());
487        model.push_error(too_long());
488        model.push(MockModel::text("never reached"));
489        let mut pool = VariablePool::new();
490        pool.insert("start", "doc", Value::from("d".repeat(90_000)));
491        pool.insert("sys", "query", Value::from("the newest question"));
492        let (ctx, _) = ctx_with(Arc::clone(&model), pool);
493        // Nothing here is history, so nothing may go: the node fails as it did before the guard.
494        let error = node.run(ctx).await.unwrap_err();
495        assert_eq!(error.kind, "model_context_length");
496        assert!(error.message.contains("nothing left to remove"), "{}", error.message);
497        assert_eq!(model.requests().len(), 1);
498
499        // The same when the template has no system message and the history starts with one.
500        let no_system = serde_json::json!({
501            "model": {"provider": "openai", "name": "m"},
502            "prompt_template": [
503                {"role": "user", "text": "Document: {{#start.doc#}}"},
504                {"role": "user", "text": "{{#sys.query#}}"},
505            ],
506            "memory": {},
507        });
508        let node = LlmNode::from_doc(&doc(no_system)).unwrap();
509        let model = Arc::new(MockModel::default());
510        model.push_error(too_long());
511        model.push(MockModel::text("short answer"));
512        let mut pool = pool_with_history(10, 5_000);
513        let mut history = vec![serde_json::json!({"role": "system", "content": "A summary the host keeps."})];
514        history.extend(
515            pool.get(&graphrt_core::Selector::of("sys", "history"))
516                .unwrap()
517                .to_json()
518                .as_array()
519                .unwrap()
520                .iter()
521                .cloned(),
522        );
523        pool.insert("sys", "history", Value::from_json(Json::Array(history)));
524        pool.insert("start", "doc", Value::from("the document"));
525        let (ctx, _) = ctx_with(Arc::clone(&model), pool);
526        completed(node.run(ctx).await);
527        let retried = model.requests().pop().unwrap();
528        assert!(retried.messages.iter().any(|m| m.text().ends_with("Document: the document")), "the template stays");
529        assert!(retried.messages.len() < 23);
530
531        // With history in front of the same template, only history goes.
532        let mut with_memory = config;
533        with_memory["memory"] = serde_json::json!({});
534        let node = LlmNode::from_doc(&doc(with_memory)).unwrap();
535        let model = Arc::new(MockModel::default());
536        model.push_error(too_long());
537        model.push(MockModel::text("short answer"));
538        let mut pool = pool_with_history(10, 5_000);
539        pool.insert("start", "doc", Value::from("the document"));
540        let (ctx, _) = ctx_with(Arc::clone(&model), pool);
541        let out = completed(node.run(ctx).await);
542        let retried = model.requests().pop().unwrap();
543        let texts: Vec<String> = retried.messages.iter().map(crate::types::Message::text).collect();
544        for kept in ["Be brief.", "Document: the document", "I have read it.", "Example question", "Example answer"] {
545            assert!(texts.iter().any(|text| text.ends_with(kept)), "`{kept}` was removed: {}", texts.len());
546        }
547        assert!(texts.len() < 27, "{}", texts.len());
548        // The node says in its warnings that the model was not sent everything.
549        let warnings = out.metadata["warnings"].to_json().to_string();
550        assert!(warnings.contains("trimmed to fit the context window"), "{warnings}");
551    }
552
553    #[cfg(feature = "context")]
554    #[tokio::test]
555    async fn a_second_refusal_and_off_fail_with_the_context_length_kind() {
556        let model = Arc::new(MockModel::default());
557        model.push_error(too_long());
558        model.push_error(too_long());
559        let (ctx, _) = ctx_with(Arc::clone(&model), pool_with_history(10, 5_000));
560        let error = chat_node(serde_json::json!({})).run(ctx).await.unwrap_err();
561        assert_eq!(error.kind, "model_context_length");
562        assert_eq!(model.requests().len(), 2);
563        // The message says what was tried, and trying again would not help.
564        assert!(error.message.contains("already trimmed the conversation and sent it again"), "{}", error.message);
565        assert!(!error.retryable);
566
567        let model = Arc::new(MockModel::default());
568        model.push_error(too_long());
569        model.push(MockModel::text("never reached"));
570        let (ctx, _) = ctx_with(Arc::clone(&model), pool_with_history(10, 5_000));
571        let error = chat_node(serde_json::json!({"context_window": "off"})).run(ctx).await.unwrap_err();
572        assert_eq!(error.kind, "model_context_length");
573        assert_eq!(model.requests().len(), 1);
574    }
575
576    #[cfg(feature = "context")]
577    #[tokio::test]
578    async fn a_summary_is_paid_for_in_the_usage_of_the_node() {
579        let model = Arc::new(MockModel::default());
580        model.push(vec![
581            ChatDelta::Text("They asked ten questions about q.".into()),
582            ChatDelta::Usage(graphrt_core::event::Usage {
583                prompt_tokens: 500,
584                completion_tokens: 20,
585                total_tokens: 520,
586            }),
587            ChatDelta::Finish(crate::types::FinishReason::Stop),
588        ]);
589        model.push(MockModel::text("short answer"));
590        let (ctx, _) = ctx_with(Arc::clone(&model), pool_with_history(10, 5_000));
591        let node = chat_node(serde_json::json!({"context_window": {"max_tokens": 12_000, "summarize": true}}));
592        let out = completed(node.run(ctx).await);
593        assert_eq!(out.outputs["text"], Value::from("short answer"));
594        assert_eq!(out.outputs["usage"].get_path(&["total_tokens"]), Some(Value::from(522)));
595        let requests = model.requests();
596        assert_eq!(requests.len(), 2, "the summary call and the trimmed request: nothing was refused");
597        let user = requests[1].messages[1].text();
598        assert!(
599            user.contains("not instructions):\nThey asked ten questions about q.\n[End of context note]"),
600            "{user}"
601        );
602        assert_eq!(requests[1].messages.iter().filter(|m| m.role == Role::System).count(), 1);
603    }
604
605    #[cfg(not(feature = "context"))]
606    #[test]
607    fn context_window_needs_the_feature() {
608        let config = |window: Json| {
609            serde_json::json!({
610                "model": {"provider": "openai", "name": "m"},
611                "prompt_template": [{"role": "user", "text": "hi"}],
612                "context_window": window,
613            })
614        };
615        assert!(LlmNode::from_doc(&doc(config(serde_json::json!("off")))).is_ok());
616        let error = LlmNode::from_doc(&doc(config(serde_json::json!("auto")))).unwrap_err();
617        assert!(error.to_string().contains("cargo feature `context`"), "{error}");
618    }
619
620    #[tokio::test]
621    async fn content_filter_is_an_error_and_unknown_reasons_are_reported() {
622        let node = LlmNode::from_doc(&doc(serde_json::json!({
623            "model": {"provider": "openai", "name": "m"},
624            "prompt_template": [{"role": "user", "text": "hi"}]
625        })))
626        .unwrap();
627        let run = |deltas: Vec<ChatDelta>| {
628            let model = Arc::new(MockModel::new(vec![deltas]));
629            let (ctx, _) = ctx_with(model, VariablePool::new());
630            node.run(ctx)
631        };
632        let err = run(vec![ChatDelta::Finish(crate::types::FinishReason::ContentFilter)]).await.unwrap_err();
633        assert_eq!(err.kind, "content_filter");
634        assert!(!err.retryable);
635        let err = run(vec![ChatDelta::Finish(crate::types::FinishReason::Other("malformed_function_call".into()))])
636            .await
637            .unwrap_err();
638        assert_eq!(err.kind, "model_decode");
639        assert!(err.retryable);
640        let out = completed(
641            run(vec![
642                ChatDelta::Warning("dropped `format`".into()),
643                ChatDelta::Text("ok".into()),
644                ChatDelta::Finish(crate::types::FinishReason::Other("language".into())),
645            ])
646            .await,
647        );
648        let warnings = out.metadata["warnings"].to_text();
649        assert!(warnings.contains("dropped `format`") && warnings.contains("language"), "{warnings}");
650    }
651
652    fn grounded_node(confirm: &str) -> LlmNode {
653        LlmNode::from_doc(&doc(serde_json::json!({
654            "model": {"provider": "langgenius/openai/openai", "name": "gpt"},
655            "prompt_template": [
656                {"role": "system", "text": "Our express laundry is 99k with free delivery."},
657                {"role": "user", "text": "{{#start.message#}}"}
658            ],
659            "grounding": {
660                "facts": [["sys", "chatbot_facts"], ["missing", "value"]],
661                "customer": [["start", "message"]],
662                "fallback": "Sorry, I don't know {{#start.message#}} yet.",
663                "confirm": confirm
664            }
665        })))
666        .unwrap()
667    }
668
669    fn laundry_pool(message: &str) -> VariablePool {
670        let mut pool = VariablePool::new();
671        pool.insert("sys", "chatbot_facts", Value::from("Laundry: 8k per kg, express 15k per kg."));
672        pool.insert("start", "message", Value::from(message));
673        pool
674    }
675
676    fn answer(text: &str) -> Vec<ChatDelta> {
677        vec![ChatDelta::Text(text.into()), ChatDelta::Finish(crate::types::FinishReason::Stop)]
678    }
679
680    #[tokio::test]
681    async fn a_grounded_answer_keeps_what_the_facts_hold_and_is_not_streamed() {
682        let model = Arc::new(MockModel::new(vec![answer("Express is $15k per kg. We also offer free delivery.")]));
683        let (ctx, events) = ctx_with(Arc::clone(&model), laundry_pool("How much is express?"));
684        let out = completed(grounded_node("off").run(ctx).await);
685        assert_eq!(out.outputs["text"], Value::from("Express is 15k per kg."));
686        assert_eq!(out.outputs["grounded"], Value::from(true));
687        assert_eq!(out.outputs["draft"], Value::from("Express is $15k per kg. We also offer free delivery."));
688        let unsupported = out.outputs["unsupported"].to_json();
689        assert_eq!(unsupported[0]["sentence"], "We also offer free delivery.");
690        assert!(events.lock().unwrap().iter().all(|event| !matches!(event, Event::NodeChunk { .. })));
691    }
692
693    #[tokio::test]
694    async fn the_prompt_is_no_source_and_the_fallback_is_a_template() {
695        // The prompt says 99k and free delivery: a builder model wrote it, the facts do not say so.
696        let model = Arc::new(MockModel::new(vec![answer("Express is 99k, with free delivery.")]));
697        let (ctx, _) = ctx_with(Arc::clone(&model), laundry_pool("express?"));
698        let out = completed(grounded_node("off").run(ctx).await);
699        assert_eq!(out.outputs["text"], Value::from("Sorry, I don't know express? yet."));
700        assert_eq!(out.outputs["grounded"], Value::from(false));
701        assert_eq!(model.requests().len(), 1);
702    }
703
704    #[tokio::test]
705    async fn a_model_confirms_words_the_check_missed_but_never_numbers() {
706        let model = Arc::new(MockModel::new(vec![
707            answer("Yes, the express service washes your clothes within a day. It costs 20k."),
708            answer("1. [1] ALL\n2. [1] ALL"),
709        ]));
710        let (ctx, _) = ctx_with(Arc::clone(&model), laundry_pool("Is express fast?"));
711        let out = completed(grounded_node("model").run(ctx).await);
712        assert_eq!(out.outputs["text"], Value::from("Yes, the express service washes your clothes within a day."));
713        assert_eq!(out.outputs["confirmed"].to_json()[0], "Yes, the express service washes your clothes within a day.");
714        assert!(out.outputs.get("check_usage").is_some());
715        let requests = model.requests();
716        assert_eq!(requests.len(), 2);
717        assert_eq!(requests[1].temperature, Some(0.0));
718        let asked = requests[1].messages[1].text();
719        assert!(asked.contains("1. Yes, the express service") && !asked.contains("20k"), "{asked}");
720    }
721
722    fn report_node(structured: bool, on_fail: &str) -> Result<LlmNode, ConfigError> {
723        let mut config = serde_json::json!({
724            "model": {"provider": "openai", "name": "gpt"},
725            "prompt_template": [{"role": "user", "text": "Write the report."}],
726            "grounding": {
727                "facts": [["figures", "json"]],
728                "check": "numbers",
729                "numbers": {"tolerance": "rounding", "ratios_as_percent": true},
730                "on_fail": on_fail,
731                "fallback": "The report is not ready."
732            }
733        });
734        if structured {
735            config["structured_output"] = serde_json::json!({"schema": {"type": "object", "properties": {
736                "summary": {"type": "string"},
737                "stores": {"type": "array", "items": {"type": "object", "properties": {"note": {"type": "string"}}}}
738            }}});
739        }
740        LlmNode::from_doc(&doc(config))
741    }
742
743    fn figures_pool() -> VariablePool {
744        let mut pool = VariablePool::new();
745        pool.insert(
746            "figures",
747            "json",
748            Value::from_json(serde_json::json!({"sales": 1_234_567, "growth": 0.1319, "stores": [{"orders": 1520}]})),
749        );
750        pool
751    }
752
753    #[tokio::test]
754    async fn a_structured_report_lists_the_unsupported_numbers_per_field() {
755        let report = r#"{"summary": "Sales reached 1.2 million, up 13.2%.",
756            "stores": [{"note": "North took 1,520 orders."}, {"note": "South grew 17%. It had 2 new staff."}]}"#;
757        let model = Arc::new(MockModel::new(vec![answer(report)]));
758        let (ctx, events) = ctx_with(Arc::clone(&model), figures_pool());
759        let out = completed(report_node(true, "output").unwrap().run(ctx).await);
760        assert_eq!(out.outputs["grounded"], Value::from(false));
761        assert_eq!(
762            out.outputs["unsupported"].to_json(),
763            serde_json::json!([{"field": "stores[1].note", "number": "17%", "sentence": "South grew 17%."}])
764        );
765        // The draft is kept as written, and streamed: the check changes nothing.
766        assert_eq!(
767            out.outputs["structured_output"].to_json()["stores"][1]["note"],
768            "South grew 17%. It had 2 new staff."
769        );
770        assert!(events.lock().unwrap().iter().any(|event| matches!(event, Event::NodeChunk { .. })));
771    }
772
773    #[tokio::test]
774    async fn a_text_report_falls_back_or_keeps_its_draft() {
775        let model = Arc::new(MockModel::new(vec![
776            answer("Sales were 1,234,567 and growth 13.19%."),
777            answer("Growth was 15%."),
778        ]));
779        let (ctx, _) = ctx_with(Arc::clone(&model), figures_pool());
780        let out = completed(report_node(false, "fallback").unwrap().run(ctx).await);
781        assert_eq!(out.outputs["grounded"], Value::from(true));
782        assert_eq!(out.outputs["text"], Value::from("Sales were 1,234,567 and growth 13.19%."));
783        let (ctx, _) = ctx_with(Arc::clone(&model), figures_pool());
784        let out = completed(report_node(false, "fallback").unwrap().run(ctx).await);
785        assert_eq!(out.outputs["text"], Value::from("The report is not ready."));
786        assert_eq!(out.outputs["draft"], Value::from("Growth was 15%."));
787        assert_eq!(out.outputs["unsupported"].to_json()[0]["field"], "text");
788    }
789
790    #[test]
791    fn numbers_grounding_is_checked_for_what_it_can_do() {
792        let error = report_node(true, "fallback").err().unwrap();
793        assert!(error.to_string().contains("on_fail: output"), "{error}");
794        assert!(report_node(false, "output").is_ok());
795        let sentences_output = LlmNode::from_doc(&doc(serde_json::json!({
796            "model": {"provider": "openai", "name": "gpt"},
797            "prompt_template": [{"role": "user", "text": "hi"}],
798            "grounding": {"on_fail": "output"}
799        })));
800        assert!(sentences_output.err().unwrap().to_string().contains("check: numbers"));
801        let no_fallback = LlmNode::from_doc(&doc(serde_json::json!({
802            "model": {"provider": "openai", "name": "gpt"},
803            "prompt_template": [{"role": "user", "text": "hi"}],
804            "grounding": {"facts": []}
805        })));
806        assert!(no_fallback.err().unwrap().to_string().contains("fallback"));
807    }
808
809    #[test]
810    fn grounding_does_not_go_with_structured_output() {
811        let error = LlmNode::from_doc(&doc(serde_json::json!({
812            "model": {"provider": "openai", "name": "gpt"},
813            "prompt_template": [{"role": "user", "text": "hi"}],
814            "structured_output": {"schema": {"type": "object"}},
815            "grounding": {"fallback": "?"}
816        })))
817        .unwrap_err();
818        assert!(error.to_string().contains("structured output"), "{error}");
819    }
820
821    #[tokio::test]
822    async fn streams_and_outputs() {
823        let model = Arc::new(MockModel::new(vec![vec![
824            ChatDelta::Reasoning("why".into()),
825            ChatDelta::Text("Hel".into()),
826            ChatDelta::Text("lo".into()),
827            ChatDelta::Finish(crate::types::FinishReason::Stop),
828        ]]));
829        let mut pool = VariablePool::new();
830        pool.insert("sys", "query", Value::from("hi there"));
831        let node = LlmNode::from_doc(&doc(serde_json::json!({
832            "model": {"provider": "langgenius/openai/openai", "name": "gpt", "completion_params": {"temperature": 0.2}},
833            "prompt_template": [{"role": "system", "text": "be nice"}, {"role": "user", "text": "{{#sys.query#}}"}]
834        })))
835        .unwrap();
836        let (ctx, events) = ctx_with(Arc::clone(&model), pool);
837        let out = completed(node.run(ctx).await);
838        assert_eq!(out.outputs["text"], Value::from("Hello"));
839        assert_eq!(out.outputs["reasoning"], Value::from("why"));
840        assert_eq!(out.outputs["finish_reason"], Value::from("stop"));
841        let chunks: Vec<(String, String)> = events
842            .lock()
843            .unwrap()
844            .iter()
845            .filter_map(|e| match e {
846                Event::NodeChunk { field, chunk, .. } => Some((field.to_string(), chunk.clone())),
847                _ => None,
848            })
849            .collect();
850        assert_eq!(chunks.len(), 3);
851        assert_eq!(chunks[0].0, "reasoning");
852        let req = &model.requests()[0];
853        assert_eq!(req.model, "gpt");
854        assert_eq!(req.temperature, Some(0.2));
855        assert_eq!(req.messages[0].role, Role::System);
856        assert!(matches!(&req.messages[1].content[0], ContentPart::Text { text } if text == "hi there"));
857    }
858
859    #[tokio::test]
860    async fn rendered_messages_are_reported_only_when_the_host_captures_content() {
861        let node = LlmNode::from_doc(&doc(serde_json::json!({
862            "model": {"provider": "openai", "name": "gpt"},
863            "prompt_template": [{"role": "system", "text": "key {{#env.KEY#}}"}, {"role": "user", "text": "hi"}]
864        })))
865        .unwrap();
866        let mut pool = VariablePool::new();
867        pool.insert("env", "KEY", Value::Secret(Arc::from("sk-live-1")));
868        let requests = |events: &Arc<Mutex<Vec<Event>>>| -> Vec<Value> {
869            let events = events.lock().unwrap();
870            let found = events.iter().filter_map(|e| match e {
871                Event::NodeProgress { name, data, .. } if name == "model_request" => Some(data.clone()),
872                _ => None,
873            });
874            found.collect()
875        };
876
877        let model = Arc::new(MockModel::new(vec![MockModel::text("ok")]));
878        let (ctx, events) = ctx_with(Arc::clone(&model), pool.clone());
879        completed(node.run(ctx).await);
880        assert!(requests(&events).is_empty());
881
882        let model = Arc::new(MockModel::new(vec![MockModel::text("ok")]));
883        let (ctx, events) = ctx_with(model, pool);
884        let services = (*ctx.services).clone().with(graphrt_core::node::CaptureContent);
885        completed(node.run(ctx.with_services(Arc::new(services))).await);
886        let reported = requests(&events);
887        assert_eq!(reported.len(), 1);
888        let json = reported[0].to_json();
889        assert_eq!(json["messages"][0]["role"], "system");
890        assert_eq!(json["messages"][0]["content"][0]["text"], "key ******");
891        assert_eq!(json["messages"][1]["content"][0]["text"], "hi");
892    }
893
894    #[tokio::test]
895    async fn structured_output_and_separated_reasoning() {
896        let model = Arc::new(MockModel::new(vec![MockModel::text("<think>plan</think>{\"n\": 3}")]));
897        let node = LlmNode::from_doc(&doc(serde_json::json!({
898            "model": {"provider": "openai", "name": "gpt"},
899            "prompt_template": [{"role": "user", "text": "give n"}],
900            "structured_output_switch_on": true,
901            "structured_output": {"schema": {"type": "object", "properties": {"n": {"type": "integer"}}}},
902            "reasoning_format": "separated"
903        })))
904        .unwrap();
905        let (ctx, _) = ctx_with(Arc::clone(&model), VariablePool::new());
906        let out = completed(node.run(ctx).await);
907        assert_eq!(out.outputs["structured_output"].get_path(&["n"]), Some(Value::Int(3)));
908        assert_eq!(out.outputs["reasoning"], Value::from("plan"));
909        assert!(matches!(model.requests()[0].response_format, Some(ResponseFormat::JsonSchema { .. })));
910    }
911
912    #[tokio::test]
913    async fn separated_reasoning_streams_without_think_tags() {
914        let model = Arc::new(MockModel::new(vec![vec![
915            ChatDelta::Text("<thi".into()),
916            ChatDelta::Text("nk>plan</th".into()),
917            ChatDelta::Text("ink>\nHel".into()),
918            ChatDelta::Text("lo".into()),
919            ChatDelta::Finish(crate::types::FinishReason::Stop),
920        ]]));
921        let node = LlmNode::from_doc(&doc(serde_json::json!({
922            "model": {"provider": "openai", "name": "gpt"},
923            "prompt_template": [{"role": "user", "text": "hi"}],
924            "reasoning_format": "separated"
925        })))
926        .unwrap();
927        let (ctx, events) = ctx_with(model, VariablePool::new());
928        let out = completed(node.run(ctx).await);
929        let mut streamed = String::new();
930        let mut reasoning = String::new();
931        for e in events.lock().unwrap().iter() {
932            if let Event::NodeChunk { field, chunk, .. } = e {
933                match field.as_ref() {
934                    "text" => streamed.push_str(chunk),
935                    _ => reasoning.push_str(chunk),
936                }
937            }
938        }
939        assert_eq!(streamed, "Hello");
940        assert_eq!(out.outputs["text"], Value::from(streamed.as_str()));
941        assert_eq!(reasoning, "plan");
942    }
943
944    #[tokio::test]
945    async fn structured_output_is_validated() {
946        let model = Arc::new(MockModel::new(vec![MockModel::text("see [1] and {\"m\": 1}")]));
947        let node = LlmNode::from_doc(&doc(serde_json::json!({
948            "model": {"provider": "openai", "name": "gpt"},
949            "prompt_template": [{"role": "user", "text": "give n"}],
950            "structured_output": {"schema": {"type": "object", "required": ["n"], "properties": {"n": {"type": "integer"}}}}
951        })))
952        .unwrap();
953        let (ctx, _) = ctx_with(model, VariablePool::new());
954        let err = node.run(ctx).await.unwrap_err();
955        assert_eq!(err.kind, "structured_output");
956        assert!(err.message.contains("`n`"), "{}", err.message);
957        assert!(err.retryable);
958    }
959
960    #[tokio::test]
961    async fn invalid_completion_params_fail_the_node() {
962        let model = Arc::new(MockModel::new(vec![MockModel::text("x")]));
963        let node = LlmNode::from_doc(&doc(serde_json::json!({
964            "model": {"provider": "openai", "name": "gpt", "completion_params": {"temperature": "abc"}},
965            "prompt_template": [{"role": "user", "text": "hi"}]
966        })))
967        .unwrap();
968        let (ctx, _) = ctx_with(Arc::clone(&model), VariablePool::new());
969        let err = node.run(ctx).await.unwrap_err();
970        assert_eq!(err.kind, "invalid_input");
971        assert!(err.message.contains("temperature"));
972        assert!(model.requests().is_empty());
973    }
974
975    #[test]
976    fn inputs_cover_every_reference() {
977        let node = LlmNode::from_doc(&doc(serde_json::json!({
978            "model": {"provider": "openai", "name": "gpt", "completion_params": {"temperature": "{{#cfg.t#}}"}},
979            "prompt_template": [{"role": "user", "text": "{{#start.q#}}"}],
980            "context": {"enabled": true, "variable_selector": ["kb", "result"]},
981            "vision": {"enabled": true, "configs": {"variable_selector": ["start", "files"]}},
982            "memory": {"window": {"enabled": false}}
983        })))
984        .unwrap();
985        let inputs: Vec<String> = node.inputs().iter().map(ToString::to_string).collect();
986        for expected in ["start.q", "kb.result", "start.files", "sys.history", "sys.query", "cfg.t"] {
987            assert!(inputs.iter().any(|i| i == expected), "missing {expected} in {inputs:?}");
988        }
989    }
990
991    #[tokio::test]
992    async fn model_errors_map_to_node_errors() {
993        let model = Arc::new(MockModel::new(vec![]));
994        model.push_error(crate::error::LlmError::Server { status: 503, message: "down".into() });
995        let node = LlmNode::from_doc(&doc(serde_json::json!({
996            "model": {"provider": "openai", "name": "gpt"},
997            "prompt_template": {"text": "completion style"}
998        })))
999        .unwrap();
1000        let (ctx, _) = ctx_with(model, VariablePool::new());
1001        let err = node.run(ctx).await.unwrap_err();
1002        assert!(err.retryable);
1003        assert_eq!(err.kind, "model_server");
1004    }
1005
1006    #[tokio::test]
1007    async fn missing_registry_is_a_fatal_error() {
1008        let node = LlmNode::from_doc(&doc(serde_json::json!({
1009            "model": {"provider": "openai", "name": "gpt"},
1010            "prompt_template": [{"role": "user", "text": "x"}]
1011        })))
1012        .unwrap();
1013        let err = node.run(NodeContext::for_test("llm", VariablePool::new())).await.unwrap_err();
1014        assert!(!err.retryable);
1015    }
1016
1017    #[test]
1018    fn rejects_empty_prompt() {
1019        let err = LlmNode::from_doc(&doc(serde_json::json!({"model": {"provider": "p", "name": "m"}}))).unwrap_err();
1020        assert!(err.message.contains("prompt_template"));
1021    }
1022}