Export live conversation logs from CX Agent Studio to BigQuery to run
custom SQL queries, evaluate agent behavior, and build dashboards in business
intelligence tools. BigQuery export streams each conversational
turn to a table in your Google Cloud project, including messages, tool calls,
updated variables, and execution trace spans.

For more information about how conversation data is stored and redacted across
CX Agent Studio, see
[Conversation history](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/conversation-history.md.txt).

## Before you begin

Before you configure BigQuery export, make sure that you have:

- An existing CX Agent Studio agent application. To create one, see [Create an agent application](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/quick/create-agent.md.txt).
- The BigQuery API (`bigquery.googleapis.com`) enabled in the destination Google Cloud project.

### Required roles


To get the permissions that
you need to configure BigQuery export and query exported
conversation logs,

ask your administrator to grant you the
following IAM roles on your project:

- Configure BigQuery export on an agent application: [Gemini Enterprise for Customer Experience App Editor](https://docs.cloud.google.com/iam/docs/roles-permissions/ces.md.txt#ces.appEditor) (`roles/ces.appEditor`)
- Query exported conversation logs in BigQuery:
  - [BigQuery Data Viewer](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.dataViewer) (`roles/bigquery.dataViewer`)
  - [BigQuery Job User](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.jobUser) (`roles/bigquery.jobUser`)


For more information about granting roles, see [Manage access to projects, folders, and organizations](https://docs.cloud.google.com/iam/docs/granting-changing-revoking-access.md.txt).


You might also be able to get
the required permissions through [custom
roles](https://docs.cloud.google.com/iam/docs/creating-custom-roles) or other [predefined
roles](https://docs.cloud.google.com/iam/docs/roles-overview#predefined).

### Cross-project permissions

When you export logs to a BigQuery dataset in the same project as
your agent application, the default
[Customer Engagement Suite service agent](https://docs.cloud.google.com/iam/docs/service-agents.md.txt#customer-engagement-suite-service-account)
(`roles/ces.serviceAgent`) handles access without additional
Identity and Access Management (IAM) configuration.

If you export logs to a BigQuery dataset in a different
Google Cloud project---or if you replace the default
`roles/ces.serviceAgent` role binding---grant the
[BigQuery Data Editor role](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.dataEditor)
(`roles/bigquery.dataEditor`) or the
[BigQuery Admin role](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.admin)
(`roles/bigquery.admin`) on the destination dataset or project to your
CX Agent Studio service agent:

`service-PROJECT_NUMBER@gcp-sa-ces.iam.gserviceaccount.com`

Replace `PROJECT_NUMBER` with the project number of the
project that hosts your CX Agent Studio agent application.

If you use a custom IAM role instead of a predefined role,
include the following permissions in the custom role:

- `bigquery.datasets.get`
- `bigquery.tables.create`
- `bigquery.tables.get`
- `bigquery.tables.update`
- `bigquery.tables.getData`
- `bigquery.tables.updateData`
- `bigquery.datasets.create` (required on the destination project if CX Agent Studio creates the dataset)

## Enable BigQuery export

You can enable BigQuery export using the [CX Agent Studio console](https://ces.cloud.google.com) or
the REST API. BigQuery export operates independently of
**Log your customer conversations** and **Enable Cloud Logging** in your agent
application settings. If
[Sensitive Data Protection redaction](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/reference/rest/v1/projects.locations.apps.md.txt#App.RedactionConfig)
is enabled on the application, sensitive data is redacted before logs are
written to BigQuery.

### Configure export in the console

1. Open the [CX Agent Studio console](https://ces.cloud.google.com) and select your agent application.
2. Click the **Settings** icon in the agent builder.
3. On the **Advanced** tab, go to the **Logging** section.
4. Turn on the **Export logs to BigQuery** toggle. If the **Export logs to
   BigQuery** panel doesn't open automatically, click **\>** (**Edit BigQuery
   export settings**) next to the toggle.
5. In the **Project** field, select the destination Google Cloud project.
6. In the **BigQuery dataset** field, select an existing dataset or enter a dataset ID for CX Agent Studio to create.
7. Click **Done** , and then click **Save**.

### Configure export using the REST API

Call the
[`projects.locations.apps.patch` method](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/reference/rest/v1/projects.locations.apps/patch)
to update
[`loggingSettings.bigqueryExportSettings`](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/reference/rest/v1/projects.locations.apps.md.txt#App.BigQueryExportSettings):

```bash
curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://ces.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/apps/APP_ID?updateMask=loggingSettings.bigqueryExportSettings" \
    -d '{
      "loggingSettings": {
        "bigqueryExportSettings": {
          "enabled": true,
          "project": "BQ_PROJECT_ID",
          "dataset": "DATASET_ID"
        }
      }
    }'
```

Replace the following:

- `PROJECT_ID`: the project ID that hosts your CX Agent Studio agent application
- `LOCATION_ID`: the location of your agent application, such as `us` or `eu`
- `APP_ID`: the ID of your agent application
- `BQ_PROJECT_ID`: the project ID of the destination BigQuery dataset
- `DATASET_ID`: the destination BigQuery dataset ID

> [!NOTE]
> **Note:** [App versions](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/version.md.txt) capture a snapshot of all application logging settings. Updating BigQuery export settings in your draft doesn't affect existing versions or active deployments. To apply updated export settings to live traffic, save the settings, create a version, and deploy that version.

### Verify export

To verify that conversation logs are flowing to BigQuery:

1. Send a test message to your agent application in the [Simulator](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/simulator.md.txt) or through a deployed channel.
2. In the Google Cloud console, go to the **BigQuery** page:


   [Go to BigQuery](https://console.cloud.google.com/bigquery)

   <br />

3. In the **Explorer** pane, expand your destination project and dataset, and
   confirm that a table matching your agent application ID
   (`APP_ID`) exists and contains rows for your test
   conversation.

## Table creation, partitioning, and CDC behavior

When you save BigQuery export settings, CX Agent Studio
automatically provisions and manages the destination dataset and table with the
following behaviors:

- **Table naming** : CX Agent Studio creates a table in the specified dataset using your agent application ID (`APP_ID`) as the table ID. The full table identifier is `BQ_PROJECT_ID.DATASET_ID.APP_ID`.
- **Dataset creation and location** : The destination dataset must reside in a location compatible with your agent application (`global` and `us` apps map to the `US` multi-region, and also accept `northamerica-northeast1` and `northamerica-northeast2`; `eu` apps map to the `EU` multi-region; regional apps match their region). If the specified dataset doesn't exist, CX Agent Studio creates it in the matching BigQuery location. If a dataset with that name already exists in an incompatible location, CX Agent Studio creates, saves, and uses a dataset suffixed with the sanitized BigQuery location (for example, `DATASET_ID_US`, `DATASET_ID_EU`, or `DATASET_ID_us_central1`).
- **Partitioning and default retention** : Auto-created tables are time-partitioned by `DAY` on the `create_time` column with a default partition expiration of 30 days (auto-created datasets also set a 30-day default partition expiration). To retain logs longer than 30 days, update the [partition expiration](https://docs.cloud.google.com/bigquery/docs/managing-partitioned-tables.md.txt#update_the_partition_expiration) on the table in BigQuery.
- **Change data capture (CDC) deduplication** : Exported tables use [BigQuery change data capture (CDC)](https://docs.cloud.google.com/bigquery/docs/change-data-capture.md.txt) `UPSERT` streaming to prevent duplicate rows for a conversation turn. CX Agent Studio automatically configures `PRIMARY KEY (project_id, conversation_id, turn_index) NOT ENFORCED` and sets `max_staleness` to 15 minutes when `max_staleness` isn't already set, while preserving existing partitioning and customer-configured `max_staleness` values.
- **DML and custom primary key constraints** : While CDC streaming or unmerged upsert changes are active on an exported table, BigQuery blocks direct `DELETE`, `UPDATE`, and `MERGE` DML statements until unmerged changes settle. Tables with an existing custom primary key keep their constraints and continue receiving append-only inserts without CDC `UPSERT` deduplication.

## Table schema

The exported table uses a turn-based schema where each row represents a single
conversational turn (`turn_index`) within a conversation (`conversation_id`).

The following table describes the top-level columns of the exported
BigQuery table:

| Column | Type | Mode | Description |
|---|---|---|---|
| `project_id` | `STRING` | `REQUIRED` | Project ID of the CX Agent Studio agent application that handles the conversation. |
| `location` | `STRING` | `NULLABLE` | Location of the CX Agent Studio agent application. |
| `app_id` | `STRING` | `NULLABLE` | ID of the CX Agent Studio agent application. |
| `app_version_id` | `STRING` | `NULLABLE` | Version ID of the agent application that served the turn, or an empty string (`""`) if served by the draft application. |
| `deployment_id` | `STRING` | `NULLABLE` | ID of the [deployment](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/deploy.md.txt) channel that served the turn, or an empty string (`""`) if the turn wasn't served through a deployment (for example, in the Simulator). |
| `conversation_id` | `STRING` | `REQUIRED` | Unique session ID of the conversation. |
| `turn_index` | `INTEGER` (`INT64`) | `REQUIRED` | 1-based sequential index of the turn within the conversation. |
| `create_time` | `TIMESTAMP` | `REQUIRED` | Creation timestamp of the turn (matches the root span start time). Used as the daily partitioning column. |
| `messages` | `RECORD` (`STRUCT`) | `REPEATED` | Ordered list of messages recorded during the turn. |
| `root_spans` | `RECORD` (`STRUCT`) | `REPEATED` | Execution trace spans recorded for the turn. |

### The `messages` record

Each element in the `messages` array contains the fields described in the
following table:

| Field | Type | Mode | Description |
|---|---|---|---|
| `messages.role` | `STRING` | `NULLABLE` | Sender role for the message, such as `user`, `agent`, or a specific sub-agent name. |
| `messages.event_time` | `TIMESTAMP` | `NULLABLE` | Timestamp when the message was sent or received. |
| `messages.chunks` | `JSON` | `NULLABLE` | JSON array of [`Chunk`](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/reference/rest/v1/Message.md.txt#Chunk) objects representing message content. |

Because `messages.chunks` is a `JSON` column containing an array of
[`Chunk`](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/reference/rest/v1/Message.md.txt#Chunk)
objects serialized in camelCase JSON, unnest it in GoogleSQL using
`UNNEST(JSON_QUERY_ARRAY(m.chunks))`. Each chunk element contains one of the
following top-level JSON keys:

- **`text`**: text content for chat utterances and responses.
- **`transcript`**: speech transcript associated with audio input or output.
- **`toolCall`** : tool invocation request containing `id`, `displayName`, `args`, and either `tool` (resource name) or `toolsetTool`.
- **`toolResponse`** : tool execution result containing the matching `id`, `displayName`, `response`, and either `tool` or `toolsetTool`.
- **`agentTransfer`** : sub-agent handoff event containing `targetAgent` and `displayName`.
- **`updatedVariables`**: JSON object of session variables modified during the turn, keyed by variable name.
- **`defaultVariables`**: JSON object of default session variables at the start of the conversation.
- **`payload`**: custom JSON payload data.
- **`blob`** or **`image`** : binary or image data containing `mimeType` and base64-encoded `data`.

### The `root_spans` record

Each element in the `root_spans` array captures execution timing and trace
metadata for the turn, as described in the following table:

| Field | Type | Mode | Description |
|---|---|---|---|
| `root_spans.name` | `STRING` | `NULLABLE` | Name of the root span. |
| `root_spans.start_time` | `TIMESTAMP` | `NULLABLE` | Start timestamp of the root span. |
| `root_spans.end_time` | `TIMESTAMP` | `NULLABLE` | End timestamp of the root span. |
| `root_spans.attributes` | `JSON` | `NULLABLE` | JSON object of key-value metadata attributes for the root span. |
| `root_spans.child_spans` | `JSON` | `NULLABLE` | JSON array of nested [`Span`](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/reference/rest/v1/projects.locations.apps.conversations.md.txt#Span) objects for sub-operations such as LLM calls, tool executions, guardrails, and speech synthesis. |

Each object inside the `root_spans.child_spans` JSON array uses camelCase
[`Span`](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/reference/rest/v1/projects.locations.apps.conversations.md.txt#Span)
keys: `name`, `startTime`, `endTime`, `duration` (formatted as a Protobuf
duration string, such as `"0.450s"`), `attributes`, and nested `childSpans`.
Because `child_spans` is a `JSON` column rather than a `RECORD` array, unnest
it with `UNNEST(JSON_QUERY_ARRAY(rs.child_spans))`.

## Example queries

Because the exported table stores one row per turn rather than one row per
conversation, aggregate rows by `conversation_id` when computing session-level
metrics. Always include a filter on `create_time` to take advantage of daily
partitioning and reduce scanned bytes.

In the following examples, replace the placeholders with your values:

- `BQ_PROJECT_ID`: your destination BigQuery project ID
- `DATASET_ID`: your BigQuery dataset ID
- `APP_ID`: your CX Agent Studio agent application ID (the auto-created table ID)

### Reconstruct a conversation transcript

Copy the following query into the BigQuery query editor to
retrieve the chronological text and voice transcript for a single conversation:

```sql
SELECT
  t.turn_index,
  m.role,
  m.event_time,
  COALESCE(
    JSON_VALUE(chunk, '$.text'),
    JSON_VALUE(chunk, '$.transcript')
  ) AS message_text
FROM
  `BQ_PROJECT_ID.DATASET_ID.APP_ID` AS t,
  UNNEST(t.messages) AS m,
  UNNEST(JSON_QUERY_ARRAY(m.chunks)) AS chunk
WHERE
  t.create_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
  AND t.conversation_id = 'CONVERSATION_ID'
  AND COALESCE(
    JSON_VALUE(chunk, '$.text'),
    JSON_VALUE(chunk, '$.transcript')
  ) IS NOT NULL
ORDER BY
  t.turn_index ASC,
  m.event_time ASC;
```

Replace `CONVERSATION_ID` with the session ID of the
conversation to inspect.

### Count turns and calculate session duration

Copy the following query into the BigQuery query editor to roll
up turn rows into session-level turn counts and durations:

```sql
SELECT
  DATE(MIN(t.create_time)) AS conversation_date,
  t.conversation_id,
  MAX(t.turn_index) AS total_turns,
  TIMESTAMP_DIFF(
    MAX(rs.end_time),
    MIN(rs.start_time),
    SECOND
  ) AS session_duration_seconds
FROM
  `BQ_PROJECT_ID.DATASET_ID.APP_ID` AS t
LEFT JOIN
  UNNEST(t.root_spans) AS rs
WHERE
  t.create_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
GROUP BY
  t.conversation_id
ORDER BY
  conversation_date DESC,
  session_duration_seconds DESC;
```

### Analyze tool calls and responses

Copy the following query into the BigQuery query editor to join
tool invocations with their corresponding tool responses:

```sql
WITH
  tool_calls AS (
    SELECT
      t.conversation_id,
      t.turn_index,
      m.event_time,
      JSON_VALUE(chunk, '$.toolCall.id') AS tool_call_id,
      JSON_VALUE(chunk, '$.toolCall.displayName') AS tool_name,
      JSON_QUERY(chunk, '$.toolCall.args') AS tool_args
    FROM
      `BQ_PROJECT_ID.DATASET_ID.APP_ID` AS t,
      UNNEST(t.messages) AS m,
      UNNEST(JSON_QUERY_ARRAY(m.chunks)) AS chunk
    WHERE
      t.create_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
      AND JSON_QUERY(chunk, '$.toolCall') IS NOT NULL
  ),
  tool_responses AS (
    SELECT
      t.conversation_id,
      JSON_VALUE(chunk, '$.toolResponse.id') AS tool_call_id,
      JSON_QUERY(chunk, '$.toolResponse.response') AS tool_response
    FROM
      `BQ_PROJECT_ID.DATASET_ID.APP_ID` AS t,
      UNNEST(t.messages) AS m,
      UNNEST(JSON_QUERY_ARRAY(m.chunks)) AS chunk
    WHERE
      t.create_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
      AND JSON_QUERY(chunk, '$.toolResponse') IS NOT NULL
  )
SELECT
  tc.conversation_id,
  tc.turn_index,
  tc.tool_name,
  tc.tool_args,
  tr.tool_response,
  tc.event_time
FROM
  tool_calls AS tc
LEFT JOIN
  tool_responses AS tr
  ON tc.conversation_id = tr.conversation_id
  AND tc.tool_call_id = tr.tool_call_id
ORDER BY
  tc.conversation_id,
  tc.event_time;
```

### Inspect child span latency

Copy the following query into the BigQuery query editor to
measure latency percentiles across nested child spans (such as LLM calls,
guardrails, and tools):

```sql
SELECT
  JSON_VALUE(child_span, '$.name') AS span_name,
  COUNT(1) AS span_count,
  ROUND(
    APPROX_QUANTILES(
      TIMESTAMP_DIFF(
        TIMESTAMP(JSON_VALUE(child_span, '$.endTime')),
        TIMESTAMP(JSON_VALUE(child_span, '$.startTime')),
        MILLISECOND
      ),
      100
    )[OFFSET(50)],
    1
  ) AS p50_latency_ms,
  ROUND(
    APPROX_QUANTILES(
      TIMESTAMP_DIFF(
        TIMESTAMP(JSON_VALUE(child_span, '$.endTime')),
        TIMESTAMP(JSON_VALUE(child_span, '$.startTime')),
        MILLISECOND
      ),
      100
    )[OFFSET(95)],
    1
  ) AS p95_latency_ms
FROM
  `BQ_PROJECT_ID.DATASET_ID.APP_ID` AS t,
  UNNEST(t.root_spans) AS rs,
  UNNEST(JSON_QUERY_ARRAY(rs.child_spans)) AS child_span
WHERE
  t.create_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
  AND JSON_VALUE(child_span, '$.startTime') IS NOT NULL
  AND JSON_VALUE(child_span, '$.endTime') IS NOT NULL
GROUP BY
  span_name
ORDER BY
  span_count DESC;
```

## Visualize data in Data Studio

You can connect exported conversation logs to Data Studio to build
interactive reports and dashboards. Because `messages.chunks`,
`root_spans.attributes`, and `root_spans.child_spans` are nested `JSON`
columns---and each row represents one turn rather than one session---create a
BigQuery view that flattens turn records into session-level
metrics before connecting Data Studio.

### Create a session summary view

Copy the following query into the BigQuery query editor to
create a flattened view of session metrics:

```sql
CREATE OR REPLACE VIEW
  `BQ_PROJECT_ID.DATASET_ID.conversation_summary` AS
WITH
  turn_stats AS (
    SELECT
      t.project_id,
      t.location,
      t.app_id,
      NULLIF(t.app_version_id, '') AS app_version_id,
      NULLIF(t.deployment_id, '') AS deployment_id,
      t.conversation_id,
      t.turn_index,
      t.create_time,
      (
        SELECT COUNT(1)
        FROM
          UNNEST(t.messages) AS m,
          UNNEST(JSON_QUERY_ARRAY(m.chunks)) AS chunk
        WHERE JSON_QUERY(chunk, '$.toolCall') IS NOT NULL
      ) AS turn_tool_calls,
      (
        SELECT MIN(rs.start_time)
        FROM UNNEST(t.root_spans) AS rs
      ) AS turn_start_time,
      (
        SELECT MAX(rs.end_time)
        FROM UNNEST(t.root_spans) AS rs
      ) AS turn_end_time
    FROM
      `BQ_PROJECT_ID.DATASET_ID.APP_ID` AS t
  )
SELECT
  conversation_id,
  ANY_VALUE(project_id) AS project_id,
  ANY_VALUE(location) AS location,
  ANY_VALUE(app_id) AS app_id,
  ARRAY_AGG(
    app_version_id IGNORE NULLS
    ORDER BY turn_index DESC
    LIMIT 1
  )[SAFE_OFFSET(0)] AS app_version_id,
  ARRAY_AGG(
    deployment_id IGNORE NULLS
    ORDER BY turn_index DESC
    LIMIT 1
  )[SAFE_OFFSET(0)] AS deployment_id,
  MIN(create_time) AS session_start_time,
  MAX(create_time) AS session_end_time,
  MAX(turn_index) AS total_turns,
  SUM(turn_tool_calls) AS total_tool_calls,
  TIMESTAMP_DIFF(
    MAX(turn_end_time),
    MIN(turn_start_time),
    SECOND
  ) AS session_duration_seconds
FROM turn_stats
GROUP BY conversation_id;
```

Replace the following:

- `BQ_PROJECT_ID`: your destination BigQuery project ID
- `DATASET_ID`: your BigQuery dataset ID
- `APP_ID`: your CX Agent Studio agent application ID

> [!TIP]
> **Tip:** Because `session_start_time` aggregates `MIN(create_time)` across turns, filtering on `session_start_time` in Data Studio doesn't prune `create_time` partitions. If you extend your table's partition expiration beyond 30 days, add a rolling `WHERE t.create_time >= ...` filter inside `turn_stats` or materialize session summaries on a schedule to control query scan costs.

### Connect the view to Data Studio

After creating the `conversation_summary` view, follow the
BigQuery and Data Studio connection guides to
select the view as a data source, configure data credentials (such as service
account credentials with the BigQuery Job User and BigQuery Data Viewer roles),
and build reports:

- [Analyze data with Data Studio](https://docs.cloud.google.com/bigquery/docs/visualize-looker-studio.md.txt)
- [Connect Data Studio to BigQuery](https://docs.cloud.google.com/looker/docs/studio/connect-to-google-bigquery)

## What's next

- Review [Conversation history](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/conversation-history.md.txt) to learn about data retention, Sensitive Data Protection redaction, and storage options.
- Use the [Monitoring dashboard](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/monitor.md.txt) to track built-in operational metrics and CX Insights outcomes.
- Compare performance across agent versions with [Traffic splitting (A/B testing)](https://docs.cloud.google.com/gemini-enterprise-cx/cx-agent-studio/deploy/traffic-split.md.txt).