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