Tool execution callbacks allow you to monitor when agents use tools, track their execution lifecycle, and analyze the results. This provides visibility into how agents interact with external systems and APIs.
Sign in to save downloads to your library and vote.
Preview
π― Tutorial 6.3: Tool Execution Callbacks
π― What You'll Learn
- Before Tool Callbacks: Monitor when tools begin execution
- After Tool Callbacks: Track tool completion and results
- Tool Context: Understand how tool execution is monitored
π§ Core Concept: Tool Execution Monitoring
Tool execution callbacks allow you to monitor when agents use tools, track their execution lifecycle, and analyze the results. This provides visibility into how agents interact with external systems and APIs.
Tool Execution Flow
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β Tool Call βββββΆβ Before Tool βββββΆβ Tool Execution β
β (Agent) β β Callback β β (External) β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β β
βΌ βΌ
βββββββββββββββββββ βββββββββββββββββββ
β After Tool β β Tool Result β
β Callback β β (Agent) β
βββββββββββββββββββ βββββββββββββββββββ
Callback Execution Timeline
Time β 0ms 5ms 10ms 15ms 20ms 25ms
β β β β β β
βΌ βΌ βΌ βΌ βΌ βΌ
[Tool] [Before] [Exec] [After] [Result]
Call Callback Start Callback Return
Use Cases
- Execution Monitoring: Track when tools start and complete
- Parameter Validation: Check tool inputs before execution
- Result Logging: Record tool outputs and errors
- Debugging: Understand tool execution patterns
- Analytics: Monitor which tools are used most
π Tutorial Overview
In this tutorial, we'll create an agent with tool execution callbacks that:
- Uses a simple calculator tool
- Monitors tool execution start and end
- Tracks tool parameters and results
- Provides detailed tool usage visibility
π Project Structure
6_3_tool_execution_callbacks/
βββ README.md # This file
βββ requirements.txt # Dependencies
βββ agent.py # Agent with tool callbacks
βββ app.py # Streamlit interface
π― Learning Objectives
By the end of this tutorial, you'll understand:
- β Before Tool Callbacks: How to monitor tool execution start
- β After Tool Callbacks: How to track tool completion
- β Tool Context: How to access tool and agent information
- β FunctionTool: How to properly register tools with callbacks
- β Callback Integration: How to integrate callbacks with agents
π Getting Started
Setup
- Install dependencies:
pip install -r requirements.txt - Set up environment: Create
.envwithGOOGLE_API_KEY=your_key - Run the app:
streamlit run app.py
Test the Agent
# Run the Streamlit app
streamlit run app.py
# Try these test messages:
- "Calculate 15 + 27"
- "What is 100 divided by 4?"
- "Multiply 8 by 12"
π§ Key Concepts
1. Before Tool Callback
- Trigger: When tool execution begins
- Parameters:
tool,args,tool_context - Use Cases: Log tool usage, validate parameters, record start
2. After Tool Callback
- Trigger: When tool execution completes
- Parameters:
tool,args,tool_context,tool_response - Use Cases: Log results, handle errors, provide feedback
3. Tool Context
- Agent Information: Access
tool_context.agent_name - State Management: Use
tool_context.statefor data sharing - Tool Details: Access tool information via
tool.name
π Testing Examples
Basic Tool Usage
User: "Calculate 15 + 27"
π§ Tool calculator_tool started
π Parameters: {'operation': 'add', 'a': 15.0, 'b': 27.0}
π Agent: tool_execution_demo_agent
β
Tool calculator_tool completed
β±οΈ Duration: 0.0012s
π Result: 15 + 27 = 42
Error Handling
User: "What is 10 divided by 0?"
π§ Tool calculator_tool started
π Parameters: {'operation': 'divide', 'a': 10.0, 'b': 0.0}
π Agent: tool_execution_demo_agent
β
Tool calculator_tool completed
β±οΈ Duration: 0.0008s
π Result: Error: Division by zero
π― What Each Metric Tells You
Before Tool Callback Output
- π§ Tool Name: Which tool is being executed
- π Parameters: Input parameters passed to the tool
- π Agent: Which agent is using the tool
After Tool Callback Output
- β Completion Status: Tool execution completed successfully
- β±οΈ Duration: How long the tool took to execute
- π Result: The output or result from the tool
π― Critical Implementation Notes
FunctionTool Requirement
Tools must be wrapped with FunctionTool for callbacks to work:
# β
Correct - Use FunctionTool
calculator_function_tool = FunctionTool(func=calculator_tool)
agent = LlmAgent(tools=[calculator_function_tool], ...)
# β Incorrect - Raw function won't trigger callbacks
agent = LlmAgent(tools=[calculator_tool], ...)
Callback Signatures
Use the correct parameter order for tool callbacks:
# β
Correct signatures
def before_tool_callback(tool: BaseTool, args: dict, tool_context: ToolContext):
pass
def after_tool_callback(tool: BaseTool, args: dict, tool_context: ToolContext, tool_response: any):
pass
Event Loop Completion
Don't break the event loop immediately after is_final_response():
# β
Do this - allows callbacks to complete
if event.is_final_response() and event.content:
response_text = event.content.parts[0].text.strip()
# Don't break - let the loop complete naturally
π― Advanced Patterns
Multiple Tools
Register multiple tools with the same callbacks:
def weather_tool(city: str) -> str:
return f"Weather in {city}: Sunny, 25Β°C"
def calculator_tool(operation: str, a: float, b: float) -> str:
# ... implementation
# Register multiple tools
weather_function_tool = FunctionTool(func=weather_tool)
calculator_function_tool = FunctionTool(func=calculator_tool)
agent = LlmAgent(
name="multi_tool_agent",
model="gemini-3-flash-preview",
tools=[calculator_function_tool, weather_function_tool],
before_tool_callback=before_tool_callback,
after_tool_callback=after_tool_callback
)
Parameter Validation
Implement validation in before_tool_callback:
def before_tool_callback(tool: BaseTool, args: dict, tool_context: ToolContext):
tool_name = tool.name
# Validate calculator tool parameters
if tool_name == "calculator_tool":
if "operation" not in args:
print("β οΈ Warning: Missing operation parameter")
if "a" not in args or "b" not in args:
print("β οΈ Warning: Missing numeric parameters")
print(f"π§ Tool {tool_name} started")
print(f"π Parameters: {args}")
return None
Result Modification
Modify tool results in after_tool_callback:
def after_tool_callback(tool: BaseTool, args: dict, tool_context: ToolContext, tool_response: any):
tool_name = tool.name
# Add context to calculator results
if tool_name == "calculator_tool" and "result" in tool_response:
operation = args.get("operation", "unknown")
tool_response["context"] = f"Performed {operation} operation"
print(f"β
Tool {tool_name} completed")
print(f"π Result: {tool_response}")
return tool_response # Return modified response
π Next Steps
After completing this tutorial, you'll be ready for:
- Advanced Tool Patterns - Complex tool architectures
- Custom Tool Development - Building custom tools
- Tool Integration - Integrating external APIs
π Additional Resources
Ingestion metadata
- Source catalog
- awesome-llm-apps
- Repository
- Shubhamsaboo/awesome-llm-apps Β· main
- File path
- ai_agent_framework_crash_course/google_adk_crash_course/6_callbacks/6_3_tool_execution_callbacks/README.md
- Last refreshed
- 7/24/2026, 3:00:13 AM (52m ago)
- Refresh schedule
- Daily Β· 03:00 UTC
- Dedupe status
- Unique Β· deduped by (source, url)