擷取資料資產的脈絡

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

lookupContext 方法會使用單一 API 要求,擷取預先格式化的資料資產中繼資料套件,並針對互動式 Agentic Workflows 進行最佳化,藉此彌補情境落差。您可以使用這個精簡、可供 LLM 使用的脈絡,讓代理在評估及使用資料資產時,能以實際資料為依據。

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

代理如何取得資料脈絡?

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

    回應包含下列情境元素:

    Context 元素 說明
    技術中繼資料 資源結構定義和實體設定,例如 BigQuery 分區和分群策略,以及 BigQuery 常式定義,包括引數、傳回類型和原始碼。
    作業中繼資料 根據歷來查詢記錄和資料洞察,提供彙整和其他關係。詳情請參閱「查看資料關係」。
    商家描述 相關業務術語、總覽、目錄註解、來源系統擷取和 Knowledge Catalog 自動生成的說明,以及指南。

    注意:您可以在資料資產上使用指南切面,擷取其他背景資訊,方便代理探索、檢查或使用資料資產。
    資料剖析 分布統計資料、不重複值計數、空值比率和樣本值。
    資料品質 自動根據預先定義的規則檢查資料品質。
    相關資料資產的背景資訊 相關資料資產的背景資訊,例如詞彙表字詞或其他相關資產,像是經常彙整的資料表。相關資產傳回的情境,包含與主要資產相同的元素範圍。
  4. 代理會根據這項回覆,選取相關素材資源或決定使用方式。

事前準備

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

必要的角色

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

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

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

啟用 API

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

  • Dataplex API

啟用 API 所需的角色

您必須具備 serviceusage.services.enable 權限,才能啟用 API。如果您建立了專案,可能已透過「擁有者」角色 (roles/owner) 取得這項權限。否則,您可以透過「Service Usage 管理員」角色 (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 方法擷取 BigQuery 常式的內容,例如使用者定義函式、資料表函式和預存程序。代理可使用這項背景資訊,瞭解常式的作用和呼叫方式,例如生成 SQL 查詢時。常式的背景資訊包含下列資訊:

  • 常式類型,例如純量函式、資料表函式或程序。
  • 日常安排的語言。
  • 常式引數和傳回類型。
  • 常式原始碼 (定義主體)。
  • Knowledge Catalog 的說明和其他中繼資料。

如要擷取常式的內容,請在要求的 resources 清單中加入常式的項目名稱。項目名稱的格式如下:

projects/PROJECT_ID/locations/LOCATION/entryGroups/@bigquery/entries/bigquery.googleapis.com/projects/PROJECT_ID/datasets/DATASET_ID/routines/ROUTINE_ID

更改下列內容:

  • PROJECT_ID:包含常式的專案 ID。
  • LOCATION:包含常式的資料集位置 (例如 us)。
  • DATASET_ID:包含常式的資料集 ID。
  • ROUTINE_ID:日常安排的 ID。

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

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

  • 使用 context_budget 參數,要求輸出脈絡達到指定長度。lookupContext 方法會盡可能在參數規定的限制內,將最相關的內容納入輸出。
  • resources 清單最多可列出十項資料資產。舉例來說,如果在 resources 清單中加入多個資料表,API 不僅會提供這些資料表的背景資訊,還會提供資料表之間可能的彙整路徑,進而提供必要指引,說明如何搭配使用這些資料表。
  • 請根據 LLM 或代理的剖析邏輯,選擇最合適的 format 選項 (例如 yaml 或 json),避免耗費大量資源進行轉換。

後續步驟