Skip to main content

BigQuery Callback Handler

CommunityPythonPreview
Google BigQuery is a serverless and cost-effective enterprise data warehouse that works across clouds and scales with your data.
The BigQueryCallbackHandler allows you to log events from LangChain and LangGraph to Google BigQuery. This is useful for monitoring, auditing, and analyzing the performance of your LLM applications. Key features:
  • LangGraph support: Automatic detection of LangGraph nodes with NODE_STARTING, NODE_COMPLETED, and GRAPH_START/END events
  • Latency tracking: Built-in latency measurement for all LLM and tool calls
  • Event filtering: Configurable allowlist/denylist to control which events are logged
  • Graph context manager: Explicit graph execution boundaries with accurate timing
  • Real-time dashboard: FastAPI-based monitoring webapp with live event streaming
Preview releaseThe BigQuery Callback Handler is in Preview. APIs and functionality are subject to change. For more information, see the launch stage descriptions.
BigQuery Storage Write APIThis feature uses the BigQuery Storage Write API, which is a paid service. For information on costs, see the BigQuery documentation.

Installation

You need to install langchain-google-community with bigquery extra dependencies. For this example, you will also need langchain-google-genai and langgraph.

Prerequisites

  1. Google Cloud Project with the BigQuery API enabled.
  2. BigQuery Dataset: Create a dataset to store logging tables before using the callback handler. The callback handler automatically creates the necessary events table within the dataset if the table does not exist.
  3. Google Cloud Storage Bucket (Optional): If you plan to log multimodal content (images, audio, etc.), creating a GCS bucket is recommended for offloading large files.
  4. Authentication:
    • Local: Run gcloud auth application-default login.
    • Cloud: Ensure your service account has the required permissions.

IAM Permissions

For the callback handler to work properly, the principal (e.g., service account, user account) under which the application is running needs these Google Cloud roles:
  • roles/bigquery.jobUser at Project Level to run BigQuery queries.
  • roles/bigquery.dataEditor at Table Level to write log/event data.
  • If using GCS offloading: roles/storage.objectCreator and roles/storage.objectViewer on the target bucket.

Use with LangGraph agent

To use the BigQueryCallbackHandler with a LangGraph agent, instantiate it with your Google Cloud project ID, dataset ID, and table ID. Use the graph_context() method to track graph execution boundaries and enable GRAPH_START/GRAPH_END events with latency measurements. Pass session_id, user_id, and agent via the metadata dictionary in the config object when invoking the agent.

Configuration options

You can customize the callback handler using BigQueryLoggerConfig.
bool
default:"True"
To disable the handler from logging data to the BigQuery table, set this parameter to False.
List[str]
default:"['event_type', 'agent', 'user_id']"
The fields used to cluster the BigQuery table when it is automatically created.
str
default:"None"
The name of the GCS bucket to offload large content (images, blobs, large text) to. If not provided, large content may be truncated or replaced with placeholders.
str
default:"None"
The BigQuery connection ID (e.g., us.my-connection) to use as the authorizer for ObjectRef columns. Required for using ObjectRef with BigQuery ML.
int
default:"512000"
(500 KB) The maximum length (in characters) of text content to store inline in BigQuery before offloading to GCS (if configured) or truncating.
int
default:"1"
The number of events to batch before writing to BigQuery.
float
default:"1.0"
The maximum time (in seconds) to wait before flushing a partial batch.
float
default:"10.0"
Seconds to wait for logs to flush during shutdown.
List[str]
default:"None"
A list of event types to log. If None, all events are logged except those in event_denylist.
List[str]
default:"None"
A list of event types to skip logging.
bool
default:"True"
Whether to log detailed content parts (including GCS references).
str
default:"agent_events_v2"
The default table ID to use if not explicitly provided to the callback handler constructor.
RetryConfig
default:"RetryConfig()"
Configuration for retry logic (max retries, delay, multiplier) when writing to BigQuery fails.
int
default:"10000"
The maximum number of events to hold in the internal buffer queue before dropping new events.
The following code sample shows how to define a configuration for the BigQuery callback handler with event filtering:

Schema and production setup

The plugin automatically creates the table if it does not exist. However, for production, we recommend creating the table manually using the following DDL, which utilizes the JSON type for flexibility and REPEATED RECORDs for multimodal content. Recommended DDL:

Event types and payloads

The content column contains a JSON object specific to the event_type. The content_parts column provides a structured view of the content, especially useful for images or offloaded data.
Content Truncation
  • Variable content fields are truncated to max_content_length (configured in BigQueryLoggerConfig, default 500KB).
  • If gcs_bucket_name is configured, large content is offloaded to GCS instead of being truncated, and a reference is stored in content_parts.object_ref.

LLM interactions

These events track the raw requests sent to and responses received from the LLM.

Tool usage

These events track the execution of tools by the agent.

Chain Execution

These events track the start and end of high-level chains/graphs.

Retriever usage

These events track the execution of retrievers.

Agent Actions

These events track specific actions taken by the agent.

Other Events

Advanced analysis queries

Once your agent is running and logging events, you can perform power analysis on the agent_events_v2 table.

1. Reconstruct a Trace (Conversation Turn)

Use the trace_id to group all events (Chain, LLM, Tool) belonging to a single execution flow.

2. Analyze LLM Latency & Token Usage

Calculate the average latency and total token usage for your LLM calls.

3. Analyze Multimodal Content with BigQuery Remote Model (Gemini)

If you are offloading images to GCS, you can use BigQuery ML to analyze them directly.

4. Analyze Span Hierarchy & Duration

Visualize the execution flow and performance of your agent’s operations (LLM calls, Tool usage) using span IDs.

5. Querying Offloaded Content (Get Signed URLs)

6. Advanced SQL Scenarios

These advanced patterns demonstrate how to sessionize data, analyze tool usage, and perform root cause analysis using BigQuery ML.

Conversational Analytics in BigQuery

Conversational AnalyticsYou can also use BigQuery Conversational Analytics to analyze your agent logs using natural language. Just ask questions like:
  • “Show me the error rate over time”
  • “What are the most common tool calls?”
  • “Identify sessions with high token usage”

Looker Studio Dashboard

You can visualize your agent’s performance using our pre-built Looker Studio Dashboard template. To connect this dashboard to your own BigQuery table, use the following link format, replacing the placeholders with your specific project, dataset, and table IDs:

LangGraph integration

The BigQueryCallbackHandler provides enhanced support for LangGraph agents with automatic node detection, graph-level tracking, and latency measurements.

LangGraph event types

In addition to standard LangChain events, the callback handler automatically detects and logs LangGraph-specific events:

Graph context manager

Use the graph_context() method to explicitly mark graph execution boundaries. This enables GRAPH_START and GRAPH_END events with accurate latency measurements:

Latency tracking

The callback handler automatically tracks latency for all operations and stores measurements in the latency_ms JSON column:

Event filtering

Use event_allowlist and event_denylist to control which events are logged:
Or exclude noisy events:

Examples and resources

Example code

The following examples demonstrate various features of the BigQuery callback handler:

Analytics notebook

The LangGraph Agent Analytics notebook provides comprehensive BigQuery analytics queries for:
  • Real-time event monitoring
  • Tool usage analytics
  • Latency analysis and trends
  • Error debugging
  • User engagement metrics
  • Time-series visualization

Real-time monitoring dashboard

A FastAPI-based monitoring dashboard is available for real-time agent monitoring: Features:
  • Live event stream via Server-Sent Events (SSE)
  • Interactive charts for event distribution and latency trends
  • Session tracing with detailed timeline view
  • 20+ REST API endpoints for analytics queries
  • Auto-refresh every 5 seconds

Feedback

We welcome your feedback on BigQuery Agent Analytics. If you have questions, suggestions, or encounter any issues, please reach out to the team at bqaa-feedback@google.com.

Additional resources


Connect these docs to Claude, VSCode, and more via MCP for real-time answers.