Skip to main content

adk_graph/
decision.rs

1//! [`DecisionNode`]: a graph router node whose route a model decides, with structured output.
2//!
3//! The node reads its input from the state, asks a [`Decider`] to pick one of its options,
4//! and writes the option's name to its output key, where a conditional edge reads it with
5//! [`Router::by_field`](crate::edge::Router::by_field). It writes the rationale and the
6//! confidence beside it under `<output_key>_decision`.
7
8use std::sync::Arc;
9
10use adk_core::{Choice, ChoiceOption, Decider, Llm, ModelCallScope};
11use async_trait::async_trait;
12use serde_json::{Value, json};
13
14use crate::error::{GraphError, Result};
15use crate::node::{Node, NodeContext, NodeOutput};
16
17/// A graph node that routes by a model's typed decision.
18///
19/// The decision's call runs in the graph run's [`ModelCallScope`] when the graph runs with a
20/// `RunConfig` (as a graph agent under a runner, or
21/// [`invoke_with_run_config`](crate::CompiledGraph::invoke_with_run_config)), so it counts
22/// against the run's budget and spend ledger; otherwise in the scope current at the call. A
23/// decision below [`min_confidence`](Self::min_confidence) routes to the
24/// [`fallback`](Self::fallback) option.
25///
26/// # Example
27///
28/// ```rust,no_run
29/// use std::sync::Arc;
30///
31/// use adk_graph::node::FunctionNode;
32/// use adk_graph::{DecisionNode, END, NodeOutput, Router, START, StateGraph, StateSchema};
33///
34/// fn triage_graph(
35///     model: Arc<dyn adk_core::Llm>,
36/// ) -> adk_graph::Result<adk_graph::CompiledGraph> {
37///     let triage = DecisionNode::new("triage", model)
38///         .instruction("Route the support ticket.")
39///         .option("billing", "Invoices, refunds and payment problems")
40///         .option("technical", "Errors, outages and how-to questions")
41///         .input_key("ticket")
42///         .output_key("route");
43///     StateGraph::new(StateSchema::simple(&["ticket", "route"]))
44///         .add_node(triage)
45///         .add_node(FunctionNode::new("billing", |_| async { Ok(NodeOutput::new()) }))
46///         .add_node(FunctionNode::new("technical", |_| async { Ok(NodeOutput::new()) }))
47///         .add_edge(START, "triage")
48///         .add_conditional_edges(
49///             "triage",
50///             Router::by_field("route"),
51///             [("billing", "billing"), ("technical", "technical")],
52///         )
53///         .add_edge("billing", END)
54///         .add_edge("technical", END)
55///         .compile()
56/// }
57/// ```
58#[derive(Clone)]
59pub struct DecisionNode {
60    name: String,
61    model: Arc<dyn Llm>,
62    instruction: Option<String>,
63    options: Vec<ChoiceOption>,
64    input_key: String,
65    output_key: String,
66    min_confidence: f64,
67    fallback: Option<String>,
68}
69
70impl std::fmt::Debug for DecisionNode {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        f.debug_struct("DecisionNode")
73            .field("name", &self.name)
74            .field("options", &self.options)
75            .field("input_key", &self.input_key)
76            .field("output_key", &self.output_key)
77            .finish_non_exhaustive()
78    }
79}
80
81impl DecisionNode {
82    /// A node named `name` deciding with `model`; it reads state key `input` and writes the
83    /// option's name to `route` until configured otherwise.
84    pub fn new(name: impl Into<String>, model: Arc<dyn Llm>) -> Self {
85        Self {
86            name: name.into(),
87            model,
88            instruction: None,
89            options: Vec::new(),
90            input_key: "input".to_string(),
91            output_key: "route".to_string(),
92            min_confidence: 0.0,
93            fallback: None,
94        }
95    }
96
97    /// A node whose options are those of `T`.
98    pub fn for_choice<T: Choice>(name: impl Into<String>, model: Arc<dyn Llm>) -> Self {
99        let mut node = Self::new(name, model);
100        node.options = T::options();
101        node
102    }
103
104    /// What to decide, shown to the model before the options.
105    #[must_use]
106    pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
107        self.instruction = Some(instruction.into());
108        self
109    }
110
111    /// An option: the route `name` and what it is for.
112    #[must_use]
113    pub fn option(mut self, name: impl Into<String>, description: impl Into<String>) -> Self {
114        self.options.push(ChoiceOption::new(name, description));
115        self
116    }
117
118    /// The state key the decision reads: a string as is, any other value as JSON.
119    #[must_use]
120    pub fn input_key(mut self, key: impl Into<String>) -> Self {
121        self.input_key = key.into();
122        self
123    }
124
125    /// The state key the option's name is written to; the rationale and confidence go to
126    /// `<key>_decision`.
127    #[must_use]
128    pub fn output_key(mut self, key: impl Into<String>) -> Self {
129        self.output_key = key.into();
130        self
131    }
132
133    /// The least confidence, from 0.0 to 1.0, at which the decision is followed; below it the
134    /// node routes to [`fallback`](Self::fallback), or fails without one. Default 0.0.
135    #[must_use]
136    pub fn min_confidence(mut self, confidence: f64) -> Self {
137        self.min_confidence = confidence;
138        self
139    }
140
141    /// The route written when the decision is below `min_confidence`.
142    #[must_use]
143    pub fn fallback(mut self, route: impl Into<String>) -> Self {
144        self.fallback = Some(route.into());
145        self
146    }
147
148    fn failed(&self, message: String) -> GraphError {
149        GraphError::NodeExecutionFailed { node: self.name.clone(), message }
150    }
151}
152
153#[async_trait]
154impl Node for DecisionNode {
155    fn name(&self) -> &str {
156        &self.name
157    }
158
159    fn description(&self) -> &str {
160        "Routes by a model's typed decision"
161    }
162
163    fn kind(&self) -> crate::shape::NodeKind {
164        crate::shape::NodeKind::ModelStep
165    }
166
167    async fn execute(&self, ctx: &NodeContext) -> Result<NodeOutput> {
168        if !(0.0..=1.0).contains(&self.min_confidence) {
169            return Err(self
170                .failed(format!("min_confidence {} is outside 0.0 to 1.0", self.min_confidence)));
171        }
172        let input = match ctx.state.get(&self.input_key) {
173            Some(Value::String(text)) => text.clone(),
174            Some(other) => other.to_string(),
175            None => {
176                return Err(self.failed(format!(
177                    "state key `{}`, the decision's input, is not set",
178                    self.input_key
179                )));
180            }
181        };
182        let mut decider = Decider::new(self.model.clone());
183        if let Some(config) = ctx.run_config() {
184            let app = ctx.config.parent_context.as_ref().map_or_else(
185                || crate::node::STANDALONE_APP_NAME.to_string(),
186                |parent| parent.app_name().to_string(),
187            );
188            decider = decider.with_scope(ModelCallScope::for_run(&config, &app, &self.name));
189        }
190        if let Some(instruction) = &self.instruction {
191            decider = decider.with_instruction(instruction.clone());
192        }
193        let decision = decider.decide_among(&self.options, &input).await.map_err(|error| {
194            GraphError::AgentFailed { node: self.name.clone(), source: Box::new(error) }
195        })?;
196        let followed = decision.confidence >= self.min_confidence;
197        let route = match (followed, &self.fallback) {
198            (true, _) => decision.option.clone(),
199            (false, Some(fallback)) => fallback.clone(),
200            (false, None) => {
201                return Err(self.failed(format!(
202                    "decided `{}` with confidence {:.2}, below min_confidence {:.2}, and has no \
203                     fallback route",
204                    decision.option, decision.confidence, self.min_confidence
205                )));
206            }
207        };
208        tracing::info!(
209            node.name = %self.name,
210            decision.option = %decision.option,
211            decision.confidence = decision.confidence,
212            decision.followed = followed,
213            route = %route,
214            "graph decision routed"
215        );
216        Ok(NodeOutput::new().with_update(&self.output_key, json!(route)).with_update(
217            &format!("{}_decision", self.output_key),
218            json!({
219                "option": decision.option,
220                "rationale": decision.rationale,
221                "confidence": decision.confidence,
222                "followed": followed,
223            }),
224        ))
225    }
226}