1use std::collections::HashMap;
12use std::sync::Arc;
13
14use adk_core::{
15 AdkError, Agent, Choice, ChoiceOption, Content, Decider, Event, EventStream, InvocationContext,
16 Llm, ModelCallScope, Part, Result, WorkflowPosition,
17};
18use async_stream::stream;
19use async_trait::async_trait;
20use futures::StreamExt;
21use serde_json::json;
22
23pub struct DecisionAgent {
57 name: String,
58 description: String,
59 model: Arc<dyn Llm>,
60 instruction: Option<String>,
61 options: Vec<ChoiceOption>,
62 routes: HashMap<String, Arc<dyn Agent>>,
63 fallback: Option<Arc<dyn Agent>>,
64 min_confidence: f64,
65 output_key: Option<String>,
66 all_agents: Vec<Arc<dyn Agent>>,
67}
68
69impl std::fmt::Debug for DecisionAgent {
70 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71 f.debug_struct("DecisionAgent")
72 .field("name", &self.name)
73 .field("options", &self.options)
74 .field("min_confidence", &self.min_confidence)
75 .finish_non_exhaustive()
76 }
77}
78
79pub struct DecisionAgentBuilder {
81 name: String,
82 description: Option<String>,
83 model: Arc<dyn Llm>,
84 instruction: Option<String>,
85 options: Vec<ChoiceOption>,
86 routes: HashMap<String, Arc<dyn Agent>>,
87 fallback: Option<Arc<dyn Agent>>,
88 min_confidence: f64,
89 output_key: Option<String>,
90 error: Option<AdkError>,
91}
92
93impl DecisionAgentBuilder {
94 pub fn new(name: impl Into<String>, model: Arc<dyn Llm>) -> Self {
96 Self {
97 name: name.into(),
98 description: None,
99 model,
100 instruction: None,
101 options: Vec::new(),
102 routes: HashMap::new(),
103 fallback: None,
104 min_confidence: 0.0,
105 output_key: None,
106 error: None,
107 }
108 }
109
110 #[must_use]
112 pub fn description(mut self, description: impl Into<String>) -> Self {
113 self.description = Some(description.into());
114 self
115 }
116
117 #[must_use]
119 pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
120 self.instruction = Some(instruction.into());
121 self
122 }
123
124 #[must_use]
126 pub fn route(
127 mut self,
128 name: impl Into<String>,
129 description: impl Into<String>,
130 agent: Arc<dyn Agent>,
131 ) -> Self {
132 let name = name.into();
133 self.options.push(ChoiceOption::new(name.clone(), description));
134 self.routes.insert(name, agent);
135 self
136 }
137
138 #[must_use]
151 pub fn routes<T: Choice>(mut self, agent_for: impl Fn(T) -> Arc<dyn Agent>) -> Self {
152 for option in T::options() {
153 match T::from_option(&option.name) {
154 Some(value) => {
155 let agent = agent_for(value);
156 self.routes.insert(option.name.clone(), agent);
157 self.options.push(option);
158 }
159 None => {
160 self.error.get_or_insert_with(|| {
161 AdkError::config(format!(
162 "option `{}` of the choice type does not map to a value",
163 option.name
164 ))
165 });
166 }
167 }
168 }
169 self
170 }
171
172 #[must_use]
174 pub fn fallback(mut self, agent: Arc<dyn Agent>) -> Self {
175 self.fallback = Some(agent);
176 self
177 }
178
179 #[must_use]
183 pub fn min_confidence(mut self, confidence: f64) -> Self {
184 self.min_confidence = confidence;
185 self
186 }
187
188 #[must_use]
191 pub fn output_key(mut self, key: impl Into<String>) -> Self {
192 self.output_key = Some(key.into());
193 self
194 }
195
196 pub fn build(self) -> Result<DecisionAgent> {
204 if let Some(error) = self.error {
205 return Err(error);
206 }
207 if self.options.is_empty() {
208 return Err(AdkError::config(format!(
209 "DecisionAgent `{}` needs at least one route",
210 self.name
211 )));
212 }
213 if self.routes.len() != self.options.len() {
214 return Err(AdkError::config(format!(
215 "DecisionAgent `{}` names a route twice; give each route a distinct name",
216 self.name
217 )));
218 }
219 if !(0.0..=1.0).contains(&self.min_confidence) {
220 return Err(AdkError::config(format!(
221 "DecisionAgent `{}`: min_confidence {} is outside 0.0 to 1.0",
222 self.name, self.min_confidence
223 )));
224 }
225 let mut all_agents: Vec<Arc<dyn Agent>> = self
226 .options
227 .iter()
228 .filter_map(|option| self.routes.get(&option.name).cloned())
229 .collect();
230 all_agents.extend(self.fallback.clone());
231 Ok(DecisionAgent {
232 name: self.name,
233 description: self.description.unwrap_or_default(),
234 model: self.model,
235 instruction: self.instruction,
236 options: self.options,
237 routes: self.routes,
238 fallback: self.fallback,
239 min_confidence: self.min_confidence,
240 output_key: self.output_key,
241 all_agents,
242 })
243 }
244}
245
246impl DecisionAgent {
247 pub fn builder(name: impl Into<String>, model: Arc<dyn Llm>) -> DecisionAgentBuilder {
249 DecisionAgentBuilder::new(name, model)
250 }
251
252 pub fn options(&self) -> &[ChoiceOption] {
254 &self.options
255 }
256}
257
258#[async_trait]
259impl Agent for DecisionAgent {
260 fn name(&self) -> &str {
261 &self.name
262 }
263
264 fn description(&self) -> &str {
265 &self.description
266 }
267
268 fn sub_agents(&self) -> &[Arc<dyn Agent>] {
269 &self.all_agents
270 }
271
272 fn supports_agent_transfer(&self) -> bool {
273 false
276 }
277
278 async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
279 if let Some(refused) = crate::requested_call::refused_by_root(
282 ctx.as_ref(),
283 &self.name,
284 crate::requested_call::RUNS_OTHER_AGENTS,
285 ) {
286 return Ok(refused);
287 }
288 let resuming =
291 ctx.session().workflow_resume_positions(&self.name, ctx.branch()).into_iter().find_map(
292 |position| {
293 self.all_agents.iter().find(|agent| agent.name() == position.sub_agent).cloned()
294 },
295 );
296 let (agent, routing) = match resuming {
297 Some(agent) => (agent, None),
298 None => {
299 ctx.run_config().check_governance()?;
300 let input: String =
301 ctx.user_content().parts.iter().filter_map(Part::text).collect();
302 let scope = ModelCallScope::for_run(ctx.run_config(), ctx.app_name(), &self.name);
303 let mut decider = Decider::new(self.model.clone()).with_scope(scope);
304 if let Some(instruction) = &self.instruction {
305 decider = decider.with_instruction(instruction.clone());
306 }
307 let decision = decider.decide_among(&self.options, &input).await?;
308 let followed = decision.confidence >= self.min_confidence;
309 let agent = match (followed, &self.fallback) {
310 (true, _) => self.routes.get(&decision.option).cloned(),
311 (false, Some(fallback)) => Some(fallback.clone()),
312 (false, None) => None,
313 }
314 .ok_or_else(|| {
315 AdkError::new(
316 adk_core::ErrorComponent::Agent,
317 adk_core::ErrorCategory::Unavailable,
318 "decision.low_confidence",
319 format!(
320 "DecisionAgent `{}` decided `{}` with confidence {:.2}, below its \
321 min_confidence {:.2}, and has no fallback route",
322 self.name, decision.option, decision.confidence, self.min_confidence
323 ),
324 )
325 })?;
326 tracing::info!(
327 agent.name = %self.name,
328 decision.option = %decision.option,
329 decision.confidence = decision.confidence,
330 decision.followed = followed,
331 route = %agent.name(),
332 "decision routed"
333 );
334 let mut event = Event::new(ctx.invocation_id());
335 event.author = self.name.clone();
336 event.branch = ctx.branch().to_string();
337 let note = if followed {
338 String::new()
339 } else {
340 format!(" (below {:.2}; fallback {})", self.min_confidence, agent.name())
341 };
342 event.llm_response.content = Some(Content::new("model").with_text(format!(
343 "[Decision: {} ({:.2}){note}] {}",
344 decision.option, decision.confidence, decision.rationale
345 )));
346 if let Some(key) = &self.output_key {
347 event.actions.state_delta.insert(
348 key.clone(),
349 json!({
350 "option": decision.option,
351 "rationale": decision.rationale,
352 "confidence": decision.confidence,
353 "followed": followed,
354 "route": agent.name(),
355 }),
356 );
357 }
358 (agent, Some(event))
359 }
360 };
361 let name = self.name.clone();
362 let s = stream! {
363 if let Some(routing) = routing {
364 yield Ok(routing);
365 }
366 let mut inner = match agent.run(ctx.clone()).await {
367 Ok(inner) => inner,
368 Err(error) => {
369 yield Err(error);
370 return;
371 }
372 };
373 while let Some(result) = inner.next().await {
374 yield result.map(|mut event| {
375 if event.actions.tool_confirmation.is_some() {
376 event
377 .actions
378 .workflow_positions
379 .insert(name.clone(), WorkflowPosition::new(0, agent.name()));
380 }
381 event
382 });
383 }
384 };
385 Ok(Box::pin(s))
386 }
387}