0

6.2 LLM Interaction Callbacks

awesome-llm-apps6_2_llm_interaction_callbacks

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

  1. Install dependencies:

    pip install -r requirements.txt
    
  2. 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 initiation
  • after_model_callback: Monitors response completion
  • Uses InMemoryRunner for 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

  1. Incorrect callback signatures:

    # ❌ Wrong
    def before_model_callback(context, model, prompt):
    
    # βœ… Correct
    def before_model_callback(callback_context: CallbackContext, llm_request):
    
  2. Wrong token extraction:

    # ❌ Wrong
    tokens = llm_response.usage_metadata.get('total_token_count')
    
    # βœ… Correct
    tokens = getattr(llm_response.usage_metadata, 'total_token_count', 0)
    
  3. 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)