Skip to main content

adk_agent/workflow/
decision_agent.rs

1//! `DecisionAgent`: routes to a sub-agent by a typed decision a model makes with
2//! structured output.
3//!
4//! Where [`LlmConditionalAgent`](crate::LlmConditionalAgent) reads a free-text label from the
5//! model, `DecisionAgent` asks for a [`Decision`](adk_core::Decision) through
6//! [`Decider`]: the reply is constrained to one of the route names by the provider's
7//! structured outputs, carries the model's rationale and confidence, and is recorded in the
8//! session. A decision below [`min_confidence`](DecisionAgentBuilder::min_confidence) goes to
9//! the fallback route.
10
11use 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
23/// Routes each turn to one sub-agent by a model's typed decision.
24///
25/// Each run checks the kill switch, decides among the routes with a [`Decider`] metered
26/// against the run's budget and spend ledger (`ModelCallScope::for_run`), yields a routing
27/// event that names the route, rationale and confidence (and writes them to
28/// [`output_key`](DecisionAgentBuilder::output_key) when set), then runs the chosen
29/// sub-agent. A run that resumes a held call returns to the route that holds it without
30/// deciding again.
31///
32/// # Example
33///
34/// ```rust,no_run
35/// use std::sync::Arc;
36///
37/// use adk_agent::DecisionAgent;
38/// use adk_core::{Agent, Llm};
39///
40/// fn triage(
41///     model: Arc<dyn Llm>,
42///     billing: Arc<dyn Agent>,
43///     technical: Arc<dyn Agent>,
44///     general: Arc<dyn Agent>,
45/// ) -> adk_core::Result<DecisionAgent> {
46///     DecisionAgent::builder("triage", model)
47///         .instruction("Route the support request to the team that should answer it.")
48///         .route("billing", "Invoices, refunds and payment problems", billing)
49///         .route("technical", "Errors, outages and how-to questions", technical)
50///         .fallback(general)
51///         .min_confidence(0.6)
52///         .output_key("triage")
53///         .build()
54/// }
55/// ```
56pub 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
79/// Builds a [`DecisionAgent`].
80pub 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    /// A builder for agent `name` deciding with `model`.
95    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    /// The agent description.
111    #[must_use]
112    pub fn description(mut self, description: impl Into<String>) -> Self {
113        self.description = Some(description.into());
114        self
115    }
116
117    /// What to decide, shown to the model before the routes.
118    #[must_use]
119    pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
120        self.instruction = Some(instruction.into());
121        self
122    }
123
124    /// A route: the option `name`, what it is for, and the agent that handles it.
125    #[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    /// One route per option of `T`, each to the agent `agent_for` gives its value.
139    ///
140    /// # Example
141    ///
142    /// ```rust,ignore
143    /// let router = DecisionAgent::builder("triage", model)
144    ///     .routes::<Route>(|route| match route {
145    ///         Route::Billing => billing.clone(),
146    ///         Route::Technical => technical.clone(),
147    ///     })
148    ///     .build()?;
149    /// ```
150    #[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    /// The agent that handles a decision below [`min_confidence`](Self::min_confidence).
173    #[must_use]
174    pub fn fallback(mut self, agent: Arc<dyn Agent>) -> Self {
175        self.fallback = Some(agent);
176        self
177    }
178
179    /// The least confidence, from 0.0 to 1.0, at which a decision is followed; below it the
180    /// fallback route runs, or the run fails with `decision.low_confidence` without one.
181    /// Default 0.0, which follows every decision.
182    #[must_use]
183    pub fn min_confidence(mut self, confidence: f64) -> Self {
184        self.min_confidence = confidence;
185        self
186    }
187
188    /// The session-state key the decision is written to:
189    /// `{option, rationale, confidence, followed, route}`.
190    #[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    /// Builds the agent.
197    ///
198    /// # Errors
199    ///
200    /// Returns a configuration error when there is no route, two routes share a name, a
201    /// [`routes`](Self::routes) option maps to no value, or `min_confidence` is outside 0.0 to
202    /// 1.0.
203    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    /// A builder for agent `name` deciding with `model`.
248    pub fn builder(name: impl Into<String>, model: Arc<dyn Llm>) -> DecisionAgentBuilder {
249        DecisionAgentBuilder::new(name, model)
250    }
251
252    /// The routes the model decides among, in the order it sees them.
253    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        // On cross-turn resumption the runner restarts from this root, so the next turn is
274        // decided again rather than resuming the route that answered last.
275        false
276    }
277
278    async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
279        // A call a person asked for needs an agent that holds it for their decision itself
280        // (spec 3.3 ยง7.4 rule 5).
281        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        // A run that resumes a hold returns to the route that holds it: the resuming run's
289        // input is not the input that chose the route.
290        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}