擷取資料資產的脈絡

資料脈絡可讓 AI 應用程式深入瞭解資料資產,進而提高 LLM 生成回覆的準確度和關聯性。

lookupContext 方法會使用單一 API 要求,擷取預先格式化的資料資產中繼資料套件,並針對互動式代理工作流程進行最佳化,藉此彌補情境落差。您可以運用這個精簡的 LLM 適用脈絡,讓虛擬服務專員評估及使用資料資產。

您可以對儲存在 Knowledge Catalog 中的任何資料資產使用 lookupContext 方法,例如 BigQuery 資料表、資料集或任何其他項目。

代理程式如何取得資料脈絡?

  1. 代理程式會擷取可能與情境擷取相關的資料資產,例如使用 Knowledge Catalog 語意搜尋。
  2. 代理會使用 lookupContext 方法發出單一 API 呼叫或 MCP 工具要求,擷取特定資產的脈絡。
  3. 這個方法會傳回包含預先格式化文字區塊的回應。視您在要求中指定的 format 參數而定,文件可採用 YAML、XML 或 JSON 格式。

    回應包含下列背景資訊元素:

    脈絡元素 說明
    技術中繼資料 資源結構定義和實體設定,例如 BigQuery 分區和分群策略。
    作業中繼資料 根據歷來查詢記錄和資料洞察資料,建立聯結和其他關係。詳情請參閱「查看資料關係」。
    商家描述 相關業務用語、總覽、目錄註解、來源系統擷取並在 Knowledge Catalog 中自動生成的說明,以及指南。

    注意:您可以在資料資產上使用指南,擷取對代理商有用的額外背景資訊,方便他們探索、檢查或使用資料資產。
    資料剖析 分布統計資料、不重複值數量、空值比例和樣本值。
    資料品質 根據預先定義的規則,自動檢查資料品質。
    相關資料資產的背景資訊 相關資料資產的背景資訊,例如術語或其他相關資產,像是經常聯結的資料表。相關資產傳回的內容與主要資產或資產相同。
  4. 代理會根據這項回應,選取相關素材資源或決定如何使用。

事前準備

使用 lookupContext 方法前,請確認您具備必要角色,並啟用必要 API。

必要的角色

如要取得呼叫 lookupContext 方法所需的權限,請要求管理員在 Google Cloud 專案 iam.gserviceaccount.com中授予您下列 IAM 角色:

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

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

啟用 API

如要使用 lookupContext 方法,請在專案中啟用下列 API:

  • Knowledge Catalog API

啟用 API 時所需的角色

如要啟用 API,您必須具備 serviceusage.services.enable 權限。如果您建立了專案,可能已透過「擁有者」角色 (roles/owner) 取得這項權限。否則,您可以透過「服務使用情形管理員」角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色。

啟用 API

擷取資料資產的脈絡

如要擷取資料資產的脈絡,請使用 Dataplex API 直接存取 lookupContext 方法,或使用 Knowledge Catalog 遠端 Model Context Protocol (MCP) 伺服器或 MCP Toolbox For Databases。

lookupContext 方法會根據您的權限篩選資源。回應只會包含您的身分具備必要 Identity and Access Management (IAM) 權限的資產資料。如果您對要求的資源沒有任何權限,這個方法會傳回空白的回應。

REST

如要擷取資料資產的內容,請傳送下列要求:

curl --request POST \
   'https://dataplex.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION:lookupContext' \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
  "resources": RESOURCES
  "options": OPTIONS
  }' \
--compressed

更改下列內容:

  • PROJECT_ID:您 Google Cloud 專案的 ID
  • LOCATION:資產所在的區域 (例如 us-central1)
  • RESOURCES:最多十個要擷取內容的項目名稱,格式為 projects/{project}/locations/{location}/entryGroups/{entryGroup}/entries/{entry}。如果是多個資源,API 會建立所要求資源之間的關係 (例如常見的結構定義聯結),並在內容中傳回關係資訊。
  • OPTIONS:可定義環境的選項:
    • format 是結構定義檔案的格式。例如:yaml。
    • context_budget 是回覆的字元數上限。如果將 all_schema_fields 參數設為 true,API 會傳回所有結構定義欄位,不論 context_budget 值為何。

以下是擷取 BigQuery 資料表內容的範例要求:

curl --request POST \
'https://dataplex.googleapis.com/v1/projects/test-project/locations/us:lookupContext?key=[YOUR_API_KEY]' \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
    "resources":
    ["projects/test-project/locations/us/entryGroups/@bigquery/entries/bigquery.googleapis.com/projects/test-project/datasets/test-dataset/tables/test-table"],
    "options":
    {
      "format":"yaml",
      "context_budget":"4000"
    }
  }' \
--compressed

回覆內容是預先格式化的文字區塊,類似於下列內容:

{
"context": "resource: \"projects/test-project/locations/us/entryGroups/@bigquery/entries/bigquery.googleapis.com/projects/test-project/datasets/sales_data/tables/orders\"\ntechnical_metadata:\n  schema:\n    - name: order_id\n      type: STRING\n      description: \"Primary key for the order.\"\n    - name: customer_id\n      type: STRING\n    - name: total_amount\n      type: NUMERIC\n  partitioning:\n    type: TIMESTAMP\n    field: order_date\nbusiness_descriptions:\n  overview: \"Historical record of all customer transactions.\"\n  related_terms:\n    - \"Revenue\"\n    - \"Sales Transactions\"\n  guidelines: \"Always filter by 'order_date' to optimize query costs due to partitioning.\"\ndata_profile:\n  columns:\n    - name: total_amount\n      null_ratio: 0.001\n      distinct_values: 52340\n      sample_values: [45.99, 120.00, 15.50]\ndata_quality:\n  summary:\n    - rule: \"positive_amounts\"\n      status: PASSED\n      description: \"Ensures total_amount is greater than zero.\"\noperational_metadata:\n  frequent_joins:\n    - table: \"projects/test-project/locations/us/entryGroups/@bigquery/entries/bigquery.googleapis.com/projects/test-project/datasets/sales_data/tables/customers\"\n      join_key: \"customer_id\"\n"
}

Python

Python

在試用這個範例之前,請先按照「使用用戶端程式庫的 Knowledge Catalog 快速入門導覽課程」中的 Python 設定說明操作。詳情請參閱 Knowledge Catalog Python API 參考文件。

如要向 Knowledge Catalog 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
#   client as shown in:
#   https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import dataplex_v1


def sample_lookup_context():
    # Create a client
    client = dataplex_v1.CatalogServiceClient()

    # Initialize request argument(s)
    request = dataplex_v1.LookupContextRequest(
        name="name_value",
        resources=["resources_value1", "resources_value2"],
    )

    # Make the request
    response = client.lookup_context(request=request)

    # Handle the response
    print(response)

以下範例說明如何擷取 BigQuery 資料表的內容:

 from google.cloud import dataplex_v1

 # Initialize the client
 client = dataplex_v1.CatalogServiceClient()

 # Define the request with a seed resource
 request = dataplex_v1.LookupContextRequest(
     name="projects/test-project/locations/us",
     resources=["projects/test-project/locations/us/entryGroups/@bigquery/entries/bigquery.googleapis.com/projects/test-project/datasets/test-dataset/tables/test-table"],
     options={"format": "yaml", "budget": "4000"}
 )

 # Retrieve the LLM-ready context
 response = client.lookup_context(request=request)
 context_yaml = response.context

 print(f"Retrieved Context: \n{context_yaml}")

有哪些情境查詢最佳做法?

如要在使用 lookupContext 方法時獲得最佳成效,請考慮下列最佳做法:

  • 使用 context_budget 參數要求所選長度的輸出內容。lookupContext 方法會盡可能在參數規定的限制內,將最相關的內容納入輸出結果。
  • 您最多可以在 resources 清單中列出十項資料資產。舉例來說,在 resources 清單中加入多個資料表,API 不僅會提供這些資料表的背景資訊,也會提供這些資料表之間可能的聯結路徑,因此可提供必要指引,說明如何一起使用這些資料表。
  • 請使用最符合 LLM 或代理程式剖析邏輯的 format 選項,例如 yaml 或 json,避免耗費大量資源進行轉換。

後續步驟