1use 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#[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 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 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 #[must_use]
106 pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
107 self.instruction = Some(instruction.into());
108 self
109 }
110
111 #[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 #[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 #[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 #[must_use]
136 pub fn min_confidence(mut self, confidence: f64) -> Self {
137 self.min_confidence = confidence;
138 self
139 }
140
141 #[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}