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