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 to Google BigQuery. This is useful for monitoring, auditing, and analyzing the performance of your LLM applications.
Preview releaseThe BigQuery Callback Handler is in Preview. APIs and functionality are subject to change.
For more information, see the
launch stage descriptions.
Installation
You need to installlangchain-google-community with bigquery extra dependencies. For this example, you will also need langchain-google-genai and langgraph.
Prerequisites
- Google Cloud Project with the BigQuery API enabled.
- 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.
- 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.
- Authentication:
- Local: Run
gcloud auth application-default login. - Cloud: Ensure your service account has the required permissions.
- Local: Run
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.jobUserat Project Level to run BigQuery queries.roles/bigquery.dataEditorat Table Level to write log/event data.- If using GCS offloading:
roles/storage.objectCreatorandroles/storage.objectVieweron the target bucket.
Use with LangChain Agent
To use theAsyncBigQueryCallbackHandler, you need to instantiate it with your Google Cloud project ID, dataset ID, and table ID.
If you want to log session_id, user_id, and agent fields to BigQuery, you must pass them via the metadata dictionary in the config object when invoking the chain or agent. If you do not have an agent field, we recommend creating and using different tables for different agents.
Configuration options
You can customize the callback handler usingBigQueryLoggerConfig.
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.
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
Thecontent 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 inBigQueryLoggerConfig, default 500KB). - If
gcs_bucket_nameis configured, large content is offloaded to GCS instead of being truncated, and a reference is stored incontent_parts.object_ref.
LLM interactions
These events track the raw requests sent to and responses received from the LLM.| Event Type | Content (JSON) Structure | Attributes (JSON) | Example Content (Simplified) |
|---|---|---|---|
LLM_REQUEST | |||
LLM_RESPONSE | |||
LLM_ERROR | null | null |
Tool usage
These events track the execution of tools by the agent.| Event Type | Content (JSON) Structure |
|---|---|
TOOL_STARTING | “city=‘Paris‘“ |
TOOL_COMPLETED | “25°C, Sunny” |
TOOL_ERROR | ”Error: Connection timeout” |
Chain Execution
These events track the start and end of high-level chains/graphs.| Event Type | Content (JSON) Structure |
|---|---|
CHAIN_START | {
“messages”: […]
} |
CHAIN_END | {
“output”: ”…”
} |
CHAIN_ERROR | null (See error_message column) |
Retriever usage
These events track the execution of retrievers.| Event Type | Content (JSON) Structure |
|---|---|
RETRIEVER_START | “What is the capital of France?” |
RETRIEVER_END | [
{
“page_content”: “Paris is the capital…”,
“metadata”: {“source”: “wiki”}
}
] |
RETRIEVER_ERROR | null (See error_message column) |
Agent Actions
These events track specific actions taken by the agent.| Event Type | Content (JSON) Structure |
|---|---|
AGENT_ACTION | {
“tool”: “Calculator”,
“input”: “2 + 2”
} |
AGENT_FINISH | {
“output”: “The answer is 4”
} |
Other Events
| Event Type | Content (JSON) Structure |
|---|---|
TEXT | “Some logging text…” |
Advanced analysis queries
Once your agent is running and logging events, you can perform power analysis on theagent_events_v2 table.
1. Reconstruct a Trace (Conversation Turn)
Use thetrace_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”