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}
81
82impl LlmConfig {
83    /// JSON Schema for structured output, when enabled.
84    fn output_schema(&self) -> Option<Json> {
85        let so = self.structured_output.as_ref()?;
86        let enabled = self.structured_output_enabled.or(so.enabled).unwrap_or(true);
87        if !enabled {
88            return None;
89        }
90        let schema = so.schema.clone()?;
91        // Accept both `{schema: {...}}` and a bare schema.
92        match schema.get("schema") {
93            Some(inner) if inner.is_object() => Some(inner.clone()),
94            _ => Some(schema),
95        }
96    }
97}
98
99/// The `llm` node.
100#[derive(Debug)]
101pub struct LlmNode {
102    config: LlmConfig,
103    schema: Option<Json>,
104    /// `model` and `provider` metadata, built once instead of per run.
105    model_name: Value,
106    provider: Value,
107    /// Parsed `context_window`.
108    #[cfg(feature = "context")]
109    context: crate::context::ContextWindow,
110}
111
112impl LlmNode {
113    pub fn from_doc(doc: &NodeDoc) -> Result<Self, ConfigError> {
114        let config: LlmConfig = parse_config(doc)?;
115        if config.prompt_template.messages().is_empty() && config.memory.is_none() {
116            return Err(ConfigError::new(doc, "prompt_template must contain at least one message"));
117        }
118        let schema = config.output_schema();
119        let model_name = Value::from(config.model.name.as_str());
120        let provider = Value::from(config.model.provider.as_str());
121        #[cfg(not(feature = "context"))]
122        if super::agent::asks_for_context_guard(config.context_window.as_ref()) {
123            return Err(ConfigError::new(
124                doc,
125                "`context_window` needs a build with the context guard (cargo feature `context`)",
126            ));
127        }
128        #[cfg(feature = "context")]
129        let context = crate::context::ContextWindow::parse(doc, config.context_window.as_ref())?;
130        Ok(Self {
131            config,
132            schema,
133            model_name,
134            provider,
135            #[cfg(feature = "context")]
136            context,
137        })
138    }
139
140    async fn execute(&self, ctx: NodeContext) -> NodeResult {
141        let cfg = &self.config;
142        let pool = &ctx.pool;
143        let context = cfg.context.resolve(pool);
144        #[cfg(feature = "vision-preparer")]
145        let images = cfg.vision.prepared_image_parts(&ctx).await?;
146        #[cfg(not(feature = "vision-preparer"))]
147        let images = cfg.vision.image_parts(pool)?;
148        let messages = build_messages(&cfg.prompt_template, pool, context.as_deref(), cfg.memory.as_ref(), images)?;
149        if messages.is_empty() {
150            return Err(NodeError::invalid_input("prompt rendered to no messages"));
151        }
152        let request = |messages: Vec<crate::types::Message>| -> Result<crate::types::ChatRequest, NodeError> {
153            let mut request = cfg.model.request(messages, pool)?;
154            if let Some(schema) = &self.schema {
155                request.response_format = Some(ResponseFormat::JsonSchema {
156                    name: "structured_output".into(),
157                    schema: schema.clone(),
158                    strict: false,
159                });
160            }
161            if ctx.captures_content() {
162                report_request_messages(&ctx, &request.messages);
163            }
164            Ok(request)
165        };
166
167        let model = model_for(&ctx, &cfg.model)?;
168        let mode = match cfg.reasoning_format {
169            ReasoningFormat::Tagged => StreamMode::Raw,
170            ReasoningFormat::Separated => StreamMode::SeparateThink,
171        };
172        #[cfg(not(feature = "context"))]
173        let response = invoke(&ctx, model.as_ref(), request(messages)?, mode).await?;
174        #[cfg(feature = "context")]
175        let (response, trimmed) = {
176            let mut messages = messages;
177            // Only the history may be removed: the messages of the prompt
178            // template are the owner's, wherever they stand.
179            // `build_messages` puts the history right after the leading system
180            // messages of the template (the history may start with system items of its own).
181            let template = cfg.prompt_template.messages();
182            let leading = template.iter().take_while(|m| m.role == crate::types::Role::System).count();
183            let history = match &cfg.memory {
184                Some(memory) if self.context.is_on() => memory.history(pool)?.len(),
185                _ => 0,
186            };
187            let scope = crate::context::Scope { pinned: &[], tail: messages.len().saturating_sub(leading + history) };
188            let mut guard = self.context.session(&ctx, model.as_ref(), &cfg.model, scope);
189            let mut state = crate::context::ContextState::default();
190            // Tokens of a summary the guard asked a model for.
191            let mut spent = graphrt_core::event::Usage::default();
192            let mut response = loop {
193                guard.fit(&mut state, &mut messages, &[], &mut spent).await?;
194                match invoke(&ctx, model.as_ref(), request(state.request_messages(&messages))?, mode).await {
195                    Ok(response) => break response,
196                    // A request the provider refused for its size is trimmed and sent
197                    // once more. Any other error, and a second refusal, fail the node.
198                    Err(error) => guard.refused(&mut state, &mut messages, &[], error, &mut spent).await?,
199                }
200            };
201            response.usage.add(&spent);
202            (response, state.report())
203        };
204        let finish = check_finish(&response)?;
205        let finish_reason = finish_reason_value(response.finish_reason.as_ref());
206        let ChatResponse { text: answer, reasoning: model_reasoning, usage, warnings, .. } = response;
207
208        let (text, mut reasoning) = match cfg.reasoning_format {
209            ReasoningFormat::Tagged => (answer, String::new()),
210            ReasoningFormat::Separated => split_think_tags(&answer),
211        };
212        if !model_reasoning.is_empty() {
213            reasoning = if reasoning.is_empty() { model_reasoning } else { format!("{model_reasoning}\n{reasoning}") };
214        }
215
216        let mut output = NodeOutput::new()
217            .with("text", text.as_str())
218            .with("usage", usage_value(&usage))
219            .with("finish_reason", finish_reason)
220            .usage(usage)
221            .meta("model", self.model_name.clone())
222            .meta("provider", self.provider.clone());
223        if !reasoning.is_empty() {
224            output = output.with("reasoning", reasoning);
225        }
226        let mut warnings: Vec<Value> = warnings.into_iter().map(Value::from).collect();
227        if let FinishCheck::Unknown(reason) = &finish {
228            warnings.push(Value::from(format!("unrecognized finish reason `{reason}`")));
229        }
230        #[cfg(feature = "context")]
231        if let Some(report) = trimmed {
232            warnings.push(Value::from(format!("the conversation was trimmed to fit the context window: {report}")));
233        }
234        if !warnings.is_empty() {
235            output = output.meta("warnings", Value::from(warnings));
236        }
237        if let Some(schema) = &self.schema {
238            let parsed = extract_json_where(&text, |v| schema::matches_top_level_type(v, schema)).ok_or_else(|| {
239                NodeError::new("structured_output", "model output contains no JSON value of the requested type")
240            })?;
241            schema::validate(&parsed, schema).map_err(|problem| {
242                NodeError::new("structured_output", format!("model output does not match the schema: {problem}"))
243            })?;
244            output = output.with("structured_output", Value::from_json(parsed));
245        }
246        Ok(output.into())
247    }
248}
249
250impl Node for LlmNode {
251    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
252        Box::pin(self.execute(ctx))
253    }
254
255    fn inputs(&self) -> Vec<Selector> {
256        let cfg = &self.config;
257        let mut out = cfg.prompt_template.selectors();
258        out.extend(cfg.context.selectors());
259        out.extend(cfg.vision.selectors());
260        if let Some(memory) = &cfg.memory {
261            out.extend(memory.selectors());
262        }
263        out.extend(cfg.model.selectors());
264        #[cfg(feature = "context")]
265        out.extend(self.context.selectors());
266        out
267    }
268}
269
270/// Factory for the node registry.
271pub fn factory(doc: &NodeDoc) -> Result<Arc<dyn Node>, ConfigError> {
272    Ok(Arc::new(LlmNode::from_doc(doc)?))
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278    use crate::mock::MockModel;
279    use crate::registry::ModelRegistry;
280    use crate::types::{ChatDelta, ContentPart, Role};
281    use graphrt_core::event::Event;
282    use graphrt_core::{NodeOutcome, Services, VariablePool};
283    use std::sync::Mutex;
284
285    fn doc(config: Json) -> NodeDoc {
286        NodeDoc::new("llm", "llm", config)
287    }
288
289    fn ctx_with(model: Arc<MockModel>, pool: VariablePool) -> (NodeContext, Arc<Mutex<Vec<Event>>>) {
290        let services = Services::new().with(ModelRegistry::new().with("openai", model));
291        let events = Arc::new(Mutex::new(Vec::new()));
292        let sink_events = Arc::clone(&events);
293        let ctx = NodeContext::for_test("llm", pool)
294            .with_services(Arc::new(services))
295            .with_sink(Arc::new(move |e| sink_events.lock().unwrap().push(e)));
296        (ctx, events)
297    }
298
299    fn completed(r: NodeResult) -> NodeOutput {
300        match r.unwrap() {
301            NodeOutcome::Completed(o) => o,
302            NodeOutcome::Paused(p) => panic!("unexpected pause {p:?}"),
303        }
304    }
305
306    /// A pool with `turns` history turns of `chars` characters each and a query.
307    #[cfg(feature = "context")]
308    fn pool_with_history(turns: usize, chars: usize) -> VariablePool {
309        let history: Vec<Json> = (0..turns)
310            .flat_map(|n| {
311                [
312                    serde_json::json!({"role": "user", "content": format!("question {n} {}", "q".repeat(chars))}),
313                    serde_json::json!({"role": "assistant", "content": format!("answer {n} {}", "a".repeat(chars))}),
314                ]
315            })
316            .collect();
317        let mut pool = VariablePool::new();
318        pool.insert("sys", "history", Value::from_json(Json::Array(history)));
319        pool.insert("sys", "query", Value::from("the newest question"));
320        pool
321    }
322
323    #[cfg(feature = "context")]
324    fn chat_node(extra: Json) -> LlmNode {
325        let mut config = serde_json::json!({
326            "model": {"provider": "openai", "name": "m"},
327            "prompt_template": [{"role": "system", "text": "Be brief."}],
328            "memory": {},
329        });
330        if let (Some(config), Json::Object(extra)) = (config.as_object_mut(), extra) {
331            config.extend(extra);
332        }
333        LlmNode::from_doc(&doc(config)).unwrap()
334    }
335
336    #[cfg(feature = "context")]
337    fn too_long() -> crate::LlmError {
338        crate::LlmError::ContextLength("prompt is too long: 30100 tokens > 16000 maximum".into())
339    }
340
341    #[cfg(feature = "context")]
342    #[tokio::test]
343    async fn a_request_refused_for_its_size_loses_its_oldest_history_and_is_sent_again() {
344        let model = Arc::new(MockModel::default());
345        model.push_error(too_long());
346        model.push(MockModel::text("short answer"));
347        let (ctx, events) = ctx_with(Arc::clone(&model), pool_with_history(10, 5_000));
348        let out = completed(chat_node(serde_json::json!({})).run(ctx).await);
349        assert_eq!(out.outputs["text"], Value::from("short answer"));
350        let requests = model.requests();
351        assert_eq!(requests.len(), 2);
352        let (refused, retried) = (&requests[0], &requests[1]);
353        assert_eq!(refused.messages.len(), 22);
354        assert!(retried.messages.len() < 12, "{}", retried.messages.len());
355        assert_eq!(retried.messages[0].text(), "Be brief.");
356        let last = retried.messages.last().unwrap();
357        assert_eq!((last.role, last.text().as_str()), (Role::User, "the newest question"));
358        // Whole turns were removed: what is left still alternates and starts with a user message.
359        let roles: Vec<Role> = retried.messages.iter().skip(1).map(|m| m.role).collect();
360        assert!(roles.chunks(2).all(|pair| pair[0] == Role::User), "{roles:?}");
361        assert!(retried.messages[1].text().starts_with("[Context note, written by the runtime."));
362        // The newest history is what stays.
363        assert!(retried.messages.iter().any(|m| m.text().starts_with("answer 9 ")));
364        assert!(!retried.messages.iter().any(|m| m.text().contains("question 0 ")));
365        let trimmed = events.lock().unwrap().iter().any(
366            |event| matches!(event, Event::NodeProgress { name, data, .. } if name == "context_trimmed" && data.get_path(&["reason"]) == Some(Value::from("provider_limit"))),
367        );
368        assert!(trimmed);
369    }
370
371    #[cfg(feature = "context")]
372    #[tokio::test]
373    async fn the_messages_of_the_prompt_template_are_never_removed() {
374        // A template with a document and an example before the question, and no history.
375        let config = serde_json::json!({
376            "model": {"provider": "openai", "name": "m"},
377            "prompt_template": [
378                {"role": "system", "text": "Be brief."},
379                {"role": "user", "text": "Document: {{#start.doc#}}"},
380                {"role": "assistant", "text": "I have read it."},
381                {"role": "user", "text": "Example question"},
382                {"role": "assistant", "text": "Example answer"},
383                {"role": "user", "text": "{{#sys.query#}}"},
384            ],
385        });
386        let node = LlmNode::from_doc(&doc(config.clone())).unwrap();
387        let model = Arc::new(MockModel::default());
388        model.push_error(too_long());
389        model.push(MockModel::text("never reached"));
390        let mut pool = VariablePool::new();
391        pool.insert("start", "doc", Value::from("d".repeat(90_000)));
392        pool.insert("sys", "query", Value::from("the newest question"));
393        let (ctx, _) = ctx_with(Arc::clone(&model), pool);
394        // Nothing here is history, so nothing may go: the node fails as it did before the guard.
395        let error = node.run(ctx).await.unwrap_err();
396        assert_eq!(error.kind, "model_context_length");
397        assert!(error.message.contains("nothing left to remove"), "{}", error.message);
398        assert_eq!(model.requests().len(), 1);
399
400        // The same when the template has no system message and the history starts with one.
401        let no_system = serde_json::json!({
402            "model": {"provider": "openai", "name": "m"},
403            "prompt_template": [
404                {"role": "user", "text": "Document: {{#start.doc#}}"},
405                {"role": "user", "text": "{{#sys.query#}}"},
406            ],
407            "memory": {},
408        });
409        let node = LlmNode::from_doc(&doc(no_system)).unwrap();
410        let model = Arc::new(MockModel::default());
411        model.push_error(too_long());
412        model.push(MockModel::text("short answer"));
413        let mut pool = pool_with_history(10, 5_000);
414        let mut history = vec![serde_json::json!({"role": "system", "content": "A summary the host keeps."})];
415        history.extend(
416            pool.get(&graphrt_core::Selector::of("sys", "history"))
417                .unwrap()
418                .to_json()
419                .as_array()
420                .unwrap()
421                .iter()
422                .cloned(),
423        );
424        pool.insert("sys", "history", Value::from_json(Json::Array(history)));
425        pool.insert("start", "doc", Value::from("the document"));
426        let (ctx, _) = ctx_with(Arc::clone(&model), pool);
427        completed(node.run(ctx).await);
428        let retried = model.requests().pop().unwrap();
429        assert!(retried.messages.iter().any(|m| m.text().ends_with("Document: the document")), "the template stays");
430        assert!(retried.messages.len() < 23);
431
432        // With history in front of the same template, only history goes.
433        let mut with_memory = config;
434        with_memory["memory"] = serde_json::json!({});
435        let node = LlmNode::from_doc(&doc(with_memory)).unwrap();
436        let model = Arc::new(MockModel::default());
437        model.push_error(too_long());
438        model.push(MockModel::text("short answer"));
439        let mut pool = pool_with_history(10, 5_000);
440        pool.insert("start", "doc", Value::from("the document"));
441        let (ctx, _) = ctx_with(Arc::clone(&model), pool);
442        let out = completed(node.run(ctx).await);
443        let retried = model.requests().pop().unwrap();
444        let texts: Vec<String> = retried.messages.iter().map(crate::types::Message::text).collect();
445        for kept in ["Be brief.", "Document: the document", "I have read it.", "Example question", "Example answer"] {
446            assert!(texts.iter().any(|text| text.ends_with(kept)), "`{kept}` was removed: {}", texts.len());
447        }
448        assert!(texts.len() < 27, "{}", texts.len());
449        // The node says in its warnings that the model was not sent everything.
450        let warnings = out.metadata["warnings"].to_json().to_string();
451        assert!(warnings.contains("trimmed to fit the context window"), "{warnings}");
452    }
453
454    #[cfg(feature = "context")]
455    #[tokio::test]
456    async fn a_second_refusal_and_off_fail_with_the_context_length_kind() {
457        let model = Arc::new(MockModel::default());
458        model.push_error(too_long());
459        model.push_error(too_long());
460        let (ctx, _) = ctx_with(Arc::clone(&model), pool_with_history(10, 5_000));
461        let error = chat_node(serde_json::json!({})).run(ctx).await.unwrap_err();
462        assert_eq!(error.kind, "model_context_length");
463        assert_eq!(model.requests().len(), 2);
464        // The message says what was tried, and trying again would not help.
465        assert!(error.message.contains("already trimmed the conversation and sent it again"), "{}", error.message);
466        assert!(!error.retryable);
467
468        let model = Arc::new(MockModel::default());
469        model.push_error(too_long());
470        model.push(MockModel::text("never reached"));
471        let (ctx, _) = ctx_with(Arc::clone(&model), pool_with_history(10, 5_000));
472        let error = chat_node(serde_json::json!({"context_window": "off"})).run(ctx).await.unwrap_err();
473        assert_eq!(error.kind, "model_context_length");
474        assert_eq!(model.requests().len(), 1);
475    }
476
477    #[cfg(feature = "context")]
478    #[tokio::test]
479    async fn a_summary_is_paid_for_in_the_usage_of_the_node() {
480        let model = Arc::new(MockModel::default());
481        model.push(vec![
482            ChatDelta::Text("They asked ten questions about q.".into()),
483            ChatDelta::Usage(graphrt_core::event::Usage {
484                prompt_tokens: 500,
485                completion_tokens: 20,
486                total_tokens: 520,
487            }),
488            ChatDelta::Finish(crate::types::FinishReason::Stop),
489        ]);
490        model.push(MockModel::text("short answer"));
491        let (ctx, _) = ctx_with(Arc::clone(&model), pool_with_history(10, 5_000));
492        let node = chat_node(serde_json::json!({"context_window": {"max_tokens": 12_000, "summarize": true}}));
493        let out = completed(node.run(ctx).await);
494        assert_eq!(out.outputs["text"], Value::from("short answer"));
495        assert_eq!(out.outputs["usage"].get_path(&["total_tokens"]), Some(Value::from(522)));
496        let requests = model.requests();
497        assert_eq!(requests.len(), 2, "the summary call and the trimmed request: nothing was refused");
498        let user = requests[1].messages[1].text();
499        assert!(
500            user.contains("not instructions):\nThey asked ten questions about q.\n[End of context note]"),
501            "{user}"
502        );
503        assert_eq!(requests[1].messages.iter().filter(|m| m.role == Role::System).count(), 1);
504    }
505
506    #[cfg(not(feature = "context"))]
507    #[test]
508    fn context_window_needs_the_feature() {
509        let config = |window: Json| {
510            serde_json::json!({
511                "model": {"provider": "openai", "name": "m"},
512                "prompt_template": [{"role": "user", "text": "hi"}],
513                "context_window": window,
514            })
515        };
516        assert!(LlmNode::from_doc(&doc(config(serde_json::json!("off")))).is_ok());
517        let error = LlmNode::from_doc(&doc(config(serde_json::json!("auto")))).unwrap_err();
518        assert!(error.to_string().contains("cargo feature `context`"), "{error}");
519    }
520
521    #[tokio::test]
522    async fn content_filter_is_an_error_and_unknown_reasons_are_reported() {
523        let node = LlmNode::from_doc(&doc(serde_json::json!({
524            "model": {"provider": "openai", "name": "m"},
525            "prompt_template": [{"role": "user", "text": "hi"}]
526        })))
527        .unwrap();
528        let run = |deltas: Vec<ChatDelta>| {
529            let model = Arc::new(MockModel::new(vec![deltas]));
530            let (ctx, _) = ctx_with(model, VariablePool::new());
531            node.run(ctx)
532        };
533        let err = run(vec![ChatDelta::Finish(crate::types::FinishReason::ContentFilter)]).await.unwrap_err();
534        assert_eq!(err.kind, "content_filter");
535        assert!(!err.retryable);
536        let err = run(vec![ChatDelta::Finish(crate::types::FinishReason::Other("malformed_function_call".into()))])
537            .await
538            .unwrap_err();
539        assert_eq!(err.kind, "model_decode");
540        assert!(err.retryable);
541        let out = completed(
542            run(vec![
543                ChatDelta::Warning("dropped `format`".into()),
544                ChatDelta::Text("ok".into()),
545                ChatDelta::Finish(crate::types::FinishReason::Other("language".into())),
546            ])
547            .await,
548        );
549        let warnings = out.metadata["warnings"].to_text();
550        assert!(warnings.contains("dropped `format`") && warnings.contains("language"), "{warnings}");
551    }
552
553    #[tokio::test]
554    async fn streams_and_outputs() {
555        let model = Arc::new(MockModel::new(vec![vec![
556            ChatDelta::Reasoning("why".into()),
557            ChatDelta::Text("Hel".into()),
558            ChatDelta::Text("lo".into()),
559            ChatDelta::Finish(crate::types::FinishReason::Stop),
560        ]]));
561        let mut pool = VariablePool::new();
562        pool.insert("sys", "query", Value::from("hi there"));
563        let node = LlmNode::from_doc(&doc(serde_json::json!({
564            "model": {"provider": "langgenius/openai/openai", "name": "gpt", "completion_params": {"temperature": 0.2}},
565            "prompt_template": [{"role": "system", "text": "be nice"}, {"role": "user", "text": "{{#sys.query#}}"}]
566        })))
567        .unwrap();
568        let (ctx, events) = ctx_with(Arc::clone(&model), pool);
569        let out = completed(node.run(ctx).await);
570        assert_eq!(out.outputs["text"], Value::from("Hello"));
571        assert_eq!(out.outputs["reasoning"], Value::from("why"));
572        assert_eq!(out.outputs["finish_reason"], Value::from("stop"));
573        let chunks: Vec<(String, String)> = events
574            .lock()
575            .unwrap()
576            .iter()
577            .filter_map(|e| match e {
578                Event::NodeChunk { field, chunk, .. } => Some((field.to_string(), chunk.clone())),
579                _ => None,
580            })
581            .collect();
582        assert_eq!(chunks.len(), 3);
583        assert_eq!(chunks[0].0, "reasoning");
584        let req = &model.requests()[0];
585        assert_eq!(req.model, "gpt");
586        assert_eq!(req.temperature, Some(0.2));
587        assert_eq!(req.messages[0].role, Role::System);
588        assert!(matches!(&req.messages[1].content[0], ContentPart::Text { text } if text == "hi there"));
589    }
590
591    #[tokio::test]
592    async fn rendered_messages_are_reported_only_when_the_host_captures_content() {
593        let node = LlmNode::from_doc(&doc(serde_json::json!({
594            "model": {"provider": "openai", "name": "gpt"},
595            "prompt_template": [{"role": "system", "text": "key {{#env.KEY#}}"}, {"role": "user", "text": "hi"}]
596        })))
597        .unwrap();
598        let mut pool = VariablePool::new();
599        pool.insert("env", "KEY", Value::Secret(Arc::from("sk-live-1")));
600        let requests = |events: &Arc<Mutex<Vec<Event>>>| -> Vec<Value> {
601            let events = events.lock().unwrap();
602            let found = events.iter().filter_map(|e| match e {
603                Event::NodeProgress { name, data, .. } if name == "model_request" => Some(data.clone()),
604                _ => None,
605            });
606            found.collect()
607        };
608
609        let model = Arc::new(MockModel::new(vec![MockModel::text("ok")]));
610        let (ctx, events) = ctx_with(Arc::clone(&model), pool.clone());
611        completed(node.run(ctx).await);
612        assert!(requests(&events).is_empty());
613
614        let model = Arc::new(MockModel::new(vec![MockModel::text("ok")]));
615        let (ctx, events) = ctx_with(model, pool);
616        let services = (*ctx.services).clone().with(graphrt_core::node::CaptureContent);
617        completed(node.run(ctx.with_services(Arc::new(services))).await);
618        let reported = requests(&events);
619        assert_eq!(reported.len(), 1);
620        let json = reported[0].to_json();
621        assert_eq!(json["messages"][0]["role"], "system");
622        assert_eq!(json["messages"][0]["content"][0]["text"], "key ******");
623        assert_eq!(json["messages"][1]["content"][0]["text"], "hi");
624    }
625
626    #[tokio::test]
627    async fn structured_output_and_separated_reasoning() {
628        let model = Arc::new(MockModel::new(vec![MockModel::text("<think>plan</think>{\"n\": 3}")]));
629        let node = LlmNode::from_doc(&doc(serde_json::json!({
630            "model": {"provider": "openai", "name": "gpt"},
631            "prompt_template": [{"role": "user", "text": "give n"}],
632            "structured_output_switch_on": true,
633            "structured_output": {"schema": {"type": "object", "properties": {"n": {"type": "integer"}}}},
634            "reasoning_format": "separated"
635        })))
636        .unwrap();
637        let (ctx, _) = ctx_with(Arc::clone(&model), VariablePool::new());
638        let out = completed(node.run(ctx).await);
639        assert_eq!(out.outputs["structured_output"].get_path(&["n"]), Some(Value::Int(3)));
640        assert_eq!(out.outputs["reasoning"], Value::from("plan"));
641        assert!(matches!(model.requests()[0].response_format, Some(ResponseFormat::JsonSchema { .. })));
642    }
643
644    #[tokio::test]
645    async fn separated_reasoning_streams_without_think_tags() {
646        let model = Arc::new(MockModel::new(vec![vec![
647            ChatDelta::Text("<thi".into()),
648            ChatDelta::Text("nk>plan</th".into()),
649            ChatDelta::Text("ink>\nHel".into()),
650            ChatDelta::Text("lo".into()),
651            ChatDelta::Finish(crate::types::FinishReason::Stop),
652        ]]));
653        let node = LlmNode::from_doc(&doc(serde_json::json!({
654            "model": {"provider": "openai", "name": "gpt"},
655            "prompt_template": [{"role": "user", "text": "hi"}],
656            "reasoning_format": "separated"
657        })))
658        .unwrap();
659        let (ctx, events) = ctx_with(model, VariablePool::new());
660        let out = completed(node.run(ctx).await);
661        let mut streamed = String::new();
662        let mut reasoning = String::new();
663        for e in events.lock().unwrap().iter() {
664            if let Event::NodeChunk { field, chunk, .. } = e {
665                match field.as_ref() {
666                    "text" => streamed.push_str(chunk),
667                    _ => reasoning.push_str(chunk),
668                }
669            }
670        }
671        assert_eq!(streamed, "Hello");
672        assert_eq!(out.outputs["text"], Value::from(streamed.as_str()));
673        assert_eq!(reasoning, "plan");
674    }
675
676    #[tokio::test]
677    async fn structured_output_is_validated() {
678        let model = Arc::new(MockModel::new(vec![MockModel::text("see [1] and {\"m\": 1}")]));
679        let node = LlmNode::from_doc(&doc(serde_json::json!({
680            "model": {"provider": "openai", "name": "gpt"},
681            "prompt_template": [{"role": "user", "text": "give n"}],
682            "structured_output": {"schema": {"type": "object", "required": ["n"], "properties": {"n": {"type": "integer"}}}}
683        })))
684        .unwrap();
685        let (ctx, _) = ctx_with(model, VariablePool::new());
686        let err = node.run(ctx).await.unwrap_err();
687        assert_eq!(err.kind, "structured_output");
688        assert!(err.message.contains("`n`"), "{}", err.message);
689        assert!(err.retryable);
690    }
691
692    #[tokio::test]
693    async fn invalid_completion_params_fail_the_node() {
694        let model = Arc::new(MockModel::new(vec![MockModel::text("x")]));
695        let node = LlmNode::from_doc(&doc(serde_json::json!({
696            "model": {"provider": "openai", "name": "gpt", "completion_params": {"temperature": "abc"}},
697            "prompt_template": [{"role": "user", "text": "hi"}]
698        })))
699        .unwrap();
700        let (ctx, _) = ctx_with(Arc::clone(&model), VariablePool::new());
701        let err = node.run(ctx).await.unwrap_err();
702        assert_eq!(err.kind, "invalid_input");
703        assert!(err.message.contains("temperature"));
704        assert!(model.requests().is_empty());
705    }
706
707    #[test]
708    fn inputs_cover_every_reference() {
709        let node = LlmNode::from_doc(&doc(serde_json::json!({
710            "model": {"provider": "openai", "name": "gpt", "completion_params": {"temperature": "{{#cfg.t#}}"}},
711            "prompt_template": [{"role": "user", "text": "{{#start.q#}}"}],
712            "context": {"enabled": true, "variable_selector": ["kb", "result"]},
713            "vision": {"enabled": true, "configs": {"variable_selector": ["start", "files"]}},
714            "memory": {"window": {"enabled": false}}
715        })))
716        .unwrap();
717        let inputs: Vec<String> = node.inputs().iter().map(ToString::to_string).collect();
718        for expected in ["start.q", "kb.result", "start.files", "sys.history", "sys.query", "cfg.t"] {
719            assert!(inputs.iter().any(|i| i == expected), "missing {expected} in {inputs:?}");
720        }
721    }
722
723    #[tokio::test]
724    async fn model_errors_map_to_node_errors() {
725        let model = Arc::new(MockModel::new(vec![]));
726        model.push_error(crate::error::LlmError::Server { status: 503, message: "down".into() });
727        let node = LlmNode::from_doc(&doc(serde_json::json!({
728            "model": {"provider": "openai", "name": "gpt"},
729            "prompt_template": {"text": "completion style"}
730        })))
731        .unwrap();
732        let (ctx, _) = ctx_with(model, VariablePool::new());
733        let err = node.run(ctx).await.unwrap_err();
734        assert!(err.retryable);
735        assert_eq!(err.kind, "model_server");
736    }
737
738    #[tokio::test]
739    async fn missing_registry_is_a_fatal_error() {
740        let node = LlmNode::from_doc(&doc(serde_json::json!({
741            "model": {"provider": "openai", "name": "gpt"},
742            "prompt_template": [{"role": "user", "text": "x"}]
743        })))
744        .unwrap();
745        let err = node.run(NodeContext::for_test("llm", VariablePool::new())).await.unwrap_err();
746        assert!(!err.retryable);
747    }
748
749    #[test]
750    fn rejects_empty_prompt() {
751        let err = LlmNode::from_doc(&doc(serde_json::json!({"model": {"provider": "p", "name": "m"}}))).unwrap_err();
752        assert!(err.message.contains("prompt_template"));
753    }
754}