This tutorial demonstrates how to use before_model_callback and after_model_callback to monitor LLM requests and responses.
Sign in to save downloads to your library and vote.
Preview
6.2 LLM Interaction Callbacks
This tutorial demonstrates how to use before_model_callback and after_model_callback to monitor LLM requests and responses.
π― Learning Objectives
- Understand LLM interaction callbacks
- Learn how to monitor LLM requests and responses
- Track token usage and response times
- Estimate API costs
- Monitor LLM performance metrics
π Project Structure
6_2_llm_interaction_callbacks/
βββ agent.py # Agent with LLM interaction 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: LLM Interaction Monitoring
LLM interaction callbacks allow you to monitor the communication between your agent and the underlying language model, providing insights into requests, responses, and performance metrics.
LLM Interaction Flow
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β User Input βββββΆβ LLM Request βββββΆβ LLM Response β
β β β Callback β β Callback β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β β
βΌ βΌ
βββββββββββββββββββ βββββββββββββββββββ
β Model API β β Token Usage β
β (Gemini) β β & Performance β
βββββββββββββββββββ βββββββββββββββββββ
Callback Execution Timeline
Timeline: βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββΆ
User Message
β
βΌ
βββββββββββββββββββ
β before_model β β Records start time, model info
β _callback β
βββββββββββββββββββ
β
βΌ
βββββββββββββββββββ
β LLM API Call β β Actual request to Gemini
β (Gemini 3 Flash) β
βββββββββββββββββββ
β
βΌ
βββββββββββββββββββ
β after_model β β Calculates duration, tokens, cost
β _callback β
βββββββββββββββββββ
β
βΌ
Response to User
π Code Walkthrough
1. Callback Functions
The callbacks work in pairs to monitor the complete LLM interaction:
Before Callback (before_model_callback):
- Extracts model information from
llm_request - Records request timestamp
- Stores data in session state for after callback
- Logs request details (model, time, agent)
After Callback (after_model_callback):
- Retrieves stored request data from session state
- Calculates response duration
- Extracts token usage from
llm_response.usage_metadata - Estimates API costs based on token count
- Logs performance metrics
2. State Management Between Callbacks
Session State Flow:
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β before_callback βββββΆβ Session State βββββΆβ after_callback β
β stores: β β β β retrieves: β
β - start_time β β - llm_request_ β β - start_time β
β - model β β time β β - model β
β - prompt_length β β - llm_model β β - prompt_length β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
3. Agent Setup
The agent is configured with both callbacks:
before_model_callback: Monitors request initiationafter_model_callback: Monitors response completion- Uses
InMemoryRunnerfor proper callback triggering
π§ͺ Testing Examples
Example Output Format
π€ LLM Request to gemini-3-flash-preview
β° Request time: 19:15:30
π Agent: llm_monitor_agent
π LLM Response from gemini-3-flash-preview
β±οΈ Duration: 1.45s
π’ Tokens: 156
π° Estimated cost: $0.0004
What Each Metric Tells You
- β° Request time: When the LLM request was initiated
- β±οΈ Duration: Total time from request to response
- π’ Tokens: Total tokens consumed (input + output)
- π° Estimated cost: Approximate API cost based on token usage
π Key Concepts
LLM Request Monitoring
- Model Information: Track which model is being used
- Timing: Record request timestamps
- State Management: Store request data for response analysis
LLM Response Monitoring
- Response Time: Calculate duration from request to response
- Token Usage: Track total tokens consumed
- Cost Estimation: Approximate API costs
Usage Metadata
- Token Count:
llm_response.usage_metadata.total_token_count - Model Information: Available in request and response
- Timing Data: Stored in session state between callbacks
π― Use Cases
- Performance Monitoring: Track LLM response times
- Cost Management: Monitor API usage and costs
- Quality Assurance: Analyze prompt and response patterns
- Debugging: Troubleshoot LLM interaction issues
- Analytics: Collect usage statistics and metrics
π¨ Common Mistakes
-
Incorrect callback signatures:
# β Wrong def before_model_callback(context, model, prompt): # β Correct def before_model_callback(callback_context: CallbackContext, llm_request): -
Wrong token extraction:
# β Wrong tokens = llm_response.usage_metadata.get('total_token_count') # β Correct tokens = getattr(llm_response.usage_metadata, 'total_token_count', 0) -
Not using InMemoryRunner:
# β Wrong - callbacks won't trigger agent.run(message) # β Correct runner.run_async(...)
π Next Steps
- Try Tutorial 6.3: Tool Execution Callbacks
- Experiment with different cost estimation models
- Add response quality metrics
- Implement rate limiting and quota management
- Create custom analytics dashboards
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_2_llm_interaction_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)