|---|---|
| [![](https://www.tensorflow.org/images/colab_logo_32px.png)Run in Google Colab](https://colab.research.google.com/github/googleanalytics/python-docs-samples/blob/main/google-analytics-data/notebooks/advisor-chat.ipynb) | [![](https://www.tensorflow.org/images/GitHub-Mark-32px.png)View source on GitHub](https://github.com/googleanalytics/python-docs-samples/blob/main/google-analytics-data/notebooks/advisor-chat.ipynb) |

The [`chat`](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1alpha/properties/chat) method of the [Google Analytics Data API](https://developers.google.com/analytics/devguides/reporting/data/v1) (`v1alpha`) provides programmatic access to [Ask Advisor in Google Analytics](https://support.google.com/analytics/answer/16675569)---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`](https://pypi.org/project/google-analytics-data/) Python client library (`AlphaAnalyticsDataClient`) to interact with Ask Advisor:

0. [Configure the Colab environment](https://developers.google.com/analytics/devguides/reporting/data/v1/notebooks/advisor-chat#colab-config)
1. [Install and initialize the Python client](https://developers.google.com/analytics/devguides/reporting/data/v1/notebooks/advisor-chat#install)
2. [Configure your GA property ID](https://developers.google.com/analytics/devguides/reporting/data/v1/notebooks/advisor-chat#configure-property)
3. [Example 1: Single-turn query with quota tracking](https://developers.google.com/analytics/devguides/reporting/data/v1/notebooks/advisor-chat#single-turn)
4. [Parse and render structured response blocks](https://developers.google.com/analytics/devguides/reporting/data/v1/notebooks/advisor-chat#parse-blocks)
5. [Example 2: Multi-turn conversational diagnostic](https://developers.google.com/analytics/devguides/reporting/data/v1/notebooks/advisor-chat#multi-turn)
6. [Interactive Ask Advisor assistant](https://developers.google.com/analytics/devguides/reporting/data/v1/notebooks/advisor-chat#interactive-chat)

> > [!IMPORTANT]
> > **Important:** This product uses AI and may display inaccurate info. Your chat activity may be used to improve the product and your use is subject to Google's [Terms](https://policies.google.com/terms), [AI Use Policy](https://policies.google.com/terms/generative-ai/use-policy), and [Privacy Policy](https://policies.google.com/privacy).
>
## Step 0: Configure the Colab environment

To run this notebook in Google Colab, configure [Application Default Credentials (ADC)](https://cloud.google.com/docs/authentication/application-default-credentials) in the Colab runtime:

1. Grant your user credentials the `https://www.googleapis.com/auth/analytics.chatbot.read` scope using `gcloud auth application-default login`.
2. Set a [Google Cloud quota project](https://cloud.google.com/docs/authentication/adc-troubleshooting/user-creds) that has the [Google Analytics Data API enabled](https://console.cloud.google.com/flows/enableapi?apiid=analyticsdata.googleapis.com) 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](https://console.cloud.google.com/flows/enableapi?apiid=analyticsdata.googleapis.com) 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.
>
> > [!NOTE]
> > **Note:** This step is only required to set up the temporary Google Colab VM environment (since Colab's built-in `google.colab.auth.authenticate_user()` helper only requests default Google Cloud scopes). When running outside of Colab, see [Before you begin](https://developers.google.com/analytics/devguides/reporting/data/v1/advisor-basics#before-you-begin) to configure credentials in your local or server environment.
>
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](https://support.google.com/analytics/answer/9305788), 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`](https://pypi.org/project/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](https://analytics.google.com/) 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`](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1alpha/properties/chat#request-body) 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`](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1alpha/properties/chat#response-body) object contains:

- `session_id`: A newly assigned session identifier that you can pass in follow-up turns.
- `blocks`: A list of [`ResponseBlock`](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1alpha/properties/chat#ResponseBlock) items:
  - `block.text`: Markdown-formatted narrative summary and analytical takeaways.
  - `block.table`: A structured [`DataTable`](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1alpha/properties/chat#DataTable) containing `headers` (column names and semantic `data_type` such as `string` or `float`) and `rows` (lists of `columns` with `.value`).
- `property_quota`: The property's [`PropertyChatQuota`](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1alpha/properties/chat#PropertyChatQuota) details (`tokens_per_day` and `tokens_per_hour`) when `return_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`](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1alpha/properties/chat#request-body).

### 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](https://developers.google.com/analytics/devguides/reporting/data/v1/advisor-basics)
- [`properties.chat` REST API Reference (`v1alpha`)](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1alpha/properties/chat)
- [Google Analytics Data API Quotas](https://developers.google.com/analytics/devguides/reporting/data/v1/quotas)
- [Python Client Library Reference (`google-analytics-data`)](https://googleapis.dev/python/analyticsdata/latest/index.html)