This tutorial demonstrates how to use before_agent_callback and after_agent_callback to monitor agent execution lifecycle.
Sign in to save downloads to your library and vote.
Preview
6.1 Agent Lifecycle Callbacks
This tutorial demonstrates how to use before_agent_callback and after_agent_callback to monitor agent execution lifecycle.
π― Learning Objectives
- Understand agent lifecycle callbacks
- Learn how to monitor agent execution timing
- See how to share state between callbacks
- Practice implementing performance monitoring
π Project Structure
6_1_agent_lifecycle_callbacks/
βββ agent.py # Agent with lifecycle callbacks
βββ app.py # Streamlit web interface
βββ requirements.txt # Python dependencies
βββ README.md # This file
π§ Setup
-
Install dependencies:
pip install -r requirements.txt -
Set up API key:
# Create .env file echo "GOOGLE_API_KEY=your_api_key_here" > .env
π Running the Demo
Command Line Demo
python agent.py
Web Interface
streamlit run app.py
π§ Core Concept: Agent Lifecycle Monitoring
Agent lifecycle callbacks allow you to monitor the beginning and end of agent execution, providing visibility into when agents start and complete their tasks.
Agent Lifecycle Flow
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β User Input βββββΆβ Agent Start βββββΆβ Agent End β
β β β Callback β β Callback β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β β
βΌ βΌ
βββββββββββββββββββ βββββββββββββββββββ
β Agent Logic β β Performance β
β Execution β β Metrics β
βββββββββββββββββββ βββββββββββββββββββ
Callback Execution Timeline
Timeline: βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββΆ
User Message
β
βΌ
βββββββββββββββββββ
β before_agent β β Records start time, agent info
β _callback β
βββββββββββββββββββ
β
βΌ
βββββββββββββββββββ
β Agent Logic β β Core agent processing
β Execution β
βββββββββββββββββββ
β
βΌ
βββββββββββββββββββ
β after_agent β β Calculates duration, logs completion
β _callback β
βββββββββββββββββββ
β
βΌ
Response to User
π Code Walkthrough
1. Callback Functions
The callbacks work in pairs to monitor the complete agent lifecycle:
Before Callback (before_agent_callback):
- Records execution start timestamp
- Stores start time in session state for after callback
- Logs agent execution start (agent name, time)
- Returns
Noneto allow normal execution
After Callback (after_agent_callback):
- Retrieves start time from session state
- Calculates total execution duration
- Logs completion with performance metrics
- Returns
Noneto use original result
2. State Management Between Callbacks
Session State Flow:
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β before_callback βββββΆβ Session State βββββΆβ after_callback β
β stores: β β β β retrieves: β
β - start_time β β - request_start β β - start_time β
β β β _time β β β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
3. Agent Setup
The agent is configured with both lifecycle callbacks:
before_agent_callback: Monitors agent execution startafter_agent_callback: Monitors agent execution completion- Uses
InMemoryRunnerfor proper callback triggering
π§ͺ Testing Examples
Example Output Format
π Agent LifecycleDemoAgent started at 19:15:30
β° Start time: 2024-01-15 19:15:30
β
Agent LifecycleDemoAgent completed
β±οΈ Duration: 1.23s
β° End time: 2024-01-15 19:15:31
π Performance: 1.23s | LifecycleDemoAgent
What Each Metric Tells You
- π Start time: When the agent began processing
- β Completion time: When the agent finished processing
- β±οΈ Duration: Total execution time in seconds
- π Performance: Formatted performance summary
π Key Concepts
Agent Lifecycle Monitoring
- Execution Start: Track when agents begin processing
- Execution End: Track when agents complete their tasks
- Performance Timing: Calculate total execution duration
- State Sharing: Pass timing data between callbacks
CallbackContext
- agent_name: Name of the agent being executed
- invocation_id: Unique identifier for this execution
- state: Session state that persists between callbacks
State Management
- Use
callback_context.state.to_dict()to get current state - Use
callback_context.state.update()to modify state - State is shared between before and after callbacks
π― Use Cases
- Performance Monitoring: Track execution times
- Logging: Record agent activities
- Analytics: Collect usage statistics
- Debugging: Monitor agent behavior
- Custom Logic: Add pre/post processing
π¨ Common Mistakes
-
Forgetting to await session creation:
# β Wrong session_service.create_session(...) # β Correct await session_service.create_session(...) -
Using wrong callback signature:
# β Wrong def after_agent_callback(context, result): # β Correct def after_agent_callback(callback_context: CallbackContext): -
Not using InMemoryRunner:
# β Wrong - callbacks won't trigger agent.run(message) # β Correct runner.run_async(...)
β οΈ Critical Implementation Note
Event Loop Completion: The after_agent_callback will not trigger if you break the event loop immediately upon receiving is_final_response().
Correct Pattern: Allow the event loop to complete naturally:
# β Wrong - breaks loop early, after_agent_callback won't run
if event.is_final_response() and event.content:
response_text = event.content.parts[0].text.strip()
break # This prevents after_agent_callback from running
# β
Correct - let loop complete naturally
if event.is_final_response() and event.content:
response_text = event.content.parts[0].text.strip()
# Don't break - let the loop complete to ensure callbacks run
This is a known ADK behavior where breaking the loop early prevents cleanup callbacks from executing.
π Next Steps
- Try Tutorial 6.2: LLM Interaction Callbacks
- Experiment with state management between callbacks
- Add custom logging or analytics
- Implement performance alerts for slow responses
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_1_agent_lifecycle_callbacks/README.md
- Last refreshed
- 7/23/2026, 10:39:09 PM (4h ago)
- Refresh schedule
- Daily Β· 03:00 UTC
- Dedupe status
- Unique Β· deduped by (source, url)