1use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditRecordOutcome};
2use adk_core::{
3 AfterAgentCallback, AfterModelCallback, AfterToolCallback, AfterToolCallbackFull, Agent,
4 BeforeAgentCallback, BeforeModelCallback, BeforeModelResult, BeforeToolCallback,
5 CallbackContext, Content, Event, EventActions, FunctionResponseData, GlobalInstructionProvider,
6 GovernedCall, InstructionProvider, InvocationContext, Llm, LlmRequest, LlmResponse,
7 MemoryEntry, OnToolErrorCallback, Part, ReadonlyContext, Result, RetryBudget, Tool,
8 ToolAuthorization, ToolCallbackContext, ToolConfirmationPolicy, ToolConfirmationRequest,
9 ToolContext, ToolEffect, ToolExecutionStrategy, ToolGate, ToolOutcome, ToolResultStatus,
10 Toolset, authorize_tool_call,
11};
12use async_stream::stream;
13use async_trait::async_trait;
14use std::{
15 collections::{HashMap, HashSet},
16 sync::{Arc, Mutex},
17};
18use tracing::Instrument;
19
20#[cfg(feature = "enhanced-plugins")]
21use adk_plugin::{
22 BeforeModelCallResult, BeforeToolCallResult, EnhancedPlugin, EnhancedPluginManager,
23};
24
25#[cfg(feature = "skills")]
26use crate::skill_shim::load_skill_index;
27use crate::{
28 grounding::answer_citations,
29 guardrails::{
30 Grounding, GuardrailScreen, GuardrailSet, Phase, Screened, ToolGuardrailSet, Warnings,
31 enforce_guardrails, screen_model_output, screen_tool_result,
32 },
33 invocation_hooks::HookCallbacks,
34 skill_shim::{SelectionPolicy, SkillIndex, apply_skill_injection},
35 tool_call_markup::normalize_option_content,
36 workflow::with_user_content_override,
37};
38
39pub const DEFAULT_MAX_ITERATIONS: u32 = 100;
41
42pub const DEFAULT_TOOL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(300);
44
45const PAYLOAD_OMITTED: &str = "[omitted: set RunConfig::record_payloads to record payloads]";
48
49fn trace_json_payload<T: serde::Serialize>(
55 value: &T,
56 record_payloads: bool,
57 max_bytes: usize,
58) -> String {
59 if !record_payloads {
60 return PAYLOAD_OMITTED.to_string();
61 }
62 let json = serde_json::to_string(value).unwrap_or_default();
63 if cfg!(feature = "record-payloads") {
64 return json;
65 }
66
67 let max_bytes = max_bytes.max(32);
68 if json.len() <= max_bytes {
69 return json;
70 }
71
72 let mut end = max_bytes;
73 while !json.is_char_boundary(end) {
74 end -= 1;
75 }
76 format!("{}...[truncated {} bytes]", &json[..end], json.len() - end)
77}
78
79fn traced_message(run_config: &adk_core::RunConfig, message: &str) -> String {
86 trace_json_payload(&message, run_config.record_payloads, run_config.trace_payload_max_bytes)
87}
88
89const SHORT_CIRCUIT_ACTION: &str = "tool.short_circuit";
92#[cfg(feature = "enhanced-plugins")]
94const SHORT_CIRCUIT_BY_ENHANCED_PLUGIN: &str = "enhanced_plugin";
95const SHORT_CIRCUIT_BY_INVOCATION_HOOK: &str = "invocation_hook";
97const SHORT_CIRCUIT_BY_BEFORE_TOOL_CALLBACK: &str = "before_tool_callback";
99
100#[derive(Debug, Clone)]
101struct PendingToolCall {
102 index: usize,
103 name: String,
104 args: serde_json::Value,
105 id: Option<String>,
106 function_call_id: String,
107 resumes: Option<ToolConfirmationRequest>,
109}
110
111fn build_generation_config(
112 base: Option<&adk_core::GenerateContentConfig>,
113 output_schema: Option<&serde_json::Value>,
114 cached_content: Option<&str>,
115) -> Option<adk_core::GenerateContentConfig> {
116 let mut config = base.cloned().unwrap_or_default();
117 if let Some(schema) = output_schema {
118 config.response_schema = Some(schema.clone());
119 }
120 if config.cached_content.is_none()
121 && let Some(cached_content) = cached_content
122 {
123 config.cached_content = Some(cached_content.to_string());
124 }
125
126 if base.is_some() || output_schema.is_some() || cached_content.is_some() {
127 Some(config)
128 } else {
129 None
130 }
131}
132
133fn append_streamed_parts(parts: &mut Vec<Part>, incoming: Vec<Part>) {
138 for part in incoming {
139 match (parts.last_mut(), part) {
140 (Some(Part::Text { text }), Part::Text { text: delta }) => text.push_str(&delta),
141 (
142 Some(Part::Thinking { thinking, signature: signature @ None }),
143 Part::Thinking { thinking: delta, signature: delta_signature },
144 ) => {
145 thinking.push_str(&delta);
146 *signature = delta_signature;
147 }
148 (_, part) => parts.push(part),
149 }
150 }
151}
152
153fn collect_function_calls(content: &Content, invocation_id: &str) -> Vec<PendingToolCall> {
154 content
155 .parts
156 .iter()
157 .filter_map(|part| {
158 if let Part::FunctionCall { name, args, id, .. } = part {
159 Some((name, args, id))
160 } else {
161 None
162 }
163 })
164 .enumerate()
165 .map(|(index, (name, args, id))| PendingToolCall {
166 index,
167 name: name.clone(),
168 args: args.clone(),
169 id: id.clone(),
170 function_call_id: id
171 .clone()
172 .unwrap_or_else(|| format!("{invocation_id}_{name}_{index}")),
173 resumes: None,
174 })
175 .collect()
176}
177
178fn collect_long_running_tool_ids(
181 tool_map: &HashMap<String, Arc<dyn Tool>>,
182 content: &Content,
183) -> Vec<String> {
184 content
185 .parts
186 .iter()
187 .filter_map(|part| {
188 if let Part::FunctionCall { name, id, .. } = part
189 && tool_map.get(name).is_some_and(|tool| tool.is_long_running())
190 {
191 return Some(id.clone().unwrap_or_else(|| name.clone()));
192 }
193 None
194 })
195 .collect()
196}
197
198fn build_partial_llm_event(
204 event_id: &str,
205 invocation_id: &str,
206 agent_name: &str,
207 request_debug: &str,
208 chunk: &LlmResponse,
209 long_running_tool_ids: Vec<String>,
210) -> Event {
211 let mut event = Event::with_id(event_id, invocation_id);
212 event.author = agent_name.to_string();
213 if !chunk.partial {
216 event.llm_request = Some(request_debug.to_string());
217 event.provider_metadata.insert(
218 "gcp.vertex.agent.llm_response".to_string(),
219 serde_json::to_string(chunk).unwrap_or_default(),
220 );
221 }
222 event.llm_response.partial = chunk.partial;
223 event.llm_response.turn_complete = chunk.turn_complete;
224 event.llm_response.finish_reason = chunk.finish_reason;
225 event.llm_response.usage_metadata = chunk.usage_metadata.clone();
226 event.llm_response.citation_metadata = chunk.citation_metadata.clone();
227 event.llm_response.content = chunk.content.clone();
228 event.llm_response.provider_metadata = chunk.provider_metadata.clone();
229 event.llm_response.interaction_id = chunk.interaction_id.clone();
230 event.llm_response.interrupted = chunk.interrupted;
233 event.llm_response.error_code = chunk.error_code.clone();
234 event.llm_response.error_message = chunk.error_message.clone();
235 event.llm_response.model = chunk.model.clone();
236 event.llm_response.provider = chunk.provider.clone();
237 event.long_running_tool_ids = long_running_tool_ids;
238 event
239}
240
241fn build_final_llm_event(
244 event_id: &str,
245 invocation_id: &str,
246 agent_name: &str,
247 request_debug: &str,
248 content: Option<&Content>,
249 last_chunk: Option<&LlmResponse>,
250 long_running_tool_ids: Vec<String>,
251) -> Event {
252 let mut event = Event::with_id(event_id, invocation_id);
253 event.author = agent_name.to_string();
254 event.llm_request = Some(request_debug.to_string());
255 event.llm_response.content = content.cloned();
256 event.llm_response.partial = false;
257 event.llm_response.turn_complete = true;
258
259 if let Some(last_chunk) = last_chunk {
260 event.llm_response.turn_complete = last_chunk.turn_complete;
261 event.llm_response.finish_reason = last_chunk.finish_reason;
262 event.llm_response.usage_metadata = last_chunk.usage_metadata.clone();
263 event.llm_response.citation_metadata = last_chunk.citation_metadata.clone();
264 event.llm_response.provider_metadata = last_chunk.provider_metadata.clone();
265 event.llm_response.interaction_id = last_chunk.interaction_id.clone();
266 event.llm_response.interrupted = last_chunk.interrupted;
267 event.llm_response.error_code = last_chunk.error_code.clone();
268 event.llm_response.error_message = last_chunk.error_message.clone();
269 event.llm_response.model = last_chunk.model.clone();
270 event.llm_response.provider = last_chunk.provider.clone();
271 event.provider_metadata.insert(
272 "gcp.vertex.agent.llm_response".to_string(),
273 serde_json::to_string(last_chunk).unwrap_or_default(),
274 );
275 }
276
277 event.long_running_tool_ids = long_running_tool_ids;
278 event
279}
280
281pub(crate) fn confirmation_event(
283 invocation_id: &str,
284 agent_name: &str,
285 request: ToolConfirmationRequest,
286) -> Event {
287 let mut event = Event::new(invocation_id);
288 event.author = agent_name.to_string();
289 event.llm_response.interrupted = true;
290 event.llm_response.turn_complete = true;
291 event.llm_response.content = Some(Content::new("model").with_text(format!(
292 "Tool confirmation required for '{}'. Provide approve/deny decision to continue.",
293 request.tool_name
294 )));
295 event.actions.tool_confirmation = Some(request);
296 event
297}
298
299pub struct LlmAgent {
307 name: String,
308 description: String,
309 model: Arc<dyn Llm>,
310 instruction: Option<String>,
311 instruction_provider: Option<Arc<InstructionProvider>>,
312 static_instruction: Option<String>,
313 global_instruction: Option<String>,
314 global_instruction_provider: Option<Arc<GlobalInstructionProvider>>,
315 skills_index: Option<Arc<SkillIndex>>,
316 skill_policy: SelectionPolicy,
317 max_skill_chars: usize,
318 #[allow(dead_code)] input_schema: Option<serde_json::Value>,
320 output_schema: Option<serde_json::Value>,
321 output_max_retries: usize,
323 disallow_transfer_to_parent: bool,
324 disallow_transfer_to_peers: bool,
325 include_contents: adk_core::IncludeContents,
326 tools: Vec<Arc<dyn Tool>>,
327 toolsets: Vec<Arc<dyn Toolset>>,
328 strict_toolsets: bool,
330 sub_agents: Vec<Arc<dyn Agent>>,
331 output_key: Option<String>,
332 generate_content_config: Option<adk_core::GenerateContentConfig>,
334 max_iterations: u32,
336 tool_timeout: std::time::Duration,
338 expose_tool_error_messages: bool,
340 before_callbacks: Arc<Vec<BeforeAgentCallback>>,
341 after_callbacks: Arc<Vec<AfterAgentCallback>>,
342 history_processors: Arc<Vec<adk_core::HistoryProcessor>>,
343 before_model_callbacks: Arc<Vec<BeforeModelCallback>>,
344 after_model_callbacks: Arc<Vec<AfterModelCallback>>,
345 before_tool_callbacks: Arc<Vec<BeforeToolCallback>>,
346 after_tool_callbacks: Arc<Vec<AfterToolCallback>>,
347 on_tool_error_callbacks: Arc<Vec<OnToolErrorCallback>>,
348 after_tool_callbacks_full: Arc<Vec<AfterToolCallbackFull>>,
350 default_retry_budget: Option<RetryBudget>,
352 tool_retry_budgets: std::collections::HashMap<String, RetryBudget>,
354 circuit_breaker_threshold: Option<u32>,
357 tool_confirmation_policy: ToolConfirmationPolicy,
358 tool_execution_strategy: Option<ToolExecutionStrategy>,
361 parallelize_agent_delegations: bool,
363 input_guardrails: Arc<GuardrailSet>,
364 output_guardrails: Arc<GuardrailSet>,
365 tool_guardrails: Arc<ToolGuardrailSet>,
366 #[cfg(feature = "enhanced-plugins")]
369 enhanced_plugin_manager: Option<Arc<EnhancedPluginManager>>,
370 #[cfg(feature = "sandbox")]
374 sandbox_config: Option<adk_sandbox::workspace::SandboxConfig>,
375}
376
377struct PromptConfig {
378 instruction: Option<String>,
379 instruction_provider: Option<Arc<InstructionProvider>>,
380 static_instruction: Option<String>,
381 global_instruction: Option<String>,
382 global_instruction_provider: Option<Arc<GlobalInstructionProvider>>,
383 skills_index: Option<Arc<SkillIndex>>,
384 skill_policy: SelectionPolicy,
385 max_skill_chars: usize,
386 output_schema: Option<serde_json::Value>,
387 include_contents: adk_core::IncludeContents,
388}
389
390impl PromptConfig {
391 fn from_agent(agent: &LlmAgent) -> Self {
392 Self {
393 instruction: agent.instruction.clone(),
394 instruction_provider: agent.instruction_provider.clone(),
395 static_instruction: agent.static_instruction.clone(),
396 global_instruction: agent.global_instruction.clone(),
397 global_instruction_provider: agent.global_instruction_provider.clone(),
398 skills_index: agent.skills_index.clone(),
399 skill_policy: agent.skill_policy.clone(),
400 max_skill_chars: agent.max_skill_chars,
401 output_schema: agent.output_schema.clone(),
402 include_contents: agent.include_contents,
403 }
404 }
405
406 async fn prepare_conversation(
407 &self,
408 ctx: &Arc<dyn InvocationContext>,
409 agent_name: &str,
410 ) -> Result<Vec<Content>> {
411 let mut preamble = Vec::new();
414
415 if let Some(text) = self.static_instruction.as_ref().filter(|text| !text.is_empty()) {
417 preamble.push(Content::new("system").with_text(text.clone()));
418 }
419
420 if let Some(provider) = &self.global_instruction_provider {
421 let instruction = provider(ctx.clone() as Arc<dyn ReadonlyContext>).await?;
422 if !instruction.is_empty() {
423 preamble.push(Content::new("system").with_text(instruction));
424 }
425 } else if let Some(template) = &self.global_instruction {
426 let instruction = adk_core::inject_session_state(ctx.as_ref(), template).await?;
427 if !instruction.is_empty() {
428 preamble.push(Content::new("system").with_text(instruction));
429 }
430 }
431
432 if let Some(provider) = &self.instruction_provider {
433 let instruction = provider(ctx.clone() as Arc<dyn ReadonlyContext>).await?;
434 if !instruction.is_empty() {
435 preamble.push(Content::new("system").with_text(instruction));
436 }
437 } else if let Some(template) = &self.instruction {
438 let instruction = adk_core::inject_session_state(ctx.as_ref(), template).await?;
439 if !instruction.is_empty() {
440 preamble.push(Content::new("system").with_text(instruction));
441 }
442 }
443
444 if let Some(schema) = &self.output_schema {
445 preamble.push(Content::new("system").with_text(format!(
446 "You MUST respond with valid JSON conforming to this schema: {schema}. Do not include any text outside the JSON object."
447 )));
448 }
449
450 let mut session_history = if ctx.authoritative_transfer_targets()
454 || !ctx.run_config().transfer_targets.is_empty()
455 {
456 ctx.session().conversation_history_scoped(Some(agent_name), ctx.branch())
457 } else {
458 ctx.session().conversation_history_with_context(agent_name, ctx.branch())
459 };
460 let mut current_user_content = ctx.user_content().clone();
461 if let Some(index) = &self.skills_index {
462 apply_skill_injection(
463 &mut current_user_content,
464 index.as_ref(),
465 &self.skill_policy,
466 self.max_skill_chars,
467 );
468 }
469 let empty_turn = current_user_content
473 .parts
474 .iter()
475 .all(|part| matches!(part, Part::Text { text } if text.trim().is_empty()));
476 let answers_only = !current_user_content.parts.is_empty()
480 && current_user_content
481 .parts
482 .iter()
483 .all(|part| matches!(part, Part::FunctionResponse { .. }));
484 if !empty_turn {
485 let own = session_history.iter().rposition(|content| content == ctx.user_content());
487 let last_message = || {
488 session_history.iter().rposition(|content| {
489 content.role == "user"
490 && !adk_core::history::is_other_agent_context(content)
491 && !adk_core::history::is_system_notice(content)
492 })
493 };
494 match own {
495 Some(index) => session_history[index] = current_user_content.clone(),
496 None if answers_only => {}
497 None => match last_message() {
498 Some(index) => session_history[index] = current_user_content.clone(),
499 None => session_history.push(current_user_content.clone()),
500 },
501 }
502 }
503 session_history.retain(|content| {
506 content.role != "user"
507 || content
508 .parts
509 .iter()
510 .any(|part| !matches!(part, Part::Text { text } if text.trim().is_empty()))
511 });
512 let turn_start = match self.include_contents {
518 adk_core::IncludeContents::Default => None,
519 adk_core::IncludeContents::None => {
520 let gate = ToolGate::for_context(ctx.as_ref());
522 let mut held = Vec::<String>::new();
523 for call in ctx.session().held_tool_calls(agent_name, ctx.branch()) {
524 if let Some(id) = call.id
525 && adk_core::confirmation_decision_available(&gate, &call.request).await?
526 {
527 held.push(id);
528 }
529 }
530 let earliest_held = session_history.iter().position(|content| {
531 content.parts.iter().any(|part| {
532 matches!(part, Part::FunctionCall { id: Some(id), .. } if held.contains(id))
533 })
534 });
535 let is_message = |content: &Content| {
536 content.role == "user"
537 && content.carries_user_input()
538 && !adk_core::history::is_other_agent_context(content)
539 && !adk_core::history::is_system_notice(content)
540 };
541 match earliest_held {
542 Some(call) => {
543 Some(session_history[..call].iter().rposition(is_message).unwrap_or(0))
544 }
545 None if empty_turn => {
546 Some(session_history.iter().rposition(is_message).unwrap_or(0))
547 }
548 None => None,
549 }
550 }
551 };
552 if session_history.last().is_some_and(|last| {
557 last.role == "model"
558 && !last.parts.iter().any(|part| matches!(part, Part::FunctionCall { .. }))
559 }) {
560 let note = if empty_turn { RESUMED_TURN_NOTE } else { CONTINUE_TURN_NOTE };
561 session_history.push(Content::new("user").with_text(note));
562 }
563
564 Ok(match (self.include_contents, turn_start) {
565 (adk_core::IncludeContents::None, Some(start)) => {
566 preamble.extend(session_history.drain(start..));
567 preamble
568 }
569 (adk_core::IncludeContents::None, None) => {
570 preamble.push(current_user_content);
571 preamble
572 }
573 (adk_core::IncludeContents::Default, _) => {
574 preamble.extend(session_history);
575 preamble
576 }
577 })
578 }
579}
580
581fn transfer_instruction(targets: &[(&str, &str)], parent: Option<&str>) -> String {
586 let mut text = String::from("You can transfer the conversation to these agents:\n");
587 for (name, description) in targets {
588 text.push_str(&format!("\nAgent name: {name}\n"));
589 if !description.trim().is_empty() {
590 text.push_str(&format!("Agent description: {description}\n"));
591 }
592 }
593 text.push_str(
594 "\nIf you are the best agent to answer according to your own description, answer. If \
595 another agent fits the request better according to its description, call \
596 `transfer_to_agent` with its name, and write no text other than the function call.",
597 );
598 if let Some(parent) = parent {
599 text.push_str(&format!(
600 "\n\nYour parent agent is {parent}. If neither you nor the other agents fit the \
601 request, transfer to {parent}."
602 ));
603 }
604 text
605}
606
607const RESUMED_TURN_NOTE: &str =
610 "(No new message from the user. Continue from the tool results above.)";
611
612const CONTINUE_TURN_NOTE: &str =
614 "(No new message from the user. Continue from the conversation above.)";
615
616struct ToolSetup {
617 tools: Vec<Arc<dyn Tool>>,
618 toolsets: Vec<Arc<dyn Toolset>>,
619 strict_toolsets: bool,
620 sub_agents: Vec<Arc<dyn Agent>>,
621 disallow_transfer_to_parent: bool,
622 disallow_transfer_to_peers: bool,
623}
624
625struct ResolvedTools {
626 map: HashMap<String, Arc<dyn Tool>>,
627 declarations: adk_core::ToolDeclarations,
628 transfer_targets: Vec<String>,
629 transfer_guidance: Option<String>,
631}
632
633impl ToolSetup {
634 fn from_agent(agent: &LlmAgent) -> Self {
635 Self {
636 tools: agent.tools.clone(),
637 toolsets: agent.toolsets.clone(),
638 strict_toolsets: agent.strict_toolsets,
639 sub_agents: agent.sub_agents.clone(),
640 disallow_transfer_to_parent: agent.disallow_transfer_to_parent,
641 disallow_transfer_to_peers: agent.disallow_transfer_to_peers,
642 }
643 }
644
645 async fn resolve(&self, ctx: &Arc<dyn InvocationContext>) -> Result<ResolvedTools> {
646 let mut tools = self.tools.clone();
647 let static_tool_names: std::collections::HashSet<_> =
648 tools.iter().map(|tool| tool.name().to_string()).collect();
649 let mut toolset_sources = std::collections::HashMap::<String, String>::new();
650 let mut active_toolsets: Vec<&dyn Toolset> =
651 self.toolsets.iter().map(AsRef::as_ref).collect();
652 active_toolsets.extend(
653 ctx.run_config().runtime_toolsets.iter().map(|runtime| runtime.toolset().as_ref()),
654 );
655
656 for toolset in active_toolsets {
657 let provided = match toolset.tools(ctx.clone() as Arc<dyn ReadonlyContext>).await {
658 Ok(provided) => provided,
659 Err(error) if !self.strict_toolsets => {
661 tracing::warn!(
662 agent.name = %ctx.agent_name(),
663 toolset.name = %toolset.name(),
664 error = %error.diagnostics(),
665 error.message = %traced_message(ctx.run_config(), &error.message),
666 "toolset failed to resolve its tools; continuing without them"
667 );
668 continue;
669 }
670 Err(error) => return Err(error),
671 };
672 for tool in provided {
673 let name = tool.name().to_string();
674 if static_tool_names.contains(&name) {
675 return Err(adk_core::AdkError::agent(format!(
676 "Duplicate tool name '{name}': conflict between static tool and toolset '{}'",
677 toolset.name()
678 )));
679 }
680 if let Some(other_toolset) = toolset_sources.get(&name) {
681 return Err(adk_core::AdkError::agent(format!(
682 "Duplicate tool name '{name}': conflict between toolset '{other_toolset}' and toolset '{}'",
683 toolset.name()
684 )));
685 }
686 toolset_sources.insert(name, toolset.name().to_string());
687 tools.push(tool);
688 }
689 }
690
691 let map = tools.iter().map(|tool| (tool.name().to_string(), tool.clone())).collect();
692 let mut declarations = tools
693 .iter()
694 .map(|tool| (tool.name().to_string(), tool.declaration()))
695 .collect::<adk_core::ToolDeclarations>();
696 let mut transfer_targets: Vec<String> = if ctx.authoritative_transfer_targets() {
697 Vec::new()
698 } else {
699 self.sub_agents.iter().map(|agent| agent.name().to_string()).collect()
700 };
701 let child_names: std::collections::HashSet<_> =
702 self.sub_agents.iter().map(|agent| agent.name()).collect();
703 let parent_name = ctx.run_config().parent_agent.as_deref();
704
705 for target in &ctx.run_config().transfer_targets {
706 if child_names.contains(target.as_str()) {
707 continue;
708 }
709 let is_parent = parent_name == Some(target.as_str());
710 if (is_parent && self.disallow_transfer_to_parent)
711 || (!is_parent && self.disallow_transfer_to_peers)
712 {
713 continue;
714 }
715 transfer_targets.push(target.clone());
716 }
717
718 if !transfer_targets.is_empty() {
719 declarations.insert(
720 "transfer_to_agent".to_string(),
721 serde_json::json!({
722 "name": "transfer_to_agent",
723 "description": format!(
724 "Transfer execution to another agent. Valid targets: {}",
725 transfer_targets.join(", ")
726 ),
727 "parameters": {
728 "type": "object",
729 "properties": {
730 "agent_name": {
731 "type": "string",
732 "description": "The name of the agent to transfer to.",
733 "enum": transfer_targets
734 }
735 },
736 "required": ["agent_name"]
737 }
738 }),
739 );
740 }
741
742 let transfer_guidance = (!transfer_targets.is_empty()).then(|| {
743 let descriptions = &ctx.run_config().transfer_target_descriptions;
744 let described: Vec<(&str, &str)> = transfer_targets
745 .iter()
746 .map(|name| {
747 let description = self
748 .sub_agents
749 .iter()
750 .find(|agent| agent.name() == name)
751 .map(|agent| agent.description())
752 .or_else(|| descriptions.get(name).map(String::as_str))
753 .unwrap_or("");
754 (name.as_str(), description)
755 })
756 .collect();
757 let parent = parent_name.filter(|parent| transfer_targets.iter().any(|t| t == parent));
758 transfer_instruction(&described, parent)
759 });
760
761 Ok(ResolvedTools { map, declarations, transfer_targets, transfer_guidance })
762 }
763
764 async fn process_llm_request(
766 &self,
767 ctx: &Arc<dyn InvocationContext>,
768 request: &mut LlmRequest,
769 ) -> Result<()> {
770 for toolset in self.toolsets.iter().map(AsRef::as_ref).chain(
771 ctx.run_config().runtime_toolsets.iter().map(|runtime| runtime.toolset().as_ref()),
772 ) {
773 toolset.process_llm_request(ctx.clone() as Arc<dyn ReadonlyContext>, request).await?;
774 }
775 Ok(())
776 }
777}
778
779impl std::fmt::Debug for LlmAgent {
780 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
781 f.debug_struct("LlmAgent")
782 .field("name", &self.name)
783 .field("description", &self.description)
784 .field("model", &self.model.name())
785 .field("instruction", &self.instruction)
786 .field("tools_count", &self.tools.len())
787 .field("sub_agents_count", &self.sub_agents.len())
788 .finish()
789 }
790}
791
792impl LlmAgent {
793 #[cfg(feature = "sandbox")]
800 pub fn sandbox_config(&self) -> Option<&adk_sandbox::workspace::SandboxConfig> {
801 self.sandbox_config.as_ref()
802 }
803
804 async fn apply_input_guardrails(
805 ctx: Arc<dyn InvocationContext>,
806 input_guardrails: Arc<GuardrailSet>,
807 ) -> Result<Arc<dyn InvocationContext>> {
808 let content =
809 enforce_guardrails(input_guardrails.as_ref(), ctx.user_content(), Phase::Input)
810 .await?
811 .content;
812 if content.role != ctx.user_content().role || content.parts != ctx.user_content().parts {
813 Ok(with_user_content_override(ctx, content))
814 } else {
815 Ok(ctx)
816 }
817 }
818
819 fn history_parts_from_provider_metadata(
820 provider_metadata: Option<&serde_json::Value>,
821 ) -> Vec<Part> {
822 let Some(provider_metadata) = provider_metadata else {
823 return Vec::new();
824 };
825
826 let history_parts = provider_metadata
827 .get("conversation_history_parts")
828 .or_else(|| {
829 provider_metadata
830 .get("openai")
831 .and_then(|openai| openai.get("conversation_history_parts"))
832 })
833 .and_then(serde_json::Value::as_array);
834
835 history_parts
836 .into_iter()
837 .flatten()
838 .filter_map(|value| serde_json::from_value::<Part>(value.clone()).ok())
839 .collect()
840 }
841
842 fn continues_turn(metadata: Option<&serde_json::Value>) -> bool {
843 metadata
844 .and_then(|metadata| metadata.get("continue_turn"))
845 .and_then(serde_json::Value::as_bool)
846 == Some(true)
847 }
848
849 fn augment_content_for_history(
850 content: &Content,
851 provider_metadata: Option<&serde_json::Value>,
852 ) -> Content {
853 let mut augmented = content.clone();
854 augmented.parts.extend(Self::history_parts_from_provider_metadata(provider_metadata));
855 adk_core::history::mark_origin(
858 &mut augmented,
859 adk_core::history::ProviderOrigin::of_response(provider_metadata).as_ref(),
860 );
861 augmented
862 }
863}
864
865fn validate_output_against_schema(
870 text: &str,
871 schema: &serde_json::Value,
872) -> std::result::Result<serde_json::Value, String> {
873 let parsed: serde_json::Value = serde_json::from_str(strip_json_code_fence(text))
874 .map_err(|e| format!("Response is not valid JSON: {e}"))?;
875
876 let validator =
877 jsonschema::validator_for(schema).map_err(|e| format!("Invalid schema: {e}"))?;
878
879 let errors: Vec<String> = validator.iter_errors(&parsed).map(|e| e.to_string()).collect();
880
881 if errors.is_empty() { Ok(parsed) } else { Err(errors.join("; ")) }
882}
883
884fn strip_json_code_fence(text: &str) -> &str {
890 let trimmed = text.trim();
891 let Some(rest) = trimmed.strip_prefix("```") else {
892 return text;
893 };
894 let Some(body) = rest.strip_suffix("```") else {
895 return text;
896 };
897 let body = match body.find('\n') {
899 Some(newline) if body[..newline].chars().all(|c| c.is_ascii_alphanumeric()) => {
900 &body[newline + 1..]
901 }
902 _ => body.trim_start_matches(|c: char| c.is_ascii_alphanumeric()),
903 };
904 if body.contains("```") {
905 return text;
906 }
907 body.trim()
908}
909
910fn replace_chunk(original: &LlmResponse, mut replacement: LlmResponse) -> LlmResponse {
918 replacement.partial |= original.partial;
919 replacement.turn_complete |= original.turn_complete;
920 if replacement.finish_reason.is_none() {
921 replacement.finish_reason = original.finish_reason;
922 }
923 if replacement.usage_metadata.is_none() {
924 replacement.usage_metadata = original.usage_metadata.clone();
925 }
926 replacement
927}
928
929fn has_answer_content(content: &Content) -> bool {
932 content.parts.iter().any(|part| match part {
933 Part::Text { text } => !text.trim().is_empty(),
934 Part::Thinking { .. } => false,
935 Part::InlineData { .. }
936 | Part::FileData { .. }
937 | Part::FunctionCall { .. }
938 | Part::FunctionResponse { .. }
939 | Part::ServerToolCall { .. }
940 | Part::ServerToolResponse { .. }
941 | Part::EmbeddedResource { .. } => true,
942 })
943}
944
945fn empty_response_error(finish_reason: Option<adk_core::FinishReason>) -> adk_core::AdkError {
947 let mut details = adk_core::ErrorDetails::default();
948 if let Some(reason) = finish_reason {
949 details
950 .metadata
951 .insert("finish_reason".to_string(), serde_json::json!(format!("{reason:?}")));
952 }
953 let reason = finish_reason.map_or_else(|| "none".to_string(), |reason| format!("{reason:?}"));
954 let message = match finish_reason {
955 Some(adk_core::FinishReason::MaxTokens) => "the model reached its output-token limit \
957 before it answered: the whole limit went to thinking (finish reason: MaxTokens); \
958 raise the model's maximum output tokens or lower its reasoning effort"
959 .to_string(),
960 _ => format!(
961 "the model ended its turn without an answer: no text, data or tool call, only \
962 thinking or whitespace (finish reason: {reason}); retry the run, or check the \
963 model's output limit and safety settings"
964 ),
965 };
966 adk_core::AdkError::new(
967 adk_core::ErrorComponent::Model,
968 adk_core::ErrorCategory::Internal,
969 "model.empty_response",
970 message,
971 )
972 .with_details(details)
973}
974
975pub(crate) fn finish_error(
986 finish_reason: Option<adk_core::FinishReason>,
987 description: Option<&str>,
988 provider_code: Option<&str>,
989) -> Option<adk_core::AdkError> {
990 let reason = finish_reason?;
991 let description = description
992 .map(|text| adk_core::upstream_excerpt(text).trim_end_matches('.'))
993 .filter(|text| !text.is_empty())
994 .map(|text| format!(": {text}"))
995 .unwrap_or_default();
996 let (category, code, message) = match reason {
997 adk_core::FinishReason::Refusal => (
998 adk_core::ErrorCategory::Forbidden,
999 "model.refusal",
1000 format!(
1001 "the model declined the request{description}. Rephrase the request, or retry \
1002 it on another model"
1003 ),
1004 ),
1005 adk_core::FinishReason::MalformedToolCall => (
1006 adk_core::ErrorCategory::Internal,
1007 "model.malformed_tool_call",
1008 format!(
1009 "the model produced a tool call the provider reports as invalid{description}. \
1010 Retry the run; if it recurs, simplify the tool's parameter schema or offer \
1011 fewer tools"
1012 ),
1013 ),
1014 _ => return None,
1015 };
1016 let mut details = adk_core::ErrorDetails::default();
1017 details.metadata.insert("finish_reason".to_string(), serde_json::json!(format!("{reason:?}")));
1018 if let Some(provider_code) = provider_code {
1019 details
1020 .metadata
1021 .insert("provider_error_code".to_string(), serde_json::json!(provider_code));
1022 }
1023 Some(
1024 adk_core::AdkError::new(adk_core::ErrorComponent::Model, category, code, message)
1025 .with_details(details),
1026 )
1027}
1028
1029fn extract_text_from_events(events: &[Event]) -> Option<String> {
1034 for event in events.iter().rev() {
1035 if let Some(ref content) = event.llm_response.content {
1036 let text: String =
1037 content
1038 .parts
1039 .iter()
1040 .filter_map(|p| {
1041 if let Part::Text { text } = p { Some(text.as_str()) } else { None }
1042 })
1043 .collect::<Vec<_>>()
1044 .join("");
1045 if !text.is_empty() {
1046 return Some(text);
1047 }
1048 }
1049 }
1050 None
1051}
1052
1053pub fn extract_typed<T: serde::de::DeserializeOwned>(events: &[Event]) -> Result<T> {
1076 let text = extract_text_from_events(events).ok_or_else(|| {
1077 adk_core::AdkError::agent("no text content found in events for typed extraction")
1078 })?;
1079
1080 serde_json::from_str(strip_json_code_fence(&text))
1081 .map_err(|e| adk_core::AdkError::agent(format!("output deserialization failed: {e}")))
1082}
1083
1084pub struct LlmAgentBuilder {
1086 name: String,
1087 description: Option<String>,
1088 model: Option<Arc<dyn Llm>>,
1089 instruction: Option<String>,
1090 instruction_provider: Option<Arc<InstructionProvider>>,
1091 static_instruction: Option<String>,
1092 global_instruction: Option<String>,
1093 global_instruction_provider: Option<Arc<GlobalInstructionProvider>>,
1094 skills_index: Option<Arc<SkillIndex>>,
1095 skill_policy: SelectionPolicy,
1096 max_skill_chars: usize,
1097 input_schema: Option<serde_json::Value>,
1098 output_schema: Option<serde_json::Value>,
1099 output_max_retries: usize,
1100 disallow_transfer_to_parent: bool,
1101 disallow_transfer_to_peers: bool,
1102 include_contents: adk_core::IncludeContents,
1103 tools: Vec<Arc<dyn Tool>>,
1104 toolsets: Vec<Arc<dyn Toolset>>,
1105 strict_toolsets: bool,
1106 sub_agents: Vec<Arc<dyn Agent>>,
1107 output_key: Option<String>,
1108 generate_content_config: Option<adk_core::GenerateContentConfig>,
1109 max_iterations: u32,
1110 tool_timeout: std::time::Duration,
1111 expose_tool_error_messages: bool,
1112 before_callbacks: Vec<BeforeAgentCallback>,
1113 after_callbacks: Vec<AfterAgentCallback>,
1114 history_processors: Vec<adk_core::HistoryProcessor>,
1115 before_model_callbacks: Vec<BeforeModelCallback>,
1116 after_model_callbacks: Vec<AfterModelCallback>,
1117 before_tool_callbacks: Vec<BeforeToolCallback>,
1118 after_tool_callbacks: Vec<AfterToolCallback>,
1119 on_tool_error_callbacks: Vec<OnToolErrorCallback>,
1120 after_tool_callbacks_full: Vec<AfterToolCallbackFull>,
1121 default_retry_budget: Option<RetryBudget>,
1122 tool_retry_budgets: std::collections::HashMap<String, RetryBudget>,
1123 circuit_breaker_threshold: Option<u32>,
1124 tool_confirmation_policy: ToolConfirmationPolicy,
1125 tool_execution_strategy: Option<ToolExecutionStrategy>,
1126 parallelize_agent_delegations: bool,
1127 input_guardrails: GuardrailSet,
1128 output_guardrails: GuardrailSet,
1129 tool_guardrails: ToolGuardrailSet,
1130 #[cfg(feature = "enhanced-plugins")]
1132 enhanced_plugins: Vec<Arc<dyn EnhancedPlugin>>,
1133 #[cfg(feature = "sandbox")]
1135 sandbox_config: Option<adk_sandbox::workspace::SandboxConfig>,
1136}
1137
1138impl LlmAgentBuilder {
1139 pub fn new(name: impl Into<String>) -> Self {
1141 Self {
1142 name: name.into(),
1143 description: None,
1144 model: None,
1145 instruction: None,
1146 instruction_provider: None,
1147 static_instruction: None,
1148 global_instruction: None,
1149 global_instruction_provider: None,
1150 skills_index: None,
1151 skill_policy: SelectionPolicy::default(),
1152 max_skill_chars: 2000,
1153 input_schema: None,
1154 output_schema: None,
1155 output_max_retries: 3,
1156 disallow_transfer_to_parent: false,
1157 disallow_transfer_to_peers: false,
1158 include_contents: adk_core::IncludeContents::Default,
1159 tools: Vec::new(),
1160 toolsets: Vec::new(),
1161 strict_toolsets: false,
1162 sub_agents: Vec::new(),
1163 output_key: None,
1164 generate_content_config: None,
1165 max_iterations: DEFAULT_MAX_ITERATIONS,
1166 tool_timeout: DEFAULT_TOOL_TIMEOUT,
1167 expose_tool_error_messages: false,
1168 before_callbacks: Vec::new(),
1169 after_callbacks: Vec::new(),
1170 history_processors: Vec::new(),
1171 before_model_callbacks: Vec::new(),
1172 after_model_callbacks: Vec::new(),
1173 before_tool_callbacks: Vec::new(),
1174 after_tool_callbacks: Vec::new(),
1175 on_tool_error_callbacks: Vec::new(),
1176 after_tool_callbacks_full: Vec::new(),
1177 default_retry_budget: None,
1178 tool_retry_budgets: std::collections::HashMap::new(),
1179 circuit_breaker_threshold: None,
1180 tool_confirmation_policy: ToolConfirmationPolicy::Never,
1181 tool_execution_strategy: None,
1182 parallelize_agent_delegations: false,
1183 input_guardrails: GuardrailSet::new(),
1184 output_guardrails: GuardrailSet::new(),
1185 tool_guardrails: ToolGuardrailSet::new(),
1186 #[cfg(feature = "enhanced-plugins")]
1187 enhanced_plugins: Vec::new(),
1188 #[cfg(feature = "sandbox")]
1189 sandbox_config: None,
1190 }
1191 }
1192
1193 pub fn description(mut self, desc: impl Into<String>) -> Self {
1195 self.description = Some(desc.into());
1196 self
1197 }
1198
1199 pub fn model(mut self, model: Arc<dyn Llm>) -> Self {
1201 self.model = Some(model);
1202 self
1203 }
1204
1205 pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
1214 self.instruction = Some(instruction.into());
1215 self
1216 }
1217
1218 pub fn instruction_provider(mut self, provider: InstructionProvider) -> Self {
1234 self.instruction_provider = Some(Arc::new(provider));
1235 self
1236 }
1237
1238 pub fn static_instruction(mut self, instruction: impl Into<String>) -> Self {
1255 self.static_instruction = Some(instruction.into());
1256 self
1257 }
1258
1259 pub fn global_instruction(mut self, instruction: impl Into<String>) -> Self {
1261 self.global_instruction = Some(instruction.into());
1262 self
1263 }
1264
1265 pub fn global_instruction_provider(mut self, provider: GlobalInstructionProvider) -> Self {
1267 self.global_instruction_provider = Some(Arc::new(provider));
1268 self
1269 }
1270
1271 #[cfg(feature = "skills")]
1276 pub fn with_skills(mut self, index: SkillIndex) -> Self {
1277 self.skills_index = Some(Arc::new(index));
1278 self
1279 }
1280
1281 #[cfg(feature = "skills")]
1283 pub fn with_auto_skills(self) -> Result<Self> {
1284 self.with_skills_from_root(".")
1285 }
1286
1287 #[cfg(feature = "skills")]
1289 pub fn with_skills_from_root(mut self, root: impl AsRef<std::path::Path>) -> Result<Self> {
1290 let index = load_skill_index(root).map_err(|e| adk_core::AdkError::agent(e.to_string()))?;
1291 self.skills_index = Some(Arc::new(index));
1292 Ok(self)
1293 }
1294
1295 #[cfg(feature = "skills")]
1297 pub fn with_skill_policy(mut self, policy: SelectionPolicy) -> Self {
1298 self.skill_policy = policy;
1299 self
1300 }
1301
1302 #[cfg(feature = "skills")]
1304 pub fn with_skill_budget(mut self, max_chars: usize) -> Self {
1305 self.max_skill_chars = max_chars;
1306 self
1307 }
1308
1309 pub fn input_schema(mut self, schema: serde_json::Value) -> Self {
1329 self.input_schema = Some(schema);
1330 self
1331 }
1332
1333 pub fn output_schema(mut self, schema: serde_json::Value) -> Self {
1335 self.output_schema = Some(schema);
1336 self
1337 }
1338
1339 pub fn output_type<T: schemars::JsonSchema>(mut self) -> Self {
1362 let schema = schemars::schema_for!(T);
1363 self.output_schema =
1364 Some(serde_json::to_value(schema).expect("schema serialization cannot fail"));
1365 self
1366 }
1367
1368 pub fn output_max_retries(mut self, n: usize) -> Self {
1373 self.output_max_retries = n;
1374 self
1375 }
1376
1377 pub fn disallow_transfer_to_parent(mut self, disallow: bool) -> Self {
1382 self.disallow_transfer_to_parent = disallow;
1383 self
1384 }
1385
1386 pub fn disallow_transfer_to_peers(mut self, disallow: bool) -> Self {
1391 self.disallow_transfer_to_peers = disallow;
1392 self
1393 }
1394
1395 pub fn include_contents(mut self, include: adk_core::IncludeContents) -> Self {
1397 self.include_contents = include;
1398 self
1399 }
1400
1401 pub fn output_key(mut self, key: impl Into<String>) -> Self {
1410 self.output_key = Some(key.into());
1411 self
1412 }
1413
1414 pub fn generate_content_config(mut self, config: adk_core::GenerateContentConfig) -> Self {
1435 self.generate_content_config = Some(config);
1436 self
1437 }
1438
1439 pub fn temperature(mut self, temperature: f32) -> Self {
1442 self.generate_content_config
1443 .get_or_insert(adk_core::GenerateContentConfig::default())
1444 .temperature = Some(temperature);
1445 self
1446 }
1447
1448 pub fn top_p(mut self, top_p: f32) -> Self {
1450 self.generate_content_config
1451 .get_or_insert(adk_core::GenerateContentConfig::default())
1452 .top_p = Some(top_p);
1453 self
1454 }
1455
1456 pub fn top_k(mut self, top_k: i32) -> Self {
1458 self.generate_content_config
1459 .get_or_insert(adk_core::GenerateContentConfig::default())
1460 .top_k = Some(top_k);
1461 self
1462 }
1463
1464 pub fn max_output_tokens(mut self, max_tokens: i32) -> Self {
1466 self.generate_content_config
1467 .get_or_insert(adk_core::GenerateContentConfig::default())
1468 .max_output_tokens = Some(max_tokens);
1469 self
1470 }
1471
1472 pub fn max_iterations(mut self, max: u32) -> Self {
1475 self.max_iterations = max;
1476 self
1477 }
1478
1479 pub fn tool_timeout(mut self, timeout: std::time::Duration) -> Self {
1488 self.tool_timeout = timeout;
1489 self
1490 }
1491
1492 pub fn expose_tool_error_messages(mut self, expose: bool) -> Self {
1518 self.expose_tool_error_messages = expose;
1519 self
1520 }
1521
1522 pub fn tool(mut self, tool: Arc<dyn Tool>) -> Self {
1527 self.tools.push(tool);
1528 self
1529 }
1530
1531 pub fn toolset(mut self, toolset: Arc<dyn Toolset>) -> Self {
1543 self.toolsets.push(toolset);
1544 self
1545 }
1546
1547 pub fn strict_toolsets(mut self, strict: bool) -> Self {
1566 self.strict_toolsets = strict;
1567 self
1568 }
1569
1570 pub fn sub_agent(mut self, agent: Arc<dyn Agent>) -> Self {
1572 self.sub_agents.push(agent);
1573 self
1574 }
1575
1576 pub fn before_callback(mut self, callback: BeforeAgentCallback) -> Self {
1578 self.before_callbacks.push(callback);
1579 self
1580 }
1581
1582 pub fn after_callback(mut self, callback: AfterAgentCallback) -> Self {
1584 self.after_callbacks.push(callback);
1585 self
1586 }
1587
1588 pub fn history_processor(mut self, processor: adk_core::HistoryProcessor) -> Self {
1636 self.history_processors.push(processor);
1637 self
1638 }
1639
1640 pub fn before_model_callback(mut self, callback: BeforeModelCallback) -> Self {
1642 self.before_model_callbacks.push(callback);
1643 self
1644 }
1645
1646 pub fn after_model_callback(mut self, callback: AfterModelCallback) -> Self {
1648 self.after_model_callbacks.push(callback);
1649 self
1650 }
1651
1652 pub fn before_tool_callback(mut self, callback: BeforeToolCallback) -> Self {
1654 self.before_tool_callbacks.push(callback);
1655 self
1656 }
1657
1658 pub fn after_tool_callback(mut self, callback: AfterToolCallback) -> Self {
1660 self.after_tool_callbacks.push(callback);
1661 self
1662 }
1663
1664 pub fn after_tool_callback_full(mut self, callback: AfterToolCallbackFull) -> Self {
1679 self.after_tool_callbacks_full.push(callback);
1680 self
1681 }
1682
1683 pub fn on_tool_error(mut self, callback: OnToolErrorCallback) -> Self {
1696 self.on_tool_error_callbacks.push(callback);
1697 self
1698 }
1699
1700 pub fn default_retry_budget(mut self, budget: RetryBudget) -> Self {
1710 self.default_retry_budget = Some(budget);
1711 self
1712 }
1713
1714 pub fn tool_retry_budget(mut self, tool_name: impl Into<String>, budget: RetryBudget) -> Self {
1719 self.tool_retry_budgets.insert(tool_name.into(), budget);
1720 self
1721 }
1722
1723 pub fn circuit_breaker_threshold(mut self, threshold: u32) -> Self {
1730 self.circuit_breaker_threshold = Some(threshold);
1731 self
1732 }
1733
1734 pub fn tool_confirmation_policy(mut self, policy: ToolConfirmationPolicy) -> Self {
1742 self.tool_confirmation_policy = policy;
1743 self
1744 }
1745
1746 pub fn require_tool_confirmation(mut self, tool_name: impl Into<String>) -> Self {
1748 self.tool_confirmation_policy = self.tool_confirmation_policy.with_tool(tool_name);
1749 self
1750 }
1751
1752 pub fn require_tool_confirmation_for_all(mut self) -> Self {
1754 self.tool_confirmation_policy = ToolConfirmationPolicy::Always;
1755 self
1756 }
1757
1758 pub fn tool_execution_strategy(mut self, strategy: ToolExecutionStrategy) -> Self {
1764 self.tool_execution_strategy = Some(strategy);
1765 self
1766 }
1767
1768 pub fn parallelize_agent_delegations(mut self, parallelize: bool) -> Self {
1774 self.parallelize_agent_delegations = parallelize;
1775 self
1776 }
1777
1778 pub fn input_guardrails(mut self, guardrails: GuardrailSet) -> Self {
1787 self.input_guardrails = guardrails;
1788 self
1789 }
1790
1791 pub fn output_guardrails(mut self, guardrails: GuardrailSet) -> Self {
1808 self.output_guardrails = guardrails;
1809 self
1810 }
1811
1812 pub fn tool_guardrails(mut self, guardrails: ToolGuardrailSet) -> Self {
1845 self.tool_guardrails = guardrails;
1846 self
1847 }
1848
1849 #[cfg(feature = "enhanced-plugins")]
1869 pub fn enhanced_plugin(mut self, plugin: Arc<dyn EnhancedPlugin>) -> Self {
1870 self.enhanced_plugins.push(plugin);
1871 self
1872 }
1873
1874 #[cfg(feature = "enhanced-plugins")]
1896 pub fn enhanced_plugins(mut self, plugins: Vec<Arc<dyn EnhancedPlugin>>) -> Self {
1897 self.enhanced_plugins.extend(plugins);
1898 self
1899 }
1900
1901 #[cfg(feature = "sandbox")]
1936 pub fn sandbox_config(mut self, config: adk_sandbox::workspace::SandboxConfig) -> Self {
1937 self.sandbox_config = Some(config);
1938 self
1939 }
1940
1941 pub fn build(self) -> Result<LlmAgent> {
1949 let model = self.model.ok_or_else(|| adk_core::AdkError::agent("Model is required"))?;
1950
1951 let mut seen_names = std::collections::HashSet::new();
1952 for agent in &self.sub_agents {
1953 if !seen_names.insert(agent.name()) {
1954 return Err(adk_core::AdkError::agent(format!(
1955 "Duplicate sub-agent name: {}",
1956 agent.name()
1957 )));
1958 }
1959 }
1960 adk_core::ensure_unique_tool_names(&self.name, &self.tools)?;
1961
1962 #[cfg(feature = "sandbox")]
1965 if let Some(ref sandbox_cfg) = self.sandbox_config {
1966 use adk_sandbox::workspace::Capability;
1967 if model.uses_interactions_api()
1968 && (sandbox_cfg.capabilities.contains(&Capability::Shell)
1969 || sandbox_cfg.capabilities.contains(&Capability::Filesystem))
1970 {
1971 return Err(adk_core::AdkError::new(
1972 adk_core::ErrorComponent::Agent,
1973 adk_core::ErrorCategory::InvalidInput,
1974 "code.gemini_interactions_conflict",
1975 "Cannot combine Gemini Interactions API (server-managed environment) \
1976 with client-side sandbox tools (Shell/Filesystem). These provide \
1977 competing filesystems and would produce nondeterministic behavior. \
1978 Either disable use_interactions_api or remove sandbox capabilities.",
1979 ));
1980 }
1981 }
1982
1983 #[cfg(feature = "enhanced-plugins")]
1985 let enhanced_plugin_manager = if self.enhanced_plugins.is_empty() {
1986 None
1987 } else {
1988 Some(Arc::new(EnhancedPluginManager::new(self.enhanced_plugins)))
1989 };
1990
1991 Ok(LlmAgent {
1992 name: self.name,
1993 description: self.description.unwrap_or_default(),
1994 model,
1995 instruction: self.instruction,
1996 instruction_provider: self.instruction_provider,
1997 static_instruction: self.static_instruction,
1998 global_instruction: self.global_instruction,
1999 global_instruction_provider: self.global_instruction_provider,
2000 skills_index: self.skills_index,
2001 skill_policy: self.skill_policy,
2002 max_skill_chars: self.max_skill_chars,
2003 input_schema: self.input_schema,
2004 output_schema: self.output_schema,
2005 output_max_retries: self.output_max_retries,
2006 disallow_transfer_to_parent: self.disallow_transfer_to_parent,
2007 disallow_transfer_to_peers: self.disallow_transfer_to_peers,
2008 include_contents: self.include_contents,
2009 tools: self.tools,
2010 toolsets: self.toolsets,
2011 strict_toolsets: self.strict_toolsets,
2012 sub_agents: self.sub_agents,
2013 output_key: self.output_key,
2014 generate_content_config: self.generate_content_config,
2015 max_iterations: self.max_iterations,
2016 tool_timeout: self.tool_timeout,
2017 expose_tool_error_messages: self.expose_tool_error_messages,
2018 before_callbacks: Arc::new(self.before_callbacks),
2019 after_callbacks: Arc::new(self.after_callbacks),
2020 history_processors: Arc::new(self.history_processors),
2021 before_model_callbacks: Arc::new(self.before_model_callbacks),
2022 after_model_callbacks: Arc::new(self.after_model_callbacks),
2023 before_tool_callbacks: Arc::new(self.before_tool_callbacks),
2024 after_tool_callbacks: Arc::new(self.after_tool_callbacks),
2025 on_tool_error_callbacks: Arc::new(self.on_tool_error_callbacks),
2026 after_tool_callbacks_full: Arc::new(self.after_tool_callbacks_full),
2027 default_retry_budget: self.default_retry_budget,
2028 tool_retry_budgets: self.tool_retry_budgets,
2029 circuit_breaker_threshold: self.circuit_breaker_threshold,
2030 tool_confirmation_policy: self.tool_confirmation_policy,
2031 tool_execution_strategy: self.tool_execution_strategy,
2032 parallelize_agent_delegations: self.parallelize_agent_delegations,
2033 input_guardrails: Arc::new(self.input_guardrails),
2034 output_guardrails: Arc::new(self.output_guardrails),
2035 tool_guardrails: Arc::new(self.tool_guardrails),
2036 #[cfg(feature = "enhanced-plugins")]
2037 enhanced_plugin_manager,
2038 #[cfg(feature = "sandbox")]
2039 sandbox_config: self.sandbox_config,
2040 })
2041 }
2042}
2043
2044const TOOL_PROGRESS_CAPACITY: usize = 256;
2052
2053const TOOL_PROGRESS_SEND_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(100);
2058
2059const TOOL_PROGRESS_MAX_CHUNK_BYTES: usize = 8 * 1024;
2061
2062const TOOL_PROGRESS_MAX_TOTAL_BYTES: usize = 1024 * 1024;
2064
2065const TOOL_PROGRESS_TRUNCATION_MARKER: &str = "[adk: tool progress truncated]";
2067
2068const FORWARDED_EVENTS_STREAM: &str = "events";
2070
2071const FORWARDED_EVENTS_DROPPED_MARKER: &str = "[adk: forwarded events dropped]";
2074
2075type ProgressOverflow = Arc<std::sync::Mutex<Vec<Event>>>;
2078
2079fn send_marker(tx: &tokio::sync::mpsc::Sender<Event>, overflow: &ProgressOverflow, marker: Event) {
2082 if let Err(tokio::sync::mpsc::error::TrySendError::Full(marker)) = tx.try_send(marker) {
2083 overflow.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(marker);
2084 }
2085}
2086
2087fn truncate_on_char_boundary(text: &str, max_bytes: usize) -> &str {
2089 if text.len() <= max_bytes {
2090 return text;
2091 }
2092 let mut end = max_bytes;
2093 while end > 0 && !text.is_char_boundary(end) {
2094 end -= 1;
2095 }
2096 &text[..end]
2097}
2098
2099struct AgentToolContext {
2100 parent_ctx: Arc<dyn InvocationContext>,
2101 function_call_id: String,
2102 tool_name: Option<String>,
2105 idempotency_key: Option<String>,
2108 agent_tools: Option<Vec<String>>,
2110 actions: Mutex<EventActions>,
2111 progress_tx: Option<tokio::sync::mpsc::Sender<Event>>,
2112 progress_overflow: ProgressOverflow,
2114 progress_bytes: std::sync::atomic::AtomicUsize,
2116 progress_truncated: std::sync::atomic::AtomicBool,
2118 events_dropped: std::sync::atomic::AtomicUsize,
2120 events_drop_marked: std::sync::atomic::AtomicBool,
2122}
2123
2124impl Drop for AgentToolContext {
2125 fn drop(&mut self) {
2126 let dropped = *self.events_dropped.get_mut();
2127 if dropped == 0 {
2128 return;
2129 }
2130 tracing::warn!(
2131 function_call.id = %self.function_call_id,
2132 events.dropped = dropped,
2133 "forwarded partial events were dropped for this tool call"
2134 );
2135 if !*self.events_drop_marked.get_mut()
2136 && let Some(tx) = &self.progress_tx
2137 {
2138 send_marker(tx, &self.progress_overflow, self.events_dropped_marker());
2139 }
2140 }
2141}
2142
2143impl AgentToolContext {
2144 fn new(parent_ctx: Arc<dyn InvocationContext>, function_call_id: String) -> Self {
2145 Self {
2146 parent_ctx,
2147 function_call_id,
2148 tool_name: None,
2149 idempotency_key: None,
2150 agent_tools: None,
2151 actions: Mutex::new(EventActions::default()),
2152 progress_tx: None,
2153 progress_overflow: ProgressOverflow::default(),
2154 progress_bytes: std::sync::atomic::AtomicUsize::new(0),
2155 progress_truncated: std::sync::atomic::AtomicBool::new(false),
2156 events_dropped: std::sync::atomic::AtomicUsize::new(0),
2157 events_drop_marked: std::sync::atomic::AtomicBool::new(false),
2158 }
2159 }
2160
2161 fn with_tool_name(mut self, tool_name: impl Into<String>) -> Self {
2163 self.tool_name = Some(tool_name.into());
2164 self
2165 }
2166
2167 fn with_idempotency_key(mut self, key: Option<String>) -> Self {
2169 self.idempotency_key = key;
2170 self
2171 }
2172
2173 fn with_agent_tools(mut self, tools: impl IntoIterator<Item = String>) -> Self {
2175 self.agent_tools = Some(tools.into_iter().collect());
2176 self
2177 }
2178
2179 fn with_progress(
2182 mut self,
2183 tx: tokio::sync::mpsc::Sender<Event>,
2184 overflow: ProgressOverflow,
2185 ) -> Self {
2186 self.progress_tx = Some(tx);
2187 self.progress_overflow = overflow;
2188 self
2189 }
2190
2191 async fn request_secret(&self, name: &str, purpose: Option<&str>) -> Result<Option<String>> {
2196 let mut request = adk_core::SecretRequest::new(name)
2197 .with_identity(
2198 self.parent_ctx.app_name(),
2199 self.parent_ctx.user_id(),
2200 self.parent_ctx.session_id(),
2201 )
2202 .with_invocation_id(self.parent_ctx.invocation_id());
2203 if let Some(tool_name) = &self.tool_name {
2204 request = request.with_tool_name(tool_name);
2205 }
2206 if let Some(purpose) = purpose {
2207 request = request.with_purpose(purpose);
2208 }
2209 self.parent_ctx.get_secret_for(&request).await
2210 }
2211
2212 async fn forward_progress(
2219 &self,
2220 tx: &tokio::sync::mpsc::Sender<Event>,
2221 stream: &str,
2222 chunk: &str,
2223 ) {
2224 use std::sync::atomic::Ordering;
2225
2226 if self.progress_truncated.load(Ordering::Relaxed) {
2227 return;
2228 }
2229
2230 let payload = truncate_on_char_boundary(chunk, TOOL_PROGRESS_MAX_CHUNK_BYTES);
2233 let forwarded = self.progress_bytes.fetch_add(payload.len(), Ordering::Relaxed);
2234 if forwarded.saturating_add(payload.len()) > TOOL_PROGRESS_MAX_TOTAL_BYTES {
2235 self.mark_progress_truncated(tx, stream).await;
2236 return;
2237 }
2238
2239 let event = Event::tool_progress(
2240 self.parent_ctx.invocation_id(),
2241 self.parent_ctx.agent_name(),
2242 &self.function_call_id,
2243 stream,
2244 payload,
2245 );
2246
2247 match tx.try_send(event) {
2248 Ok(()) => {}
2249 Err(tokio::sync::mpsc::error::TrySendError::Full(event)) => {
2250 match tokio::time::timeout(TOOL_PROGRESS_SEND_TIMEOUT, tx.send(event)).await {
2253 Ok(Ok(())) => {}
2254 Ok(Err(_)) => {}
2255 Err(_) => self.mark_progress_truncated(tx, stream).await,
2256 }
2257 }
2258 Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {}
2259 }
2260 }
2261
2262 fn events_dropped_marker(&self) -> Event {
2264 Event::tool_progress(
2265 self.parent_ctx.invocation_id(),
2266 self.parent_ctx.agent_name(),
2267 &self.function_call_id,
2268 FORWARDED_EVENTS_STREAM,
2269 FORWARDED_EVENTS_DROPPED_MARKER,
2270 )
2271 }
2272
2273 async fn mark_progress_truncated(&self, tx: &tokio::sync::mpsc::Sender<Event>, stream: &str) {
2275 use std::sync::atomic::Ordering;
2276 if self.progress_truncated.swap(true, Ordering::Relaxed) {
2277 return;
2278 }
2279 tracing::warn!(
2280 function_call.id = %self.function_call_id,
2281 progress.stream = %stream,
2282 "tool progress exceeded its budget, remaining output is not forwarded"
2283 );
2284 let marker = Event::tool_progress(
2285 self.parent_ctx.invocation_id(),
2286 self.parent_ctx.agent_name(),
2287 &self.function_call_id,
2288 stream,
2289 TOOL_PROGRESS_TRUNCATION_MARKER,
2290 );
2291 send_marker(tx, &self.progress_overflow, marker);
2292 }
2293
2294 fn actions_guard(&self) -> std::sync::MutexGuard<'_, EventActions> {
2295 self.actions.lock().unwrap_or_else(|e| e.into_inner())
2296 }
2297}
2298
2299#[async_trait]
2300impl ReadonlyContext for AgentToolContext {
2301 fn invocation_id(&self) -> &str {
2302 self.parent_ctx.invocation_id()
2303 }
2304
2305 fn agent_name(&self) -> &str {
2306 self.parent_ctx.agent_name()
2307 }
2308
2309 fn user_id(&self) -> &str {
2310 self.parent_ctx.user_id()
2312 }
2313
2314 fn app_name(&self) -> &str {
2315 self.parent_ctx.app_name()
2317 }
2318
2319 fn session_id(&self) -> &str {
2320 self.parent_ctx.session_id()
2322 }
2323
2324 fn branch(&self) -> &str {
2325 self.parent_ctx.branch()
2326 }
2327
2328 fn user_content(&self) -> &Content {
2329 self.parent_ctx.user_content()
2330 }
2331
2332 fn acting_context(&self) -> adk_core::ActingContext {
2333 self.parent_ctx.acting_context()
2334 }
2335
2336 fn is_authenticated(&self) -> bool {
2337 self.parent_ctx.is_authenticated()
2338 }
2339}
2340
2341#[async_trait]
2342impl CallbackContext for AgentToolContext {
2343 fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
2344 self.parent_ctx.artifacts()
2346 }
2347
2348 fn shared_state(&self) -> Option<Arc<adk_core::SharedState>> {
2349 self.parent_ctx.shared_state()
2350 }
2351}
2352
2353#[async_trait]
2354impl ToolContext for AgentToolContext {
2355 fn function_call_id(&self) -> &str {
2356 &self.function_call_id
2357 }
2358
2359 fn agent_tool_names(&self) -> Option<Vec<String>> {
2360 self.agent_tools.clone()
2361 }
2362
2363 fn idempotency_key(&self) -> String {
2367 self.idempotency_key.clone().unwrap_or_else(|| {
2368 format!(
2369 "{}/{}/{}/{}/{}",
2370 self.app_name(),
2371 self.user_id(),
2372 self.session_id(),
2373 self.invocation_id(),
2374 self.function_call_id
2375 )
2376 })
2377 }
2378
2379 fn actions(&self) -> EventActions {
2380 self.actions_guard().clone()
2381 }
2382
2383 fn set_actions(&self, actions: EventActions) {
2384 *self.actions_guard() = actions;
2385 }
2386
2387 async fn search_memory(&self, query: &str) -> Result<Vec<MemoryEntry>> {
2388 if let Some(memory) = self.parent_ctx.memory() {
2390 memory.search(query).await
2391 } else {
2392 Ok(vec![])
2393 }
2394 }
2395
2396 fn memory(&self) -> Option<Arc<dyn adk_core::Memory>> {
2397 self.parent_ctx.memory()
2398 }
2399
2400 fn session(&self) -> Option<&dyn adk_core::Session> {
2401 Some(self.parent_ctx.session())
2402 }
2403
2404 fn run_config(&self) -> Option<&adk_core::RunConfig> {
2405 Some(self.parent_ctx.run_config())
2406 }
2407
2408 fn is_cancelled(&self) -> bool {
2409 self.parent_ctx.is_cancelled()
2410 }
2411
2412 fn request_metadata(&self) -> HashMap<String, serde_json::Value> {
2413 self.parent_ctx.request_metadata()
2414 }
2415
2416 fn delegation_depth(&self) -> u32 {
2417 self.parent_ctx.delegation_depth()
2418 }
2419
2420 fn max_delegation_depth(&self) -> Option<u32> {
2421 self.parent_ctx.max_delegation_depth()
2422 }
2423
2424 fn orchestration_root_invocation_id(&self) -> &str {
2425 self.parent_ctx.orchestration_root_invocation_id()
2426 }
2427
2428 fn orchestration_edge_id(&self) -> Option<&str> {
2429 self.parent_ctx.orchestration_edge_id()
2430 }
2431
2432 async fn emit_event(&self, event: Event) {
2433 use std::sync::atomic::Ordering;
2434
2435 let Some(tx) = &self.progress_tx else {
2436 return;
2437 };
2438 if tx.is_closed() {
2439 return;
2440 }
2441 if !event.llm_response.partial {
2444 let _ = tx.send(event).await;
2445 return;
2446 }
2447 if self.events_dropped.load(Ordering::Relaxed) > 0
2449 && !self.events_drop_marked.load(Ordering::Relaxed)
2450 && tokio::time::timeout(
2451 TOOL_PROGRESS_SEND_TIMEOUT,
2452 tx.send(self.events_dropped_marker()),
2453 )
2454 .await
2455 .is_ok_and(|sent| sent.is_ok())
2456 {
2457 self.events_drop_marked.store(true, Ordering::Relaxed);
2458 }
2459 if tokio::time::timeout(TOOL_PROGRESS_SEND_TIMEOUT, tx.send(event)).await.is_ok() {
2460 return;
2461 }
2462 if self.events_dropped.fetch_add(1, Ordering::Relaxed) == 0 {
2463 tracing::warn!(
2464 function_call.id = %self.function_call_id,
2465 "consumer is not keeping up; forwarded partial events are being dropped"
2466 );
2467 }
2468 }
2469
2470 fn user_scopes(&self) -> Vec<String> {
2471 self.parent_ctx.user_scopes()
2472 }
2473
2474 async fn get_secret(&self, name: &str) -> Result<Option<String>> {
2475 self.request_secret(name, None).await
2476 }
2477
2478 async fn get_secret_for_purpose(&self, name: &str, purpose: &str) -> Result<Option<String>> {
2479 self.request_secret(name, Some(purpose)).await
2480 }
2481
2482 async fn emit_progress(&self, stream: &str, chunk: &str) {
2483 if let Some(tx) = &self.progress_tx {
2486 if !tx.is_closed() {
2488 self.forward_progress(tx, stream, chunk).await;
2489 }
2490 }
2491 tracing::debug!(
2493 target: "adk_agent::tool_progress",
2494 tool_call_id = %self.function_call_id,
2495 stream = %stream,
2496 "{chunk}",
2497 );
2498 }
2499}
2500
2501struct ToolOutcomeCallbackContext {
2505 inner: Arc<dyn CallbackContext>,
2506 outcome: ToolOutcome,
2507}
2508
2509#[async_trait]
2510impl ReadonlyContext for ToolOutcomeCallbackContext {
2511 fn invocation_id(&self) -> &str {
2512 self.inner.invocation_id()
2513 }
2514
2515 fn agent_name(&self) -> &str {
2516 self.inner.agent_name()
2517 }
2518
2519 fn user_id(&self) -> &str {
2520 self.inner.user_id()
2521 }
2522
2523 fn app_name(&self) -> &str {
2524 self.inner.app_name()
2525 }
2526
2527 fn session_id(&self) -> &str {
2528 self.inner.session_id()
2529 }
2530
2531 fn branch(&self) -> &str {
2532 self.inner.branch()
2533 }
2534
2535 fn user_content(&self) -> &Content {
2536 self.inner.user_content()
2537 }
2538
2539 fn acting_context(&self) -> adk_core::ActingContext {
2540 self.inner.acting_context()
2541 }
2542
2543 fn is_authenticated(&self) -> bool {
2544 self.inner.is_authenticated()
2545 }
2546}
2547
2548#[async_trait]
2549impl CallbackContext for ToolOutcomeCallbackContext {
2550 fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> {
2551 self.inner.artifacts()
2552 }
2553
2554 fn tool_outcome(&self) -> Option<ToolOutcome> {
2555 Some(self.outcome.clone())
2556 }
2557
2558 fn shared_state(&self) -> Option<Arc<adk_core::SharedState>> {
2559 self.inner.shared_state()
2560 }
2561}
2562
2563struct CircuitBreakerState {
2573 threshold: u32,
2574 failures: std::collections::HashMap<String, u32>,
2576}
2577
2578impl CircuitBreakerState {
2579 fn new(threshold: u32) -> Self {
2580 Self { threshold, failures: std::collections::HashMap::new() }
2581 }
2582
2583 fn is_open(&self, tool_name: &str) -> bool {
2585 self.failures.get(tool_name).copied().unwrap_or(0) >= self.threshold
2586 }
2587
2588 fn record(&mut self, outcome: &ToolOutcome) {
2590 if outcome.success {
2591 self.failures.remove(&outcome.tool_name);
2592 } else {
2593 let count = self.failures.entry(outcome.tool_name.clone()).or_insert(0);
2594 *count += 1;
2595 }
2596 }
2597}
2598
2599struct ToolExecutionResult {
2600 index: usize,
2601 content: Content,
2602 actions: EventActions,
2603 escalate_or_skip: bool,
2604 pending: Option<ToolConfirmationRequest>,
2606 executed: bool,
2608}
2609
2610async fn screen_terminal_tool_output(
2616 guardrails: &GuardrailSet,
2617 mut content: Content,
2618) -> Result<Screened> {
2619 let mut warnings = Warnings::default();
2620 for part in &mut content.parts {
2621 if let Part::FunctionResponse { function_response, .. } = part {
2622 let text = function_response.response.to_string();
2623 let screened = enforce_guardrails(
2624 guardrails,
2625 &Content::new("model").with_text(&text),
2626 Phase::Output,
2627 )
2628 .await?;
2629 let screened_text: String =
2630 screened.content.parts.iter().filter_map(Part::text).collect();
2631 if screened_text != text {
2632 function_response.response = serde_json::from_str(&screened_text)
2633 .unwrap_or_else(|_| serde_json::json!({ "result": screened_text }));
2634 }
2635 warnings.extend(screened.warnings);
2636 }
2637 }
2638 Ok(Screened { content, warnings })
2639}
2640
2641fn callback_tool_response(
2649 content: Content,
2650 name: &str,
2651 id: Option<&String>,
2652 wrap_text: impl FnOnce(String) -> serde_json::Value,
2653 text_status: Option<ToolResultStatus>,
2654) -> Content {
2655 let mut text = String::new();
2656 let mut response = None;
2657 for part in content.parts {
2658 match part {
2659 Part::FunctionResponse { mut function_response, annotations, .. }
2660 if response.is_none() =>
2661 {
2662 function_response.name = name.to_string();
2663 response = Some(Part::FunctionResponse {
2664 function_response,
2665 id: id.cloned(),
2666 annotations,
2667 });
2668 }
2669 other => {
2670 if let Some(chunk) = other.text() {
2671 text.push_str(chunk);
2672 }
2673 }
2674 }
2675 }
2676 let response = response.unwrap_or_else(|| {
2677 let mut part = Part::FunctionResponse {
2678 function_response: FunctionResponseData::new(name, wrap_text(text)),
2679 id: id.cloned(),
2680 annotations: None,
2681 };
2682 if let Some(status) = text_status {
2683 part.set_tool_result_status(status, None);
2684 }
2685 part
2686 });
2687 Content { role: "function".to_string(), parts: vec![response] }
2688}
2689
2690fn completed(result: &ToolExecutionResult) -> bool {
2693 result.pending.is_none()
2694 && result.content.parts.iter().all(|part| {
2695 part.tool_result_status()
2696 .is_none_or(|status| matches!(status, ToolResultStatus::Succeeded))
2697 })
2698}
2699
2700#[derive(Clone, Copy)]
2701enum ToolDispatchMode {
2702 Sequential,
2703 Parallel,
2704 ParallelDelegations,
2705 Auto,
2706}
2707
2708impl ToolDispatchMode {
2709 fn resolve(strategy: ToolExecutionStrategy, parallelize_agent_delegations: bool) -> Self {
2710 if parallelize_agent_delegations {
2711 return Self::ParallelDelegations;
2712 }
2713 match strategy {
2714 ToolExecutionStrategy::Sequential => Self::Sequential,
2715 ToolExecutionStrategy::Parallel => Self::Parallel,
2716 ToolExecutionStrategy::Auto => Self::Auto,
2717 }
2718 }
2719}
2720
2721struct ToolExecutor<'a> {
2722 ctx: Arc<dyn InvocationContext>,
2723 agent_name: &'a str,
2726 tool_map: &'a std::collections::HashMap<String, Arc<dyn Tool>>,
2727 tool_retry_budgets: &'a std::collections::HashMap<String, RetryBudget>,
2728 default_retry_budget: &'a Option<RetryBudget>,
2729 before_tool_callbacks: &'a Arc<Vec<BeforeToolCallback>>,
2730 after_tool_callbacks: &'a Arc<Vec<AfterToolCallback>>,
2731 after_tool_callbacks_full: &'a Arc<Vec<AfterToolCallbackFull>>,
2732 on_tool_error_callbacks: &'a Arc<Vec<OnToolErrorCallback>>,
2733 hook_callbacks: &'a HookCallbacks,
2735 tool_confirmation_policy: &'a ToolConfirmationPolicy,
2736 tool_guardrails: &'a ToolGuardrailSet,
2737 output_guardrails: &'a GuardrailSet,
2739 cb_mutex: &'a std::sync::Mutex<Option<CircuitBreakerState>>,
2740 invocation_id: &'a str,
2741 concurrency_manager: &'a adk_core::ToolConcurrencyManager,
2742 progress_tx: tokio::sync::mpsc::Sender<Event>,
2743 progress_overflow: ProgressOverflow,
2744 tool_timeout: std::time::Duration,
2745 expose_tool_error_messages: bool,
2746 approval_failed: tokio::sync::watch::Sender<bool>,
2748 halted_batches: std::sync::Mutex<std::collections::HashSet<String>>,
2751 #[cfg(feature = "enhanced-plugins")]
2752 enhanced_plugin_manager: &'a Option<Arc<EnhancedPluginManager>>,
2753}
2754
2755impl ToolExecutor<'_> {
2756 async fn dispatch(
2758 &self,
2759 strategy: ToolDispatchMode,
2760 fc_parts: Vec<PendingToolCall>,
2761 ) -> Result<Vec<ToolExecutionResult>> {
2762 let strategy = match strategy {
2764 ToolDispatchMode::Parallel
2765 if fc_parts.iter().any(|call| self.batch_of(&call.name).is_some()) =>
2766 {
2767 ToolDispatchMode::Sequential
2768 }
2769 other => other,
2770 };
2771 let results: Vec<ToolExecutionResult> = match strategy {
2772 ToolDispatchMode::Sequential => {
2773 let mut results = Vec::with_capacity(fc_parts.len());
2774 for call in fc_parts {
2775 results.push(self.execute(call).await?);
2776 }
2777 results
2778 }
2779 ToolDispatchMode::Parallel => {
2780 use futures::StreamExt as _;
2781 let buffer_size = fc_parts.len().max(1);
2788 futures::stream::iter(fc_parts.into_iter().map(|call| self.execute(call)))
2789 .buffer_unordered(buffer_size)
2790 .collect::<Vec<_>>()
2792 .await
2793 .into_iter()
2794 .collect::<Result<Vec<_>>>()?
2795 }
2796 ToolDispatchMode::ParallelDelegations => {
2797 use futures::StreamExt as _;
2798
2799 let mut all_results = Vec::with_capacity(fc_parts.len());
2800 let mut calls = fc_parts.into_iter().peekable();
2801 while let Some(call) = calls.next() {
2802 let is_delegation = self
2803 .tool_map
2804 .get(&call.name)
2805 .is_some_and(|tool| tool.is_agent_delegation());
2806 if !is_delegation {
2807 all_results.push(self.execute(call).await?);
2808 continue;
2809 }
2810
2811 let mut delegation_batch = vec![call];
2812 while calls.peek().is_some_and(|next| {
2813 self.tool_map.get(&next.name).is_some_and(|tool| tool.is_agent_delegation())
2814 }) {
2815 if let Some(next) = calls.next() {
2816 delegation_batch.push(next);
2817 }
2818 }
2819
2820 let buffer_size = delegation_batch.len();
2821 all_results.extend(
2822 futures::stream::iter(
2823 delegation_batch.into_iter().map(|call| self.execute(call)),
2824 )
2825 .buffer_unordered(buffer_size)
2826 .collect::<Vec<_>>()
2827 .await
2828 .into_iter()
2829 .collect::<Result<Vec<_>>>()?,
2830 );
2831 }
2832 all_results
2833 }
2834 ToolDispatchMode::Auto => {
2835 use futures::StreamExt as _;
2836
2837 let is_concurrent = |call: &PendingToolCall| {
2842 self.tool_map.get(&call.name).is_some_and(|tool| {
2843 tool.is_read_only()
2844 && tool.is_concurrency_safe()
2845 && tool.batch_group().is_none()
2846 })
2847 };
2848 let mut all_results = Vec::with_capacity(fc_parts.len());
2849 let mut calls = fc_parts.into_iter().peekable();
2850 while let Some(call) = calls.next() {
2851 if !is_concurrent(&call) {
2852 all_results.push(self.execute(call).await?);
2853 continue;
2854 }
2855
2856 let mut concurrent_batch = vec![call];
2857 while calls.peek().is_some_and(is_concurrent) {
2858 if let Some(next) = calls.next() {
2859 concurrent_batch.push(next);
2860 }
2861 }
2862
2863 let buffer_size = concurrent_batch.len();
2865 all_results.extend(
2866 futures::stream::iter(
2867 concurrent_batch.into_iter().map(|call| self.execute(call)),
2868 )
2869 .buffer_unordered(buffer_size)
2870 .collect::<Vec<_>>()
2871 .await
2872 .into_iter()
2873 .collect::<Result<Vec<_>>>()?,
2874 );
2875 }
2876 all_results
2877 }
2878 };
2879 Ok(results)
2880 }
2881
2882 async fn execute(&self, call: PendingToolCall) -> Result<ToolExecutionResult> {
2883 let screened_call =
2884 (!self.tool_guardrails.is_empty()).then(|| (call.name.clone(), call.args.clone()));
2885 let requested = self
2887 .ctx
2888 .run_config()
2889 .requested_call
2890 .as_ref()
2891 .filter(|requested| requested.function_call_id == call.function_call_id);
2892 let batch = self.batch_of(&call.name);
2893 let halted = batch.as_ref().is_some_and(|batch| {
2894 self.halted_batches
2895 .lock()
2896 .unwrap_or_else(|e| e.into_inner())
2897 .contains(batch.name.as_ref())
2898 });
2899 let mut result = match &batch {
2900 Some(batch) if halted => self.halted_call(call, batch).await?,
2901 _ => self.execute_inner(call).await?,
2902 };
2903 if let Some(batch) = &batch
2905 && !completed(&result)
2906 {
2907 self.halted_batches
2908 .lock()
2909 .unwrap_or_else(|e| e.into_inner())
2910 .insert(batch.name.to_string());
2911 }
2912 if let Some((name, args)) = screened_call
2915 && result.pending.is_none()
2916 {
2917 let (content, withheld) = screen_tool_result(
2918 self.tool_guardrails,
2919 &name,
2920 &args,
2921 result.executed,
2922 result.content,
2923 )
2924 .await;
2925 result.content = content;
2926 for reason in withheld {
2927 tracing::debug!(
2929 tool.name = %name,
2930 reason = %self.logged_message(&reason),
2931 "tool result withheld"
2932 );
2933 }
2934 }
2935 let mut warnings = Warnings::default();
2938 if result.escalate_or_skip && result.pending.is_none() && !self.output_guardrails.is_empty()
2939 {
2940 let screened =
2941 screen_terminal_tool_output(self.output_guardrails, result.content).await?;
2942 result.content = screened.content;
2943 warnings = screened.warnings;
2944 }
2945 let mut event = Event::new(self.invocation_id);
2946 event.author = self.agent_name.to_owned();
2947 event.branch = self.ctx.branch().to_owned();
2948 warnings.record_on(&mut event);
2949 event.actions = result.actions.clone();
2950 event.llm_response.content = Some(result.content.clone());
2951 if let Some(requested) = requested {
2952 requested.mark(&mut event);
2953 }
2954 let _ = self.progress_tx.send(event).await;
2956 Ok(result)
2957 }
2958
2959 fn batch_of(&self, name: &str) -> Option<adk_core::BatchGroup> {
2961 self.tool_map.get(name).and_then(|tool| tool.batch_group())
2962 }
2963
2964 async fn halted_call(
2966 &self,
2967 call: PendingToolCall,
2968 batch: &adk_core::BatchGroup,
2969 ) -> Result<ToolExecutionResult> {
2970 self.record_short_circuit(&call.name, &call.function_call_id, &call.args, "batch_halt")
2971 .await?;
2972 let mut part = Part::FunctionResponse {
2973 function_response: FunctionResponseData::new(
2974 call.name,
2975 serde_json::Value::String(batch.halt_text.to_string()),
2976 ),
2977 id: call.id,
2978 annotations: None,
2979 };
2980 part.set_tool_result_status(ToolResultStatus::NotRun, None);
2981 Ok(ToolExecutionResult {
2982 index: call.index,
2983 content: Content { role: "function".to_string(), parts: vec![part] },
2984 actions: EventActions::default(),
2985 escalate_or_skip: false,
2986 pending: None,
2987 executed: false,
2988 })
2989 }
2990
2991 fn logged_message(&self, message: &str) -> String {
2993 traced_message(self.ctx.run_config(), message)
2994 }
2995
2996 async fn record_short_circuit(
3004 &self,
3005 name: &str,
3006 function_call_id: &str,
3007 args: &serde_json::Value,
3008 answered_by: &str,
3009 ) -> Result<()> {
3010 tracing::debug!(
3011 tool.name = %name,
3012 tool.answered_by = %answered_by,
3013 "tool call answered before authorization; the tool was not run"
3014 );
3015 let Some(trail) = &self.ctx.run_config().audit else {
3016 return Ok(());
3017 };
3018 let mut draft = AuditRecordDraft::new(AuditRecordKind::ToolCall, SHORT_CIRCUIT_ACTION)
3019 .actor(AuditActor::for_context(self.ctx.as_ref()))
3020 .args_digest(trail.digest(args))
3021 .outcome(AuditRecordOutcome::NotRun)
3022 .ext("toolName", serde_json::Value::String(name.to_string()))
3023 .ext("agentName", serde_json::Value::String(self.agent_name.to_string()))
3024 .ext("answeredBy", serde_json::Value::String(answered_by.to_string()))
3025 .ext("functionCallId", serde_json::Value::String(function_call_id.to_string()))
3026 .ext("sessionId", serde_json::Value::String(self.ctx.session_id().to_string()));
3027 if let Some(tool) = self.tool_map.get(name) {
3028 let origin = adk_core::ToolOrigin::of(tool.as_ref());
3029 draft = draft
3030 .ext("toolSource", serde_json::Value::String(origin.source))
3031 .ext("declarationDigest", serde_json::Value::String(origin.declaration_digest));
3032 }
3033 if let Err(error) = trail.record(draft).await {
3034 self.approval_failed.send_replace(true);
3035 return Err(error);
3036 }
3037 Ok(())
3038 }
3039
3040 async fn execute_inner(&self, call: PendingToolCall) -> Result<ToolExecutionResult> {
3041 let PendingToolCall { index, name, args, id, function_call_id, resumes } = call;
3042 let resumed_ledger_key = resumes.as_ref().map(|held| {
3045 crate::tool_ledger::held_call_ledger_key(
3046 self.ctx.app_name(),
3047 self.ctx.user_id(),
3048 self.ctx.session_id(),
3049 &function_call_id,
3050 &held.fingerprint(),
3051 )
3052 });
3053 let mut tool_actions = EventActions::default();
3054 let mut response_content: Option<Content> = None;
3055 let mut run_after_tool_callbacks = true;
3056 let mut tool_outcome_for_callback: Option<ToolOutcome> = None;
3057 let mut executed_tool: Option<Arc<dyn Tool>> = None;
3058 let mut executed_tool_response: Option<serde_json::Value> = None;
3059 let mut tool_executed = false;
3061 let mut pending_confirmation: Option<ToolConfirmationRequest> = None;
3062 let mut unknown_outcome: Option<Arc<adk_core::AdkError>> = None;
3064 let answer = |response: serde_json::Value,
3066 status: Option<ToolResultStatus>,
3067 cause: Option<&adk_core::AdkError>| {
3068 let mut part = Part::FunctionResponse {
3069 function_response: FunctionResponseData::from_tool_result(name.clone(), response),
3070 id: id.clone(),
3071 annotations: None,
3072 };
3073 if let Some(status) = status {
3074 part.set_tool_result_status(status, cause);
3075 }
3076 Content { role: "function".to_string(), parts: vec![part] }
3077 };
3078 let not_run = |message: String, cause: Option<&adk_core::AdkError>| {
3079 answer(serde_json::json!({ "error": message }), Some(ToolResultStatus::NotRun), cause)
3080 };
3081 let callback_failure = |error: &adk_core::AdkError| {
3083 if self.expose_tool_error_messages { error.to_string() } else { error.redacted() }
3084 };
3085
3086 if let Some(reason) = adk_core::invalid_tool_arguments_reason(&args) {
3089 tracing::warn!(
3090 tool.name = %name,
3091 reason = %reason,
3092 "tool call arguments are not a JSON object; answering without executing"
3093 );
3094 return Ok(ToolExecutionResult {
3095 index,
3096 content: not_run(
3097 format!(
3098 "tool '{name}' was not run: {reason}. Call it again with arguments that \
3099 are one JSON object matching its parameters."
3100 ),
3101 None,
3102 ),
3103 actions: tool_actions,
3104 escalate_or_skip: false,
3105 pending: None,
3106 executed: false,
3107 });
3108 }
3109
3110 let mut final_args = args;
3113
3114 #[cfg(feature = "enhanced-plugins")]
3116 if let Some(epm) = self.enhanced_plugin_manager.as_ref()
3117 && let Some(tool_ref) = self.tool_map.get(&name)
3118 {
3119 match epm
3120 .run_before_tool_call(
3121 tool_ref.clone(),
3122 final_args.clone(),
3123 self.ctx.clone() as Arc<dyn CallbackContext>,
3124 )
3125 .await
3126 {
3127 Ok(BeforeToolCallResult::Continue(modified_args)) => {
3128 final_args = modified_args;
3129 }
3130 Ok(BeforeToolCallResult::ShortCircuit(synthetic_result)) => {
3131 self.record_short_circuit(
3133 &name,
3134 &function_call_id,
3135 &final_args,
3136 SHORT_CIRCUIT_BY_ENHANCED_PLUGIN,
3137 )
3138 .await?;
3139 response_content = Some(Content {
3140 role: "function".to_string(),
3141 parts: vec![Part::FunctionResponse {
3142 function_response: FunctionResponseData::from_tool_result(
3143 name.clone(),
3144 synthetic_result,
3145 ),
3146 id: id.clone(),
3147 annotations: None,
3148 }],
3149 });
3150 executed_tool = Some(tool_ref.clone());
3151 }
3152 Err(e) => {
3153 tracing::warn!(
3154 tool.name = %name,
3155 error.code = %e.code,
3156 error.category = %e.category,
3157 error.message = %self.logged_message(&e.message),
3158 "before-tool plugin failed; the tool was not run"
3159 );
3160 response_content = Some(not_run(
3161 format!(
3162 "tool '{name}' was not run: a before-tool plugin failed with {}",
3163 callback_failure(&e)
3164 ),
3165 Some(&e),
3166 ));
3167 run_after_tool_callbacks = false;
3168 }
3169 }
3170 }
3171
3172 if response_content.is_none() {
3173 let tool_ctx = Arc::new(ToolCallbackContext::new(
3174 self.ctx.clone(),
3175 name.clone(),
3176 final_args.clone(),
3177 ));
3178 let hooks = self.hook_callbacks.before_tool.len();
3179 for (position, callback) in self
3180 .hook_callbacks
3181 .before_tool
3182 .iter()
3183 .chain(self.before_tool_callbacks.iter())
3184 .enumerate()
3185 {
3186 let decided = adk_core::guard_callback(
3188 "before-tool callback",
3189 callback(tool_ctx.clone() as Arc<dyn CallbackContext>),
3190 )
3191 .await;
3192 match decided {
3193 Ok(Some(c)) => {
3194 let answered_by = if position < hooks {
3195 SHORT_CIRCUIT_BY_INVOCATION_HOOK
3196 } else {
3197 SHORT_CIRCUIT_BY_BEFORE_TOOL_CALLBACK
3198 };
3199 self.record_short_circuit(
3200 &name,
3201 &function_call_id,
3202 &final_args,
3203 answered_by,
3204 )
3205 .await?;
3206 response_content = Some(callback_tool_response(
3208 c,
3209 &name,
3210 id.as_ref(),
3211 |text| serde_json::json!({ "error": text }),
3212 Some(ToolResultStatus::NotRun),
3213 ));
3214 break;
3215 }
3216 Ok(None) => continue,
3217 Err(e) => {
3218 tracing::warn!(
3219 tool.name = %name,
3220 error.code = %e.code,
3221 error.category = %e.category,
3222 error.message = %self.logged_message(&e.message),
3223 "before-tool callback failed; the tool was not run"
3224 );
3225 response_content = Some(not_run(
3226 format!(
3227 "tool '{name}' was not run: a before-tool callback failed with {}",
3228 callback_failure(&e)
3229 ),
3230 Some(&e),
3231 ));
3232 run_after_tool_callbacks = false;
3233 break;
3234 }
3235 }
3236 }
3237 }
3238
3239 if response_content.is_none() {
3241 let guard = self.cb_mutex.lock().unwrap_or_else(|e| e.into_inner());
3242 if let Some(ref cb_state) = *guard
3243 && cb_state.is_open(&name)
3244 {
3245 let msg = format!(
3246 "Tool '{}' is temporarily disabled after {} consecutive failures",
3247 name, cb_state.threshold
3248 );
3249 tracing::warn!(tool.name = %name, "circuit breaker open, skipping tool execution");
3250 response_content = Some(not_run(msg, None));
3251 run_after_tool_callbacks = false;
3252 }
3253 drop(guard);
3254 }
3255
3256 if response_content.is_none()
3260 && let Some(tool) = self.tool_map.get(&name)
3261 {
3262 let screen = GuardrailScreen(self.tool_guardrails);
3263 let mut gate = ToolGate::for_context(self.ctx.as_ref())
3264 .with_abandon_signal(self.approval_failed.subscribe());
3265 if !self.tool_guardrails.is_empty() {
3266 gate = gate.with_screen(&screen);
3267 }
3268 let mut call =
3269 GovernedCall::for_tool(tool.as_ref(), function_call_id.clone(), final_args.clone())
3270 .requiring_confirmation(
3271 self.tool_confirmation_policy.requires_confirmation(&name)
3272 || self.ctx.requires_tool_confirmation(&name),
3273 );
3274 let resumed = resumes.filter(|held| held.tool_name == name);
3278 if let Some(held) = resumed.clone() {
3279 call = call.resuming(held);
3280 }
3281 call = call.requested(adk_core::RequestedCall::is_requested_id(&function_call_id));
3284 match authorize_tool_call(&gate, call).await {
3285 Ok(ToolAuthorization::Execute { args, confirmation }) => {
3286 final_args = args;
3287 tool_actions.tool_confirmation_decision = confirmation;
3288 }
3289 Ok(ToolAuthorization::Refuse { reason, confirmation }) => {
3290 tracing::debug!(
3292 tool.name = %name,
3293 reason = %self.logged_message(&reason),
3294 "tool call refused"
3295 );
3296 tool_actions.tool_confirmation_decision = confirmation;
3297 response_content = Some(answer(
3298 serde_json::json!({ "error": reason }),
3299 Some(ToolResultStatus::Refused),
3300 None,
3301 ));
3302 run_after_tool_callbacks = false;
3303 }
3304 Ok(ToolAuthorization::Pending { request, reason }) => {
3305 response_content = Some(answer(
3306 adk_core::confirmation_pending_response(reason),
3307 Some(ToolResultStatus::Held),
3308 None,
3309 ));
3310 pending_confirmation = Some(request);
3311 run_after_tool_callbacks = false;
3312 }
3313 Err(error)
3317 if error.code == adk_core::GOVERNANCE_FROZEN_CODE
3318 || error.code == adk_core::GOVERNANCE_STALE_CODE =>
3319 {
3320 tracing::info!(
3321 tool.name = %name,
3322 error = %error.diagnostics(),
3323 "tool call not run: the governance control refuses work"
3324 );
3325 if let Some(held) = &resumed {
3329 adk_core::withdraw_held_call(&gate, held).await?;
3330 }
3331 response_content = Some(not_run(adk_core::not_run_text(&error), Some(&error)));
3332 run_after_tool_callbacks = false;
3333 }
3334 Err(error) => {
3335 self.approval_failed.send_replace(true);
3336 return Err(error);
3337 }
3338 }
3339 }
3340
3341 let _concurrency_permit = if response_content.is_some() {
3346 None
3347 } else {
3348 match self.concurrency_manager.acquire(&name).await {
3349 Ok(permit) => Some(permit),
3350 Err(e) => {
3351 return Ok(ToolExecutionResult {
3353 index,
3354 content: not_run(e.to_string(), Some(&e)),
3355 actions: tool_actions,
3356 escalate_or_skip: false,
3357 pending: None,
3358 executed: false,
3359 });
3360 }
3361 }
3362 };
3363
3364 if response_content.is_none() {
3366 if let Some(tool) = self.tool_map.get(&name) {
3367 let attempt_context = || -> Arc<dyn ToolContext> {
3370 Arc::new(
3371 AgentToolContext::new(self.ctx.clone(), function_call_id.clone())
3372 .with_tool_name(tool.name())
3373 .with_agent_tools(self.tool_map.keys().cloned())
3374 .with_idempotency_key(resumed_ledger_key.clone())
3375 .with_progress(
3376 self.progress_tx.clone(),
3377 self.progress_overflow.clone(),
3378 ),
3379 )
3380 };
3381 let mut tool_ctx = attempt_context();
3382 let effect = tool.effect();
3383
3384 let ledgered = match crate::tool_ledger::begin_ledgered_call(
3388 self.ctx.as_ref(),
3389 effect,
3390 tool_ctx.idempotency_key(),
3392 &name,
3393 &final_args,
3394 )
3395 .await?
3396 {
3397 Ok(ledgered) => ledgered,
3398 Err(recorded) => {
3399 return Ok(ToolExecutionResult {
3400 index,
3401 content: answer(
3402 recorded.response,
3403 Some(recorded.status),
3404 recorded.cause.as_ref(),
3405 ),
3406 actions: tool_actions,
3407 escalate_or_skip: false,
3408 pending: None,
3409 executed: false,
3410 });
3411 }
3412 };
3413
3414 if let Err(refusal) = self.ctx.run_config().check_governance() {
3419 let text = adk_core::not_run_text(&refusal);
3420 tracing::info!(
3421 tool.name = %name,
3422 error = %refusal.diagnostics(),
3423 "tool call not run: the governance control refused it before it started"
3424 );
3425 if let Some(trail) = &self.ctx.run_config().audit {
3426 let draft = AuditRecordDraft::new(AuditRecordKind::ToolCall, &name)
3427 .actor(AuditActor::for_context(self.ctx.as_ref()))
3428 .args_digest(trail.digest(&final_args))
3429 .outcome(AuditRecordOutcome::NotRun)
3430 .ext("reason", serde_json::Value::String(text.clone()))
3431 .ext(
3432 "sessionId",
3433 serde_json::Value::String(self.ctx.session_id().to_string()),
3434 );
3435 trail.record(draft).await?;
3436 }
3437 if let Some(ledgered) = ledgered {
3438 ledgered.complete(&name, None, &text).await;
3439 }
3440 return Ok(ToolExecutionResult {
3441 index,
3442 content: not_run(text, Some(&refusal)),
3443 actions: tool_actions,
3444 escalate_or_skip: false,
3445 pending: None,
3446 executed: false,
3447 });
3448 }
3449
3450 let span_name = format!("execute_tool {name}");
3453 let tool_span = tracing::info_span!(
3454 "",
3455 otel.name = %span_name,
3456 otel.kind = "internal",
3457 "gen_ai.operation.name" = "execute_tool",
3458 "gen_ai.tool.name" = %name,
3459 "gen_ai.tool.type" = "function",
3460 "gen_ai.tool.call.id" = tracing::field::Empty,
3461 "gen_ai.tool.description" = %tool.description(),
3462 "gen_ai.agent.name" = %self.agent_name,
3463 "gen_ai.tool.call.arguments" = tracing::field::Empty,
3464 "gen_ai.tool.call.result" = tracing::field::Empty,
3465 "error.type" = tracing::field::Empty,
3466 tool.name = %name,
3467 "gcp.vertex.agent.event_id" = %format!("{}_{}", self.invocation_id, name),
3468 "gcp.vertex.agent.invocation_id" = %self.invocation_id,
3469 "gcp.vertex.agent.session_id" = %self.ctx.session_id(),
3470 "gen_ai.conversation.id" = %self.ctx.session_id()
3471 );
3472 if let Some(call_id) =
3474 id.as_deref().filter(|id| !id.starts_with(adk_core::GENERATED_CALL_ID_PREFIX))
3475 {
3476 tool_span.record("gen_ai.tool.call.id", call_id);
3477 }
3478 let capture_on_span = adk_telemetry::config::capture_content().on_spans();
3479 if capture_on_span {
3480 tool_span.record("gen_ai.tool.call.arguments", final_args.to_string().as_str());
3481 }
3482
3483 let budget = self
3485 .tool_retry_budgets
3486 .get(&name)
3487 .or(self.default_retry_budget.as_ref())
3488 .filter(|_| effect.is_retry_safe());
3489 let max_attempts = budget.map(|b| b.max_retries + 1).unwrap_or(1);
3490 let timeout = tool.timeout_override().unwrap_or(Some(self.tool_timeout));
3491
3492 let mut started = Event::new(self.invocation_id);
3493 started.author = self.agent_name.to_owned();
3494 started.branch = self.ctx.branch().to_owned();
3495 started.llm_response.partial = true;
3497 started.provider_metadata.insert(
3498 "adk_tool_started".into(),
3499 serde_json::json!({"id": id, "name": name}).to_string(),
3500 );
3501 let _ = self.progress_tx.send(started).await;
3502 tool_executed = true;
3503 let tool_clone = tool.clone();
3504 let tool_start = std::time::Instant::now();
3505 let mut last_error: Option<Arc<adk_core::AdkError>> = None;
3506 let mut interrupted = false;
3510 let mut final_attempt: u32 = 0;
3511 let mut retry_result: Option<serde_json::Value> = None;
3512
3513 for attempt in 0..max_attempts {
3514 if attempt > 0 {
3515 if let Some(budget) = budget {
3516 tokio::time::sleep(budget.backoff_delay(attempt)).await;
3517 }
3518 if self.ctx.run_config().check_governance().is_err() {
3521 break;
3522 }
3523 tool_ctx = attempt_context();
3524 }
3525 final_attempt = attempt;
3526 let attempt_result = async {
3527 let args_payload = trace_json_payload(
3528 &final_args,
3529 self.ctx.run_config().record_payloads,
3530 self.ctx.run_config().trace_payload_max_bytes,
3531 );
3532 tracing::debug!(tool.name = %name, tool.args = %args_payload, attempt = attempt, "tool_call");
3533 let exec_future = execute_tool(
3534 Arc::clone(&tool_clone),
3535 tool_ctx.clone(),
3536 final_args.clone(),
3537 );
3538 let bounded = async {
3539 match timeout {
3540 Some(limit) => tokio::time::timeout(limit, exec_future)
3541 .await
3542 .map_err(|_| limit),
3543 None => Ok(exec_future.await),
3544 }
3545 };
3546 match futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(bounded)).await {
3547 Ok(Ok(result)) => result.map_err(|error| {
3548 let retryable = error.is_retryable();
3549 (error, retryable, false)
3550 }),
3551 Ok(Err(limit)) => Err((
3552 adk_core::AdkError::new(
3553 adk_core::ErrorComponent::Tool,
3554 adk_core::ErrorCategory::Timeout,
3555 "tool.timeout",
3556 format!("Tool '{name}' timed out after {limit:?}"),
3557 ),
3558 true,
3559 true,
3560 )),
3561 Err(_panic) => Err((
3562 adk_core::AdkError::new(
3563 adk_core::ErrorComponent::Tool,
3564 adk_core::ErrorCategory::Internal,
3565 "tool.panicked",
3566 format!("tool '{name}' panicked during execution"),
3567 ),
3568 false,
3569 true,
3570 )),
3571 }
3572 }
3573 .instrument(tool_span.clone())
3574 .await;
3575 match attempt_result {
3576 Ok(value) => {
3577 let result_payload = trace_json_payload(
3578 &value,
3579 self.ctx.run_config().record_payloads,
3580 self.ctx.run_config().trace_payload_max_bytes,
3581 );
3582 tracing::debug!(tool.name = %name, tool.result = %result_payload, "tool_result");
3583 if capture_on_span {
3584 tool_span
3585 .record("gen_ai.tool.call.result", value.to_string().as_str());
3586 }
3587 retry_result = Some(value);
3588 break;
3589 }
3590 Err((error, retryable, mid_flight)) => {
3591 interrupted = mid_flight;
3592 let message = if mid_flight {
3593 error.message.clone()
3594 } else {
3595 self.logged_message(&error.message)
3596 };
3597 if retryable && attempt + 1 < max_attempts {
3598 tracing::warn!(tool.name = %name, attempt = attempt, error.code = %error.code, error.category = %error.category, error.message = %message, "tool execution failed, retrying");
3599 } else {
3600 tracing::warn!(tool.name = %name, error.code = %error.code, error.category = %error.category, error.message = %message, "tool_error");
3601 }
3602 let retry = retryable && attempt + 1 < max_attempts;
3603 if !retry {
3604 tool_span.record("error.type", error.code);
3605 }
3606 last_error = Some(Arc::new(error));
3607 if !retry {
3608 break;
3609 }
3610 }
3611 }
3612 }
3613
3614 let outcome_unknown = interrupted && effect == ToolEffect::NonIdempotent;
3615 let failure_response = match (&retry_result, &last_error) {
3618 (None, Some(error)) if outcome_unknown => {
3619 Some(crate::tool_ledger::interrupted_call_response(&error.message))
3620 }
3621 (None, Some(error)) if interrupted => {
3622 Some(serde_json::json!({ "error": error.message }))
3623 }
3624 (None, Some(error)) => Some(adk_core::tool_error_response(
3625 &name,
3626 error,
3627 self.expose_tool_error_messages,
3628 )),
3629 (None, None) | (Some(_), _) => None,
3630 };
3631 if outcome_unknown {
3632 crate::tool_ledger::record_outcome_unknown(
3633 self.ctx.as_ref(),
3634 &name,
3635 &final_args,
3636 "interrupted",
3637 )
3638 .await?;
3639 }
3640 if let Some(ledgered) = ledgered
3644 && !outcome_unknown
3645 {
3646 let failure_text = failure_response
3647 .as_ref()
3648 .and_then(|response| response.get("error"))
3649 .and_then(serde_json::Value::as_str)
3650 .unwrap_or_default();
3651 ledgered.complete(&name, retry_result.as_ref(), failure_text).await;
3652 }
3653
3654 let tool_duration = tool_start.elapsed();
3655 let error_message =
3657 last_error.as_ref().filter(|_| retry_result.is_none()).map(|error| {
3658 if interrupted { error.message.clone() } else { error.to_string() }
3659 });
3660 let tool_success = retry_result.is_some();
3661 let mut status = match last_error.as_deref() {
3663 _ if tool_success => None,
3664 _ if outcome_unknown => Some(ToolResultStatus::OutcomeUnknown),
3665 Some(error) => Some(ToolResultStatus::of_tool_error(error)),
3666 None => Some(ToolResultStatus::Failed),
3667 };
3668 if outcome_unknown {
3669 unknown_outcome = last_error.clone();
3670 }
3671 let function_response = match retry_result {
3672 Some(value) => value,
3673 None => failure_response.unwrap_or_else(
3674 || serde_json::json!({ "error": format!("tool '{name}' failed") }),
3675 ),
3676 };
3677
3678 let outcome = ToolOutcome {
3679 tool_name: name.clone(),
3680 tool_args: final_args.clone(),
3681 success: tool_success,
3682 duration: tool_duration,
3683 error_message: error_message.clone(),
3684 error: if tool_success { None } else { last_error.clone() },
3685 attempt: final_attempt,
3686 };
3687
3688 {
3690 let mut guard = self.cb_mutex.lock().unwrap_or_else(|e| e.into_inner());
3691 if let Some(ref mut cb_state) = *guard {
3692 cb_state.record(&outcome);
3693 }
3694 }
3695
3696 let final_function_response = if !tool_success {
3698 let error_ctx: Arc<dyn CallbackContext> =
3699 Arc::new(ToolOutcomeCallbackContext {
3700 inner: self.ctx.clone() as Arc<dyn CallbackContext>,
3701 outcome: outcome.clone(),
3702 });
3703 let mut fallback_result = None;
3704 let error_msg = error_message.unwrap_or_default();
3705 for callback in self
3706 .hook_callbacks
3707 .on_tool_error
3708 .iter()
3709 .chain(self.on_tool_error_callbacks.iter())
3710 {
3711 match callback(
3712 error_ctx.clone(),
3713 tool.clone(),
3714 final_args.clone(),
3715 error_msg.clone(),
3716 )
3717 .await
3718 {
3719 Ok(Some(result)) => {
3720 fallback_result = Some(result);
3721 break;
3722 }
3723 Ok(None) => continue,
3724 Err(e) => {
3725 tracing::warn!(error.code = %e.code, error.message = %self.logged_message(&e.message), "on_tool_error callback failed");
3726 break;
3727 }
3728 }
3729 }
3730 match fallback_result {
3731 Some(result) => {
3734 if !outcome_unknown {
3735 status = None;
3736 }
3737 result
3738 }
3739 None => function_response,
3740 }
3741 } else {
3742 function_response
3743 };
3744 tool_outcome_for_callback = Some(outcome);
3745
3746 let confirmation_decision = tool_actions.tool_confirmation_decision;
3747 tool_actions = tool_ctx.actions();
3748 if tool_actions.tool_confirmation_decision.is_none() {
3749 tool_actions.tool_confirmation_decision = confirmation_decision;
3750 }
3751 let final_function_response = match tool_actions.tool_confirmation.take() {
3755 Some(request) if outcome_unknown => {
3759 tracing::warn!(
3760 tool.name = %name,
3761 "a call with an unknown outcome asked for a confirmation; withdrawing the request"
3762 );
3763 let gate = ToolGate::for_context(self.ctx.as_ref());
3764 if let Err(error) = adk_core::withdraw_held_call(&gate, &request).await {
3765 self.approval_failed.send_replace(true);
3766 return Err(error);
3767 }
3768 final_function_response
3769 }
3770 Some(request) => {
3771 tool_actions.skip_summarization = false;
3772 tool_actions.escalate = false;
3773 pending_confirmation = Some(request);
3774 run_after_tool_callbacks = false;
3775 status = Some(ToolResultStatus::Held);
3776 if adk_core::is_confirmation_pending(&final_function_response) {
3777 final_function_response
3778 } else {
3779 adk_core::confirmation_pending_response(format!(
3780 "Tool '{name}' is waiting for a confirmation"
3781 ))
3782 }
3783 }
3784 None => final_function_response,
3785 };
3786 executed_tool = Some(tool.clone());
3787 executed_tool_response = Some(final_function_response.clone());
3788 let cause =
3789 last_error.as_deref().filter(|_| status != Some(ToolResultStatus::Held));
3790 response_content = Some(answer(final_function_response, status, cause));
3791 } else {
3792 response_content = Some(not_run(format!("Tool {name} not found"), None));
3793 }
3794 }
3795
3796 let mut response_content = response_content.expect("tool response content is set");
3801 if run_after_tool_callbacks {
3802 let mut failure: Option<adk_core::AdkError> = None;
3803 let outcome_ctx: Arc<dyn CallbackContext> = match tool_outcome_for_callback {
3804 Some(outcome) => Arc::new(ToolOutcomeCallbackContext {
3805 inner: self.ctx.clone() as Arc<dyn CallbackContext>,
3806 outcome,
3807 }),
3808 None => self.ctx.clone() as Arc<dyn CallbackContext>,
3809 };
3810 let cb_ctx: Arc<dyn CallbackContext> =
3811 Arc::new(ToolCallbackContext::new(outcome_ctx, name.clone(), final_args.clone()));
3812 for callback in
3813 self.hook_callbacks.after_tool.iter().chain(self.after_tool_callbacks.iter())
3814 {
3815 match callback(cb_ctx.clone()).await {
3816 Ok(Some(modified)) => {
3817 response_content = callback_tool_response(
3818 modified,
3819 &name,
3820 id.as_ref(),
3821 |text| serde_json::json!({ "result": text }),
3822 None,
3823 );
3824 break;
3825 }
3826 Ok(None) => continue,
3827 Err(e) => {
3828 failure = Some(e);
3829 break;
3830 }
3831 }
3832 }
3833 if failure.is_none()
3834 && let (Some(tool_ref), Some(tool_resp)) = (&executed_tool, executed_tool_response)
3835 {
3836 for callback in self.after_tool_callbacks_full.as_ref() {
3837 match callback(
3838 cb_ctx.clone(),
3839 tool_ref.clone(),
3840 final_args.clone(),
3841 tool_resp.clone(),
3842 )
3843 .await
3844 {
3845 Ok(Some(modified_value)) => {
3846 response_content = answer(modified_value, None, None);
3847 break;
3848 }
3849 Ok(None) => continue,
3850 Err(e) => {
3851 failure = Some(e);
3852 break;
3853 }
3854 }
3855 }
3856 }
3857
3858 #[cfg(feature = "enhanced-plugins")]
3861 if failure.is_none()
3862 && let Some(epm) = self.enhanced_plugin_manager.as_ref()
3863 && let Some(tool_ref) = &executed_tool
3864 {
3865 let result_value = response_content
3867 .parts
3868 .iter()
3869 .find_map(|p| {
3870 if let Part::FunctionResponse { function_response, .. } = p {
3871 Some(function_response.response.clone())
3872 } else {
3873 None
3874 }
3875 })
3876 .unwrap_or(serde_json::json!(null));
3877
3878 match epm
3881 .run_after_tool_call(
3882 tool_ref.clone(),
3883 &final_args,
3884 result_value.clone(),
3885 cb_ctx.clone(),
3886 )
3887 .await
3888 {
3889 Ok(adk_plugin::AfterToolCallResult::Continue(modified_result)) => {
3891 if modified_result != result_value {
3892 response_content = answer(modified_result, None, None);
3893 }
3894 }
3895 Err(e) => failure = Some(e),
3896 }
3897 }
3898
3899 if let Some(error) = failure {
3900 tracing::error!(
3901 tool.name = %name,
3902 tool.executed = tool_executed,
3903 error.code = %error.code,
3904 error.category = %error.category,
3905 error.message = %self.logged_message(&error.message),
3906 "after-tool pipeline failed; withholding the tool result"
3907 );
3908 response_content = if tool_executed {
3911 answer(
3912 adk_core::result_withheld_response(
3913 &name,
3914 &error,
3915 self.expose_tool_error_messages,
3916 ),
3917 Some(ToolResultStatus::Withheld),
3918 Some(&error),
3919 )
3920 } else {
3921 not_run(
3922 format!(
3923 "tool '{name}' was not run, and its after-tool pipeline failed with {}",
3924 callback_failure(&error)
3925 ),
3926 Some(&error),
3927 )
3928 };
3929 }
3930 if let Some(cause) = &unknown_outcome {
3932 for part in &mut response_content.parts {
3933 part.set_tool_result_status(ToolResultStatus::OutcomeUnknown, Some(cause));
3934 }
3935 }
3936 }
3937
3938 let escalate_or_skip = tool_actions.escalate || tool_actions.skip_summarization;
3939 Ok(ToolExecutionResult {
3940 index,
3941 content: response_content,
3942 actions: tool_actions,
3943 escalate_or_skip,
3944 pending: pending_confirmation,
3945 executed: tool_executed,
3946 })
3947 }
3948}
3949
3950#[async_trait]
3951impl Agent for LlmAgent {
3952 fn name(&self) -> &str {
3953 &self.name
3954 }
3955
3956 fn description(&self) -> &str {
3957 &self.description
3958 }
3959
3960 fn profile(&self) -> adk_core::AgentProfile {
3961 adk_core::AgentProfile {
3962 kind: adk_core::AgentKind::Llm,
3963 instruction: self.instruction.clone().filter(|text| !text.is_empty()),
3964 global_instruction: self.global_instruction.clone().filter(|text| !text.is_empty()),
3965 tools: self
3966 .tools
3967 .iter()
3968 .map(|tool| adk_core::ToolProfile {
3969 name: tool.name().to_string(),
3970 description: tool.description().to_string(),
3971 })
3972 .collect(),
3973 }
3974 }
3975
3976 fn sub_agents(&self) -> &[Arc<dyn Agent>] {
3977 &self.sub_agents
3978 }
3979
3980 fn allows_transfer_to_parent(&self) -> bool {
3981 !self.disallow_transfer_to_parent
3982 }
3983
3984 fn allows_transfer_to_peers(&self) -> bool {
3985 !self.disallow_transfer_to_peers
3986 }
3987
3988 async fn close(&self) {
3989 for toolset in &self.toolsets {
3990 toolset.close().await;
3991 }
3992 #[cfg(feature = "enhanced-plugins")]
3993 if let Some(manager) = &self.enhanced_plugin_manager {
3994 manager.close().await;
3995 }
3996 for agent in &self.sub_agents {
3997 agent.close().await;
3998 }
3999 }
4000
4001 async fn prewarm(&self) -> Result<()> {
4004 self.model.prewarm().await?;
4005 for agent in &self.sub_agents {
4006 agent.prewarm().await?;
4007 }
4008 Ok(())
4009 }
4010
4011 fn capabilities(&self) -> adk_core::AgentCapabilities {
4012 adk_core::AgentCapabilities {
4013 runtime_tools: true,
4014 handoff: true,
4015 relationship_confirmation: true,
4016 checkpoint_resume: false,
4017 shared_state: true,
4018 invocation_metadata: true,
4019 }
4020 }
4021
4022 async fn screen_user_input(&self, content: &Content) -> Result<Option<Content>> {
4023 let own = if self.input_guardrails.is_empty() {
4024 None
4025 } else {
4026 Some(
4027 enforce_guardrails(self.input_guardrails.as_ref(), content, Phase::Input)
4028 .await?
4029 .content,
4030 )
4031 };
4032 let below =
4033 adk_core::screen_user_input_with(&self.sub_agents, own.as_ref().unwrap_or(content))
4034 .await?;
4035 Ok(below.or(own))
4036 }
4037
4038 #[adk_telemetry::instrument(
4039 skip(self, ctx),
4040 fields(
4041 agent.name = %self.name,
4042 agent.description = %self.description,
4043 invocation.id = %ctx.invocation_id(),
4044 user.id = %ctx.user_id(),
4045 session.id = %ctx.session_id()
4046 )
4047 )]
4048 async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<adk_core::EventStream> {
4049 adk_telemetry::info!("Starting agent execution");
4050 let starts_run = ctx.agent_name() == self.name;
4053 let ctx = crate::acting_agent_context::ActingAgentContext::scope(ctx, &self.name);
4055 let ctx = Self::apply_input_guardrails(ctx, self.input_guardrails.clone()).await?;
4056
4057 let agent_name = self.name.clone();
4058 let invocation_id = ctx.invocation_id().to_string();
4059 let model = self.model.clone();
4060 let prompt_config = PromptConfig::from_agent(self);
4061 let tool_setup = ToolSetup::from_agent(self);
4062 let output_key = self.output_key.clone();
4063 let output_max_retries = self.output_max_retries;
4064 let generate_content_config = self.generate_content_config.clone();
4065 let max_iterations = self.max_iterations;
4066 let tool_timeout = self.tool_timeout;
4067 let expose_tool_error_messages = self.expose_tool_error_messages;
4068 let before_agent_callbacks = self.before_callbacks.clone();
4070 let after_agent_callbacks = self.after_callbacks.clone();
4071 let history_processors = self.history_processors.clone();
4072 let before_model_callbacks = self.before_model_callbacks.clone();
4073 let after_model_callbacks = self.after_model_callbacks.clone();
4074 let before_tool_callbacks = self.before_tool_callbacks.clone();
4075 let after_tool_callbacks = self.after_tool_callbacks.clone();
4076 let on_tool_error_callbacks = self.on_tool_error_callbacks.clone();
4077 let after_tool_callbacks_full = self.after_tool_callbacks_full.clone();
4078 let default_retry_budget = self.default_retry_budget.clone();
4079 let tool_retry_budgets = self.tool_retry_budgets.clone();
4080 let circuit_breaker_threshold = self.circuit_breaker_threshold;
4081 let tool_confirmation_policy = self.tool_confirmation_policy.clone();
4082 let tool_guardrails = Arc::clone(&self.tool_guardrails);
4083 let output_guardrails = self.output_guardrails.clone();
4084 let agent_tool_execution_strategy = self.tool_execution_strategy;
4085 let parallelize_agent_delegations = self.parallelize_agent_delegations;
4086 #[cfg(feature = "enhanced-plugins")]
4087 let enhanced_plugin_manager = self.enhanced_plugin_manager.clone();
4088 let mut hook_callbacks = HookCallbacks::new(&ctx.run_config().invocation_hooks);
4090 let hook_before_agent = std::mem::take(&mut hook_callbacks.before_agent);
4092 let hook_after_agent = Arc::new(std::mem::take(&mut hook_callbacks.after_agent));
4093 let stage_ctx = ctx.clone();
4094 let stage_invocation_id = invocation_id.clone();
4095 let stage_agent_name = agent_name.clone();
4096 let stage_output_key = output_key.clone();
4097 let structured_output = self.output_schema.is_some();
4098
4099 let body: adk_core::EventStream = Box::pin(stream! {
4103 let mut conversation_history = match prompt_config
4105 .prepare_conversation(&ctx, &agent_name)
4106 .await
4107 {
4108 Ok(history) => history,
4109 Err(error) => {
4110 yield Err(error);
4111 return;
4112 }
4113 };
4114
4115 let resolved_tools = match tool_setup.resolve(&ctx).await {
4116 Ok(tools) => tools,
4117 Err(error) => {
4118 yield Err(error);
4119 return;
4120 }
4121 };
4122 let mut tool_map = resolved_tools.map;
4123 let mut tool_declarations = resolved_tools.declarations;
4124 let mut valid_transfer_targets = resolved_tools.transfer_targets;
4125 if let Some(guidance) = resolved_tools.transfer_guidance {
4127 let at = conversation_history
4128 .iter()
4129 .position(|content| content.role != "system")
4130 .unwrap_or(conversation_history.len());
4131 conversation_history.insert(at, Content::new("system").with_text(guidance));
4132 }
4133
4134 let mut circuit_breaker_state = circuit_breaker_threshold.map(CircuitBreakerState::new);
4137
4138 let mut last_interaction_id: Option<String> = None;
4147
4148 let budget_tracker = ctx.run_config().budget_tracker.clone();
4150 let mut builtin_governor = adk_core::BuiltinToolGovernor::new();
4153
4154 let mut resumed_calls = Vec::<PendingToolCall>::new();
4160 let mut ends_here = false;
4163 let mut steering_due = false;
4165 {
4166 let gate = ToolGate::for_context(ctx.as_ref());
4167 for held in ctx.session().held_tool_calls(&agent_name, ctx.branch()) {
4168 let Some(function_call_id) = held.request.function_call_id.clone() else {
4169 continue;
4170 };
4171 match adk_core::confirmation_decision_available(&gate, &held.request).await {
4172 Ok(true) => match resumed_calls
4176 .iter_mut()
4177 .find(|resumed| resumed.function_call_id == function_call_id)
4178 {
4179 Some(resumed) => resumed.resumes = Some(held.request),
4180 None => resumed_calls.push(PendingToolCall {
4181 index: resumed_calls.len(),
4182 name: held.name,
4183 args: held.args,
4184 id: held.id,
4185 function_call_id,
4186 resumes: Some(held.request),
4187 }),
4188 },
4189 Ok(false) => {}
4190 Err(error) => {
4191 yield Err(error);
4192 return;
4193 }
4194 }
4195 }
4196 }
4197 let mut retrieved: Vec<adk_core::GroundingSource> = Vec::new();
4199 if !resumed_calls.is_empty() {
4200 if ctx.is_cancelled() {
4201 return;
4202 }
4203 if let Some(tracker) = budget_tracker.as_ref()
4206 && let Err(exceeded) = tracker.begin_tool_calls(resumed_calls.len() as u64)
4207 {
4208 yield Err(exceeded.into());
4209 return;
4210 }
4211 tracing::info!(
4212 agent.name = %agent_name,
4213 tool.calls = resumed_calls.len(),
4214 "resuming tool calls held for confirmation"
4215 );
4216 let strategy = ToolDispatchMode::resolve(
4217 agent_tool_execution_strategy.unwrap_or(ToolExecutionStrategy::Sequential),
4218 parallelize_agent_delegations,
4219 );
4220 let cb_mutex = std::sync::Mutex::new(circuit_breaker_state.take());
4221 let concurrency_manager =
4222 adk_core::ToolConcurrencyManager::new(&ctx.run_config().tool_concurrency);
4223 let (progress_tx, mut progress_rx) =
4224 tokio::sync::mpsc::channel::<Event>(TOOL_PROGRESS_CAPACITY);
4225 let progress_overflow = ProgressOverflow::default();
4226 let executor = ToolExecutor {
4227 ctx: ctx.clone(),
4228 agent_name: &agent_name,
4229 tool_map: &tool_map,
4230 tool_retry_budgets: &tool_retry_budgets,
4231 default_retry_budget: &default_retry_budget,
4232 output_guardrails: output_guardrails.as_ref(),
4233 before_tool_callbacks: &before_tool_callbacks,
4234 after_tool_callbacks: &after_tool_callbacks,
4235 after_tool_callbacks_full: &after_tool_callbacks_full,
4236 on_tool_error_callbacks: &on_tool_error_callbacks,
4237 hook_callbacks: &hook_callbacks,
4238 tool_confirmation_policy: &tool_confirmation_policy,
4239 tool_guardrails: tool_guardrails.as_ref(),
4240 cb_mutex: &cb_mutex,
4241 invocation_id: &invocation_id,
4242 concurrency_manager: &concurrency_manager,
4243 progress_tx,
4244 progress_overflow: progress_overflow.clone(),
4245 tool_timeout,
4246 expose_tool_error_messages,
4247 approval_failed: tokio::sync::watch::channel(false).0,
4248 halted_batches: Default::default(),
4249 #[cfg(feature = "enhanced-plugins")]
4250 enhanced_plugin_manager: &enhanced_plugin_manager,
4251 };
4252 let mut results = {
4253 let dispatch = executor.dispatch(strategy, resumed_calls);
4254 tokio::pin!(dispatch);
4255 let results = loop {
4256 tokio::select! {
4257 biased;
4258 Some(progress_event) = progress_rx.recv() => {
4259 yield Ok(progress_event);
4260 }
4261 done = &mut dispatch => break done,
4262 }
4263 };
4264 while let Ok(progress_event) = progress_rx.try_recv() {
4265 yield Ok(progress_event);
4266 }
4267 let markers = std::mem::take(
4268 &mut *progress_overflow.lock().unwrap_or_else(std::sync::PoisonError::into_inner),
4269 );
4270 for marker in markers {
4271 yield Ok(marker);
4272 }
4273 match results {
4274 Ok(results) => results,
4275 Err(error) => {
4276 yield Err(error);
4277 return;
4278 }
4279 }
4280 };
4281 results.sort_by_key(|r| r.index);
4282 drop(executor);
4283 circuit_breaker_state = cb_mutex.into_inner().unwrap_or_else(|e| e.into_inner());
4284
4285 if let Some(tracker) = budget_tracker.as_ref() {
4287 let held = results.iter().filter(|result| result.pending.is_some()).count();
4288 tracker.release_tool_calls(held as u64);
4289 }
4290 let mut held_again = Vec::new();
4291 for result in results {
4292 if result.escalate_or_skip {
4293 if ctx.user_content().carries_user_input() {
4296 yield Err(adk_core::AdkError::new(
4297 adk_core::ErrorComponent::Agent,
4298 adk_core::ErrorCategory::InvalidInput,
4299 "agent.resume_ended_turn",
4300 "a resumed tool call ended the turn, so the message sent with \
4301 this run is saved but was not answered; run again with an \
4302 empty message to answer it, or resume held calls with an \
4303 empty message before sending a new one",
4304 ));
4305 return;
4306 }
4307 ends_here = true;
4308 break;
4309 }
4310 held_again.extend(result.pending);
4311 retrieved.extend(result.actions.grounding_sources);
4312 let _ = adk_core::supersede_pending_responses(
4315 &mut conversation_history,
4316 result.content,
4317 );
4318 }
4319 if !ends_here && !held_again.is_empty() {
4320 for request in held_again {
4321 yield Ok(confirmation_event(&invocation_id, &agent_name, request));
4322 }
4323 ends_here = true;
4324 }
4325
4326 if !ends_here {
4327 let refreshed_tools = match tool_setup.resolve(&ctx).await {
4328 Ok(tools) => tools,
4329 Err(error) => {
4330 yield Err(error);
4331 return;
4332 }
4333 };
4334 tool_map = refreshed_tools.map;
4335 tool_declarations = refreshed_tools.declarations;
4336 valid_transfer_targets = refreshed_tools.transfer_targets;
4337 steering_due = true;
4338 }
4339 }
4340
4341 if starts_run
4347 && let Some(requested) = ctx.run_config().requested_call.as_ref()
4348 && !crate::requested_call::taken(ctx.as_ref(), requested)
4349 {
4350 if let Some(reason) =
4351 crate::requested_call::refusal(ctx.as_ref(), &tool_map, requested)
4352 {
4353 for event in crate::requested_call::refusal_events(
4354 ctx.as_ref(),
4355 &agent_name,
4356 requested,
4357 &reason,
4358 ) {
4359 yield Ok(event);
4360 }
4361 return;
4362 }
4363 for event in crate::requested_call::asked_events(ctx.as_ref(), &agent_name, requested) {
4364 yield Ok(event);
4365 }
4366 let cb_mutex = std::sync::Mutex::new(circuit_breaker_state.take());
4367 let concurrency_manager =
4368 adk_core::ToolConcurrencyManager::new(&ctx.run_config().tool_concurrency);
4369 let (progress_tx, mut progress_rx) =
4370 tokio::sync::mpsc::channel::<Event>(TOOL_PROGRESS_CAPACITY);
4371 let progress_overflow = ProgressOverflow::default();
4372 let executor = ToolExecutor {
4373 ctx: ctx.clone(),
4374 agent_name: &agent_name,
4375 tool_map: &tool_map,
4376 tool_retry_budgets: &tool_retry_budgets,
4377 default_retry_budget: &default_retry_budget,
4378 output_guardrails: output_guardrails.as_ref(),
4379 before_tool_callbacks: &before_tool_callbacks,
4380 after_tool_callbacks: &after_tool_callbacks,
4381 after_tool_callbacks_full: &after_tool_callbacks_full,
4382 on_tool_error_callbacks: &on_tool_error_callbacks,
4383 hook_callbacks: &hook_callbacks,
4384 tool_confirmation_policy: &tool_confirmation_policy,
4385 tool_guardrails: tool_guardrails.as_ref(),
4386 cb_mutex: &cb_mutex,
4387 invocation_id: &invocation_id,
4388 concurrency_manager: &concurrency_manager,
4389 progress_tx,
4390 progress_overflow: progress_overflow.clone(),
4391 tool_timeout,
4392 expose_tool_error_messages,
4393 approval_failed: tokio::sync::watch::channel(false).0,
4394 halted_batches: Default::default(),
4395 #[cfg(feature = "enhanced-plugins")]
4396 enhanced_plugin_manager: &enhanced_plugin_manager,
4397 };
4398 let call = PendingToolCall {
4399 index: 0,
4400 name: requested.tool_name.clone(),
4401 args: requested.args.clone(),
4402 id: Some(requested.function_call_id.clone()),
4403 function_call_id: requested.function_call_id.clone(),
4404 resumes: None,
4405 };
4406 let results = {
4407 let dispatch = executor.dispatch(ToolDispatchMode::Sequential, vec![call]);
4408 tokio::pin!(dispatch);
4409 let results = loop {
4410 tokio::select! {
4411 biased;
4412 Some(progress_event) = progress_rx.recv() => {
4413 yield Ok(progress_event);
4414 }
4415 done = &mut dispatch => break done,
4416 }
4417 };
4418 while let Ok(progress_event) = progress_rx.try_recv() {
4419 yield Ok(progress_event);
4420 }
4421 let markers = std::mem::take(
4422 &mut *progress_overflow.lock().unwrap_or_else(std::sync::PoisonError::into_inner),
4423 );
4424 for marker in markers {
4425 yield Ok(marker);
4426 }
4427 results
4428 };
4429 match results {
4430 Ok(results) => {
4431 for request in results.into_iter().filter_map(|result| result.pending) {
4432 yield Ok(crate::requested_call::held_event(
4433 ctx.as_ref(),
4434 &agent_name,
4435 requested,
4436 request,
4437 ));
4438 }
4439 }
4440 Err(error) => yield Err(error),
4441 }
4442 return;
4443 }
4444 if ends_here {
4445 return;
4446 }
4447
4448 let mut iteration = 0;
4450 let mut schema_retry_count: usize = 0;
4451 let mut reported_prompt_tokens: Option<u64> = None;
4454 let mut rejected_as_too_long: Option<adk_core::AdkError> = None;
4457 let mut resent_after_compaction = false;
4458
4459 'model_calls: loop {
4460 if ctx.is_cancelled() {
4463 tracing::info!(agent.name = %agent_name, "invocation cancelled — stopping agent loop");
4464 return;
4465 }
4466 if let Err(error) = ctx.run_config().check_governance() {
4468 yield Err(error);
4469 return;
4470 }
4471 iteration += 1;
4472 if iteration > max_iterations {
4473 yield Err(adk_core::AdkError::agent(
4474 format!("Max iterations ({max_iterations}) exceeded")
4475 ));
4476 return;
4477 }
4478
4479 if std::mem::take(&mut steering_due)
4485 && let Some(inbox) = ctx.steering_inbox()
4486 {
4487 for message in inbox.drain() {
4488 tracing::debug!(
4489 agent.name = %agent_name,
4490 steer.id = %message.marker.steer_id,
4491 "steering message added to the history"
4492 );
4493 yield Ok(message.to_event(&invocation_id, ctx.branch()));
4494 conversation_history.push(message.content);
4495 }
4496 }
4497
4498 let config = build_generation_config(
4499 generate_content_config.as_ref(),
4500 prompt_config.output_schema.as_ref(),
4501 ctx.run_config().cached_content.as_deref(),
4502 );
4503
4504 let history_len = conversation_history.len();
4507 for processor in history_processors.iter() {
4508 match processor(
4509 ctx.clone() as Arc<dyn CallbackContext>,
4510 std::mem::take(&mut conversation_history),
4511 )
4512 .await
4513 {
4514 Ok(history) => conversation_history = history,
4515 Err(error) => {
4516 yield Err(error);
4517 return;
4518 }
4519 }
4520 }
4521 if conversation_history.len() != history_len {
4522 tracing::debug!(
4523 agent.name = %agent_name,
4524 history.before = history_len,
4525 history.after = conversation_history.len(),
4526 "history processors rewrote the history"
4527 );
4528 }
4529
4530 let rejected = rejected_as_too_long.take();
4534 if let Some(compactor) = ctx.run_config().history_compactor.clone() {
4535 let preamble = conversation_history
4536 .iter()
4537 .take_while(|content| content.role == "system")
4538 .count();
4539 let trigger = if rejected.is_some() {
4540 adk_core::CompactionTrigger::ContextLimitExceeded
4541 } else {
4542 adk_core::CompactionTrigger::BeforeModelCall
4543 };
4544 let request = adk_core::HistoryCompactionRequest::new(
4545 &conversation_history[preamble..],
4546 trigger,
4547 )
4548 .with_preamble(&conversation_history[..preamble])
4549 .with_reported_prompt_tokens(reported_prompt_tokens)
4550 .with_tools(&tool_declarations)
4551 .with_config(config.as_ref());
4552 match compactor.compact(ctx.clone(), model.clone(), request).await {
4553 Ok(Some(compacted)) => {
4554 conversation_history.truncate(preamble);
4555 conversation_history.extend(compacted.history);
4556 reported_prompt_tokens = None;
4557 if let Some(event) = compacted.event {
4558 yield Ok(event);
4559 }
4560 }
4561 Ok(None) => {
4562 if let Some(error) = rejected {
4564 yield Err(error);
4565 return;
4566 }
4567 }
4568 Err(error) => {
4569 yield Err(error);
4570 return;
4571 }
4572 }
4573 }
4574
4575 let mut contents = crate::requested_call::for_model(conversation_history.clone());
4578 contents.iter_mut().for_each(Content::strip_generated_call_ids);
4579 contents
4582 .iter_mut()
4583 .filter(|content| !matches!(content.role.as_str(), "model" | "assistant"))
4584 .for_each(adk_core::history::strip_native);
4585 let mut request = LlmRequest {
4586 model: model.name().to_string(),
4587 contents,
4588 tools: tool_declarations.clone(),
4589 config,
4590 previous_response_id: last_interaction_id.clone(),
4597 };
4598
4599 if let Err(error) = tool_setup.process_llm_request(&ctx, &mut request).await {
4600 yield Err(error);
4601 return;
4602 }
4603
4604 #[cfg(feature = "enhanced-plugins")]
4608 let (request, model_response_override_from_plugin) = {
4609 if let Some(epm) = &enhanced_plugin_manager {
4610 match epm.run_before_model_call(request, ctx.clone() as Arc<dyn CallbackContext>).await {
4611 Ok(BeforeModelCallResult::Continue(modified_request)) => {
4612 (modified_request, None)
4613 }
4614 Ok(BeforeModelCallResult::ShortCircuit(response)) => {
4615 (LlmRequest::new("", vec![]), Some(response))
4617 }
4618 Err(e) => {
4619 yield Err(e);
4620 return;
4621 }
4622 }
4623 } else {
4624 (request, None)
4625 }
4626 };
4627 #[cfg(not(feature = "enhanced-plugins"))]
4628 let model_response_override_from_plugin: Option<LlmResponse> = None;
4629
4630 let mut current_request = request;
4633 let mut model_response_override = model_response_override_from_plugin;
4634 if model_response_override.is_none() {
4635 let record_payloads = ctx.run_config().record_payloads;
4639 for callback in
4640 hook_callbacks.before_model.iter().chain(before_model_callbacks.iter())
4641 {
4642 let skipped_request = record_payloads.then(|| current_request.clone());
4643 let request =
4644 std::mem::replace(&mut current_request, LlmRequest::new("", vec![]));
4645 match callback(ctx.clone() as Arc<dyn CallbackContext>, request).await {
4646 Ok(BeforeModelResult::Continue(modified_request)) => {
4647 current_request = modified_request;
4649 }
4650 Ok(BeforeModelResult::Skip(response)) => {
4651 if let Some(skipped_request) = skipped_request {
4653 current_request = skipped_request;
4654 }
4655 model_response_override = Some(response);
4656 break;
4657 }
4658 Err(e) => {
4659 yield Err(e);
4661 return;
4662 }
4663 }
4664 }
4665 }
4666 let mut request = current_request;
4667 let withheld_builtins = if model_response_override.is_none() {
4670 let gate = ToolGate::for_context(ctx.as_ref());
4671 match builtin_governor.govern(&gate, &mut request.tools, &tool_map).await {
4672 Ok(withheld) => withheld,
4673 Err(error) => {
4674 yield Err(error);
4675 return;
4676 }
4677 }
4678 } else {
4679 Vec::new()
4680 };
4681 let withheld_builtins = (!withheld_builtins.is_empty())
4682 .then(|| serde_json::to_string(&withheld_builtins).unwrap_or_default());
4683 let request = request;
4684
4685 let mut accumulated_content: Option<Content> = None;
4687 let mut final_provider_metadata: Option<serde_json::Value> = None;
4688
4689 let produced_by_model = model_response_override.is_none();
4690 let mut last_turn_finish_reason = None;
4691 if let Some(cached_response) = model_response_override {
4692 accumulated_content = cached_response.content.clone();
4695 final_provider_metadata = cached_response.provider_metadata.clone();
4696 normalize_option_content(&mut accumulated_content);
4697 let mut output_warnings = Warnings::default();
4700 let mut citations = cached_response.citation_metadata.clone();
4701 if let Some(content) = accumulated_content.take() {
4702 let preamble = content
4703 .parts
4704 .iter()
4705 .any(|part| matches!(part, Part::FunctionCall { .. }))
4706 || Self::continues_turn(final_provider_metadata.as_ref());
4707 let shown_citations = (!preamble)
4708 .then(|| answer_citations(&content, &retrieved, citations.as_ref()))
4709 .flatten();
4710 let grounding =
4711 Grounding { retrieved: &retrieved, citations: shown_citations.as_ref() };
4712 let screened =
4713 screen_model_output(output_guardrails.as_ref(), content, preamble, grounding).await?;
4714 if !preamble {
4715 citations =
4716 answer_citations(&screened.content, &retrieved, citations.as_ref());
4717 }
4718 accumulated_content = Some(screened.content);
4719 output_warnings = screened.warnings;
4720 }
4721
4722 let mut cached_event = Event::new(&invocation_id);
4723 cached_event.author = agent_name.clone();
4724 output_warnings.record_on(&mut cached_event);
4725 cached_event.llm_response.content = accumulated_content.clone();
4726 cached_event.llm_response.turn_complete = cached_response.turn_complete;
4727 cached_event.llm_response.citation_metadata = citations;
4728 cached_event.llm_response.provider_metadata = cached_response.provider_metadata.clone();
4729 cached_event.llm_response.interaction_id = cached_response.interaction_id.clone();
4731 if cached_response.interaction_id.is_some() {
4732 last_interaction_id = cached_response.interaction_id.clone();
4733 }
4734 cached_event.llm_request = Some(trace_json_payload(
4735 &request,
4736 ctx.run_config().record_payloads,
4737 ctx.run_config().trace_payload_max_bytes,
4738 ));
4739 let mut debug_response = cached_response.clone();
4741 if !output_guardrails.is_empty() {
4742 debug_response.content = accumulated_content.clone();
4743 }
4744 cached_event.provider_metadata.insert("gcp.vertex.agent.llm_response".to_string(), serde_json::to_string(&debug_response).unwrap_or_default());
4745
4746 if let Some(ref content) = accumulated_content {
4748 cached_event.long_running_tool_ids =
4749 collect_long_running_tool_ids(&tool_map, content);
4750 }
4751
4752 yield Ok(cached_event);
4753 } else {
4754 let trace_request_json = trace_json_payload(
4756 &request,
4757 ctx.run_config().record_payloads,
4758 ctx.run_config().trace_payload_max_bytes,
4759 );
4760
4761 let llm_ts = std::time::SystemTime::now()
4763 .duration_since(std::time::UNIX_EPOCH)
4764 .unwrap_or_default()
4765 .as_nanos();
4766 let llm_event_id = format!("{}_llm_{}", invocation_id, llm_ts);
4767 let llm_span = tracing::info_span!(
4768 "call_llm",
4769 "gcp.vertex.agent.event_id" = %llm_event_id,
4770 "gcp.vertex.agent.invocation_id" = %invocation_id,
4771 "gcp.vertex.agent.session_id" = %ctx.session_id(),
4772 "gen_ai.conversation.id" = %ctx.session_id(),
4773 "gcp.vertex.agent.llm_request" = %trace_request_json,
4774 "gcp.vertex.agent.llm_response" = tracing::field::Empty );
4776 use adk_core::StreamingMode;
4789 let streaming_mode = ctx.run_config().streaming_mode;
4790 let should_stream_to_client = matches!(streaming_mode, StreamingMode::SSE | StreamingMode::Bidi)
4791 && output_guardrails.is_empty();
4792
4793 let call_scope = adk_core::ModelCallScope::for_run(
4798 ctx.run_config(),
4799 ctx.app_name(),
4800 &agent_name,
4801 );
4802 let call_metered = call_scope.budget().is_some();
4803 let failed_request = ctx
4805 .run_config()
4806 .invocation_hooks
4807 .iter()
4808 .any(|hook| hook.handles_model_errors())
4809 .then(|| request.clone());
4810 let stream_model =
4814 matches!(streaming_mode, StreamingMode::SSE | StreamingMode::Bidi);
4815 let mut response_stream = match call_scope
4816 .generate(model.as_ref(), request, stream_model)
4817 .instrument(llm_span.clone())
4818 .await
4819 {
4820 Ok(stream) => stream,
4821 Err(error) => {
4822 llm_span.in_scope(|| {
4825 tracing::warn!(
4826 agent.name = %agent_name,
4827 error = %error.diagnostics(),
4828 error.message = %traced_message(ctx.run_config(), &error.message),
4829 "model call failed"
4830 )
4831 });
4832 if ctx.run_config().history_compactor.is_some()
4834 && adk_core::intra_compaction::is_context_limit_error(&error)
4835 && !std::mem::replace(&mut resent_after_compaction, true)
4836 {
4837 rejected_as_too_long = Some(error);
4838 iteration -= 1;
4839 continue 'model_calls;
4840 }
4841 match recover_model_error(&ctx, failed_request.as_ref(), &error).await {
4844 Ok(Some(response)) => {
4845 Box::pin(futures::stream::iter([Ok(response)]))
4846 as adk_core::LlmResponseStream
4847 }
4848 Ok(None) => {
4849 yield Err(error);
4850 return;
4851 }
4852 Err(hook_error) => {
4853 yield Err(hook_error);
4854 return;
4855 }
4856 }
4857 }
4858 };
4859
4860 use futures::StreamExt;
4861
4862 let mut last_chunk: Option<LlmResponse> = None;
4864
4865 while let Some(chunk_result) =
4867 response_stream.next().instrument(llm_span.clone()).await
4868 {
4869 if ctx.is_cancelled() {
4873 llm_span.in_scope(|| {
4874 tracing::info!(agent.name = %agent_name, "invocation cancelled during LLM streaming")
4875 });
4876 return;
4877 }
4878 let mut chunk = match chunk_result {
4879 Ok(c) => c,
4880 Err(e) => {
4881 llm_span.in_scope(|| {
4882 tracing::warn!(
4883 agent.name = %agent_name,
4884 error = %e.diagnostics(),
4885 error.message = %traced_message(ctx.run_config(), &e.message),
4886 "model stream failed"
4887 )
4888 });
4889 if last_chunk.is_none()
4892 && ctx.run_config().history_compactor.is_some()
4893 && adk_core::intra_compaction::is_context_limit_error(&e)
4894 && !std::mem::replace(&mut resent_after_compaction, true)
4895 {
4896 rejected_as_too_long = Some(e);
4897 iteration -= 1;
4898 continue 'model_calls;
4899 }
4900 match recover_model_error(&ctx, failed_request.as_ref(), &e).await {
4903 Ok(Some(response)) => {
4904 accumulated_content = None;
4905 response_stream = Box::pin(futures::stream::iter([Ok(response)]));
4906 continue;
4907 }
4908 Ok(None) => {
4909 yield Err(e);
4910 return;
4911 }
4912 Err(hook_error) => {
4913 yield Err(hook_error);
4914 return;
4915 }
4916 }
4917 }
4918 };
4919 for callback in
4922 hook_callbacks.after_model.iter().chain(after_model_callbacks.iter())
4923 {
4924 match callback(ctx.clone() as Arc<dyn CallbackContext>, chunk.clone())
4925 .instrument(llm_span.clone())
4926 .await
4927 {
4928 Ok(Some(modified_chunk)) => {
4929 chunk = replace_chunk(&chunk, modified_chunk);
4930 break;
4931 }
4932 Ok(None) => {
4933 continue;
4935 }
4936 Err(e) => {
4937 yield Err(e);
4939 return;
4940 }
4941 }
4942 }
4943
4944 normalize_option_content(&mut chunk.content);
4945
4946 if let Some(chunk_content) = chunk.content.clone() {
4948 if !chunk.partial && chunk.provider_metadata.as_ref()
4949 .and_then(|metadata| metadata.get("content_complete"))
4950 .and_then(serde_json::Value::as_bool) == Some(true)
4951 {
4952 accumulated_content = Some(chunk_content);
4953 } else if let Some(ref mut acc) = accumulated_content {
4954 append_streamed_parts(&mut acc.parts, chunk_content.parts);
4955 } else {
4956 accumulated_content = Some(chunk_content);
4957 }
4958 }
4959 if !chunk.partial {
4962 normalize_option_content(&mut accumulated_content);
4963 }
4964
4965 if should_stream_to_client {
4967 let long_running_tool_ids = chunk
4968 .content
4969 .as_ref()
4970 .map(|content| collect_long_running_tool_ids(&tool_map, content))
4971 .unwrap_or_default();
4972 let mut event = build_partial_llm_event(
4973 &llm_event_id,
4974 &invocation_id,
4975 &agent_name,
4976 &trace_request_json,
4977 &chunk,
4978 long_running_tool_ids,
4979 );
4980 if call_metered {
4981 event.provider_metadata.insert(
4982 adk_core::BUDGET_RECORDED_KEY.to_string(),
4983 "true".to_string(),
4984 );
4985 }
4986 if !chunk.partial
4987 && let Some(withheld) = &withheld_builtins
4988 {
4989 event.provider_metadata.insert(
4990 adk_core::BUILTIN_TOOLS_WITHHELD_KEY.to_string(),
4991 withheld.clone(),
4992 );
4993 }
4994 if !chunk.partial {
4998 event.llm_response.content = accumulated_content.clone();
4999 if let Some(metadata) = event.llm_response.provider_metadata
5000 .get_or_insert_with(|| serde_json::json!({}))
5001 .as_object_mut()
5002 {
5003 metadata.insert("content_complete".into(), true.into());
5004 }
5005 }
5006 yield Ok(event);
5007 }
5008
5009 if chunk.interaction_id.is_some() {
5013 last_interaction_id = chunk.interaction_id.clone();
5014 }
5015
5016 if let Some(usage) = &chunk.usage_metadata
5017 && usage.prompt_token_count > 0
5018 {
5019 reported_prompt_tokens = Some(usage.prompt_token_count as u64);
5020 }
5021 if chunk.finish_reason.is_some() {
5022 last_turn_finish_reason = chunk.finish_reason;
5023 }
5024 last_chunk = Some(chunk.clone());
5026
5027 if chunk.turn_complete {
5029 break;
5030 }
5031 }
5032
5033 if let Some(last) = &last_chunk {
5034 final_provider_metadata = last.provider_metadata.clone();
5035 }
5036 resent_after_compaction = false;
5037 normalize_option_content(&mut accumulated_content);
5038
5039 if should_stream_to_client
5042 && let Some(last) = last_chunk.as_ref().filter(|chunk| chunk.partial)
5043 && accumulated_content.is_some()
5044 {
5045 let mut closing = last.clone();
5046 closing.partial = false;
5047 closing.content = accumulated_content.clone();
5048 closing.turn_complete = !closing
5049 .content
5050 .as_ref()
5051 .is_some_and(|content| {
5052 content.parts.iter().any(|part| matches!(part, Part::FunctionCall { .. }))
5053 });
5054 let long_running_tool_ids = closing
5055 .content
5056 .as_ref()
5057 .map(|content| collect_long_running_tool_ids(&tool_map, content))
5058 .unwrap_or_default();
5059 let mut event = build_partial_llm_event(
5060 &llm_event_id,
5061 &invocation_id,
5062 &agent_name,
5063 &trace_request_json,
5064 &closing,
5065 long_running_tool_ids,
5066 );
5067 if call_metered {
5068 event.provider_metadata.insert(
5069 adk_core::BUDGET_RECORDED_KEY.to_string(),
5070 "true".to_string(),
5071 );
5072 }
5073 if let Some(withheld) = &withheld_builtins {
5074 event.provider_metadata.insert(
5075 adk_core::BUILTIN_TOOLS_WITHHELD_KEY.to_string(),
5076 withheld.clone(),
5077 );
5078 }
5079 if let Some(metadata) = event.llm_response.provider_metadata
5080 .get_or_insert_with(|| serde_json::json!({}))
5081 .as_object_mut()
5082 {
5083 metadata.insert("content_complete".into(), true.into());
5084 }
5085 yield Ok(event);
5086 }
5087 drop(response_stream);
5090 let metered = call_metered;
5091
5092 if !should_stream_to_client {
5094 let mut output_warnings = Warnings::default();
5097 let provider_citations =
5098 last_chunk.as_ref().and_then(|chunk| chunk.citation_metadata.clone());
5099 let mut citations = provider_citations.clone();
5100 if let Some(content) = accumulated_content.take() {
5101 let preamble = content
5102 .parts
5103 .iter()
5104 .any(|part| matches!(part, Part::FunctionCall { .. }))
5105 || Self::continues_turn(final_provider_metadata.as_ref());
5106 let shown_citations = (!preamble)
5107 .then(|| {
5108 answer_citations(&content, &retrieved, provider_citations.as_ref())
5109 })
5110 .flatten();
5111 let grounding = Grounding {
5112 retrieved: &retrieved,
5113 citations: shown_citations.as_ref(),
5114 };
5115 let screened = screen_model_output(
5116 output_guardrails.as_ref(),
5117 content,
5118 preamble,
5119 grounding,
5120 )
5121 .instrument(llm_span.clone())
5122 .await?;
5123 if !preamble {
5124 citations = answer_citations(
5125 &screened.content,
5126 &retrieved,
5127 provider_citations.as_ref(),
5128 );
5129 }
5130 accumulated_content = Some(screened.content);
5131 output_warnings = screened.warnings;
5132 }
5133 if !output_guardrails.is_empty()
5136 && let Some(last) = last_chunk.as_mut()
5137 && last.content.is_some()
5138 {
5139 last.content = accumulated_content.clone();
5140 }
5141
5142 let long_running_tool_ids = accumulated_content
5143 .as_ref()
5144 .map(|content| collect_long_running_tool_ids(&tool_map, content))
5145 .unwrap_or_default();
5146 let mut final_event = build_final_llm_event(
5147 &llm_event_id,
5148 &invocation_id,
5149 &agent_name,
5150 &trace_request_json,
5151 accumulated_content.as_ref(),
5152 last_chunk.as_ref(),
5153 long_running_tool_ids,
5154 );
5155 output_warnings.record_on(&mut final_event);
5156 final_event.llm_response.citation_metadata = citations;
5157 if metered {
5158 final_event.provider_metadata.insert(
5159 adk_core::BUDGET_RECORDED_KEY.to_string(),
5160 "true".to_string(),
5161 );
5162 }
5163 if let Some(withheld) = &withheld_builtins {
5164 final_event.provider_metadata.insert(
5165 adk_core::BUILTIN_TOOLS_WITHHELD_KEY.to_string(),
5166 withheld.clone(),
5167 );
5168 }
5169 yield Ok(final_event);
5170 }
5171
5172 let finish_failure = finish_error(
5187 last_turn_finish_reason,
5188 last_chunk
5189 .as_ref()
5190 .and_then(|last| last.error_message.clone())
5191 .or_else(|| {
5192 accumulated_content.as_ref().map(|content| {
5193 content.parts.iter().filter_map(Part::text).collect::<String>()
5194 })
5195 })
5196 .as_deref(),
5197 last_chunk.as_ref().and_then(|last| last.error_code.as_deref()),
5198 );
5199 if let Some(error) = finish_failure {
5200 llm_span.in_scope(|| {
5201 tracing::error!(
5202 error = %error.diagnostics(),
5203 agent = %agent_name,
5204 "model turn ended without an answer it can act on"
5205 )
5206 });
5207 yield Err(error);
5208 return;
5209 }
5210 if let Some(ref last) = last_chunk
5211 && let Some(ref code) = last.error_code
5212 {
5213 let message = last
5216 .error_message
5217 .as_deref()
5218 .map(adk_core::upstream_excerpt)
5219 .unwrap_or("provider reported a terminal error");
5220 let mut details = adk_core::ErrorDetails::default();
5227 details
5228 .metadata
5229 .insert("provider_error_code".to_string(), serde_json::json!(code));
5230 let provider_error = adk_core::AdkError::new(
5231 adk_core::ErrorComponent::Model,
5232 adk_core::ErrorCategory::Internal,
5233 "model.provider_error",
5234 format!("{code}: {message}"),
5235 )
5236 .with_details(details);
5237 llm_span.in_scope(|| {
5238 tracing::error!(
5239 error = %provider_error.diagnostics(),
5240 error.message = %traced_message(ctx.run_config(), message),
5241 agent = %agent_name,
5242 "model reported a terminal error"
5243 )
5244 });
5245 yield Err(provider_error);
5246 return;
5247 }
5248
5249 if let Some(ref content) = accumulated_content {
5251 let response_json = trace_json_payload(
5252 content,
5253 ctx.run_config().record_payloads,
5254 ctx.run_config().trace_payload_max_bytes,
5255 );
5256 llm_span.record("gcp.vertex.agent.llm_response", &response_json);
5257 }
5258 }
5259
5260 #[cfg(feature = "enhanced-plugins")]
5264 if let Some(epm) = &enhanced_plugin_manager
5265 && let Some(ref content) = accumulated_content {
5266 let response_for_hook = LlmResponse {
5267 content: Some(content.clone()),
5268 provider_metadata: final_provider_metadata.clone(),
5269 ..Default::default()
5270 };
5271 match epm.run_after_model_call(response_for_hook, ctx.clone() as Arc<dyn CallbackContext>).await {
5272 Ok(adk_plugin::AfterModelCallResult::Continue(modified_response)) => {
5273 accumulated_content = modified_response.content;
5274 if modified_response.provider_metadata.is_some() {
5275 final_provider_metadata = modified_response.provider_metadata;
5276 }
5277 }
5278 Err(e) => {
5279 yield Err(e);
5280 return;
5281 }
5282 }
5283 }
5284
5285 let function_call_names: Vec<String> = accumulated_content.as_ref()
5287 .map(|c| c.parts.iter()
5288 .filter_map(|p| {
5289 if let Part::FunctionCall { name, .. } = p {
5290 Some(name.clone())
5291 } else {
5292 None
5293 }
5294 })
5295 .collect())
5296 .unwrap_or_default();
5297
5298 let has_function_calls = !function_call_names.is_empty();
5299 let continues_turn = Self::continues_turn(final_provider_metadata.as_ref());
5300
5301 let all_calls_are_long_running = has_function_calls && function_call_names.iter().all(|name| {
5305 tool_map.get(name)
5306 .map(|t| t.is_long_running())
5307 .unwrap_or(false)
5308 });
5309
5310 if let Some(ref content) = accumulated_content {
5312 conversation_history.push(Self::augment_content_for_history(
5313 content,
5314 final_provider_metadata.as_ref(),
5315 ));
5316 }
5317
5318 if !has_function_calls && continues_turn {
5321 continue;
5322 }
5323
5324 if !has_function_calls {
5325 if produced_by_model
5330 && !accumulated_content.as_ref().is_some_and(has_answer_content)
5331 {
5332 yield Err(empty_response_error(last_turn_finish_reason));
5333 return;
5334 }
5335
5336 if let Some(schema) = &prompt_config.output_schema {
5341 let text = accumulated_content
5342 .as_ref()
5343 .map(|c| {
5344 c.parts
5345 .iter()
5346 .filter_map(|p| {
5347 if let Part::Text { text } = p {
5348 Some(text.as_str())
5349 } else {
5350 None
5351 }
5352 })
5353 .collect::<Vec<_>>()
5354 .join("")
5355 })
5356 .unwrap_or_default();
5357
5358 if !text.is_empty()
5359 && let Err(validation_error) = validate_output_against_schema(&text, schema)
5360 {
5361 if schema_retry_count >= output_max_retries {
5362 yield Err(adk_core::AdkError::agent(format!(
5363 "output schema validation failed after {} attempts",
5364 output_max_retries
5365 )));
5366 return;
5367 }
5368 schema_retry_count += 1;
5369
5370 let correction = format!(
5372 "Your output did not match the required schema. Error: {}. Please produce valid JSON matching the schema.",
5373 validation_error
5374 );
5375 conversation_history.push(Content {
5376 role: "user".to_string(),
5377 parts: vec![Part::Text { text: correction }],
5378 });
5379 continue;
5380 }
5381 }
5382
5383 if let Some(ref output_key) = output_key
5386 && let Some(ref content) = accumulated_content
5387 {
5388 let text_parts =
5390 output_text(content, prompt_config.output_schema.is_some());
5391 if !text_parts.is_empty() {
5392 let mut state_event = Event::new(&invocation_id);
5393 state_event.author = agent_name.clone();
5394 state_event.actions.state_delta.insert(
5395 output_key.clone(),
5396 serde_json::Value::String(text_parts),
5397 );
5398 yield Ok(state_event);
5399 }
5400 }
5401
5402 if let Some(ref content) = accumulated_content {
5405 let response_json = trace_json_payload(
5406 content,
5407 ctx.run_config().record_payloads,
5408 ctx.run_config().trace_payload_max_bytes,
5409 );
5410 tracing::Span::current().record("gcp.vertex.agent.llm_response", &response_json);
5411 }
5412
5413 tracing::info!(agent.name = %agent_name, "Agent execution complete");
5414 break;
5415 }
5416
5417 if let Some(content) = &accumulated_content {
5419 let strategy = ToolDispatchMode::resolve(
5422 agent_tool_execution_strategy.unwrap_or(ToolExecutionStrategy::Sequential),
5423 parallelize_agent_delegations,
5424 );
5425
5426 let fc_parts = collect_function_calls(
5429 content,
5430 &format!("{invocation_id}_{}", uuid::Uuid::new_v4().simple()),
5431 );
5432
5433 let mut transfer_handled = false;
5437 let mut answered_calls = HashSet::new();
5440 for call in &fc_parts {
5441 if call.name == "transfer_to_agent" {
5442 let target_agent = call
5443 .args
5444 .get("agent_name")
5445 .and_then(|value| value.as_str())
5446 .unwrap_or_default()
5447 .to_string();
5448
5449 let valid_target = valid_transfer_targets.iter().any(|n| n == &target_agent);
5450 if !valid_target {
5451 let mut refusal = Part::FunctionResponse {
5452 function_response: FunctionResponseData::new(
5453 call.name.clone(),
5454 serde_json::json!({
5455 "error": format!(
5456 "Agent '{}' not found. Available agents: {:?}",
5457 target_agent, valid_transfer_targets
5458 )
5459 }),
5460 ),
5461 id: call.id.clone(),
5462 annotations: None,
5463 };
5464 refusal.set_tool_result_status(ToolResultStatus::NotRun, None);
5465 let error_content =
5466 Content { role: "function".to_string(), parts: vec![refusal] };
5467 conversation_history.push(error_content.clone());
5468 let mut error_event = Event::new(&invocation_id);
5469 error_event.author = agent_name.clone();
5470 error_event.llm_response.content = Some(error_content);
5471 yield Ok(error_event);
5472 answered_calls.insert(call.index);
5473 continue;
5474 }
5475
5476 let responses = fc_parts
5479 .iter()
5480 .filter(|other| !answered_calls.contains(&other.index))
5481 .map(|other| {
5482 let transfers = other.index == call.index;
5483 let response = if transfers {
5484 serde_json::json!({ "transferred_to": target_agent })
5485 } else {
5486 serde_json::json!({
5487 "error": format!("not run: control transferred to {target_agent}")
5488 })
5489 };
5490 let mut part = Part::FunctionResponse {
5491 function_response: FunctionResponseData::new(
5492 other.name.clone(),
5493 response,
5494 ),
5495 id: other.id.clone(),
5496 annotations: None,
5497 };
5498 if !transfers {
5499 part.set_tool_result_status(ToolResultStatus::NotRun, None);
5500 }
5501 part
5502 })
5503 .collect();
5504 let mut transfer_event = Event::new(&invocation_id);
5505 transfer_event.author = agent_name.clone();
5506 transfer_event.llm_response.content =
5507 Some(Content { role: "function".to_string(), parts: responses });
5508 transfer_event.actions.transfer_to_agent = Some(target_agent);
5509 yield Ok(transfer_event);
5510 transfer_handled = true;
5511 break;
5512 }
5513 }
5514 if transfer_handled {
5515 return;
5516 }
5517
5518 let fc_parts: Vec<_> = fc_parts
5520 .into_iter()
5521 .filter(|call| {
5522 if call.name == "transfer_to_agent" {
5523 return false;
5524 }
5525 if let Some(tool) = tool_map.get(&call.name)
5526 && tool.is_builtin()
5527 {
5528 adk_telemetry::debug!(tool.name = %call.name, "skipping built-in tool execution");
5529 return false;
5530 }
5531 true
5532 })
5533 .collect();
5534
5535 if let Some(tracker) = budget_tracker.as_ref()
5540 && let Err(exceeded) = tracker.begin_tool_calls(fc_parts.len() as u64)
5541 {
5542 let cause = adk_core::AdkError::from(exceeded.clone());
5543 let parts = fc_parts
5544 .iter()
5545 .map(|call| {
5546 let mut part = Part::FunctionResponse {
5547 function_response: FunctionResponseData::new(
5548 call.name.clone(),
5549 serde_json::json!({ "error": format!("not run: {exceeded}") }),
5550 ),
5551 id: call.id.clone(),
5552 annotations: None,
5553 };
5554 part.set_tool_result_status(ToolResultStatus::NotRun, Some(&cause));
5555 part
5556 })
5557 .collect();
5558 let mut budget_event = Event::new(&invocation_id);
5559 budget_event.author = agent_name.clone();
5560 budget_event.llm_response.content =
5561 Some(Content { role: "function".to_string(), parts });
5562 yield Ok(budget_event);
5563 yield Err(exceeded.into());
5564 return;
5565 }
5566
5567 if !fc_parts.is_empty()
5571 && let Some(handler) = ctx.run_config().tool_confirmation_handler.clone()
5572 {
5573 let origins: Vec<Option<adk_core::ToolOrigin>> = fc_parts
5574 .iter()
5575 .map(|call| {
5576 tool_map.get(&call.name).map(|tool| adk_core::ToolOrigin::of(tool.as_ref()))
5577 })
5578 .collect();
5579 let batch: Vec<adk_core::BatchCall<'_>> = fc_parts
5580 .iter()
5581 .zip(&origins)
5582 .map(|(call, origin)| {
5583 let entry = adk_core::BatchCall::new(&call.name, &call.args)
5584 .with_function_call_id(&call.function_call_id);
5585 match origin {
5586 Some(origin) => entry.with_origin(origin),
5587 None => entry,
5588 }
5589 })
5590 .collect();
5591 handler.batch_started(&batch).await;
5592 }
5593
5594 let cb_mutex = std::sync::Mutex::new(circuit_breaker_state.take());
5596
5597 let concurrency_manager = adk_core::ToolConcurrencyManager::new(
5600 &ctx.run_config().tool_concurrency,
5601 );
5602
5603 let (progress_tx, mut progress_rx) =
5608 tokio::sync::mpsc::channel::<Event>(TOOL_PROGRESS_CAPACITY);
5609 let progress_overflow = ProgressOverflow::default();
5610
5611 let executor = ToolExecutor {
5612 ctx: ctx.clone(),
5613 agent_name: &agent_name,
5614 tool_map: &tool_map,
5615 tool_retry_budgets: &tool_retry_budgets,
5616 default_retry_budget: &default_retry_budget,
5617 output_guardrails: output_guardrails.as_ref(),
5618 before_tool_callbacks: &before_tool_callbacks,
5619 after_tool_callbacks: &after_tool_callbacks,
5620 after_tool_callbacks_full: &after_tool_callbacks_full,
5621 on_tool_error_callbacks: &on_tool_error_callbacks,
5622 hook_callbacks: &hook_callbacks,
5623 tool_confirmation_policy: &tool_confirmation_policy,
5624 tool_guardrails: tool_guardrails.as_ref(),
5625 cb_mutex: &cb_mutex,
5626 invocation_id: &invocation_id,
5627 concurrency_manager: &concurrency_manager,
5628 progress_tx: progress_tx.clone(),
5629 progress_overflow: progress_overflow.clone(),
5630 tool_timeout,
5631 expose_tool_error_messages,
5632 approval_failed: tokio::sync::watch::channel(false).0,
5633 halted_batches: Default::default(),
5634 #[cfg(feature = "enhanced-plugins")]
5635 enhanced_plugin_manager: &enhanced_plugin_manager,
5636 };
5637
5638 if ctx.is_cancelled() {
5641 tracing::info!(agent.name = %agent_name, "invocation cancelled before tool dispatch");
5642 return;
5643 }
5644
5645 let mut results = {
5650 let dispatch = executor.dispatch(strategy, fc_parts);
5651
5652 tokio::pin!(dispatch);
5658 let results = loop {
5659 tokio::select! {
5660 biased;
5661 Some(progress_event) = progress_rx.recv() => {
5662 yield Ok(progress_event);
5663 }
5664 done = &mut dispatch => break done,
5665 }
5666 };
5667 while let Ok(progress_event) = progress_rx.try_recv() {
5669 yield Ok(progress_event);
5670 }
5671 let markers = std::mem::take(
5673 &mut *progress_overflow
5674 .lock()
5675 .unwrap_or_else(std::sync::PoisonError::into_inner),
5676 );
5677 for marker in markers {
5678 yield Ok(marker);
5679 }
5680 match results {
5681 Ok(results) => results,
5682 Err(error) => {
5683 yield Err(error);
5684 return;
5685 }
5686 }
5687 };
5688 results.sort_by_key(|r| r.index);
5690
5691 circuit_breaker_state = cb_mutex.into_inner().unwrap_or_else(|e| e.into_inner());
5693
5694 if let Some(tracker) = budget_tracker.as_ref() {
5698 let held = results.iter().filter(|result| result.pending.is_some()).count();
5699 tracker.release_tool_calls(held as u64);
5700 }
5701 let mut held_for_confirmation = Vec::new();
5702 for result in results {
5703 if result.escalate_or_skip {
5704 return;
5705 }
5706 held_for_confirmation.extend(result.pending);
5707 retrieved.extend(result.actions.grounding_sources);
5708 conversation_history.push(result.content);
5709 }
5710
5711 if !held_for_confirmation.is_empty() {
5716 for request in held_for_confirmation {
5717 yield Ok(confirmation_event(&invocation_id, &agent_name, request));
5718 }
5719 return;
5720 }
5721
5722 let refreshed_tools = match tool_setup.resolve(&ctx).await {
5727 Ok(tools) => tools,
5728 Err(error) => {
5729 yield Err(error);
5730 return;
5731 }
5732 };
5733 tool_map = refreshed_tools.map;
5734 tool_declarations = refreshed_tools.declarations;
5735 valid_transfer_targets = refreshed_tools.transfer_targets;
5736 steering_due = true;
5737 }
5738
5739 if all_calls_are_long_running {
5743 }
5747 }
5748 });
5749
5750 let s = stream! {
5751 use futures::StreamExt;
5752 let ctx = stage_ctx;
5753 let invocation_id = stage_invocation_id;
5754 let agent_name = stage_agent_name;
5755
5756 let mut answered = false;
5760 for callback in hook_before_agent.iter().chain(before_agent_callbacks.iter()) {
5761 match callback(ctx.clone() as Arc<dyn CallbackContext>).await {
5762 Ok(Some(content)) => {
5763 let mut early_event = Event::new(&invocation_id);
5764 early_event.author = agent_name.clone();
5765 if let Some(key) = &stage_output_key {
5767 let text = output_text(&content, structured_output);
5768 if !text.is_empty() {
5769 early_event
5770 .actions
5771 .state_delta
5772 .insert(key.clone(), serde_json::Value::String(text));
5773 }
5774 }
5775 early_event.llm_response.content = Some(content);
5776 yield Ok(early_event);
5777 answered = true;
5778 break;
5779 }
5780 Ok(None) => {}
5781 Err(e) => {
5782 yield Err(e);
5783 return;
5784 }
5785 }
5786 }
5787
5788 if !answered {
5789 let mut on_drop = AfterAgentOnDrop::armed(
5794 Arc::clone(&hook_after_agent),
5795 Arc::clone(&after_agent_callbacks),
5796 ctx.clone() as Arc<dyn CallbackContext>,
5797 );
5798 if ctx.run_config().durable_run_id.is_some() {
5799 on_drop.disarm();
5800 }
5801 let mut body = body;
5802 let mut finished = true;
5803 while let Some(item) = body.next().await {
5804 let pauses = match &item {
5807 Err(_) => true,
5808 Ok(event) => event.actions.tool_confirmation.is_some(),
5809 };
5810 if pauses {
5811 finished = false;
5812 on_drop.disarm();
5813 }
5814 yield item;
5815 }
5816 on_drop.disarm();
5817 if !finished {
5818 return;
5819 }
5820 }
5821
5822 for callback in hook_after_agent.iter().chain(after_agent_callbacks.iter()) {
5826 match callback(ctx.clone() as Arc<dyn CallbackContext>).await {
5827 Ok(Some(content)) => {
5828 let mut after_event = Event::new(&invocation_id);
5829 after_event.author = agent_name.clone();
5830 after_event.llm_response.content = Some(content);
5831 yield Ok(after_event);
5832 break;
5833 }
5834 Ok(None) => {}
5835 Err(e) => {
5836 yield Err(e);
5837 return;
5838 }
5839 }
5840 }
5841 };
5842
5843 Ok(Box::pin(s))
5844 }
5845}
5846
5847struct AfterAgentOnDrop {
5852 hooks: Arc<Vec<AfterAgentCallback>>,
5853 callbacks: Arc<Vec<AfterAgentCallback>>,
5854 ctx: Arc<dyn CallbackContext>,
5855 armed: bool,
5856}
5857
5858impl AfterAgentOnDrop {
5859 fn armed(
5860 hooks: Arc<Vec<AfterAgentCallback>>,
5861 callbacks: Arc<Vec<AfterAgentCallback>>,
5862 ctx: Arc<dyn CallbackContext>,
5863 ) -> Self {
5864 Self { hooks, callbacks, ctx, armed: true }
5865 }
5866
5867 fn disarm(&mut self) {
5868 self.armed = false;
5869 }
5870}
5871
5872impl Drop for AfterAgentOnDrop {
5873 fn drop(&mut self) {
5874 if !self.armed {
5875 return;
5876 }
5877 let Ok(runtime) = tokio::runtime::Handle::try_current() else {
5878 tracing::warn!(
5879 agent.name = %self.ctx.agent_name(),
5880 "no Tokio runtime to run after-agent callbacks on; they are skipped"
5881 );
5882 return;
5883 };
5884 let (hooks, callbacks, ctx) =
5885 (Arc::clone(&self.hooks), Arc::clone(&self.callbacks), Arc::clone(&self.ctx));
5886 runtime.spawn(async move {
5887 for callback in hooks.iter().chain(callbacks.iter()) {
5888 match callback(ctx.clone()).await {
5889 Ok(Some(_)) => break,
5890 Ok(None) => {}
5891 Err(error) => {
5892 tracing::warn!(
5893 agent.name = %ctx.agent_name(),
5894 error.code = %error.code,
5895 "after-agent callback failed after the agent stopped"
5896 );
5897 break;
5898 }
5899 }
5900 }
5901 });
5902 }
5903}
5904
5905async fn execute_tool(
5914 tool: Arc<dyn Tool>,
5915 ctx: Arc<dyn ToolContext>,
5916 args: serde_json::Value,
5917) -> Result<serde_json::Value> {
5918 let runtime = tokio::runtime::Handle::try_current().ok().filter(|_| tool.is_agent_delegation());
5919 let Some(runtime) = runtime else {
5921 return adk_core::ModelCallScope::within_tool(
5922 ctx.as_ref(),
5923 tool.execute(ctx.clone(), args),
5924 )
5925 .await;
5926 };
5927 let call = async move {
5928 adk_core::ModelCallScope::within_tool(ctx.as_ref(), tool.execute(ctx.clone(), args)).await
5929 };
5930 let mut task = AbortOnDrop(runtime.spawn(call.in_current_span()));
5931 match (&mut task.0).await {
5932 Ok(result) => result,
5933 Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()),
5934 Err(_) => Err(adk_core::AdkError::new(
5935 adk_core::ErrorComponent::Tool,
5936 adk_core::ErrorCategory::Cancelled,
5937 "tool.cancelled",
5938 "the delegated call's task was cancelled before it finished",
5939 )),
5940 }
5941}
5942
5943struct AbortOnDrop<T>(tokio::task::JoinHandle<T>);
5945
5946impl<T> Drop for AbortOnDrop<T> {
5947 fn drop(&mut self) {
5948 self.0.abort();
5949 }
5950}
5951
5952fn output_text(content: &Content, structured: bool) -> String {
5955 let text: String = content.parts.iter().filter_map(Part::text).collect();
5956 if structured { strip_json_code_fence(&text).to_string() } else { text }
5957}
5958
5959fn is_run_limit_refusal(error: &adk_core::AdkError) -> bool {
5962 error.component == adk_core::ErrorComponent::Guardrail
5963 || (error.component == adk_core::ErrorComponent::Agent
5964 && error.category == adk_core::ErrorCategory::ResourceExhausted)
5965}
5966
5967async fn recover_model_error(
5973 ctx: &Arc<dyn InvocationContext>,
5974 request: Option<&LlmRequest>,
5975 error: &adk_core::AdkError,
5976) -> Result<Option<LlmResponse>> {
5977 let Some(request) = request else {
5978 return Ok(None);
5979 };
5980 if is_run_limit_refusal(error) {
5981 return Ok(None);
5982 }
5983 for hook in &ctx.run_config().invocation_hooks {
5984 if let Some(response) = hook
5985 .on_model_error(ctx.clone() as Arc<dyn CallbackContext>, request.clone(), error)
5986 .await?
5987 {
5988 return Ok(Some(response));
5989 }
5990 }
5991 Ok(None)
5992}
5993
5994#[cfg(test)]
5995mod run_helper_tests {
5996 use super::*;
5997
5998 #[test]
5999 fn generation_config_layers_schema_and_cached_content() {
6000 let base =
6001 adk_core::GenerateContentConfig { temperature: Some(0.25), ..Default::default() };
6002 let schema = serde_json::json!({"type": "object"});
6003
6004 let config = build_generation_config(Some(&base), Some(&schema), Some("cached/example"))
6005 .expect("config should be present");
6006
6007 assert_eq!(config.temperature, Some(0.25));
6008 assert_eq!(config.response_schema, Some(schema));
6009 assert_eq!(config.cached_content.as_deref(), Some("cached/example"));
6010 }
6011
6012 #[test]
6013 fn function_calls_preserve_order_and_create_fallback_ids() {
6014 let content = Content {
6015 role: "model".to_string(),
6016 parts: vec![
6017 Part::Text { text: "before".to_string() },
6018 Part::FunctionCall {
6019 name: "first".to_string(),
6020 args: serde_json::json!({"value": 1}),
6021 id: None,
6022 thought_signature: None,
6023 },
6024 Part::FunctionCall {
6025 name: "second".to_string(),
6026 args: serde_json::json!({"value": 2}),
6027 id: Some("provider-id".to_string()),
6028 thought_signature: None,
6029 },
6030 ],
6031 };
6032
6033 let calls = collect_function_calls(&content, "invocation");
6034
6035 assert_eq!(calls.len(), 2);
6036 assert_eq!(calls[0].index, 0);
6037 assert_eq!(calls[0].name, "first");
6038 assert_eq!(calls[0].function_call_id, "invocation_first_0");
6039 assert_eq!(calls[1].index, 1);
6040 assert_eq!(calls[1].name, "second");
6041 assert_eq!(calls[1].function_call_id, "provider-id");
6042 }
6043
6044 #[test]
6045 fn partial_stream_events_do_not_repeat_large_payloads() {
6046 let marker = "PRIVATE-REQUEST-PAYLOAD";
6047 let request_json = format!("{marker}{}", "x".repeat(128 * 1024));
6048 let chunk = LlmResponse {
6049 content: Some(Content::new("model").with_text("x")),
6050 partial: true,
6051 ..Default::default()
6052 };
6053 let mut serialized_bytes = 0;
6054
6055 for index in 0..64 {
6056 let event = build_partial_llm_event(
6057 &format!("event-{index}"),
6058 "invocation",
6059 "agent",
6060 &request_json,
6061 &chunk,
6062 Vec::new(),
6063 );
6064 let serialized = serde_json::to_string(&event).expect("event should serialize");
6065
6066 assert!(!serialized.contains(marker));
6067 assert!(event.llm_request.is_none());
6068 assert!(!event.provider_metadata.contains_key("gcp.vertex.agent.llm_request"));
6069 assert!(!event.provider_metadata.contains_key("gcp.vertex.agent.llm_response"));
6070 serialized_bytes += serialized.len();
6071 }
6072
6073 assert!(
6074 serialized_bytes < 1024 * 1024,
6075 "64 tiny chunks unexpectedly serialized to {serialized_bytes} bytes"
6076 );
6077 }
6078}