graphrt-llm 0.2.1

Model providers (OpenAI-compatible, Anthropic, Gemini, AWS Bedrock, TypeSafe Jev) and LLM, classifier, extractor and agent nodes for the graphrt workflow runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! `llm` node: a single (streaming) model call.
//!
//! Outputs: `text`, `reasoning` (when present), `usage`, `finish_reason` and,
//! with structured output enabled, `structured_output`. Answer tokens stream
//! as chunks on field `text`, reasoning on field `reasoning`. With
//! `reasoning_format: separated`, `<think>` sections are streamed on
//! `reasoning` too, so the streamed text always equals the `text` output.
//!
//! Structured output is parsed from the answer and checked against the schema
//! (top-level type, required properties, property types); a mismatch is a
//! retryable `structured_output` error.

use std::sync::Arc;

use futures::future::BoxFuture;
use graphrt_core::dsl::NodeDoc;
use graphrt_core::node::{ConfigError, NodeResult, parse_config};
use graphrt_core::value::Value;
use graphrt_core::{Node, NodeContext, NodeError, NodeOutput, Selector};
use serde::Deserialize;
use serde_json::Value as Json;

use super::common::{
    ContextConfig, FinishCheck, MemoryConfig, ModelConfig, PromptTemplate, StreamMode, VisionConfig, build_messages,
    check_finish, extract_json_where, invoke, model_for, split_think_tags, usage_value,
};
use super::schema;
use crate::types::ResponseFormat;

/// How `<think>` tags inside the answer are treated.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ReasoningFormat {
    /// Keep tags in `text` as produced.
    #[default]
    Tagged,
    /// Move tagged reasoning into `reasoning`.
    Separated,
}

#[derive(Clone, Debug, Default, Deserialize)]
struct StructuredOutput {
    #[serde(default)]
    enabled: Option<bool>,
    #[serde(default)]
    schema: Option<Json>,
}

/// Configuration of the `llm` node.
#[derive(Clone, Debug, Deserialize)]
pub struct LlmConfig {
    pub model: ModelConfig,
    #[serde(default)]
    pub prompt_template: PromptTemplate,
    #[serde(default)]
    pub context: ContextConfig,
    #[serde(default)]
    pub vision: VisionConfig,
    #[serde(default)]
    pub memory: Option<MemoryConfig>,
    #[serde(default)]
    structured_output: Option<StructuredOutput>,
    #[serde(default, alias = "structured_output_switch_on")]
    structured_output_enabled: Option<bool>,
    #[serde(default)]
    pub reasoning_format: ReasoningFormat,
}

impl LlmConfig {
    /// JSON Schema for structured output, when enabled.
    fn output_schema(&self) -> Option<Json> {
        let so = self.structured_output.as_ref()?;
        let enabled = self.structured_output_enabled.or(so.enabled).unwrap_or(true);
        if !enabled {
            return None;
        }
        let schema = so.schema.clone()?;
        // Accept both `{schema: {...}}` and a bare schema.
        match schema.get("schema") {
            Some(inner) if inner.is_object() => Some(inner.clone()),
            _ => Some(schema),
        }
    }
}

/// The `llm` node.
#[derive(Debug)]
pub struct LlmNode {
    config: LlmConfig,
    schema: Option<Json>,
}

impl LlmNode {
    pub fn from_doc(doc: &NodeDoc) -> Result<Self, ConfigError> {
        let config: LlmConfig = parse_config(doc)?;
        if config.prompt_template.messages().is_empty() && config.memory.is_none() {
            return Err(ConfigError::new(doc, "prompt_template must contain at least one message"));
        }
        let schema = config.output_schema();
        Ok(Self { config, schema })
    }

    async fn execute(&self, ctx: NodeContext) -> NodeResult {
        let cfg = &self.config;
        let pool = &ctx.pool;
        let context = cfg.context.resolve(pool);
        let images = cfg.vision.image_parts(pool)?;
        let messages = build_messages(&cfg.prompt_template, pool, context.as_deref(), cfg.memory.as_ref(), images)?;
        if messages.is_empty() {
            return Err(NodeError::invalid_input("prompt rendered to no messages"));
        }
        let mut request = cfg.model.request(messages, pool)?;
        if let Some(schema) = &self.schema {
            request.response_format = Some(ResponseFormat::JsonSchema {
                name: "structured_output".into(),
                schema: schema.clone(),
                strict: false,
            });
        }

        let model = model_for(&ctx, &cfg.model)?;
        let mode = match cfg.reasoning_format {
            ReasoningFormat::Tagged => StreamMode::Raw,
            ReasoningFormat::Separated => StreamMode::SeparateThink,
        };
        let response = invoke(&ctx, model.as_ref(), request, mode).await?;
        let finish = check_finish(&response)?;

        let (text, mut reasoning) = match cfg.reasoning_format {
            ReasoningFormat::Tagged => (response.text.clone(), String::new()),
            ReasoningFormat::Separated => split_think_tags(&response.text),
        };
        if !response.reasoning.is_empty() {
            reasoning = if reasoning.is_empty() {
                response.reasoning.clone()
            } else {
                format!("{}\n{reasoning}", response.reasoning)
            };
        }

        let mut output = NodeOutput::new()
            .with("text", text.as_str())
            .with("usage", usage_value(&response.usage))
            .with("finish_reason", response.finish_reason.as_ref().map(|r| r.as_str()).unwrap_or_default())
            .usage(response.usage)
            .meta("model", cfg.model.name.as_str())
            .meta("provider", cfg.model.provider.as_str());
        if !reasoning.is_empty() {
            output = output.with("reasoning", reasoning);
        }
        let mut warnings: Vec<Value> = response.warnings.iter().map(|w| Value::from(w.as_str())).collect();
        if let FinishCheck::Unknown(reason) = &finish {
            warnings.push(Value::from(format!("unrecognized finish reason `{reason}`")));
        }
        if !warnings.is_empty() {
            output = output.meta("warnings", Value::from(warnings));
        }
        if let Some(schema) = &self.schema {
            let parsed = extract_json_where(&text, |v| schema::matches_top_level_type(v, schema)).ok_or_else(|| {
                NodeError::new("structured_output", "model output contains no JSON value of the requested type")
            })?;
            schema::validate(&parsed, schema).map_err(|problem| {
                NodeError::new("structured_output", format!("model output does not match the schema: {problem}"))
            })?;
            output = output.with("structured_output", Value::from_json(parsed));
        }
        Ok(output.into())
    }
}

impl Node for LlmNode {
    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
        Box::pin(self.execute(ctx))
    }

    fn inputs(&self) -> Vec<Selector> {
        let cfg = &self.config;
        let mut out = cfg.prompt_template.selectors();
        out.extend(cfg.context.selectors());
        out.extend(cfg.vision.selectors());
        if let Some(memory) = &cfg.memory {
            out.extend(memory.selectors());
        }
        out.extend(cfg.model.selectors());
        out
    }
}

/// Factory for the node registry.
pub fn factory(doc: &NodeDoc) -> Result<Arc<dyn Node>, ConfigError> {
    Ok(Arc::new(LlmNode::from_doc(doc)?))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mock::MockModel;
    use crate::registry::ModelRegistry;
    use crate::types::{ChatDelta, ContentPart, Role};
    use graphrt_core::event::Event;
    use graphrt_core::{NodeOutcome, Services, VariablePool};
    use std::sync::Mutex;

    fn doc(config: Json) -> NodeDoc {
        NodeDoc::new("llm", "llm", config)
    }

    fn ctx_with(model: Arc<MockModel>, pool: VariablePool) -> (NodeContext, Arc<Mutex<Vec<Event>>>) {
        let services = Services::new().with(ModelRegistry::new().with("openai", model));
        let events = Arc::new(Mutex::new(Vec::new()));
        let sink_events = Arc::clone(&events);
        let ctx = NodeContext::for_test("llm", pool)
            .with_services(Arc::new(services))
            .with_sink(Arc::new(move |e| sink_events.lock().unwrap().push(e)));
        (ctx, events)
    }

    fn completed(r: NodeResult) -> NodeOutput {
        match r.unwrap() {
            NodeOutcome::Completed(o) => o,
            NodeOutcome::Paused(p) => panic!("unexpected pause {p:?}"),
        }
    }

    #[tokio::test]
    async fn content_filter_is_an_error_and_unknown_reasons_are_reported() {
        let node = LlmNode::from_doc(&doc(serde_json::json!({
            "model": {"provider": "openai", "name": "m"},
            "prompt_template": [{"role": "user", "text": "hi"}]
        })))
        .unwrap();
        let run = |deltas: Vec<ChatDelta>| {
            let model = Arc::new(MockModel::new(vec![deltas]));
            let (ctx, _) = ctx_with(model, VariablePool::new());
            node.run(ctx)
        };
        let err = run(vec![ChatDelta::Finish(crate::types::FinishReason::ContentFilter)]).await.unwrap_err();
        assert_eq!(err.kind, "content_filter");
        assert!(!err.retryable);
        let err = run(vec![ChatDelta::Finish(crate::types::FinishReason::Other("malformed_function_call".into()))])
            .await
            .unwrap_err();
        assert_eq!(err.kind, "model_decode");
        assert!(err.retryable);
        let out = completed(
            run(vec![
                ChatDelta::Warning("dropped `format`".into()),
                ChatDelta::Text("ok".into()),
                ChatDelta::Finish(crate::types::FinishReason::Other("language".into())),
            ])
            .await,
        );
        let warnings = out.metadata["warnings"].to_text();
        assert!(warnings.contains("dropped `format`") && warnings.contains("language"), "{warnings}");
    }

    #[tokio::test]
    async fn streams_and_outputs() {
        let model = Arc::new(MockModel::new(vec![vec![
            ChatDelta::Reasoning("why".into()),
            ChatDelta::Text("Hel".into()),
            ChatDelta::Text("lo".into()),
            ChatDelta::Finish(crate::types::FinishReason::Stop),
        ]]));
        let mut pool = VariablePool::new();
        pool.insert("sys", "query", Value::from("hi there"));
        let node = LlmNode::from_doc(&doc(serde_json::json!({
            "model": {"provider": "langgenius/openai/openai", "name": "gpt", "completion_params": {"temperature": 0.2}},
            "prompt_template": [{"role": "system", "text": "be nice"}, {"role": "user", "text": "{{#sys.query#}}"}]
        })))
        .unwrap();
        let (ctx, events) = ctx_with(Arc::clone(&model), pool);
        let out = completed(node.run(ctx).await);
        assert_eq!(out.outputs["text"], Value::from("Hello"));
        assert_eq!(out.outputs["reasoning"], Value::from("why"));
        assert_eq!(out.outputs["finish_reason"], Value::from("stop"));
        let chunks: Vec<(String, String)> = events
            .lock()
            .unwrap()
            .iter()
            .filter_map(|e| match e {
                Event::NodeChunk { field, chunk, .. } => Some((field.clone(), chunk.clone())),
                _ => None,
            })
            .collect();
        assert_eq!(chunks.len(), 3);
        assert_eq!(chunks[0].0, "reasoning");
        let req = &model.requests()[0];
        assert_eq!(req.model, "gpt");
        assert_eq!(req.temperature, Some(0.2));
        assert_eq!(req.messages[0].role, Role::System);
        assert!(matches!(&req.messages[1].content[0], ContentPart::Text { text } if text == "hi there"));
    }

    #[tokio::test]
    async fn structured_output_and_separated_reasoning() {
        let model = Arc::new(MockModel::new(vec![MockModel::text("<think>plan</think>{\"n\": 3}")]));
        let node = LlmNode::from_doc(&doc(serde_json::json!({
            "model": {"provider": "openai", "name": "gpt"},
            "prompt_template": [{"role": "user", "text": "give n"}],
            "structured_output_switch_on": true,
            "structured_output": {"schema": {"type": "object", "properties": {"n": {"type": "integer"}}}},
            "reasoning_format": "separated"
        })))
        .unwrap();
        let (ctx, _) = ctx_with(Arc::clone(&model), VariablePool::new());
        let out = completed(node.run(ctx).await);
        assert_eq!(out.outputs["structured_output"].get_path(&["n"]), Some(Value::Int(3)));
        assert_eq!(out.outputs["reasoning"], Value::from("plan"));
        assert!(matches!(model.requests()[0].response_format, Some(ResponseFormat::JsonSchema { .. })));
    }

    #[tokio::test]
    async fn separated_reasoning_streams_without_think_tags() {
        let model = Arc::new(MockModel::new(vec![vec![
            ChatDelta::Text("<thi".into()),
            ChatDelta::Text("nk>plan</th".into()),
            ChatDelta::Text("ink>\nHel".into()),
            ChatDelta::Text("lo".into()),
            ChatDelta::Finish(crate::types::FinishReason::Stop),
        ]]));
        let node = LlmNode::from_doc(&doc(serde_json::json!({
            "model": {"provider": "openai", "name": "gpt"},
            "prompt_template": [{"role": "user", "text": "hi"}],
            "reasoning_format": "separated"
        })))
        .unwrap();
        let (ctx, events) = ctx_with(model, VariablePool::new());
        let out = completed(node.run(ctx).await);
        let mut streamed = String::new();
        let mut reasoning = String::new();
        for e in events.lock().unwrap().iter() {
            if let Event::NodeChunk { field, chunk, .. } = e {
                match field.as_str() {
                    "text" => streamed.push_str(chunk),
                    _ => reasoning.push_str(chunk),
                }
            }
        }
        assert_eq!(streamed, "Hello");
        assert_eq!(out.outputs["text"], Value::from(streamed.as_str()));
        assert_eq!(reasoning, "plan");
    }

    #[tokio::test]
    async fn structured_output_is_validated() {
        let model = Arc::new(MockModel::new(vec![MockModel::text("see [1] and {\"m\": 1}")]));
        let node = LlmNode::from_doc(&doc(serde_json::json!({
            "model": {"provider": "openai", "name": "gpt"},
            "prompt_template": [{"role": "user", "text": "give n"}],
            "structured_output": {"schema": {"type": "object", "required": ["n"], "properties": {"n": {"type": "integer"}}}}
        })))
        .unwrap();
        let (ctx, _) = ctx_with(model, VariablePool::new());
        let err = node.run(ctx).await.unwrap_err();
        assert_eq!(err.kind, "structured_output");
        assert!(err.message.contains("`n`"), "{}", err.message);
        assert!(err.retryable);
    }

    #[tokio::test]
    async fn invalid_completion_params_fail_the_node() {
        let model = Arc::new(MockModel::new(vec![MockModel::text("x")]));
        let node = LlmNode::from_doc(&doc(serde_json::json!({
            "model": {"provider": "openai", "name": "gpt", "completion_params": {"temperature": "abc"}},
            "prompt_template": [{"role": "user", "text": "hi"}]
        })))
        .unwrap();
        let (ctx, _) = ctx_with(Arc::clone(&model), VariablePool::new());
        let err = node.run(ctx).await.unwrap_err();
        assert_eq!(err.kind, "invalid_input");
        assert!(err.message.contains("temperature"));
        assert!(model.requests().is_empty());
    }

    #[test]
    fn inputs_cover_every_reference() {
        let node = LlmNode::from_doc(&doc(serde_json::json!({
            "model": {"provider": "openai", "name": "gpt", "completion_params": {"temperature": "{{#cfg.t#}}"}},
            "prompt_template": [{"role": "user", "text": "{{#start.q#}}"}],
            "context": {"enabled": true, "variable_selector": ["kb", "result"]},
            "vision": {"enabled": true, "configs": {"variable_selector": ["start", "files"]}},
            "memory": {"window": {"enabled": false}}
        })))
        .unwrap();
        let inputs: Vec<String> = node.inputs().iter().map(ToString::to_string).collect();
        for expected in ["start.q", "kb.result", "start.files", "sys.history", "sys.query", "cfg.t"] {
            assert!(inputs.iter().any(|i| i == expected), "missing {expected} in {inputs:?}");
        }
    }

    #[tokio::test]
    async fn model_errors_map_to_node_errors() {
        let model = Arc::new(MockModel::new(vec![]));
        model.push_error(crate::error::LlmError::Server { status: 503, message: "down".into() });
        let node = LlmNode::from_doc(&doc(serde_json::json!({
            "model": {"provider": "openai", "name": "gpt"},
            "prompt_template": {"text": "completion style"}
        })))
        .unwrap();
        let (ctx, _) = ctx_with(model, VariablePool::new());
        let err = node.run(ctx).await.unwrap_err();
        assert!(err.retryable);
        assert_eq!(err.kind, "model_server");
    }

    #[tokio::test]
    async fn missing_registry_is_a_fatal_error() {
        let node = LlmNode::from_doc(&doc(serde_json::json!({
            "model": {"provider": "openai", "name": "gpt"},
            "prompt_template": [{"role": "user", "text": "x"}]
        })))
        .unwrap();
        let err = node.run(NodeContext::for_test("llm", VariablePool::new())).await.unwrap_err();
        assert!(!err.retryable);
    }

    #[test]
    fn rejects_empty_prompt() {
        let err = LlmNode::from_doc(&doc(serde_json::json!({"model": {"provider": "p", "name": "m"}}))).unwrap_err();
        assert!(err.message.contains("prompt_template"));
    }
}