use std::sync::Arc;
use adk_core::{Choice, ChoiceOption, Decider, Llm, ModelCallScope};
use async_trait::async_trait;
use serde_json::{Value, json};
use crate::error::{GraphError, Result};
use crate::node::{Node, NodeContext, NodeOutput};
#[derive(Clone)]
pub struct DecisionNode {
name: String,
model: Arc<dyn Llm>,
instruction: Option<String>,
options: Vec<ChoiceOption>,
input_key: String,
output_key: String,
min_confidence: f64,
fallback: Option<String>,
}
impl std::fmt::Debug for DecisionNode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DecisionNode")
.field("name", &self.name)
.field("options", &self.options)
.field("input_key", &self.input_key)
.field("output_key", &self.output_key)
.finish_non_exhaustive()
}
}
impl DecisionNode {
pub fn new(name: impl Into<String>, model: Arc<dyn Llm>) -> Self {
Self {
name: name.into(),
model,
instruction: None,
options: Vec::new(),
input_key: "input".to_string(),
output_key: "route".to_string(),
min_confidence: 0.0,
fallback: None,
}
}
pub fn for_choice<T: Choice>(name: impl Into<String>, model: Arc<dyn Llm>) -> Self {
let mut node = Self::new(name, model);
node.options = T::options();
node
}
#[must_use]
pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
self.instruction = Some(instruction.into());
self
}
#[must_use]
pub fn option(mut self, name: impl Into<String>, description: impl Into<String>) -> Self {
self.options.push(ChoiceOption::new(name, description));
self
}
#[must_use]
pub fn input_key(mut self, key: impl Into<String>) -> Self {
self.input_key = key.into();
self
}
#[must_use]
pub fn output_key(mut self, key: impl Into<String>) -> Self {
self.output_key = key.into();
self
}
#[must_use]
pub fn min_confidence(mut self, confidence: f64) -> Self {
self.min_confidence = confidence;
self
}
#[must_use]
pub fn fallback(mut self, route: impl Into<String>) -> Self {
self.fallback = Some(route.into());
self
}
fn failed(&self, message: String) -> GraphError {
GraphError::NodeExecutionFailed { node: self.name.clone(), message }
}
}
#[async_trait]
impl Node for DecisionNode {
fn name(&self) -> &str {
&self.name
}
fn description(&self) -> &str {
"Routes by a model's typed decision"
}
fn kind(&self) -> crate::shape::NodeKind {
crate::shape::NodeKind::ModelStep
}
async fn execute(&self, ctx: &NodeContext) -> Result<NodeOutput> {
if !(0.0..=1.0).contains(&self.min_confidence) {
return Err(self
.failed(format!("min_confidence {} is outside 0.0 to 1.0", self.min_confidence)));
}
let input = match ctx.state.get(&self.input_key) {
Some(Value::String(text)) => text.clone(),
Some(other) => other.to_string(),
None => {
return Err(self.failed(format!(
"state key `{}`, the decision's input, is not set",
self.input_key
)));
}
};
let mut decider = Decider::new(self.model.clone());
if let Some(config) = ctx.run_config() {
let app = ctx.config.parent_context.as_ref().map_or_else(
|| crate::node::STANDALONE_APP_NAME.to_string(),
|parent| parent.app_name().to_string(),
);
decider = decider.with_scope(ModelCallScope::for_run(&config, &app, &self.name));
}
if let Some(instruction) = &self.instruction {
decider = decider.with_instruction(instruction.clone());
}
let decision = decider.decide_among(&self.options, &input).await.map_err(|error| {
GraphError::AgentFailed { node: self.name.clone(), source: Box::new(error) }
})?;
let followed = decision.confidence >= self.min_confidence;
let route = match (followed, &self.fallback) {
(true, _) => decision.option.clone(),
(false, Some(fallback)) => fallback.clone(),
(false, None) => {
return Err(self.failed(format!(
"decided `{}` with confidence {:.2}, below min_confidence {:.2}, and has no \
fallback route",
decision.option, decision.confidence, self.min_confidence
)));
}
};
tracing::info!(
node.name = %self.name,
decision.option = %decision.option,
decision.confidence = decision.confidence,
decision.followed = followed,
route = %route,
"graph decision routed"
);
Ok(NodeOutput::new().with_update(&self.output_key, json!(route)).with_update(
&format!("{}_decision", self.output_key),
json!({
"option": decision.option,
"rationale": decision.rationale,
"confidence": decision.confidence,
"followed": followed,
}),
))
}
}