# Conversational analytics integration

This document explains how Google Cloud Cortex Framework integrates with
[conversational analytics in BigQuery](https://docs.cloud.google.com/bigquery/docs/conversational-analytics.md.txt) and
the [Conversational Analytics API](https://docs.cloud.google.com/gemini/data-agents/conversational-analytics-api/overview.md.txt)
to provision domain-aware [BigQuery data agents](https://docs.cloud.google.com/bigquery/docs/create-data-agents.md.txt)
directly on top of your deployed Cortex Framework data products. Using the
[`uv run cortex-create-ca-agents`](https://docs.cloud.google.com/cortex/docs/uv-run-cortex-create-ca-agents.md.txt)
CLI tool, you can declaratively configure, validate, and synchronize
natural-language data agents as code alongside `config/config.yaml`. After
provisioning your data agents in BigQuery, you can also publish
and register them in [Gemini](https://docs.cloud.google.com/gemini/enterprise/docs/get-started.md.txt) so
business users across your organization can discover and query them. For
details, see [Gemini integration](https://docs.cloud.google.com/cortex/docs/gemini.md.txt).

## Key benefits

Provisioning BigQuery conversational analytics data agents through
Cortex Framework provides the following benefits:

- **Automated semantic context harvesting** : Automatically imports table and column business descriptions from each referenced data product's `annotations/*.yaml` files into the agent's BigQuery knowledge sources, improving SQL generation accuracy without manual re-entry.
- **Environment-portable verified queries (`goldenQueries`)** : Rewrites logical `{<product>.project_id}` and `{<product>.dataset_id}` placeholders (as well as camelCase `{<product>.projectId}` and `{<product>.datasetId}` variants) in your verified example SQL queries (configured under `goldenQueries`, formerly known as golden queries in BigQuery) into physical BigQuery identifiers for each environment (development, staging, or production).
- **Zero-cost pre-flight SQL validation** : Executes BigQuery dry-run compilation checks against every configured query in `goldenQueries` (in `data.bigQueryLocation`) and verifies estimated bytes processed stay within the configured byte limit before making any API changes.
- **Idempotent lifecycle management** : Reconciles agent definitions safely across repeated CI/CD runs by tracking managed resources with the `cortex-framework-version` system label, preserving customer-added labels on existing `DataAgent` resources across updates, and leaving user-created agents untouched.
- **Flexible location and automatic regional routing** : Resolves global, multi-regional, or regional Conversational Analytics API endpoints automatically from optional `conversationalAnalytics.location` (recommended: `global` to display agents in the BigQuery Agents Hub UI) or defaults to lowercased `data.bigQueryLocation`.

## How the integration works

Run `uv run cortex-create-ca-agents` after your Dataform pipelines
materialize target tables and views in BigQuery. During each
run, the tool completes the following stages:

1. Context assembly. Reads `conversationalAnalytics` in `config/config.yaml`, resolves target BigQuery tables and views as knowledge sources, attaches descriptions from `annotations/*.yaml`, and combines instructions, join paths, glossary terms, and verified queries (`goldenQueries`).
2. Pre-flight validation. Checks [required Google Cloud APIs](https://docs.cloud.google.com/cortex/docs/prerequisites.md.txt#ca-apis) in `buildEnvironment.buildProjectId`, validates the resolved agent location with a `get_location` call against the Conversational Analytics API endpoint, confirms that target datasets, tables, and views exist, and dry-runs expanded `goldenQueries` in `data.bigQueryLocation` against the byte-limit ceiling.
3. Agent synchronization. Connects to the resolved Conversational Analytics API endpoint for `conversationalAnalytics.location` (or lowercased `data.bigQueryLocation` when omitted) and creates or updates each enabled data agent in place (or reports planned changes without mutating resources when `--dry-run` is set).

### Location override and regional endpoint routing

You can set an optional `conversationalAnalytics.location` value in
`config/config.yaml` (normalized to lowercase). When omitted,
Cortex Framework defaults to the lowercased value of
`data.bigQueryLocation`.

> [!TIP]
> **Tip:** Set `conversationalAnalytics.location: global` if you want provisioned data agents to appear in the BigQuery Agents Hub UI.

Cortex Framework routes Conversational Analytics API requests to the
endpoint matching the resolved location and checks availability with
`get_location` before creating or updating agents:

- **Global (`global` or empty)** : `geminidataanalytics.googleapis.com`
- **Single region (contains a hyphen, such as `us-east4` or `europe-west2`)** : `geminidataanalytics-LOCATION.googleapis.com`
- **Multi-region (no hyphen, such as `us` or `eu`)** : `geminidataanalytics.LOCATION.rep.googleapis.com`

> [!NOTE]
> **Note:** Regardless of `conversationalAnalytics.location`, pre-flight BigQuery dry-run jobs for `goldenQueries` always execute in `data.bigQueryLocation` where your data product datasets reside.

## Before you begin

Before running `uv run cortex-create-ca-agents`, verify the following
prerequisites:

### Enable Google Cloud APIs

Complete the local environment, authentication, and core project setup in
[Prerequisites](https://docs.cloud.google.com/cortex/docs/prerequisites.md.txt). Then enable the required APIs in
your `buildEnvironment.buildProjectId` project, or pass `--enable-apis` when
running `uv run cortex-create-ca-agents`:

```bash
gcloud services enable bigquery.googleapis.com \
    geminidataanalytics.googleapis.com \
    cloudaicompanion.googleapis.com \
    --project=BUILD_PROJECT_ID
```

Replace the following:

- `BUILD_PROJECT_ID`: the Google Cloud project ID configured in `buildEnvironment.buildProjectId`, for example: `my-cortex-project`.

### Get the required roles


To get the permissions that
you need to provision and query BigQuery conversational analytics data agents,

ask your administrator to grant you the
following IAM roles:

- Provision data agents (`uv run cortex-create-ca-agents`):
  - [Gemini Data Analytics Data Agent Creator](https://docs.cloud.google.com/iam/docs/roles-permissions/geminidataanalytics.md.txt#geminidataanalytics.dataAgentCreator) (`roles/geminidataanalytics.dataAgentCreator`) on `buildProjectId`
  - [Gemini Data Analytics Data Agent Editor](https://docs.cloud.google.com/iam/docs/roles-permissions/geminidataanalytics.md.txt#geminidataanalytics.dataAgentEditor) (`roles/geminidataanalytics.dataAgentEditor`) on `buildProjectId`
  - [BigQuery Job User](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.jobUser) (`roles/bigquery.jobUser`) on `buildProjectId`
  - [BigQuery Data Viewer](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.dataViewer) (`roles/bigquery.dataViewer`) on the target data product datasets
  - [Service Usage Consumer](https://docs.cloud.google.com/iam/docs/roles-permissions/serviceusage.md.txt#serviceusage.serviceUsageConsumer) (`roles/serviceusage.serviceUsageConsumer`) on `buildProjectId`
  - [Service Usage Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/serviceusage.md.txt#serviceusage.serviceUsageAdmin) (`roles/serviceusage.serviceUsageAdmin`) on `buildProjectId` (required only when passing `--enable-apis`)
- Query published data agents:
  - [Gemini Data Analytics Data Agent User](https://docs.cloud.google.com/iam/docs/roles-permissions/geminidataanalytics.md.txt#geminidataanalytics.dataAgentUser) (`roles/geminidataanalytics.dataAgentUser`) on `buildProjectId`
  - [BigQuery Studio User](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.studioUser) (`roles/bigquery.studioUser`) on `buildProjectId`
  - [Gemini for Google Cloud User](https://docs.cloud.google.com/iam/docs/roles-permissions/cloudaicompanion.md.txt#cloudaicompanion.user) (`roles/cloudaicompanion.user`) on `buildProjectId`
  - [BigQuery Job User](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.jobUser) (`roles/bigquery.jobUser`) on the query execution project
  - [BigQuery Data Viewer](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.dataViewer) (`roles/bigquery.dataViewer`) on the underlying data product datasets


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).

> [!NOTE]
> **Note:** Data agents execute queries using the end user's Identity and Access Management (IAM) credentials. Users can only query BigQuery tables and views to which they have read access. For full role details, see [Create data agents](https://docs.cloud.google.com/bigquery/docs/create-data-agents.md.txt#required-roles).

### Deploy and run data product pipelines

Run `uv run cortex-build-and-deploy` (or `uv run cortex-deploy`) and execute
your Dataform workflow actions first so that all target tables
and views exist in BigQuery. For instructions, see
[Post-deployment steps](https://docs.cloud.google.com/cortex/docs/post-deployment-steps.md.txt).

## Prebuilt data agent templates

Cortex Framework ships three prebuilt data agent templates under
`src/agents/cortex/` (and bundled inside the installed `cortex` Python package).
Each template includes a complete `agent_settings.yaml`, a domain
`system_instruction.md`, explicit `schemaRelationships`, business
`glossaryTerms`, and parameterized verified queries (`goldenQueries`):

| Template | `agentSettings` path | Required data products and catalogs | Analytical scope |
| Financial Analysis Agent | `../src/agents/cortex/sap/financial_analysis/agent_settings.yaml` | `financial_statements`, `accounts_payable_insights`, `accounts_receivable_insights`, `cost_and_profit_centers`, and `budget_allocations` (all enabled by default in SAP deployments). | SAP Balance Sheet and P\&L variances, working capital (DPO, DSO, AP and AR turnover), early-payment cash discount defense, parked or payment-blocked AP invoices, and cost center budget overruns (5 verified queries, Python analysis enabled). |
| SAP Inbound Logistics Risk Agent | `../src/agents/cortex/sap_bdc/inbound_logistics_risk/agent_settings.yaml` | `supplier_plant_weather_risk_insights` and `supplier_inbound_delivery_weather_risk_insights` (`cortex_samples`), backed by the `sap_bdc_catalog`, `ah_weathernext_catalog`, and `ah_dnb_catalog` catalogs. | Inbound delivery execution, critical material shortages, supplier On-Time In-Full (OTIF), dispatch-anchored P50 and P90 dynamic ETAs, terrestrial and maritime weather or port delays, and Dun \& Bradstreet Bill of Lading match tiers (7 verified queries, Python analysis enabled). |
| Sales Performance \& Revenue Forecast Assistant | `../src/agents/cortex/sap_sfdc/sales_performance_revenue_forecast/agent_settings.yaml` | SAP `sales_performance` (`cortex_samples`), `sales_documents`, `customers`, and `materials`; Salesforce `opportunity_pipeline`, `sales_activities`, `leads_capture_conversions`, `case_management`, and `accounts`. | Cross-system SAP and Salesforce commercial revenue outlook bridge, realized billed revenue compared with open backorders, probability-weighted pipeline coverage, lead-source conversion performance, year-over-year customer drop recovery, and escalated support risk (4 verified queries, Python analysis enabled). |
|---|---|---|---|

Add any of the prebuilt templates to `config/config.yaml` and set
`enabled: true` after deploying their required data products and catalogs:

```yaml
buildEnvironment:
  buildProjectId: BUILD_PROJECT_ID

conversationalAnalytics:
  enabled: true
  location: global
  agents:
    - agentId: cortex-sap-financial-analysis-agent
      displayName: "Financial Analysis Agent"
      enabled: true
      contextVersion: published
      agentSettings: "../src/agents/cortex/sap/financial_analysis/agent_settings.yaml"

    - agentId: cortex-sap-inbound-logistics-risk-analyst
      displayName: "SAP Inbound Logistics Risk Agent"
      enabled: false # Enable after deploying sap_bdc_catalog, ah_weathernext_catalog, ah_dnb_catalog, and weather-risk samples
      contextVersion: published
      agentSettings: "../src/agents/cortex/sap_bdc/inbound_logistics_risk/agent_settings.yaml"

    - agentId: cortex-sales-revenue-forecast-assistant
      displayName: "Sales Performance & Revenue Forecast Assistant"
      enabled: false # Enable after deploying sap_sales_performance (cortex_samples) plus the required SAP and Salesforce products
      contextVersion: published
      agentSettings: "../src/agents/cortex/sap_sfdc/sales_performance_revenue_forecast/agent_settings.yaml"
```

Replace the following:

- `BUILD_PROJECT_ID`: the Google Cloud project ID where the data agent resources are hosted, for example: `my-cortex-project`.

> [!NOTE]
> **Note:** Keep `location: global` if you want provisioned data agents to appear in the BigQuery Agents Hub UI. When you omit `location`, Cortex Framework defaults to the lowercased `data.bigQueryLocation`. Before enabling `cortex-sap-inbound-logistics-risk-analyst` or `cortex-sales-revenue-forecast-assistant`, deploy and materialize their required `cortex_samples` [solution sample](https://docs.cloud.google.com/cortex/docs/solution-samples/overview.md.txt) modules, upstream data products, and catalogs in BigQuery. If you set an explicit `data.namespaces` allowlist in `config/config.yaml`, include `- name: cortex_samples` (see [Data: Cortex Framework namespaces](https://docs.cloud.google.com/cortex/docs/deployment-configuration.md.txt#data-namespaces)).

## Configure data agents

Add a top-level `conversationalAnalytics` section to `config/config.yaml`. Each
entry under `agents` can either point to a modular external YAML file using
`agentSettings` or define its context inline using `inlineAgentSettings`.

### Option 1: External `agent_settings.yaml`

Register the agent in `config/config.yaml`:

```yaml
buildEnvironment:
  buildProjectId: BUILD_PROJECT_ID

conversationalAnalytics:
  enabled: true
  location: global
  agents:
    - agentId: sap-procurement-spend-agent
      enabled: true
      contextVersion: published
      agentSettings: agents/procurement_spend/agent_settings.yaml
```

Replace the following:

- `BUILD_PROJECT_ID`: the Google Cloud project ID where the data agent resource is hosted, for example: `my-cortex-project`.

Create `config/agents/procurement_spend/agent_settings.yaml` with your agent's
data products (knowledge sources), system instruction, join relationships,
business glossary, and verified queries (`goldenQueries`):

```yaml
displayName: "SAP Procurement & Supplier Spend Agent"
description: "Conversational agent for analyzing SAP purchase orders, vendors, and material spend."
labels:
  domain: "procurement"
  source: "sap"

dataProducts:
  - id: sap_purchasing_documents
    includeTables:
      - purchasing_document_headers
      - purchasing_document_items
  - id: sap_vendors
    includeTables:
      - vendors
  - id: sap_materials
    includeTables:
      - materials

systemInstruction: "system_instruction.md"

schemaRelationships:
  - leftTable:
      dataProduct: sap_purchasing_documents
      table: purchasing_document_headers
      columns: ["client_mandt", "purchasing_document_number_ebeln"]
    rightTable:
      dataProduct: sap_purchasing_documents
      table: purchasing_document_items
      columns: ["client_mandt", "purchasing_document_number_ebeln"]
    confidenceScore: 1.0
  - leftTable:
      dataProduct: sap_purchasing_documents
      table: purchasing_document_headers
      columns: ["client_mandt", "vendor_account_number_lifnr"]
    rightTable:
      dataProduct: sap_vendors
      table: vendors
      columns: ["client_mandt", "account_number_of_vendor_or_creditor_lifnr"]
    confidenceScore: 1.0

glossaryTerms:
  - displayName: "Vendor Account Number (LIFNR)"
    description: "Unique SAP supplier identifier joining purchase orders to vendor master records."
    labels: ["sap", "procurement"]

goldenQueries:
  - question: "Who are the top 10 vendors by net order value in {currency}?"
    inlineSql: |
      SELECT
        v.name1_name1 AS vendor_name,
        SUM(i.net_order_value_in_po_currency_netwr) AS total_net_order_value
      FROM `{sap_purchasing_documents.project_id}.{sap_purchasing_documents.dataset_id}.purchasing_document_headers` AS p
      INNER JOIN `{sap_purchasing_documents.project_id}.{sap_purchasing_documents.dataset_id}.purchasing_document_items` AS i
        ON p.client_mandt = i.client_mandt
        AND p.purchasing_document_number_ebeln = i.purchasing_document_number_ebeln
      INNER JOIN `{sap_vendors.project_id}.{sap_vendors.dataset_id}.vendors` AS v
        ON p.client_mandt = v.client_mandt
        AND p.vendor_account_number_lifnr = v.account_number_of_vendor_or_creditor_lifnr
      WHERE p.currency_key_waers = @currency
      GROUP BY 1
      ORDER BY total_net_order_value DESC
      LIMIT 10
    parameters:
      - name: currency
        dataType: STRING
        description: "Three-letter ISO currency code (for example, 'USD' or 'EUR')"

options:
  enablePythonAnalysis: true
  maxBilledBytes: 10737418240
```

> [!NOTE]
> **Note:** In `goldenQueries`, reference data product datasets using `{<product_id>.project_id}` and `{<product_id>.dataset_id}` (or camelCase `{<product_id>.projectId}` and `{<product_id>.datasetId}`) placeholders, where `<product_id>` matches an entry in the agent's `dataProducts` list. External paths in `systemInstruction` and `goldenQueries[].sql` resolve relative to the directory containing `agent_settings.yaml`.

### Option 2: Self-contained `inlineAgentSettings`

For compact single-product agents, you can define `inlineAgentSettings` directly
inside `config/config.yaml`:

```yaml
buildEnvironment:
  buildProjectId: BUILD_PROJECT_ID

conversationalAnalytics:
  enabled: true
  location: global
  agents:
    - agentId: sfdc-opportunity-pipeline-agent
      displayName: "Salesforce Opportunity Pipeline Agent"
      enabled: true
      contextVersion: published
      inlineAgentSettings:
        description: "Answers pipeline, win-rate, and stage velocity questions on Salesforce opportunities."
        labels:
          domain: "sales"
          source: "sfdc"
        dataProducts:
          - id: sfdc_opportunity_pipeline
            includeTables:
              - opportunity_pipeline
              - opportunity_pipeline_overview
        inlineSystemInstruction: |
          You are a sales operations analyst assistant. Base pipeline totals on
          non-closed open opportunities unless the user asks for historical closed deals.
        options:
          enablePythonAnalysis: false
          maxBilledBytes: 10737418240
```

Replace the following:

- `BUILD_PROJECT_ID`: the Google Cloud project ID where the data agent resource is hosted, for example: `my-cortex-project`.

### Configuration resolution and validation rules

When resolving and validating `conversationalAnalytics` definitions,
`uv run cortex-create-ca-agents` enforces the following rules:

- **Three-tier `agentSettings` path resolution** : Absolute paths are used directly. Relative `agentSettings` paths resolve in order against:
  1. The directory containing `config.yaml` (for example, `config/`).
  2. The workspace root directory.
  3. The bundled `agents/` directory inside the installed `cortex` Python wheel package whenever the path contains an `agents` segment (so prebuilt paths such as `../src/agents/cortex/...` work in both source checkouts and wheel installations).
- **Flexible `dataProducts[].id` lookup** : Each entry in `dataProducts` (and matching references in `schemaRelationships` and `goldenQueries`) can specify either an explicit `moduleId` from `data.modules.products` (such as `sap_customers`) or an unambiguous canonical leaf `module_name` (the last segment of `modulePath`, such as `customers`). If multiple enabled product modules share the same leaf `module_name`, resolution raises `AmbiguousProductReferenceError` and you must reference the explicit `moduleId`.
- **Non-destructive `contextVersion` updates (`published` compared with
  `staging`)** : `contextVersion` defaults to `published`. Updates send a targeted protobuf `FieldMask` covering only `display_name`, `description`, `labels`, and the active context slot (`data_analytics_agent.published_context` or `data_analytics_agent.staging_context`), leaving the other context slot untouched. To register a data agent in Gemini, you must provision it with `contextVersion: published`.
- **Verified query (`goldenQueries`) byte limits and parameter types** :
  - Every verified query's BigQuery dry-run estimate (`total_bytes_processed`) must stay at or below `min(options.maxBilledBytes, 500,000,000,000)` (the 500 GB API cap; `options.maxBilledBytes` defaults to `10737418240`, or 10 GiB).
  - Placeholders support both `snake_case` (`{<product>.project_id}`, `{<product>.dataset_id}`) and `camelCase` (`{<product>.projectId}`, `{<product>.datasetId}`) forms, and every referenced product must appear in the agent's `dataProducts`.
  - Supported `parameters[].dataType` values (`STRING`, `INT64`, `FLOAT64`, `NUMERIC`, `BIGNUMERIC`, `BOOL`, `DATE`, `DATETIME`, `TIME`, `TIMESTAMP`, `BYTES`, `GEOGRAPHY`, `JSON`) automatically canonicalize aliases: `INTEGER` becomes `INT64`, `FLOAT` becomes `FLOAT64`, and `BOOLEAN` becomes `BOOL`.

For full field specifications and validation constraints, see
[Conversational analytics (`conversationalAnalytics`)](https://docs.cloud.google.com/cortex/docs/deployment-configuration.md.txt#conversational-analytics-config).

## Provision and synchronize agents

After your target data product tables and views are materialized in
BigQuery, preview pre-flight validation and planned sync actions
with `--dry-run` before applying changes:

```bash
export CORTEX_CONFIG_FILE=config/config.yaml
uv run cortex-create-ca-agents --config $CORTEX_CONFIG_FILE --dry-run
```

`--dry-run` runs all read-only pre-flight checks (APIs, `get_location`,
dataset and table existence, and zero-cost BigQuery dry-runs of
`goldenQueries`) and reports per-agent sync status (`NEEDS_CREATION`,
`NEEDS_UPDATE`, `NO_CHANGE`, or `NOT_MANAGED`) without creating or updating
agents or emitting telemetry. `--dry-run` is mutually exclusive with
`--enable-apis`.

To create or update enabled data agents, run `uv run cortex-create-ca-agents`:

```bash
export CORTEX_CONFIG_FILE=config/config.yaml
uv run cortex-create-ca-agents --config $CORTEX_CONFIG_FILE
```

To automatically enable any missing required Google Cloud APIs during the
run, add `--enable-apis`:

```bash
export CORTEX_CONFIG_FILE=config/config.yaml
uv run cortex-create-ca-agents \
    --config $CORTEX_CONFIG_FILE \
    --enable-apis
```

For all supported CLI flags, see
[CLI create conversational analytics
agents](https://docs.cloud.google.com/cortex/docs/uv-run-cortex-create-ca-agents).

## Verify and chat with your data agent

To verify your provisioned data agent and test natural-language queries:

1. In the Google Cloud console, go to the BigQuery Studio **Agents** page.

   [Go to Agents](https://console.cloud.google.com/bigquery/agents_hub)
2. Select the Google Cloud project configured in
   `buildEnvironment.buildProjectId`.

3. Select the **Agent Catalog** tab and locate the agent matching your
   configured `displayName`. (Set `conversationalAnalytics.location: global` if
   you want your agent to appear in the Agents Hub UI.)

4. Start a [conversation](https://docs.cloud.google.com/bigquery/docs/create-conversations.md.txt) and ask one of
   your configured verified queries (`goldenQueries`) to verify SQL generation
   and results.

To make your verified data agents available to business users across your
organization in Gemini, see
[Gemini integration](https://docs.cloud.google.com/cortex/docs/gemini.md.txt).

## What's next

- Publish and register your data agents in [Gemini integration](https://docs.cloud.google.com/cortex/docs/gemini.md.txt).
- Review CLI flags in [CLI create conversational analytics
  agents](https://docs.cloud.google.com/cortex/docs/uv-run-cortex-create-ca-agents).
- View full schema details in [Deployment configuration](https://docs.cloud.google.com/cortex/docs/deployment-configuration.md.txt#conversational-analytics-config).
- Synchronize governance metadata in [Knowledge Catalog
  integration](https://docs.cloud.google.com/cortex/docs/knowledge-catalog).
- Manage and share agents in [Create data agents](https://docs.cloud.google.com/bigquery/docs/create-data-agents.md.txt).