Intercepting and customizing agent behavior.
Blog Post: https://arjunprabhulal.com/adk-callbacks/
Callbacks let you intercept and customize agent behavior at various points in the execution lifecycle:
- Logging - Track agent activity
- Filtering - Block unwanted content
- Validation - Ensure data quality
- Rate Limiting - Control API usage
- Python 3.10+
- Gemini API key from AI Studio
- Navigate to this module:
cd 18-callbacks- Create and activate a virtual environment:
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate- Install dependencies:
pip install -r ../requirements.txt- Set up environment variables in
logged_agent/.env:
GOOGLE_API_KEY=your-api-key-here
| Callback | When It Runs | Use Case |
|---|---|---|
before_agent_callback |
Before agent starts | Setup, validation |
after_agent_callback |
After agent completes | Cleanup, logging |
before_model_callback |
Before LLM call | Prompt modification |
after_model_callback |
After LLM response | Response filtering |
before_tool_callback |
Before tool execution | Input validation |
after_tool_callback |
After tool result | Output processing |
def before_model_logging(callback_context, llm_request):
print(f"Sending request to model...")
return None # Continue normally
agent = Agent(
before_model_callback=before_model_logging,
)cd logged_agent
python agent.pyThe demo shows:
- Logging callbacks for all lifecycle events
- Request/response inspection
- Execution timing
Continue to 19. Artifacts