Skip to main content

graphrt_llm/nodes/
classifier.rs

1//! `question-classifier` node: routes to the branch of the class chosen by a model.
2//!
3//! The selected class id is the branch handle. Outputs: `class_id`,
4//! `class_name`, `class_label`, `usage`. An answer that names no configured
5//! class fails the node, unless `fallback_class` names the class to use; a
6//! fallback is marked with metadata `fallback: true` and `raw_answer`.
7//!
8//! With `model.provider: typesafe` (or `engine: typesafe`) the node asks
9//! TypeSafe's System One API one choice question instead of prompting a chat
10//! model. That path adds the `probabilities` (class id -> probability) and
11//! `confidence` outputs and honours `min_confidence`, `min_probability` and the
12//! optional `companion_noul` check; a decision below a threshold routes to
13//! `fallback_class`, or fails with the non-retryable `low_confidence` error.
14
15use std::sync::Arc;
16
17use futures::future::BoxFuture;
18use graphrt_core::dsl::NodeDoc;
19use graphrt_core::node::{ConfigError, NodeResult, NodeRole, parse_config};
20use graphrt_core::template::Template;
21use graphrt_core::{Node, NodeContext, NodeError, NodeOutput, Selector};
22use serde::Deserialize;
23use serde_json::Value as Json;
24
25use super::common::{
26    MemoryConfig, ModelConfig, StreamMode, VisionConfig, extract_json, invoke, model_for, usage_value,
27};
28use crate::types::Message;
29
30/// One class.
31#[derive(Clone, Debug, Deserialize)]
32pub struct ClassConfig {
33    pub id: String,
34    pub name: String,
35    #[serde(default)]
36    pub label: Option<String>,
37    /// When this class applies (System One engine: used as the option description).
38    #[serde(default)]
39    pub description: Option<String>,
40}
41
42/// Configuration of the `question-classifier` node.
43#[derive(Clone, Debug, Deserialize)]
44pub struct ClassifierConfig {
45    pub model: ModelConfig,
46    #[serde(alias = "query")]
47    pub query_variable_selector: Selector,
48    pub classes: Vec<ClassConfig>,
49    #[serde(default)]
50    pub instruction: Option<Template>,
51    #[serde(default)]
52    pub memory: Option<MemoryConfig>,
53    #[serde(default)]
54    pub vision: VisionConfig,
55    /// Class id used when the model's answer matches no class. Without it, such answers fail the node.
56    #[serde(default)]
57    pub fallback_class: Option<String>,
58    /// `chat` (default) or `typesafe`. `model.provider: typesafe` also selects the System One engine.
59    #[serde(default)]
60    pub engine: Option<String>,
61    /// System One engine: minimum confidence of the decision (0..1).
62    #[serde(default)]
63    pub min_confidence: Option<f64>,
64    /// System One engine: minimum probability of the chosen class (0..1).
65    #[serde(default)]
66    pub min_probability: Option<f64>,
67    /// System One engine: also ask whether any class fits at all (a yes/no question).
68    #[serde(default)]
69    pub companion_noul: bool,
70    /// System One engine: minimum probability of "some class fits" when `companion_noul` is on.
71    #[serde(default = "default_companion_threshold")]
72    pub companion_threshold: f64,
73}
74
75fn default_companion_threshold() -> f64 {
76    0.5
77}
78
79/// The `question-classifier` node.
80#[derive(Debug)]
81pub struct ClassifierNode {
82    config: ClassifierConfig,
83}
84
85impl ClassifierNode {
86    pub fn from_doc(doc: &NodeDoc) -> Result<Self, ConfigError> {
87        let config: ClassifierConfig = parse_config(doc)?;
88        if config.classes.is_empty() {
89            return Err(ConfigError::new(doc, "classes must not be empty"));
90        }
91        let mut seen = std::collections::HashSet::new();
92        for class in &config.classes {
93            if class.id.is_empty() || !seen.insert(class.id.as_str()) {
94                return Err(ConfigError::new(doc, format!("class ids must be unique and non-empty (`{}`)", class.id)));
95            }
96        }
97        if let Some(fallback) = &config.fallback_class
98            && !config.classes.iter().any(|c| &c.id == fallback)
99        {
100            return Err(ConfigError::new(doc, format!("fallback_class `{fallback}` is not a configured class")));
101        }
102        match config.engine.as_deref() {
103            None | Some("chat" | "typesafe") => {}
104            Some(other) => {
105                return Err(ConfigError::new(doc, format!("unknown engine `{other}` (expected `chat` or `typesafe`)")));
106            }
107        }
108        for (name, value) in [
109            ("min_confidence", config.min_confidence),
110            ("min_probability", config.min_probability),
111            ("companion_threshold", Some(config.companion_threshold)),
112        ] {
113            if let Some(v) = value
114                && !(0.0..=1.0).contains(&v)
115            {
116                return Err(ConfigError::new(doc, format!("{name} must be between 0 and 1")));
117            }
118        }
119        if config.engine.as_deref() == Some("chat") && config.model.provider == "typesafe" {
120            return Err(ConfigError::new(
121                doc,
122                "`engine: chat` conflicts with `model.provider: typesafe` (TypeSafe is not a chat model)",
123            ));
124        }
125        let node = Self { config };
126        if node.uses_system_one() {
127            if node.config.classes.len() > 255 {
128                return Err(ConfigError::new(doc, "the typesafe engine supports at most 255 classes"));
129            }
130            // Chat-only settings would be silently ignored by the System One engine.
131            let unsupported = [
132                ("memory", node.config.memory.is_some()),
133                ("vision", node.config.vision.enabled),
134                ("model.completion_params", !node.config.model.completion_params.is_empty()),
135            ];
136            if let Some((name, _)) = unsupported.iter().find(|(_, set)| *set) {
137                return Err(ConfigError::new(
138                    doc,
139                    format!("`{name}` is not supported by the typesafe engine (it only applies to chat models)"),
140                ));
141            }
142        } else if node.config.min_confidence.is_some()
143            || node.config.min_probability.is_some()
144            || node.config.companion_noul
145        {
146            return Err(ConfigError::new(
147                doc,
148                "min_confidence, min_probability and companion_noul need the typesafe engine",
149            ));
150        }
151        Ok(node)
152    }
153
154    /// Whether this node uses TypeSafe's System One API instead of a chat model.
155    pub fn uses_system_one(&self) -> bool {
156        self.config.engine.as_deref() == Some("typesafe") || self.config.model.provider == "typesafe"
157    }
158
159    fn system_prompt(&self, instruction: &str) -> String {
160        let categories: Vec<Json> = self
161            .config
162            .classes
163            .iter()
164            .map(|c| serde_json::json!({"category_id": c.id, "category_name": c.name}))
165            .collect();
166        let mut prompt = String::from(
167            "You are a text classification engine. Classify the user's input into exactly one of these categories:\n",
168        );
169        prompt.push_str(&Json::Array(categories).to_string());
170        if !instruction.trim().is_empty() {
171            prompt.push_str("\n\nAdditional instructions:\n");
172            prompt.push_str(instruction.trim());
173        }
174        prompt.push_str(
175            "\n\nRespond only with a JSON object of the form {\"category_id\": \"<id>\", \"category_name\": \"<name>\"}.",
176        );
177        prompt
178    }
179
180    /// Map a model answer to a configured class index.
181    fn match_class(&self, answer: &str) -> Option<usize> {
182        let classes = &self.config.classes;
183        let by_id = |id: &str| classes.iter().position(|c| c.id == id.trim());
184        let by_name = |name: &str| classes.iter().position(|c| c.name.trim().eq_ignore_ascii_case(name.trim()));
185        if let Some(json) = extract_json(answer) {
186            let field = |key: &str| match json.get(key) {
187                Some(Json::String(s)) => Some(s.clone()),
188                Some(Json::Number(n)) => Some(n.to_string()),
189                _ => None,
190            };
191            if let Some(i) = field("category_id").as_deref().and_then(by_id) {
192                return Some(i);
193            }
194            if let Some(i) = field("category_name").as_deref().and_then(by_name) {
195                return Some(i);
196            }
197        }
198        by_id(answer).or_else(|| by_name(answer))
199    }
200
201    async fn execute(&self, ctx: NodeContext) -> NodeResult {
202        if self.uses_system_one() {
203            return self.execute_system_one(ctx).await;
204        }
205        let cfg = &self.config;
206        let pool = &ctx.pool;
207        let query = pool.get(&cfg.query_variable_selector).map(|v| v.to_text()).ok_or_else(|| {
208            NodeError::invalid_input(format!("query variable `{}` is missing", cfg.query_variable_selector))
209        })?;
210        let instruction = cfg.instruction.as_ref().map(|t| t.render(pool)).unwrap_or_default();
211
212        let mut messages = vec![Message::system(self.system_prompt(&instruction))];
213        if let Some(memory) = &cfg.memory {
214            messages.extend(memory.history(pool)?);
215        }
216        let mut user = Message::user(query);
217        #[cfg(feature = "vision-preparer")]
218        user.content.extend(cfg.vision.prepared_image_parts(&ctx).await?);
219        #[cfg(not(feature = "vision-preparer"))]
220        user.content.extend(cfg.vision.image_parts(pool)?);
221        messages.push(user);
222
223        let model = model_for(&ctx, &cfg.model)?;
224        let mut request = cfg.model.request(messages, pool)?;
225        let capped = crate::nodes::common::fit_budget(&ctx, &cfg.model, &mut request, false)?;
226        let response = invoke(&ctx, model.as_ref(), request, StreamMode::Off).await?;
227        crate::nodes::common::charge_model(&ctx, &cfg.model, &response.usage)?;
228        // An answer the budget cut short would pick the wrong class, or the fallback.
229        if capped && response.finish_reason == Some(crate::types::FinishReason::Length) {
230            return Err(crate::nodes::common::cut_by_budget(&ctx, &cfg.model));
231        }
232
233        let (index, fallback) = match self.match_class(&response.text) {
234            Some(i) => (i, false),
235            None => match &cfg.fallback_class {
236                Some(fallback) => {
237                    let i = cfg.classes.iter().position(|c| &c.id == fallback).ok_or_else(|| {
238                        NodeError::fatal("classification", format!("fallback class `{fallback}` is not configured"))
239                    })?;
240                    (i, true)
241                }
242                None => {
243                    return Err(NodeError::new(
244                        "classification",
245                        format!("model answer matched no configured class: {}", response.text.trim()),
246                    ));
247                }
248            },
249        };
250        let class =
251            cfg.classes.get(index).ok_or_else(|| NodeError::fatal("classification", "class index out of range"))?;
252        let label = class.label.clone().filter(|l| !l.is_empty()).unwrap_or_else(|| format!("CLASS {}", index + 1));
253        let mut output = NodeOutput::new()
254            .with("class_id", class.id.as_str())
255            .with("class_name", class.name.as_str())
256            .with("class_label", label)
257            .with("usage", usage_value(&response.usage))
258            .usage(response.usage)
259            .branch(class.id.clone());
260        if fallback {
261            output = output.meta("fallback", true).meta("raw_answer", response.text.trim());
262        }
263        Ok(output.into())
264    }
265}
266
267#[cfg(not(feature = "typesafe"))]
268impl ClassifierNode {
269    async fn execute_system_one(&self, _ctx: NodeContext) -> NodeResult {
270        Err(NodeError::fatal("missing_feature", "this build has no TypeSafe support (feature `typesafe`)"))
271    }
272}
273
274#[cfg(feature = "typesafe")]
275impl ClassifierNode {
276    const CHOICE: &'static str = "category";
277    const FITS: &'static str = "fits_any_category";
278
279    /// Build the System One request: one choice question (plus the companion yes/no question).
280    fn system_one_request(&self, query: String, instruction: &str) -> crate::typesafe::SystemOneRequest {
281        use crate::typesafe::{DEFAULT_MODEL, NoulCriteria, Question, SystemOneRequest};
282        let cfg = &self.config;
283        let criteria: indexmap::IndexMap<String, Json> = cfg
284            .classes
285            .iter()
286            .map(|c| {
287                let text = match c.description.as_deref().map(str::trim).filter(|d| !d.is_empty()) {
288                    Some(d) => format!("{}: {d}", c.name),
289                    None => c.name.clone(),
290                };
291                (c.id.clone(), Json::String(text))
292            })
293            .collect();
294        let mut instructions = String::from("Which category does `state` belong to?");
295        if !instruction.trim().is_empty() {
296            instructions.push('\n');
297            instructions.push_str(instruction.trim());
298        }
299        let model = if cfg.model.name.trim().is_empty() { DEFAULT_MODEL } else { cfg.model.name.as_str() };
300        let mut request = SystemOneRequest::new(model, Json::String(query))
301            .question(Self::CHOICE, Question::choice(instructions, criteria));
302        if cfg.companion_noul {
303            let names: Vec<&str> = cfg.classes.iter().map(|c| c.name.as_str()).collect();
304            let statement = format!("`state` clearly fits one of these categories: {}.", names.join(", "));
305            let fits = NoulCriteria {
306                yes: Some(Json::from("The message is about one of the listed categories.")),
307                no: Some(Json::from("The message is about something else, or none of the categories apply.")),
308            };
309            request = request.question(Self::FITS, Question::noul_with(statement, fits));
310        }
311        request
312    }
313
314    async fn execute_system_one(&self, ctx: NodeContext) -> NodeResult {
315        use crate::typesafe::{Answer, SystemOneClient};
316        let cfg = &self.config;
317        let pool = &ctx.pool;
318        let query = pool.get(&cfg.query_variable_selector).map(|v| v.to_text()).ok_or_else(|| {
319            NodeError::invalid_input(format!("query variable `{}` is missing", cfg.query_variable_selector))
320        })?;
321        let instruction = cfg.instruction.as_ref().map(|t| t.render(pool)).unwrap_or_default();
322        let client =
323            ctx.require_service::<Arc<SystemOneClient>>("TypeSafe client (graphrt_llm::typesafe::SystemOneClient)")?;
324        let request = self.system_one_request(query, &instruction);
325        // System One has no price: a run with a cost budget could not count it.
326        if ctx.budget().is_some_and(|budget| budget.remaining_cost_micros().is_some()) {
327            return Err(NodeError::fatal(
328                "price_missing",
329                "the run has a cost budget and System One has no price: its cost could not be counted",
330            ));
331        }
332        let response = client.ask(&request).await?;
333        // Paid for whatever comes next, an answer it rejects too.
334        ctx.charge(&response.usage.to_usage(), 0)?;
335
336        let Some(Answer::Choice { choice, confidence, probabilities }) = response.answer(Self::CHOICE) else {
337            return Err(NodeError::new("model_decode", "System One returned no choice answer"));
338        };
339        let chosen =
340            cfg.classes.iter().position(|c| &c.id == choice).ok_or_else(|| {
341                NodeError::new("classification", format!("System One chose unknown class `{choice}`"))
342            })?;
343        let probability = probabilities.get(choice).copied().ok_or_else(|| {
344            NodeError::new("model_decode", format!("System One gave no probability for the chosen class `{choice}`"))
345        })?;
346        let fits = match response.answer(Self::FITS) {
347            Some(Answer::Noul { noul }) => Some(*noul),
348            _ => None,
349        };
350
351        let mut reasons: Vec<String> = Vec::new();
352        if let Some(min) = cfg.min_confidence
353            && *confidence < min
354        {
355            reasons.push(format!("confidence {confidence:.3} < {min}"));
356        }
357        if let Some(min) = cfg.min_probability
358            && probability < min
359        {
360            reasons.push(format!("probability {probability:.3} < {min}"));
361        }
362        if cfg.companion_noul {
363            match fits {
364                Some(p) if p < cfg.companion_threshold => {
365                    reasons.push(format!("fits-any probability {p:.3} < {}", cfg.companion_threshold));
366                }
367                Some(_) => {}
368                None => return Err(NodeError::new("model_decode", "System One returned no companion answer")),
369            }
370        }
371
372        let (index, low_confidence) = if reasons.is_empty() {
373            (chosen, false)
374        } else {
375            match &cfg.fallback_class {
376                Some(fallback) => {
377                    let i = cfg.classes.iter().position(|c| &c.id == fallback).ok_or_else(|| {
378                        NodeError::fatal("classification", format!("fallback class `{fallback}` is not configured"))
379                    })?;
380                    (i, true)
381                }
382                None => {
383                    return Err(NodeError::fatal(
384                        "low_confidence",
385                        format!("classification below threshold: {}", reasons.join(", ")),
386                    ));
387                }
388            }
389        };
390
391        let class =
392            cfg.classes.get(index).ok_or_else(|| NodeError::fatal("classification", "class index out of range"))?;
393        let label = class.label.clone().filter(|l| !l.is_empty()).unwrap_or_else(|| format!("CLASS {}", index + 1));
394        let usage = response.usage.to_usage();
395        let probability_map: graphrt_core::value::Map =
396            probabilities.iter().map(|(k, v)| (k.clone(), graphrt_core::Value::Float(*v))).collect();
397        let mut output = NodeOutput::new()
398            .with("class_id", class.id.as_str())
399            .with("class_name", class.name.as_str())
400            .with("class_label", label)
401            .with("probabilities", graphrt_core::Value::from(probability_map))
402            .with("confidence", *confidence)
403            .with("usage", usage_value(&usage))
404            .usage(usage)
405            .branch(class.id.clone())
406            .meta("engine", "typesafe")
407            .meta("model", response.model.as_str());
408        if let Some(p) = fits {
409            output = output.meta("fits_any_probability", p);
410        }
411        if low_confidence {
412            output = output
413                .meta("fallback", true)
414                .meta("low_confidence", true)
415                .meta("predicted_class", choice.as_str())
416                .meta("reasons", reasons.join(", "));
417        }
418        Ok(output.into())
419    }
420}
421
422impl Node for ClassifierNode {
423    fn role(&self) -> NodeRole {
424        NodeRole::Branch
425    }
426
427    /// Each model response is charged with its cost as it arrives.
428    fn tracks_turns(&self) -> bool {
429        true
430    }
431
432    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
433        Box::pin(self.execute(ctx))
434    }
435
436    fn branch_handles(&self) -> Option<Vec<String>> {
437        Some(self.config.classes.iter().map(|c| c.id.clone()).collect())
438    }
439
440    fn inputs(&self) -> Vec<Selector> {
441        let cfg = &self.config;
442        let mut out = vec![cfg.query_variable_selector.clone()];
443        if let Some(instruction) = &cfg.instruction {
444            out.extend(instruction.selectors().cloned());
445        }
446        if let Some(memory) = &cfg.memory {
447            out.extend(memory.selectors());
448        }
449        out.extend(cfg.vision.selectors());
450        out.extend(cfg.model.selectors());
451        out
452    }
453}
454
455/// Factory for the node registry.
456pub fn factory(doc: &NodeDoc) -> Result<Arc<dyn Node>, ConfigError> {
457    Ok(Arc::new(ClassifierNode::from_doc(doc)?))
458}
459
460#[cfg(test)]
461mod tests {
462    use super::*;
463    use crate::mock::MockModel;
464    use crate::registry::ModelRegistry;
465    use graphrt_core::value::Value;
466    use graphrt_core::{NodeOutcome, Services, VariablePool};
467
468    fn node(extra: Json) -> ClassifierNode {
469        let mut config = serde_json::json!({
470            "model": {"provider": "openai", "name": "gpt"},
471            "query_variable_selector": ["sys", "query"],
472            "classes": [{"id": "1", "name": "billing"}, {"id": "2", "name": "support", "label": "Help"}],
473        });
474        if let (Some(c), Json::Object(e)) = (config.as_object_mut(), extra) {
475            c.extend(e);
476        }
477        ClassifierNode::from_doc(&NodeDoc::new("qc", "question-classifier", config)).unwrap()
478    }
479
480    async fn classify(node: &ClassifierNode, answer: &str) -> NodeResult {
481        let model = Arc::new(MockModel::new(vec![MockModel::text(answer)]));
482        let mut pool = VariablePool::new();
483        pool.insert("sys", "query", Value::from("my card was charged twice"));
484        let ctx = NodeContext::for_test("qc", pool)
485            .with_services(Arc::new(Services::new().with(ModelRegistry::new().with("openai", model))));
486        node.run(ctx).await
487    }
488
489    fn output(r: NodeResult) -> NodeOutput {
490        match r.unwrap() {
491            NodeOutcome::Completed(o) => o,
492            NodeOutcome::Paused(_) => panic!("paused"),
493        }
494    }
495
496    #[tokio::test]
497    async fn routes_by_id_and_name() {
498        let n = node(serde_json::json!({}));
499        let out = output(classify(&n, "```json\n{\"category_id\": \"2\", \"category_name\": \"support\"}\n```").await);
500        assert_eq!(out.branch.as_deref(), Some("2"));
501        assert_eq!(out.outputs["class_label"], Value::from("Help"));
502        let out = output(classify(&n, "{\"category_name\": \"Billing\"}").await);
503        assert_eq!(out.branch.as_deref(), Some("1"));
504        assert_eq!(out.outputs["class_label"], Value::from("CLASS 1"));
505    }
506
507    #[tokio::test]
508    async fn unknown_class_fails_unless_fallback() {
509        let n = node(serde_json::json!({}));
510        let err = classify(&n, "{\"category_id\": \"9\"}").await.unwrap_err();
511        assert_eq!(err.kind, "classification");
512        let n = node(serde_json::json!({"fallback_class": "2"}));
513        let out = output(classify(&n, "gibberish").await);
514        assert_eq!(out.branch.as_deref(), Some("2"));
515        assert_eq!(out.metadata.get("fallback"), Some(&Value::Bool(true)));
516        assert_eq!(out.metadata.get("raw_answer"), Some(&Value::from("gibberish")));
517        let out = output(classify(&n, "{\"category_id\": \"1\"}").await);
518        assert!(!out.metadata.contains_key("fallback"));
519    }
520
521    #[test]
522    fn config_validation() {
523        let bad = NodeDoc::new(
524            "qc",
525            "question-classifier",
526            serde_json::json!({"model": {"provider": "p", "name": "m"}, "query_variable_selector": "sys.query", "classes": []}),
527        );
528        assert!(ClassifierNode::from_doc(&bad).is_err());
529        let bad = NodeDoc::new(
530            "qc",
531            "question-classifier",
532            serde_json::json!({"model": {"provider": "p", "name": "m"}, "query_variable_selector": "sys.query",
533                "classes": [{"id": "a", "name": "x"}], "fallback_class": "zzz"}),
534        );
535        assert!(ClassifierNode::from_doc(&bad).is_err());
536    }
537
538    #[test]
539    fn typesafe_engine_rejects_chat_only_settings() {
540        let doc = |extra: Json| {
541            let mut config = serde_json::json!({
542                "model": {"provider": "typesafe", "name": "jev-latest"},
543                "query_variable_selector": "sys.query",
544                "classes": [{"id": "a", "name": "x"}],
545            });
546            if let (Some(c), Json::Object(e)) = (config.as_object_mut(), extra) {
547                c.extend(e);
548            }
549            NodeDoc::new("qc", "question-classifier", config)
550        };
551        assert!(ClassifierNode::from_doc(&doc(serde_json::json!({}))).is_ok());
552        for bad in [
553            serde_json::json!({"engine": "chat"}),
554            serde_json::json!({"memory": {"window": {"enabled": true, "size": 3}}}),
555            serde_json::json!({"vision": {"enabled": true}}),
556            serde_json::json!({"model": {"provider": "typesafe", "name": "jev", "completion_params": {"temperature": 0}}}),
557        ] {
558            assert!(ClassifierNode::from_doc(&doc(bad.clone())).is_err(), "{bad}");
559        }
560    }
561}