1#[cfg(feature = "skills")]
32use crate::skill_shim::load_skill_index;
33use crate::skill_shim::{SelectionPolicy, SkillIndex};
34use adk_core::{
35 AfterAgentCallback, Agent, BeforeAgentCallback, CallbackContext, Content, Event, EventStream,
36 InvocationContext, Llm, LlmRequest, Part, Result, WorkflowPosition,
37};
38use async_stream::stream;
39use async_trait::async_trait;
40use futures::StreamExt;
41use std::collections::HashMap;
42use std::sync::Arc;
43
44pub struct LlmConditionalAgent {
63 name: String,
64 description: String,
65 model: Arc<dyn Llm>,
66 instruction: String,
67 routes: HashMap<String, Arc<dyn Agent>>,
68 default_agent: Option<Arc<dyn Agent>>,
69 all_agents: Vec<Arc<dyn Agent>>,
71 skills_index: Option<Arc<SkillIndex>>,
72 skill_policy: SelectionPolicy,
73 max_skill_chars: usize,
74 before_callbacks: Arc<Vec<BeforeAgentCallback>>,
75 after_callbacks: Arc<Vec<AfterAgentCallback>>,
76}
77
78pub struct LlmConditionalAgentBuilder {
80 name: String,
81 description: Option<String>,
82 model: Arc<dyn Llm>,
83 instruction: Option<String>,
84 routes: HashMap<String, Arc<dyn Agent>>,
85 default_agent: Option<Arc<dyn Agent>>,
86 skills_index: Option<Arc<SkillIndex>>,
87 skill_policy: SelectionPolicy,
88 max_skill_chars: usize,
89 before_callbacks: Vec<BeforeAgentCallback>,
90 after_callbacks: Vec<AfterAgentCallback>,
91}
92
93impl LlmConditionalAgentBuilder {
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 routes: HashMap::new(),
102 default_agent: None,
103 skills_index: None,
104 skill_policy: SelectionPolicy::default(),
105 max_skill_chars: 2000,
106 before_callbacks: Vec::new(),
107 after_callbacks: Vec::new(),
108 }
109 }
110
111 pub fn description(mut self, desc: impl Into<String>) -> Self {
113 self.description = Some(desc.into());
114 self
115 }
116
117 pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
122 self.instruction = Some(instruction.into());
123 self
124 }
125
126 pub fn route(mut self, label: impl Into<String>, agent: Arc<dyn Agent>) -> Self {
131 self.routes.insert(label.into().to_lowercase(), agent);
132 self
133 }
134
135 pub fn default_route(mut self, agent: Arc<dyn Agent>) -> Self {
137 self.default_agent = Some(agent);
138 self
139 }
140
141 #[cfg(feature = "skills")]
143 pub fn with_skills(mut self, index: SkillIndex) -> Self {
144 self.skills_index = Some(Arc::new(index));
145 self
146 }
147
148 #[cfg(feature = "skills")]
150 pub fn with_auto_skills(self) -> Result<Self> {
151 self.with_skills_from_root(".")
152 }
153
154 #[cfg(feature = "skills")]
156 pub fn with_skills_from_root(mut self, root: impl AsRef<std::path::Path>) -> Result<Self> {
157 let index = load_skill_index(root).map_err(|e| adk_core::AdkError::agent(e.to_string()))?;
158 self.skills_index = Some(Arc::new(index));
159 Ok(self)
160 }
161
162 #[cfg(feature = "skills")]
164 pub fn with_skill_policy(mut self, policy: SelectionPolicy) -> Self {
165 self.skill_policy = policy;
166 self
167 }
168
169 #[cfg(feature = "skills")]
171 pub fn with_skill_budget(mut self, max_chars: usize) -> Self {
172 self.max_skill_chars = max_chars;
173 self
174 }
175
176 pub fn before_callback(mut self, callback: BeforeAgentCallback) -> Self {
178 self.before_callbacks.push(callback);
179 self
180 }
181
182 pub fn after_callback(mut self, callback: AfterAgentCallback) -> Self {
184 self.after_callbacks.push(callback);
185 self
186 }
187
188 pub fn build(self) -> Result<LlmConditionalAgent> {
190 let instruction = self.instruction.ok_or_else(|| {
191 adk_core::AdkError::agent("Instruction is required for LlmConditionalAgent")
192 })?;
193
194 if self.routes.is_empty() {
195 return Err(adk_core::AdkError::agent(
196 "At least one route is required for LlmConditionalAgent",
197 ));
198 }
199
200 let mut all_agents: Vec<Arc<dyn Agent>> = self.routes.values().cloned().collect();
202 if let Some(ref default) = self.default_agent {
203 all_agents.push(default.clone());
204 }
205
206 Ok(LlmConditionalAgent {
207 name: self.name,
208 description: self.description.unwrap_or_default(),
209 model: self.model,
210 instruction,
211 routes: self.routes,
212 default_agent: self.default_agent,
213 all_agents,
214 skills_index: self.skills_index,
215 skill_policy: self.skill_policy,
216 max_skill_chars: self.max_skill_chars,
217 before_callbacks: Arc::new(self.before_callbacks),
218 after_callbacks: Arc::new(self.after_callbacks),
219 })
220 }
221}
222
223impl LlmConditionalAgent {
224 pub fn builder(name: impl Into<String>, model: Arc<dyn Llm>) -> LlmConditionalAgentBuilder {
226 LlmConditionalAgentBuilder::new(name, model)
227 }
228
229 fn resolve_route(
230 classification: &str,
231 routes: &HashMap<String, Arc<dyn Agent>>,
232 ) -> Option<Arc<dyn Agent>> {
233 if let Some(agent) = routes.get(classification) {
234 return Some(agent.clone());
235 }
236
237 let mut labels = routes.keys().collect::<Vec<_>>();
238 labels.sort_by(|left, right| right.len().cmp(&left.len()).then_with(|| left.cmp(right)));
239
240 labels
241 .into_iter()
242 .find(|label| classification.contains(label.as_str()))
243 .and_then(|label| routes.get(label).cloned())
244 }
245}
246
247#[async_trait]
248impl Agent for LlmConditionalAgent {
249 fn name(&self) -> &str {
250 &self.name
251 }
252
253 fn description(&self) -> &str {
254 &self.description
255 }
256
257 fn sub_agents(&self) -> &[Arc<dyn Agent>] {
258 &self.all_agents
259 }
260
261 fn supports_agent_transfer(&self) -> bool {
262 false
266 }
267
268 async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
269 if let Some(refused) = crate::requested_call::refused_by_root(
272 ctx.as_ref(),
273 &self.name,
274 crate::requested_call::RUNS_OTHER_AGENTS,
275 ) {
276 return Ok(refused);
277 }
278 let run_ctx = super::skill_context::with_skill_injected_context(
279 ctx,
280 self.skills_index.as_ref(),
281 &self.skill_policy,
282 self.max_skill_chars,
283 );
284 let model = self.model.clone();
285 let instruction = self.instruction.clone();
286 let routes = self.routes.clone();
287 let default_agent = self.default_agent.clone();
288 let invocation_id = run_ctx.invocation_id().to_string();
289 let agent_name = self.name.clone();
290 let before_callbacks = self.before_callbacks.clone();
291 let after_callbacks = self.after_callbacks.clone();
292 let resuming = run_ctx
295 .session()
296 .workflow_resume_positions(&agent_name, run_ctx.branch())
297 .into_iter()
298 .find_map(|position| {
299 self.all_agents.iter().find(|agent| agent.name() == position.sub_agent).cloned()
300 });
301
302 let s = stream! {
303 for callback in before_callbacks.as_ref() {
305 match callback(run_ctx.clone() as Arc<dyn CallbackContext>).await {
306 Ok(Some(content)) => {
307 let mut early_event = Event::new(&invocation_id);
308 early_event.author = agent_name.clone();
309 early_event.llm_response.content = Some(content);
310 yield Ok(early_event);
311
312 for after_cb in after_callbacks.as_ref() {
313 match after_cb(run_ctx.clone() as Arc<dyn CallbackContext>).await {
314 Ok(Some(after_content)) => {
315 let mut after_event = Event::new(&invocation_id);
316 after_event.author = agent_name.clone();
317 after_event.llm_response.content = Some(after_content);
318 yield Ok(after_event);
319 return;
320 }
321 Ok(None) => continue,
322 Err(e) => { yield Err(e); return; }
323 }
324 }
325 return;
326 }
327 Ok(None) => continue,
328 Err(e) => { yield Err(e); return; }
329 }
330 }
331
332 let (target_agent, classification) = match resuming {
333 Some(agent) => (Some(agent), None),
334 None => {
335 let user_content = run_ctx.user_content().clone();
337 let user_text: String = user_content.parts.iter()
338 .filter_map(|p| if let Part::Text { text } = p { Some(text.as_str()) } else { None })
339 .collect::<Vec<_>>()
340 .join(" ");
341
342 let classification_prompt = format!(
343 "{}\n\nUser input: {}",
344 instruction,
345 user_text
346 );
347
348 let request = LlmRequest {
349 model: model.name().to_string(),
350 contents: vec![Content::new("user").with_text(&classification_prompt)],
351 tools: adk_core::ToolDeclarations::new(),
352 config: None,
353 previous_response_id: None,
354 };
355
356 let scope = adk_core::ModelCallScope::for_run(
358 run_ctx.run_config(),
359 run_ctx.app_name(),
360 &agent_name,
361 );
362 let mut response_stream = match scope.generate(model.as_ref(), request, false).await {
363 Ok(stream) => stream,
364 Err(e) => {
365 yield Err(e);
366 return;
367 }
368 };
369
370 let mut classification = String::new();
372 while let Some(chunk_result) = response_stream.next().await {
373 match chunk_result {
374 Ok(chunk) => {
375 if let Some(content) = chunk.content {
376 for part in content.parts {
377 if let Part::Text { text } = part {
378 classification.push_str(&text);
379 }
380 }
381 }
382 }
383 Err(e) => {
384 yield Err(e);
385 return;
386 }
387 }
388 }
389
390 let classification = classification.trim().to_lowercase();
392
393 let mut routing_event = Event::new(&invocation_id);
395 routing_event.author = agent_name.clone();
396 routing_event.llm_response.content = Some(
397 Content::new("model").with_text(format!("[Routing to: {}]", classification))
398 );
399 yield Ok(routing_event);
400
401 (Self::resolve_route(&classification, &routes).or(default_agent), Some(classification))
403 }
404 };
405
406 if let Some(agent) = target_agent {
408 match agent.run(run_ctx.clone()).await {
409 Ok(mut stream) => {
410 let mut held = false;
411 while let Some(event) = stream.next().await {
412 let event = event.map(|mut event| {
413 if event.actions.tool_confirmation.is_some() {
414 held = true;
415 event.actions.workflow_positions.insert(
416 agent_name.clone(),
417 WorkflowPosition::new(0, agent.name()),
418 );
419 }
420 event
421 });
422 yield event;
423 }
424 if held {
427 return;
428 }
429 }
430 Err(e) => {
431 yield Err(e);
432 }
433 }
434 } else {
435 let mut error_event = Event::new(&invocation_id);
437 error_event.author = agent_name.clone();
438 error_event.llm_response.content = Some(
439 Content::new("model").with_text(format!(
440 "No route found for classification '{}'. Available routes: {:?}",
441 classification.unwrap_or_default(),
442 routes.keys().collect::<Vec<_>>()
443 ))
444 );
445 yield Ok(error_event);
446 }
447
448 for callback in after_callbacks.as_ref() {
450 match callback(run_ctx.clone() as Arc<dyn CallbackContext>).await {
451 Ok(Some(content)) => {
452 let mut after_event = Event::new(&invocation_id);
453 after_event.author = agent_name.clone();
454 after_event.llm_response.content = Some(content);
455 yield Ok(after_event);
456 break;
457 }
458 Ok(None) => continue,
459 Err(e) => { yield Err(e); return; }
460 }
461 }
462 };
463
464 Ok(Box::pin(s))
465 }
466}