1use 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
27pub const EXTRACT_TOOL: &str = "extract_parameters";
29
30#[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#[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
92#[serde(rename_all = "snake_case")]
93pub enum ReasoningMode {
94 #[default]
96 FunctionCall,
97 Prompt,
99}
100
101#[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#[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 capped = crate::nodes::common::fit_budget(&ctx, &cfg.model, &mut request, false)?;
190 let response = invoke(&ctx, model.as_ref(), request, StreamMode::Off).await?;
191 crate::nodes::common::charge_model(&ctx, &cfg.model, &response.usage)?;
192 if capped && response.finish_reason == Some(crate::types::FinishReason::Length) {
194 return Err(crate::nodes::common::cut_by_budget(&ctx, &cfg.model));
195 }
196 let raw: Result<Map<String, Json>, String> = match response.tool_calls.iter().find(|c| c.name == EXTRACT_TOOL) {
197 Some(call) => call.arguments_json().map_err(|e| format!("model returned invalid function arguments: {e}")),
198 None => match extract_json_where(&response.text, Json::is_object) {
199 Some(Json::Object(values)) => Ok(values),
200 _ => Err("model did not return a JSON object of parameters".to_owned()),
201 },
202 };
203
204 let mut output = NodeOutput::new();
205 let mut problems: Vec<String> = Vec::new();
206 match raw {
207 Ok(values) => {
208 for p in &cfg.parameters {
209 let value = match values.get(&p.name).filter(|v| !v.is_null()) {
210 None if p.required => {
211 problems.push(format!("missing required parameter `{}`", p.name));
212 Value::Null
213 }
214 None => Value::Null,
215 Some(v) => match coerce(p, v) {
216 Ok(v) => v,
217 Err(e) => {
218 problems.push(format!("parameter `{}`: {e}", p.name));
219 Value::Null
220 }
221 },
222 };
223 output.outputs.insert(p.name.clone(), value);
224 }
225 }
226 Err(problem) => {
227 problems.push(problem);
228 for p in &cfg.parameters {
229 output.outputs.insert(p.name.clone(), Value::Null);
230 }
231 }
232 }
233 let usage = usage_value(&response.usage);
234 Ok(output
235 .with("__is_success", i64::from(problems.is_empty()))
236 .with("__reason", problems.join("; "))
237 .with("__usage", usage.clone())
238 .with("usage", usage)
239 .usage(response.usage)
240 .into())
241 }
242}
243
244fn parameters_schema(params: &[ParamConfig]) -> Json {
246 let mut properties = Map::new();
247 let mut required = Vec::new();
248 for p in params {
249 let mut prop = Map::new();
250 prop.insert("type".into(), json!(p.ty.json_type()));
251 if let Some(elem) = p.ty.element() {
252 prop.insert("items".into(), json!({"type": elem.json_type()}));
253 }
254 if p.ty == ParamType::Select && !p.options.is_empty() {
255 prop.insert("enum".into(), json!(p.options));
256 }
257 if !p.description.is_empty() {
258 prop.insert("description".into(), json!(p.description));
259 }
260 properties.insert(p.name.clone(), Json::Object(prop));
261 if p.required {
262 required.push(json!(p.name));
263 }
264 }
265 json!({"type": "object", "properties": properties, "required": required})
266}
267
268fn coerce_scalar(ty: ParamType, options: &[String], v: &Json) -> Result<Value, String> {
269 match (ty, v) {
270 (ParamType::String, Json::String(_)) => Ok(Value::from_json(v.clone())),
271 (ParamType::String, Json::Number(n)) => Ok(Value::from(n.to_string())),
272 (ParamType::String, Json::Bool(b)) => Ok(Value::from(b.to_string())),
273 (ParamType::Select, Json::String(s)) => {
274 if options.is_empty() || options.iter().any(|o| o == s) {
275 Ok(Value::from(s.as_str()))
276 } else {
277 Err(format!("`{s}` is not one of {options:?}"))
278 }
279 }
280 (ParamType::Number, Json::Number(_)) => Ok(Value::from_json(v.clone())),
281 (ParamType::Number, Json::String(s)) => {
282 let t = s.trim();
283 t.parse::<i64>()
284 .map(Value::Int)
285 .or_else(|_| t.parse::<f64>().map(Value::Float))
286 .map_err(|_| format!("`{s}` is not a number"))
287 }
288 (ParamType::Boolean, Json::Bool(b)) => Ok(Value::Bool(*b)),
289 (ParamType::Boolean, Json::String(s)) => match s.trim().to_ascii_lowercase().as_str() {
290 "true" | "yes" => Ok(Value::Bool(true)),
291 "false" | "no" => Ok(Value::Bool(false)),
292 _ => Err(format!("`{s}` is not a boolean")),
293 },
294 (ParamType::Object, Json::Object(_)) => Ok(Value::from_json(v.clone())),
295 (t, other) => Err(format!("expected {}, got {}", t.json_type(), json_kind(other))),
296 }
297}
298
299fn json_kind(v: &Json) -> &'static str {
300 match v {
301 Json::Null => "null",
302 Json::Bool(_) => "boolean",
303 Json::Number(_) => "number",
304 Json::String(_) => "string",
305 Json::Array(_) => "array",
306 Json::Object(_) => "object",
307 }
308}
309
310fn coerce(p: &ParamConfig, v: &Json) -> Result<Value, String> {
311 match p.ty.element() {
312 None => coerce_scalar(p.ty, &p.options, v),
313 Some(elem) => match v {
314 Json::Array(items) => {
315 items.iter().map(|i| coerce_scalar(elem, &[], i)).collect::<Result<Vec<_>, _>>().map(Value::from)
316 }
317 other => Err(format!("expected array, got {}", json_kind(other))),
318 },
319 }
320}
321
322impl Node for ExtractorNode {
323 fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
324 Box::pin(self.execute(ctx))
325 }
326
327 fn tracks_turns(&self) -> bool {
329 true
330 }
331
332 fn inputs(&self) -> Vec<Selector> {
333 let cfg = &self.config;
334 let mut out = vec![cfg.query.clone()];
335 if let Some(instruction) = &cfg.instruction {
336 out.extend(instruction.selectors().cloned());
337 }
338 if let Some(memory) = &cfg.memory {
339 out.extend(memory.selectors());
340 }
341 out.extend(cfg.vision.selectors());
342 out.extend(cfg.model.selectors());
343 out
344 }
345}
346
347pub fn factory(doc: &NodeDoc) -> Result<Arc<dyn Node>, ConfigError> {
349 Ok(Arc::new(ExtractorNode::from_doc(doc)?))
350}
351
352#[cfg(test)]
353mod tests {
354 use super::*;
355 use crate::mock::MockModel;
356 use crate::registry::ModelRegistry;
357 use crate::types::ChatDelta;
358 use graphrt_core::{NodeOutcome, Services, VariablePool};
359
360 fn node(mode: &str) -> ExtractorNode {
361 ExtractorNode::from_doc(&NodeDoc::new(
362 "pe",
363 "parameter-extractor",
364 json!({
365 "model": {"provider": "openai", "name": "gpt"},
366 "query": ["sys", "query"],
367 "reasoning_mode": mode,
368 "parameters": [
369 {"name": "city", "type": "string", "required": true},
370 {"name": "days", "type": "number", "required": true},
371 {"name": "unit", "type": "select", "options": ["c", "f"]},
372 {"name": "tags", "type": "array[string]"},
373 {"name": "note", "type": "string"}
374 ]
375 }),
376 ))
377 .unwrap()
378 }
379
380 async fn run(node: &ExtractorNode, response: Vec<ChatDelta>) -> (NodeOutput, Arc<MockModel>) {
381 let model = Arc::new(MockModel::new(vec![response]));
382 let mut pool = VariablePool::new();
383 pool.insert("sys", "query", Value::from("weather in Paris for 3 days"));
384 let ctx = NodeContext::for_test("pe", pool).with_services(Arc::new(
385 Services::new().with(ModelRegistry::new().with("openai", Arc::clone(&model) as Arc<dyn crate::ChatModel>)),
386 ));
387 match node.run(ctx).await.unwrap() {
388 NodeOutcome::Completed(o) => (o, model),
389 NodeOutcome::Paused(_) => panic!("paused"),
390 }
391 }
392
393 #[tokio::test]
394 async fn function_call_mode_coerces_types() {
395 let n = node("function_call");
396 let (out, model) = run(
397 &n,
398 MockModel::tool_calls(&[("c", EXTRACT_TOOL, r#"{"city":"Paris","days":"3","unit":"c","tags":["a"]}"#)]),
399 )
400 .await;
401 assert_eq!(out.outputs["__is_success"], Value::Int(1));
402 assert_eq!(out.outputs["days"], Value::Int(3));
403 assert_eq!(out.outputs["note"], Value::Null, "missing optional parameters are fine");
404 let req = &model.requests()[0];
405 assert_eq!(req.tool_choice, Some(ToolChoice::Tool(EXTRACT_TOOL.into())));
406 assert_eq!(req.tools[0].parameters["properties"]["unit"]["enum"][1], "f");
407 assert_eq!(req.tools[0].parameters["required"][0], "city");
408 }
409
410 #[tokio::test]
411 async fn prompt_mode_reports_validation_problems() {
412 let n = node("prompt");
413 let (out, model) = run(&n, MockModel::text("Here: {\"city\": \"Paris\", \"unit\": \"k\"}")).await;
414 assert_eq!(out.outputs["__is_success"], Value::Int(0));
415 let reason = out.outputs["__reason"].to_text();
416 assert!(reason.contains("days"));
417 assert!(reason.contains("unit"));
418 assert_eq!(out.outputs["city"], Value::from("Paris"));
419 assert!(model.requests()[0].tools.is_empty());
420 }
421
422 #[tokio::test]
423 async fn malformed_function_arguments_are_not_a_success() {
424 let n = node("function_call");
425 let (out, _) = run(&n, MockModel::tool_calls(&[("c", EXTRACT_TOOL, r#"{"city":"Par"#)])).await;
426 assert_eq!(out.outputs["__is_success"], Value::Int(0));
427 assert!(out.outputs["__reason"].to_text().contains("invalid function arguments"));
428 assert_eq!(out.outputs["city"], Value::Null);
429 }
430
431 #[tokio::test]
432 async fn non_json_answer_is_soft_failure() {
433 let (out, _) = run(&node("prompt"), MockModel::text("sorry")).await;
434 assert_eq!(out.outputs["__is_success"], Value::Int(0));
435 }
436
437 #[test]
438 fn rejects_reserved_names() {
439 let doc = NodeDoc::new(
440 "pe",
441 "parameter-extractor",
442 json!({"model": {"provider": "p", "name": "m"}, "query": "sys.query",
443 "parameters": [{"name": "__reason", "type": "string"}]}),
444 );
445 assert!(ExtractorNode::from_doc(&doc).is_err());
446 }
447}