检索数据资产的上下文

围绕数据的上下文可让 AI 应用深入了解数据资产,从而提高 LLM 生成的响应的准确性和相关性。

The lookupContext 方法通过单个 API 请求来检索针对交互式 Agentic Workflows 进行了优化的预格式化数据资产元数据软件包,从而弥合上下文差距。您可以使用这种紧凑的、LLM 就绪的上下文来指导智能体评估和使用数据资产。

您可以将 lookupContext 方法用于存储在 Knowledge Catalog 中的任何数据资产,例如 BigQuery 表、数据集和 例程,以及 数据网域和任何其他 条目。

智能体如何获取数据上下文?

  1. 智能体检索可能与上下文检索相关的数据资产,例如使用 Knowledge Catalog 语义搜索。
  2. 智能体使用 lookupContext 方法发出单个 API 调用或 MCP 工具请求,以检索特定资产的上下文。
  3. 该方法会返回一个包含预格式化文本块的响应。文档的格式可以是 YAML、XML 或 JSON,具体取决于您在请求中指定的 format 参数。

    响应包含以下上下文元素:

    上下文元素 说明
    技术元数据 资源架构和物理配置,例如 BigQuery 分区和聚簇策略,以及 BigQuery 例程定义,包括参数、返回值类型和源代码。
    运营元数据 联接和其他关系,基于历史查询日志和数据洞见。如需了解详情,请参阅查看数据关系。
    商家说明 相关业务术语、概览、目录注释、在源系统中捕获并在 Knowledge Catalog 中自动生成的说明,以及指南。

    注意:您可以使用数据资产的指南方面来捕获其他上下文,以便在智能体发现、检查或使用数据资产时提供帮助。
    数据分析 分布统计信息、不同值计数、null 比率和示例值。
    数据质量 根据预定义规则自动进行数据质量检查的输出。
    相关数据资产的上下文 相关数据资产的上下文,例如术语库术语或其他相关资产,如经常联接的表。为相关资产返回的上下文包含与主要资产或资产相同的元素范围。
  4. 智能体使用此响应来指导相关资产的选择或使用。

准备工作

在使用 lookupContext 方法之前,请确保您拥有必要的角色并启用所需的 API。

所需的角色

如需获得 调用 lookupContext 方法所需的权限, 请让管理员向您授予 Google Cloud 项目 的 以下 IAM 角色:

  • 对目录资源(包括条目、条目组和术语库)的读取权限: Dataplex Catalog Viewer (roles/dataplex.catalogViewer)

如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限。

您也可以通过自定义角色或其他预定义角色来获取所需的权限。

启用 API

如需使用 lookupContext 方法,请在项目中启用以下 API:

  • Knowledge Catalog API

启用 API 所需的角色

如需启用 API,您需要拥有 serviceusage.services.enable 权限。如果您创建了项目,则您可能已通过 Owner 角色 (roles/owner) 拥有此权限。否则,您可以通过 Service Usage Admin 角色 (roles/serviceusage.serviceUsageAdmin) 获得此权限。了解如何授予角色。

启用 API

检索数据资产的上下文

如需检索数据资产的上下文,请使用 Dataplex API 直接访问 lookupContext 方法,或使用 Knowledge Catalog remote Model Context Protocol (MCP) server 或 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:最多 10 个要检索上下文的条目名称,格式为 projects/{project}/locations/{location}/entryGroups/{entryGroup}/entries/{entry}。 对于多个资源,API 会在所请求的资源之间建立关系(例如经常联接的架构),并在上下文中返回关系信息。
  • OPTIONS:用于定义上下文的选项:
    • format 是上下文文件的格式。例如,yaml。
    • context_budget 是响应的字符数上限。如果您将 all_schema_fields 参数设置为 true,则无论 context_budget 值如何,API 都会返回所有架构字段。

检索 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

试用此示例之前,请按照 Python 设置说明进行操作,具体请参阅 Knowledge Catalog 快速入门:使用 使用客户端库。 如需了解详情,请参阅 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 列表中列出 10 个数据资产。例如,在 resources 列表中添加多个表可让 API 不仅提供这些表的上下文,还提供这些表之间可能的联接路径的上下文,从而为如何一起使用这些表提供必要的指导。
  • 使用与 LLM 或智能体的解析逻辑最一致的 format 选项(例如 yaml 或 json),以避免代价高昂的转换。

后续步骤