根据文档生成答案

借助 Developer Knowledge API,您可以提出有关 Google 开发者产品的问题,并直接获得自然语言回答。对于每个查询,该 API 都会根据开发者知识语料库(在 API 参考文档中称为“有依据的生成”)撰写回答,并附上相关文档页面的引用。

准备工作

为首选工具设置环境:

gcloud

安装并配置 gcloud CLI,然后启用 Developer Knowledge API。

REST

启用该 API 并生成 Developer Knowledge API 密钥。 然后,将密钥保存到环境变量中:

export DEVELOPERKNOWLEDGE_API_KEY="YOUR_API_KEY"

将 YOUR_API_KEY 替换为您的 Developer Knowledge API 密钥。

回答查询

使用 gcloud developer-knowledge answer-query 命令或 answerQuery REST 方法提问。

以下示例发送了一个查询,询问如何创建 BigQuery 数据集:

gcloud

gcloud developer-knowledge answer-query \
  --query="How do I create a BigQuery dataset?"

REST

curl -X POST "https://developerknowledge.googleapis.com/v1:answerQuery?key=$DEVELOPERKNOWLEDGE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"query": "How do I create a BigQuery dataset?"}'

响应包含 answer.answerText 字段中的文本答案,以及 answer 对象中的 citations 和 references:

{
  "answer": {
    "answerText": "To create a BigQuery dataset, you can use the Google Cloud Console, the bq command-line tool, or the BigQuery client libraries.",
    "citations": [
      {
        "startIndex": 0,
        "endIndex": 123,
        "sources": [
          {
            "referenceIndex": 0
          }
        ]
      }
    ],
    "references": [
      {
        "documentReference": {
          "documentChunk": {
            "parent": "documents/docs.cloud.google.com/bigquery/docs/datasets",
            "content": "This page explains how to create BigQuery datasets...",
            "document": {
              "name": "documents/docs.cloud.google.com/bigquery/docs/datasets",
              "title": "Introduction to datasets",
              "uri": "https://docs.cloud.google.com/bigquery/docs/datasets"
            }
          }
        }
      }
    ]
  }
}

过滤文档来源

如需限制用于生成答案的文档来源,请在 gcloud CLI 中使用 --query-filter 标志或在 REST 请求正文中添加 filter 字段来传递过滤条件表达式。如需详细了解支持的过滤字段和运算符,请参阅过滤搜索结果。

以下示例将文档来源限制为 docs.cloud.google.com:

gcloud

gcloud developer-knowledge answer-query \
  --query="How do I create a BigQuery dataset?" \
  --query-filter='data_source = "docs.cloud.google.com"'

REST

curl -X POST "https://developerknowledge.googleapis.com/v1:answerQuery?key=$DEVELOPERKNOWLEDGE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "How do I create a BigQuery dataset?",
    "filter": "data_source = \"docs.cloud.google.com\""
  }'

在 AnswerQuery 和 SearchDocumentChunks 之间进行选择

使用 API 或 Developer Knowledge MCP 服务器时,请选择最符合您需求的搜索方法:

  • AnswerQuery(或 answer_query MCP 工具):最适合回答一般“操作方法”问题、比较产品以及提供分步指南,您希望获得包含指向源文档的链接的完整摘要。
  • SearchDocumentChunks(或 search_documents MCP 工具):最适合查找确切的 CLI 标志、代码语法、形参名称或 IAM 权限(例如 service.resource.verb)。请使用两到五个具体关键字,而不是完整的问题。

后续步骤