Run in Google Colab
|
View source on GitHub
|
The chat method of the Google Analytics Data API (v1alpha) provides programmatic access to Ask Advisor in Google Analytics—an AI-powered analytical assistant that helps you query, analyze, and diagnose your Google Analytics data using natural language.
This notebook demonstrates how to use the google-analytics-data Python client library (AlphaAnalyticsDataClient) to interact with Ask Advisor:
- Configure the Colab environment
- Install and initialize the Python client
- Configure your GA property ID
- Example 1: Single-turn query with quota tracking
- Parse and render structured response blocks
- Example 2: Multi-turn conversational diagnostic
- Interactive Ask Advisor assistant
Step 0: Configure the Colab environment
To run this notebook in Google Colab, configure Application Default Credentials (ADC) in the Colab runtime:
- Grant your user credentials the
https://www.googleapis.com/auth/analytics.chatbot.readscope usinggcloud auth application-default login. - Set a Google Cloud quota project that has the Google Analytics Data API enabled using
gcloud auth application-default set-quota-project.
Need a Google Cloud project? If you don't already have a Google Cloud project with the Data API enabled, open the 1-click Enable the Google Analytics Data API console wizard. It will create a project (default name "Quickstart") or let you select an existing one and enable the API automatically. Then copy the project ID and enter it below.
Enter your Google Cloud PROJECT_ID below, run the cell, open the printed authorization URL, sign in with a Google account that has access to a Google Analytics property, and paste the verification code when prompted.
# @title Colab Authentication and Quota Project Setup
PROJECT_ID = "YOUR_PROJECT_ID" # @param {type:"string"}
if not PROJECT_ID.strip() or PROJECT_ID == "YOUR_PROJECT_ID":
raise ValueError(
"Please enter your Google Cloud project ID. If you need a project, "
"open the 1-click wizard at https://console.cloud.google.com/flows/enableapi?apiid=analyticsdata.googleapis.com "
"to create a project and enable the Google Analytics Data API."
)
# 1. Authenticate the Colab environment with the Analytics Chatbot scope
!gcloud auth application-default login --no-launch-browser --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/analytics.chatbot.read"
# 2. Set the Google Cloud quota project for Application Default Credentials
!gcloud auth application-default set-quota-project {PROJECT_ID}
Step 1: Install and initialize the Python client
Install the google-analytics-data Python client library and initialize AlphaAnalyticsDataClient from google.analytics.data_v1alpha. The client automatically detects and uses the Application Default Credentials configured in your environment.
%pip install --upgrade -q google-analytics-data
from google.analytics import data_v1alpha
# Create a client using Application Default Credentials
client = data_v1alpha.AlphaAnalyticsDataClient()
print("AlphaAnalyticsDataClient initialized successfully.")
Step 2: Configure your GA4 property ID
Enter your numeric Google Analytics 4 Property ID below. You can find your Property ID in the Google Analytics UI under Admin > Property settings > Property details > Property ID.
# @title GA4 Property Settings
PROPERTY_ID = "YOUR_PROPERTY_ID" # @param {type:"string"}
if PROPERTY_ID == "YOUR_PROPERTY_ID" or not PROPERTY_ID.strip():
raise ValueError("Please provide a valid numeric GA4 Property ID.")
property_resource = f"properties/{PROPERTY_ID.strip()}"
print(f"Configured property resource: {property_resource}")
Step 3: Example 1 — Single-turn query with quota tracking
To start a new conversation, construct a ChatRequest containing your property resource name and user_query. Set return_property_quota=True to inspect your remaining daily and hourly chat token balance.
Scenario: Revenue and Conversion Rate by Device
Suppose you want to compare revenue and conversion rate across mobile and desktop devices over the past 30 days.
# Initialize request arguments
request = data_v1alpha.ChatRequest(
property=property_resource,
user_query=(
"Compare our revenue and conversion rate across mobile vs desktop"
" over the last 30 days."
),
return_property_quota=True,
)
# Make the request
response = client.chat(request=request)
# Save the assigned session_id for follow-up questions
session_id = response.session_id
print(f"Session ID: {session_id}")
print(f"Received {len(response.blocks)} response block(s).")
Step 4: Parse and render structured response blocks
The ChatResponse object contains:
session_id: A newly assigned session identifier that you can pass in follow-up turns.blocks: A list ofResponseBlockitems:block.text: Markdown-formatted narrative summary and analytical takeaways.block.table: A structuredDataTablecontainingheaders(column names and semanticdata_typesuch asstringorfloat) androws(lists ofcolumnswith.value).
property_quota: The property'sPropertyChatQuotadetails (tokens_per_dayandtokens_per_hour) whenreturn_property_quota=True.
Let's define a helper function to render text blocks as Markdown, convert table blocks into pandas.DataFrame objects, and display quota usage.
from IPython.display import Markdown, display
import pandas as pd
def render_chat_response(chat_response: data_v1alpha.ChatResponse) -> None:
"""Renders narrative text, data tables, and quota usage from a ChatResponse."""
for block in chat_response.blocks:
if block.text:
display(Markdown(block.text))
elif block.table and (block.table.headers or block.table.rows):
headers = [h.header for h in block.table.headers]
rows = [[col.value for col in row.columns] for row in block.table.rows]
df = pd.DataFrame(rows, columns=headers)
display(df)
if (
chat_response.property_quota
and chat_response.property_quota.tokens_per_day
):
daily = chat_response.property_quota.tokens_per_day
hourly = chat_response.property_quota.tokens_per_hour
display(
Markdown(
f"**Chat Quota:** Daily consumed: `{daily.consumed:,}` "
f"(remaining: `{daily.remaining:,}`) | "
f"Hourly consumed: `{hourly.consumed:,}` "
f"(remaining: `{hourly.remaining:,}`)"
)
)
# Render the response from Example 1
render_chat_response(response)
Step 5: Example 2 — Multi-turn conversational diagnostic
To ask a follow-up question while preserving conversation history, pass the session_id returned by the previous response in your next ChatRequest.
Scenario: Compare with the previous period
Following up on the device comparison above, use Ask Advisor to compare the results with the same period in the previous month.
# Initialize follow-up request with session_id from the previous turn
follow_up_request = data_v1alpha.ChatRequest(
property=property_resource,
session_id=session_id,
user_query="Compare results with the same period in the previous month.",
return_property_quota=True,
)
# Make the follow-up request
follow_up_response = client.chat(request=follow_up_request)
session_id = follow_up_response.session_id
# Render the follow-up response
render_chat_response(follow_up_response)
Step 6: Interactive Ask Advisor assistant
Use the interactive form cell below to ask custom questions about your GA4 property. Check reset_conversation if you want to start a new session.
# @title Query Ask Advisor
user_query = "What were our top traffic channels last week?" # @param {type:"string"}
reset_conversation = False # @param {type:"boolean"}
if reset_conversation:
session_id = ""
print("Started a new conversation session.")
chat_request = data_v1alpha.ChatRequest(
property=property_resource,
user_query=user_query,
session_id=session_id or "",
return_property_quota=True,
)
chat_response = client.chat(request=chat_request)
session_id = chat_response.session_id
render_chat_response(chat_response)
Additional resources
- Using the Ask Advisor to query and analyze your data
properties.chatREST API Reference (v1alpha)- Google Analytics Data API Quotas
- Python Client Library Reference (
google-analytics-data)
Run in Google Colab
View source on GitHub