Skip to main content

graphrt_llm/nodes/
extractor.rs

1//! `parameter-extractor` node: extracts typed parameters from text with a model.
2//!
3//! Each declared parameter becomes an output. Values are validated and coerced
4//! to their declared type. Validation problems do not fail the node: they set
5//! `__is_success` to 0 and explain the problem in `__reason`, so a graph can
6//! branch on them. This includes malformed function-call arguments, which are
7//! never treated as an empty (successful) result. Model invocation errors fail
8//! the node.
9
10use std::sync::Arc;
11
12use futures::future::BoxFuture;
13use graphrt_core::dsl::NodeDoc;
14use graphrt_core::node::{ConfigError, NodeResult, parse_config};
15use graphrt_core::template::Template;
16use graphrt_core::tool::ToolSpec;
17use graphrt_core::value::Value;
18use graphrt_core::{Node, NodeContext, NodeError, NodeOutput, Selector};
19use serde::Deserialize;
20use serde_json::{Map, Value as Json, json};
21
22use super::common::{
23    MemoryConfig, ModelConfig, StreamMode, VisionConfig, extract_json_where, invoke, model_for, usage_value,
24};
25use crate::types::{Message, ToolChoice};
26
27/// Name of the synthetic function used in function-call mode.
28pub const EXTRACT_TOOL: &str = "extract_parameters";
29
30/// Declared parameter type.
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
32#[non_exhaustive]
33pub enum ParamType {
34    #[serde(rename = "string")]
35    String,
36    #[serde(rename = "number")]
37    Number,
38    #[serde(rename = "boolean", alias = "bool")]
39    Boolean,
40    #[serde(rename = "object")]
41    Object,
42    #[serde(rename = "select")]
43    Select,
44    #[serde(rename = "array[string]")]
45    ArrayString,
46    #[serde(rename = "array[number]")]
47    ArrayNumber,
48    #[serde(rename = "array[boolean]")]
49    ArrayBoolean,
50    #[serde(rename = "array[object]")]
51    ArrayObject,
52}
53
54impl ParamType {
55    fn element(self) -> Option<ParamType> {
56        match self {
57            ParamType::ArrayString => Some(ParamType::String),
58            ParamType::ArrayNumber => Some(ParamType::Number),
59            ParamType::ArrayBoolean => Some(ParamType::Boolean),
60            ParamType::ArrayObject => Some(ParamType::Object),
61            _ => None,
62        }
63    }
64
65    fn json_type(self) -> &'static str {
66        match self {
67            ParamType::String | ParamType::Select => "string",
68            ParamType::Number => "number",
69            ParamType::Boolean => "boolean",
70            ParamType::Object => "object",
71            _ => "array",
72        }
73    }
74}
75
76/// One parameter to extract.
77#[derive(Clone, Debug, Deserialize)]
78pub struct ParamConfig {
79    pub name: String,
80    #[serde(rename = "type")]
81    pub ty: ParamType,
82    #[serde(default)]
83    pub description: String,
84    #[serde(default)]
85    pub required: bool,
86    #[serde(default)]
87    pub options: Vec<String>,
88}
89
90/// How the model is asked to answer.
91#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
92#[serde(rename_all = "snake_case")]
93pub enum ReasoningMode {
94    /// A forced function call whose schema is the parameter list.
95    #[default]
96    FunctionCall,
97    /// A JSON answer requested in the prompt.
98    Prompt,
99}
100
101/// Configuration of the `parameter-extractor` node.
102#[derive(Clone, Debug, Deserialize)]
103pub struct ExtractorConfig {
104    pub model: ModelConfig,
105    pub query: Selector,
106    pub parameters: Vec<ParamConfig>,
107    #[serde(default)]
108    pub instruction: Option<Template>,
109    #[serde(default)]
110    pub reasoning_mode: ReasoningMode,
111    #[serde(default)]
112    pub memory: Option<MemoryConfig>,
113    #[serde(default)]
114    pub vision: VisionConfig,
115}
116
117/// The `parameter-extractor` node.
118#[derive(Debug)]
119pub struct ExtractorNode {
120    config: ExtractorConfig,
121    schema: Json,
122}
123
124const RESERVED: &[&str] = &["__is_success", "__reason", "__usage", "usage"];
125
126impl ExtractorNode {
127    pub fn from_doc(doc: &NodeDoc) -> Result<Self, ConfigError> {
128        let config: ExtractorConfig = parse_config(doc)?;
129        if config.parameters.is_empty() {
130            return Err(ConfigError::new(doc, "parameters must not be empty"));
131        }
132        let mut seen = std::collections::HashSet::new();
133        for p in &config.parameters {
134            if p.name.is_empty() || RESERVED.contains(&p.name.as_str()) || !seen.insert(p.name.as_str()) {
135                return Err(ConfigError::new(doc, format!("invalid or duplicate parameter name `{}`", p.name)));
136            }
137        }
138        let schema = parameters_schema(&config.parameters);
139        Ok(Self { config, schema })
140    }
141
142    async fn execute(&self, ctx: NodeContext) -> NodeResult {
143        let cfg = &self.config;
144        let pool = &ctx.pool;
145        let query = pool
146            .get(&cfg.query)
147            .map(|v| v.to_text())
148            .ok_or_else(|| NodeError::invalid_input(format!("query variable `{}` is missing", cfg.query)))?;
149        let instruction = cfg.instruction.as_ref().map(|t| t.render(pool)).unwrap_or_default();
150
151        let mut system = match cfg.reasoning_mode {
152            ReasoningMode::FunctionCall => {
153                format!(
154                    "Extract the requested parameters from the user's input by calling the `{EXTRACT_TOOL}` function."
155                )
156            }
157            ReasoningMode::Prompt => format!(
158                "Extract the requested parameters from the user's input. Respond only with a JSON object matching this JSON Schema:\n{}",
159                self.schema
160            ),
161        };
162        system.push_str(" Omit parameters that are not present in the input; never invent values.");
163        if !instruction.trim().is_empty() {
164            system.push_str("\n\nAdditional instructions:\n");
165            system.push_str(instruction.trim());
166        }
167        let mut messages = vec![Message::system(system)];
168        if let Some(memory) = &cfg.memory {
169            messages.extend(memory.history(pool)?);
170        }
171        let mut user = Message::user(query);
172        #[cfg(feature = "vision-preparer")]
173        user.content.extend(cfg.vision.prepared_image_parts(&ctx).await?);
174        #[cfg(not(feature = "vision-preparer"))]
175        user.content.extend(cfg.vision.image_parts(pool)?);
176        messages.push(user);
177
178        let mut request = cfg.model.request(messages, pool)?;
179        if cfg.reasoning_mode == ReasoningMode::FunctionCall {
180            request.tools = vec![ToolSpec {
181                name: EXTRACT_TOOL.to_owned(),
182                description: "Record the parameters extracted from the user's input.".to_owned(),
183                parameters: self.schema.clone(),
184            }];
185            request.tool_choice = Some(ToolChoice::Tool(EXTRACT_TOOL.to_owned()));
186        }
187
188        let model = model_for(&ctx, &cfg.model)?;
189        let response = invoke(&ctx, model.as_ref(), request, StreamMode::Off).await?;
190        crate::nodes::common::charge_model(&ctx, &cfg.model, &response.usage)?;
191        let raw: Result<Map<String, Json>, String> = match response.tool_calls.iter().find(|c| c.name == EXTRACT_TOOL) {
192            Some(call) => call.arguments_json().map_err(|e| format!("model returned invalid function arguments: {e}")),
193            None => match extract_json_where(&response.text, Json::is_object) {
194                Some(Json::Object(values)) => Ok(values),
195                _ => Err("model did not return a JSON object of parameters".to_owned()),
196            },
197        };
198
199        let mut output = NodeOutput::new();
200        let mut problems: Vec<String> = Vec::new();
201        match raw {
202            Ok(values) => {
203                for p in &cfg.parameters {
204                    let value = match values.get(&p.name).filter(|v| !v.is_null()) {
205                        None if p.required => {
206                            problems.push(format!("missing required parameter `{}`", p.name));
207                            Value::Null
208                        }
209                        None => Value::Null,
210                        Some(v) => match coerce(p, v) {
211                            Ok(v) => v,
212                            Err(e) => {
213                                problems.push(format!("parameter `{}`: {e}", p.name));
214                                Value::Null
215                            }
216                        },
217                    };
218                    output.outputs.insert(p.name.clone(), value);
219                }
220            }
221            Err(problem) => {
222                problems.push(problem);
223                for p in &cfg.parameters {
224                    output.outputs.insert(p.name.clone(), Value::Null);
225                }
226            }
227        }
228        let usage = usage_value(&response.usage);
229        Ok(output
230            .with("__is_success", i64::from(problems.is_empty()))
231            .with("__reason", problems.join("; "))
232            .with("__usage", usage.clone())
233            .with("usage", usage)
234            .usage(response.usage)
235            .into())
236    }
237}
238
239/// JSON Schema object describing all parameters.
240fn parameters_schema(params: &[ParamConfig]) -> Json {
241    let mut properties = Map::new();
242    let mut required = Vec::new();
243    for p in params {
244        let mut prop = Map::new();
245        prop.insert("type".into(), json!(p.ty.json_type()));
246        if let Some(elem) = p.ty.element() {
247            prop.insert("items".into(), json!({"type": elem.json_type()}));
248        }
249        if p.ty == ParamType::Select && !p.options.is_empty() {
250            prop.insert("enum".into(), json!(p.options));
251        }
252        if !p.description.is_empty() {
253            prop.insert("description".into(), json!(p.description));
254        }
255        properties.insert(p.name.clone(), Json::Object(prop));
256        if p.required {
257            required.push(json!(p.name));
258        }
259    }
260    json!({"type": "object", "properties": properties, "required": required})
261}
262
263fn coerce_scalar(ty: ParamType, options: &[String], v: &Json) -> Result<Value, String> {
264    match (ty, v) {
265        (ParamType::String, Json::String(_)) => Ok(Value::from_json(v.clone())),
266        (ParamType::String, Json::Number(n)) => Ok(Value::from(n.to_string())),
267        (ParamType::String, Json::Bool(b)) => Ok(Value::from(b.to_string())),
268        (ParamType::Select, Json::String(s)) => {
269            if options.is_empty() || options.iter().any(|o| o == s) {
270                Ok(Value::from(s.as_str()))
271            } else {
272                Err(format!("`{s}` is not one of {options:?}"))
273            }
274        }
275        (ParamType::Number, Json::Number(_)) => Ok(Value::from_json(v.clone())),
276        (ParamType::Number, Json::String(s)) => {
277            let t = s.trim();
278            t.parse::<i64>()
279                .map(Value::Int)
280                .or_else(|_| t.parse::<f64>().map(Value::Float))
281                .map_err(|_| format!("`{s}` is not a number"))
282        }
283        (ParamType::Boolean, Json::Bool(b)) => Ok(Value::Bool(*b)),
284        (ParamType::Boolean, Json::String(s)) => match s.trim().to_ascii_lowercase().as_str() {
285            "true" | "yes" => Ok(Value::Bool(true)),
286            "false" | "no" => Ok(Value::Bool(false)),
287            _ => Err(format!("`{s}` is not a boolean")),
288        },
289        (ParamType::Object, Json::Object(_)) => Ok(Value::from_json(v.clone())),
290        (t, other) => Err(format!("expected {}, got {}", t.json_type(), json_kind(other))),
291    }
292}
293
294fn json_kind(v: &Json) -> &'static str {
295    match v {
296        Json::Null => "null",
297        Json::Bool(_) => "boolean",
298        Json::Number(_) => "number",
299        Json::String(_) => "string",
300        Json::Array(_) => "array",
301        Json::Object(_) => "object",
302    }
303}
304
305fn coerce(p: &ParamConfig, v: &Json) -> Result<Value, String> {
306    match p.ty.element() {
307        None => coerce_scalar(p.ty, &p.options, v),
308        Some(elem) => match v {
309            Json::Array(items) => {
310                items.iter().map(|i| coerce_scalar(elem, &[], i)).collect::<Result<Vec<_>, _>>().map(Value::from)
311            }
312            other => Err(format!("expected array, got {}", json_kind(other))),
313        },
314    }
315}
316
317impl Node for ExtractorNode {
318    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
319        Box::pin(self.execute(ctx))
320    }
321
322    /// Each model response is charged with its cost as it arrives.
323    fn tracks_turns(&self) -> bool {
324        true
325    }
326
327    fn inputs(&self) -> Vec<Selector> {
328        let cfg = &self.config;
329        let mut out = vec![cfg.query.clone()];
330        if let Some(instruction) = &cfg.instruction {
331            out.extend(instruction.selectors().cloned());
332        }
333        if let Some(memory) = &cfg.memory {
334            out.extend(memory.selectors());
335        }
336        out.extend(cfg.vision.selectors());
337        out.extend(cfg.model.selectors());
338        out
339    }
340}
341
342/// Factory for the node registry.
343pub fn factory(doc: &NodeDoc) -> Result<Arc<dyn Node>, ConfigError> {
344    Ok(Arc::new(ExtractorNode::from_doc(doc)?))
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350    use crate::mock::MockModel;
351    use crate::registry::ModelRegistry;
352    use crate::types::ChatDelta;
353    use graphrt_core::{NodeOutcome, Services, VariablePool};
354
355    fn node(mode: &str) -> ExtractorNode {
356        ExtractorNode::from_doc(&NodeDoc::new(
357            "pe",
358            "parameter-extractor",
359            json!({
360                "model": {"provider": "openai", "name": "gpt"},
361                "query": ["sys", "query"],
362                "reasoning_mode": mode,
363                "parameters": [
364                    {"name": "city", "type": "string", "required": true},
365                    {"name": "days", "type": "number", "required": true},
366                    {"name": "unit", "type": "select", "options": ["c", "f"]},
367                    {"name": "tags", "type": "array[string]"},
368                    {"name": "note", "type": "string"}
369                ]
370            }),
371        ))
372        .unwrap()
373    }
374
375    async fn run(node: &ExtractorNode, response: Vec<ChatDelta>) -> (NodeOutput, Arc<MockModel>) {
376        let model = Arc::new(MockModel::new(vec![response]));
377        let mut pool = VariablePool::new();
378        pool.insert("sys", "query", Value::from("weather in Paris for 3 days"));
379        let ctx = NodeContext::for_test("pe", pool).with_services(Arc::new(
380            Services::new().with(ModelRegistry::new().with("openai", Arc::clone(&model) as Arc<dyn crate::ChatModel>)),
381        ));
382        match node.run(ctx).await.unwrap() {
383            NodeOutcome::Completed(o) => (o, model),
384            NodeOutcome::Paused(_) => panic!("paused"),
385        }
386    }
387
388    #[tokio::test]
389    async fn function_call_mode_coerces_types() {
390        let n = node("function_call");
391        let (out, model) = run(
392            &n,
393            MockModel::tool_calls(&[("c", EXTRACT_TOOL, r#"{"city":"Paris","days":"3","unit":"c","tags":["a"]}"#)]),
394        )
395        .await;
396        assert_eq!(out.outputs["__is_success"], Value::Int(1));
397        assert_eq!(out.outputs["days"], Value::Int(3));
398        assert_eq!(out.outputs["note"], Value::Null, "missing optional parameters are fine");
399        let req = &model.requests()[0];
400        assert_eq!(req.tool_choice, Some(ToolChoice::Tool(EXTRACT_TOOL.into())));
401        assert_eq!(req.tools[0].parameters["properties"]["unit"]["enum"][1], "f");
402        assert_eq!(req.tools[0].parameters["required"][0], "city");
403    }
404
405    #[tokio::test]
406    async fn prompt_mode_reports_validation_problems() {
407        let n = node("prompt");
408        let (out, model) = run(&n, MockModel::text("Here: {\"city\": \"Paris\", \"unit\": \"k\"}")).await;
409        assert_eq!(out.outputs["__is_success"], Value::Int(0));
410        let reason = out.outputs["__reason"].to_text();
411        assert!(reason.contains("days"));
412        assert!(reason.contains("unit"));
413        assert_eq!(out.outputs["city"], Value::from("Paris"));
414        assert!(model.requests()[0].tools.is_empty());
415    }
416
417    #[tokio::test]
418    async fn malformed_function_arguments_are_not_a_success() {
419        let n = node("function_call");
420        let (out, _) = run(&n, MockModel::tool_calls(&[("c", EXTRACT_TOOL, r#"{"city":"Par"#)])).await;
421        assert_eq!(out.outputs["__is_success"], Value::Int(0));
422        assert!(out.outputs["__reason"].to_text().contains("invalid function arguments"));
423        assert_eq!(out.outputs["city"], Value::Null);
424    }
425
426    #[tokio::test]
427    async fn non_json_answer_is_soft_failure() {
428        let (out, _) = run(&node("prompt"), MockModel::text("sorry")).await;
429        assert_eq!(out.outputs["__is_success"], Value::Int(0));
430    }
431
432    #[test]
433    fn rejects_reserved_names() {
434        let doc = NodeDoc::new(
435            "pe",
436            "parameter-extractor",
437            json!({"model": {"provider": "p", "name": "m"}, "query": "sys.query",
438                   "parameters": [{"name": "__reason", "type": "string"}]}),
439        );
440        assert!(ExtractorNode::from_doc(&doc).is_err());
441    }
442}