use std::collections::HashMap;
use std::sync::Arc;
use adk_core::{
AdkError, Agent, Choice, ChoiceOption, Content, Decider, Event, EventStream, InvocationContext,
Llm, ModelCallScope, Part, Result, WorkflowPosition,
};
use async_stream::stream;
use async_trait::async_trait;
use futures::StreamExt;
use serde_json::json;
pub struct DecisionAgent {
name: String,
description: String,
model: Arc<dyn Llm>,
instruction: Option<String>,
options: Vec<ChoiceOption>,
routes: HashMap<String, Arc<dyn Agent>>,
fallback: Option<Arc<dyn Agent>>,
min_confidence: f64,
output_key: Option<String>,
all_agents: Vec<Arc<dyn Agent>>,
}
impl std::fmt::Debug for DecisionAgent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DecisionAgent")
.field("name", &self.name)
.field("options", &self.options)
.field("min_confidence", &self.min_confidence)
.finish_non_exhaustive()
}
}
pub struct DecisionAgentBuilder {
name: String,
description: Option<String>,
model: Arc<dyn Llm>,
instruction: Option<String>,
options: Vec<ChoiceOption>,
routes: HashMap<String, Arc<dyn Agent>>,
fallback: Option<Arc<dyn Agent>>,
min_confidence: f64,
output_key: Option<String>,
error: Option<AdkError>,
}
impl DecisionAgentBuilder {
pub fn new(name: impl Into<String>, model: Arc<dyn Llm>) -> Self {
Self {
name: name.into(),
description: None,
model,
instruction: None,
options: Vec::new(),
routes: HashMap::new(),
fallback: None,
min_confidence: 0.0,
output_key: None,
error: None,
}
}
#[must_use]
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
self.instruction = Some(instruction.into());
self
}
#[must_use]
pub fn route(
mut self,
name: impl Into<String>,
description: impl Into<String>,
agent: Arc<dyn Agent>,
) -> Self {
let name = name.into();
self.options.push(ChoiceOption::new(name.clone(), description));
self.routes.insert(name, agent);
self
}
#[must_use]
pub fn routes<T: Choice>(mut self, agent_for: impl Fn(T) -> Arc<dyn Agent>) -> Self {
for option in T::options() {
match T::from_option(&option.name) {
Some(value) => {
let agent = agent_for(value);
self.routes.insert(option.name.clone(), agent);
self.options.push(option);
}
None => {
self.error.get_or_insert_with(|| {
AdkError::config(format!(
"option `{}` of the choice type does not map to a value",
option.name
))
});
}
}
}
self
}
#[must_use]
pub fn fallback(mut self, agent: Arc<dyn Agent>) -> Self {
self.fallback = Some(agent);
self
}
#[must_use]
pub fn min_confidence(mut self, confidence: f64) -> Self {
self.min_confidence = confidence;
self
}
#[must_use]
pub fn output_key(mut self, key: impl Into<String>) -> Self {
self.output_key = Some(key.into());
self
}
pub fn build(self) -> Result<DecisionAgent> {
if let Some(error) = self.error {
return Err(error);
}
if self.options.is_empty() {
return Err(AdkError::config(format!(
"DecisionAgent `{}` needs at least one route",
self.name
)));
}
if self.routes.len() != self.options.len() {
return Err(AdkError::config(format!(
"DecisionAgent `{}` names a route twice; give each route a distinct name",
self.name
)));
}
if !(0.0..=1.0).contains(&self.min_confidence) {
return Err(AdkError::config(format!(
"DecisionAgent `{}`: min_confidence {} is outside 0.0 to 1.0",
self.name, self.min_confidence
)));
}
let mut all_agents: Vec<Arc<dyn Agent>> = self
.options
.iter()
.filter_map(|option| self.routes.get(&option.name).cloned())
.collect();
all_agents.extend(self.fallback.clone());
Ok(DecisionAgent {
name: self.name,
description: self.description.unwrap_or_default(),
model: self.model,
instruction: self.instruction,
options: self.options,
routes: self.routes,
fallback: self.fallback,
min_confidence: self.min_confidence,
output_key: self.output_key,
all_agents,
})
}
}
impl DecisionAgent {
pub fn builder(name: impl Into<String>, model: Arc<dyn Llm>) -> DecisionAgentBuilder {
DecisionAgentBuilder::new(name, model)
}
pub fn options(&self) -> &[ChoiceOption] {
&self.options
}
}
#[async_trait]
impl Agent for DecisionAgent {
fn name(&self) -> &str {
&self.name
}
fn description(&self) -> &str {
&self.description
}
fn sub_agents(&self) -> &[Arc<dyn Agent>] {
&self.all_agents
}
fn supports_agent_transfer(&self) -> bool {
false
}
async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
if let Some(refused) = crate::requested_call::refused_by_root(
ctx.as_ref(),
&self.name,
crate::requested_call::RUNS_OTHER_AGENTS,
) {
return Ok(refused);
}
let resuming =
ctx.session().workflow_resume_positions(&self.name, ctx.branch()).into_iter().find_map(
|position| {
self.all_agents.iter().find(|agent| agent.name() == position.sub_agent).cloned()
},
);
let (agent, routing) = match resuming {
Some(agent) => (agent, None),
None => {
ctx.run_config().check_governance()?;
let input: String =
ctx.user_content().parts.iter().filter_map(Part::text).collect();
let scope = ModelCallScope::for_run(ctx.run_config(), ctx.app_name(), &self.name);
let mut decider = Decider::new(self.model.clone()).with_scope(scope);
if let Some(instruction) = &self.instruction {
decider = decider.with_instruction(instruction.clone());
}
let decision = decider.decide_among(&self.options, &input).await?;
let followed = decision.confidence >= self.min_confidence;
let agent = match (followed, &self.fallback) {
(true, _) => self.routes.get(&decision.option).cloned(),
(false, Some(fallback)) => Some(fallback.clone()),
(false, None) => None,
}
.ok_or_else(|| {
AdkError::new(
adk_core::ErrorComponent::Agent,
adk_core::ErrorCategory::Unavailable,
"decision.low_confidence",
format!(
"DecisionAgent `{}` decided `{}` with confidence {:.2}, below its \
min_confidence {:.2}, and has no fallback route",
self.name, decision.option, decision.confidence, self.min_confidence
),
)
})?;
tracing::info!(
agent.name = %self.name,
decision.option = %decision.option,
decision.confidence = decision.confidence,
decision.followed = followed,
route = %agent.name(),
"decision routed"
);
let mut event = Event::new(ctx.invocation_id());
event.author = self.name.clone();
event.branch = ctx.branch().to_string();
let note = if followed {
String::new()
} else {
format!(" (below {:.2}; fallback {})", self.min_confidence, agent.name())
};
event.llm_response.content = Some(Content::new("model").with_text(format!(
"[Decision: {} ({:.2}){note}] {}",
decision.option, decision.confidence, decision.rationale
)));
if let Some(key) = &self.output_key {
event.actions.state_delta.insert(
key.clone(),
json!({
"option": decision.option,
"rationale": decision.rationale,
"confidence": decision.confidence,
"followed": followed,
"route": agent.name(),
}),
);
}
(agent, Some(event))
}
};
let name = self.name.clone();
let s = stream! {
if let Some(routing) = routing {
yield Ok(routing);
}
let mut inner = match agent.run(ctx.clone()).await {
Ok(inner) => inner,
Err(error) => {
yield Err(error);
return;
}
};
while let Some(result) = inner.next().await {
yield result.map(|mut event| {
if event.actions.tool_confirmation.is_some() {
event
.actions
.workflow_positions
.insert(name.clone(), WorkflowPosition::new(0, agent.name()));
}
event
});
}
};
Ok(Box::pin(s))
}
}