對話式數據分析整合

本文說明 Google Cloud Cortex Framework 如何與 BigQuery 對話式數據分析和 Conversational Analytics API 整合,直接在已部署的 Cortex Framework 資料產品上,佈建具備領域知識的 BigQuery 資料代理。您可以使用 uv run cortex-create-ca-agents CLI 工具,以宣告方式設定、驗證及同步處理自然語言資料代理,做為 config/config.yaml 的程式碼。在 BigQuery 佈建資料代理後,您也可以在 Gemini 發布及註冊這些代理,讓貴組織的業務使用者探索及查詢。詳情請參閱「Gemini 整合」。

主要優點

透過 Cortex Framework 佈建 BigQuery 對話式數據分析資料代理,可享有下列優勢:

  • 自動收集語意脈絡:自動將每個參照資料產品 annotations/*.yaml 檔案中的資料表和資料欄業務說明,匯入代理的 BigQuery 知識來源,不需手動重新輸入,即可提高 SQL 生成準確度。
  • 環境可攜式驗證查詢 (goldenQueries):將已驗證範例 SQL 查詢 (在 goldenQueries 下設定,先前稱為 BigQuery 中的精確查詢) 中的邏輯 {<product>.project_id} 和 {<product>.dataset_id} 預留位置 (以及駝峰式大小寫 {<product>.projectId} 和 {<product>.datasetId} 變體),重寫為每個環境 (開發、測試或正式環境) 的實體 BigQuery ID。
  • 免付費的預檢 SQL 驗證:對 goldenQueries 中設定的所有查詢執行 BigQuery 模擬編譯檢查 (在 data.bigQueryLocation 中),並在進行任何 API 變更前,確認預估處理的位元組數不超過 設定的位元組限制。
  • 冪等生命週期管理:使用 cortex-framework-version 系統標籤追蹤代管資源,在重複的 CI/CD 執行作業中安全地協調代理定義,在更新時保留現有 DataAgent 資源上由客戶新增的標籤,並保留使用者建立的代理。
  • 彈性位置和自動區域轉送:自動從選用的 conversationalAnalytics.location (建議:global,在 BigQuery Agents Hub UI 中顯示代理) 解析全域、多區域或區域 Conversational Analytics API 端點,或預設為小寫 data.bigQueryLocation。

整合功能的運作方式

在 Dataform 管道於 BigQuery 具體化目標資料表和檢視表後,執行 uv run cortex-create-ca-agents。每次執行時,工具都會完成下列階段:

  1. 脈絡組合。讀取 config/config.yaml 中的 conversationalAnalytics,將目標 BigQuery 資料表和檢視表解析為知識來源,附加 annotations/*.yaml 的說明,並結合指令、彙整路徑、詞彙表字詞和已驗證的查詢 (goldenQueries)。
  2. 預檢驗證。檢查 buildEnvironment.buildProjectId 中必要 Google Cloud 的 API,透過對 Conversational Analytics API 端點發出 get_location 呼叫,驗證解析出的代理位置,確認目標資料集、資料表和檢視表存在,並針對 data.bigQueryLocation 中的擴充 goldenQueries 執行模擬測試,確保不超過位元組上限。
  3. 代理同步。連線至 conversationalAnalytics.location (如省略,則為小寫 data.bigQueryLocation) 的已解析對話式數據分析 API 端點,並建立或更新每個已啟用的資料代理 (如設定 --dry-run,則會回報預計變更,而不變更資源)。

位置覆寫和區域端點轉送

您可以在 config/config.yaml 中設定選用的 conversationalAnalytics.location 值 (正規化為小寫)。如省略,Cortex Framework 預設會使用 data.bigQueryLocation 的小寫值。

Cortex Framework 會將對話式數據分析 API 要求轉送至與解析位置相符的端點,並在建立或更新代理前,使用 get_location 檢查可用性:

  • 全域 (global 或空白):geminidataanalytics.googleapis.com
  • 單一區域 (包含連字號,例如 us-east4 或 europe-west2):geminidataanalytics-LOCATION.googleapis.com
  • 多區域 (不含連字號,例如 us 或 eu):geminidataanalytics.LOCATION.rep.googleapis.com

事前準備

執行 uv run cortex-create-ca-agents 之前,請先確認下列必要條件:

啟用 Google Cloud API

完成「必要條件」中的本機環境、驗證和核心專案設定。接著,在 buildEnvironment.buildProjectId 專案中啟用必要的 API,或在執行 uv run cortex-create-ca-agents 時傳遞 --enable-apis:

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

更改下列內容:

  • BUILD_PROJECT_ID:在 buildEnvironment.buildProjectId 中設定的 Google Cloud 專案 ID,例如:my-cortex-project。

取得必要角色

如要取得佈建及查詢 BigQuery 對話式數據分析資料代理所需的權限,請要求管理員授予您下列 IAM 角色:

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

您或許也能透過自訂角色或其他預先定義的角色,取得必要權限。

部署及執行資料產品管道

請先執行 uv run cortex-build-and-deploy (或 uv run cortex-deploy) 並執行 Dataform 工作流程動作,確保所有目標資料表和檢視表都存在於 BigQuery 中。如需操作說明,請參閱「部署後步驟」。

預先建構的資料代理範本

Cortex Framework 在 src/agents/cortex/ 下提供三個預先建構的資料代理範本 (並隨附於已安裝的 cortex Python 套件中)。每個範本都包含完整的 agent_settings.yaml、網域 system_instruction.md、明確的 schemaRelationships、業務 glossaryTerms,以及參數化的已驗證查詢 (goldenQueries):

範本 agentSettings路徑 必要的資料產品和目錄 分析範圍
財務分析代理 ../src/agents/cortex/sap/financial_analysis/agent_settings.yaml financial_statements、accounts_payable_insights、accounts_receivable_insights、cost_and_profit_centers 和 budget_allocations (在 SAP 部署作業中,預設皆為啟用)。 SAP 資產負債表和損益差異、營運資金 (應付帳款週轉天數、應收帳款週轉天數、應付帳款和應收帳款週轉率)、提早付款現金折扣防禦、暫存或付款遭封鎖的應付帳款發票,以及成本中心預算超支 (5 項經驗證的查詢,已啟用 Python 分析)。
SAP 進貨物流風險代理 ../src/agents/cortex/sap_bdc/inbound_logistics_risk/agent_settings.yaml supplier_plant_weather_risk_insights 和 supplier_inbound_delivery_weather_risk_insights (cortex_samples),由 sap_bdc_catalog、ah_weathernext_catalog 和 ah_dnb_catalog 目錄支援。 進貨交付執行、重要物料短缺、供應商準時全額交付 (OTIF)、以調度為基準的 P50 和 P90 動態預計到達時間、陸地和海上天氣或港口延誤,以及鄧白氏提單比對層級 (7 項已驗證查詢,已啟用 Python 分析)。
銷售業績和收益預測助理 ../src/agents/cortex/sap_sfdc/sales_performance_revenue_forecast/agent_settings.yaml SAP sales_performance (cortex_samples)、sales_documents、customers 和 materials;Salesforce opportunity_pipeline、sales_activities、leads_capture_conversions、case_management 和 accounts。 跨系統 SAP 和 Salesforce 商業收益展望橋接、已實現帳單收益與未出貨訂單比較、機率加權管道涵蓋率、待開發客戶來源轉換成效、客戶流失年增率復原,以及升級支援風險 (4 項已驗證查詢,已啟用 Python 分析)。

部署必要的資料產品和目錄後,將任何預先建構的範本新增至 config/config.yaml 並設定 enabled: true:

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"

更改下列內容:

  • BUILD_PROJECT_ID:託管資料代理資源的 Google Cloud 專案 ID,例如:my-cortex-project。

設定資料代理

在 config/config.yaml 中新增頂層 conversationalAnalytics 區段。agents 下方的每個項目都可以使用 agentSettings 指向模組化外部 YAML 檔案,或使用 inlineAgentSettings 定義其內嵌內容。

選項 1:外部 agent_settings.yaml

在 config/config.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

更改下列內容:

  • BUILD_PROJECT_ID:託管資料代理程式資源的 Google Cloud 專案 ID,例如:my-cortex-project。

使用代理的資料產品 (知識來源)、系統指令、彙整關係、組織詞彙和已驗證的查詢 (goldenQueries) 建立 config/agents/procurement_spend/agent_settings.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

選項 2:獨立 inlineAgentSettings

如果是精簡的單一產品代理,可以直接在 config/config.yaml 中定義 inlineAgentSettings:

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

更改下列內容:

  • BUILD_PROJECT_ID:託管資料代理程式資源的 Google Cloud 專案 ID,例如:my-cortex-project。

設定解析和驗證規則

解析及驗證 conversationalAnalytics 定義時,uv run cortex-create-ca-agents 會強制執行下列規則:

  • 三層 agentSettings 路徑解析:直接使用絕對路徑。相對 agentSettings 路徑會依序解析:
    1. 包含 config.yaml 的目錄 (例如 config/)。
    2. 工作區根目錄。
    3. 只要路徑包含 agents 區段,就會使用已安裝 cortex Python wheel 套件中的 agents/ 目錄 (因此預先建構的路徑,例如 ../src/agents/cortex/...,在來源簽出和 wheel 安裝中都能運作)。
  • 彈性 dataProducts[].id 查詢:dataProducts 中的每個項目 (以及 schemaRelationships 和 goldenQueries 中的相符參照) 都可以指定 data.modules.products 中的明確 moduleId (例如 sap_customers),或明確的標準葉 module_name (modulePath 的最後一個區段,例如 customers)。如果多個啟用的產品模組共用相同的葉 module_name,解析度會提高 AmbiguousProductReferenceError,且您必須參照明確的 moduleId。
  • 非破壞性 contextVersion 更新 (published 與 staging 相比):contextVersion 預設為 published。更新會傳送指定的 protobuf FieldMask,僅涵蓋 display_name、description、labels 和有效情境槽 (data_analytics_agent.published_context 或 data_analytics_agent.staging_context),其他情境槽則保持不變。如要在 Gemini 註冊資料代理,必須使用 contextVersion: published 佈建。
  • 已驗證查詢 (goldenQueries) 位元組限制和參數類型:
    • 每項已驗證查詢的 BigQuery 模擬測試預估值 (total_bytes_processed) 必須等於或低於 min(options.maxBilledBytes, 500,000,000,000) (500 GB API 上限;options.maxBilledBytes 預設為 10737418240,即 10 GiB)。
    • 預留位置支援 snake_case ({<product>.project_id}、{<product>.dataset_id}) 和 camelCase ({<product>.projectId}、{<product>.datasetId}) 形式,且每個參照的產品都必須出現在代理的 dataProducts 中。
    • 支援的 parameters[].dataType 值 (STRING、INT64、FLOAT64、NUMERIC、BIGNUMERIC、BOOL、DATE、DATETIME、TIME、TIMESTAMP、BYTES、GEOGRAPHY、JSON) 會自動標準化別名:INTEGER 變成 INT64、FLOAT 變成 FLOAT64,BOOLEAN 則變成 BOOL。

如需完整的欄位規格和驗證限制,請參閱對話式數據分析 (conversationalAnalytics)。

佈建及同步處理代理

在 BigQuery 中具體化目標資料產品資料表和檢視表後,請先使用 --dry-run 預覽預檢驗證和預計同步動作,再套用變更:

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

--dry-run 會執行所有唯讀預檢 (API、get_location、資料集和資料表是否存在,以及 goldenQueries 的零成本 BigQuery 模擬測試),並回報每個代理的同步狀態 (NEEDS_CREATION、NEEDS_UPDATE、NO_CHANGE 或 NOT_MANAGED),不會建立或更新代理,也不會發出遙測資料。--dry-run 與 --enable-apis 互斥。

如要建立或更新已啟用的資料代理,請執行 uv run cortex-create-ca-agents:

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

如要在執行期間自動啟用任何缺少的必要 Google Cloud API,請新增 --enable-apis:

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

如要查看所有支援的 CLI 旗標,請參閱「CLI 建立對話式數據分析代理」。

驗證資料代理並與其對話

如要驗證佈建的資料代理並測試自然語言查詢,請按照下列步驟操作:

  1. 前往 Google Cloud 控制台的 BigQuery Studio「Agents」(代理) 頁面。

    前往「Agents」

  2. 選取在buildEnvironment.buildProjectId中設定的 Google Cloud 專案。

  3. 選取「Agent Catalog」(代理程式目錄) 分頁標籤,然後找出與設定的 displayName 相符的代理程式。(如要讓代理顯示在 Agents Hub UI 中,請設定 conversationalAnalytics.location: global)。

  4. 開始對話,並提出其中一項已設定的驗證查詢 (goldenQueries),驗證 SQL 生成和結果。

如要讓貴組織的企業使用者在 Gemini 中使用已驗證的資料代理,請參閱「Gemini 整合」。

後續步驟