使用 RAG 生成接地的回答

在 Agent Search 的检索增强生成 (RAG) 体验中,您可以根据以下接地来源生成接地回答:

  • Google 搜索:如果您想将模型与世界知识、各种主题或互联网上的最新信息相关联,请使用“依托 Google 搜索进行接地”功能。依托 Google 搜索进行接地支持动态检索,让您可以选择仅在必要时使用 Google 搜索生成接地结果。因此,动态检索配置会评估提示是否需要了解近期活动,并启用“依托 Google 搜索进行接地”功能。如需了解详情,请参阅动态检索。
  • 内嵌文本:使用内嵌文本接地,将回答接地到请求中提供的称为“事实文本”的文本片段中。事实文本是用户提供的陈述,对于给定请求,该陈述被视为事实。模型不会检查事实文本的真实性。
  • Agent Search 数据存储区:如果您想将模型连接到 Agent Search 数据存储区中的企业文档,请使用依托 Agent Search 进行接地。

本页面介绍了如何使用以下方法根据这些接地来源生成接地回答:

此外,您还可以选择从模型流式传输回答。通过流式传输生成接地回答是一项实验性功能。

您可以使用其他方法来生成有依据的回答,以适应您的应用。如需了解详情,请参阅用于构建搜索和 RAG 体验的 Vertex AI API。

术语

在使用有依据的回答生成方法之前,最好先了解输入和输出、如何构建请求以及与 RAG 相关的术语。

RAG 术语

RAG 是一种方法,可让大语言模型 (LLM) 生成基于您所选数据源的回答。RAG 包含两个阶段:

  1. 检索:快速获取最相关的事实可能是常见的搜索问题。借助 RAG,您可以快速检索对生成答案至关重要的事实。
  2. 生成:LLM 使用检索到的事实来生成有依据的回答。

因此,有依据的回答生成方法会从接地来源中检索事实,并生成有依据的回答。

输入数据

接地回答生成方法需要在请求中提供以下输入:

  • 角色:给定文本的发送者,可以是用户 (user) 或模型 (model)。

  • 文本:当角色为 user 时,文本是提示;当角色为 model 时,文本是接地回答。在请求中指定角色和文本的方式取决于以下因素:

    • 对于单轮回答生成,用户在请求中发送提示文本,模型在回答中发送回答文本。
    • 对于多轮回答生成,请求包含之前所有轮次的提示-回答对,以及用户在当前轮次中输入的提示文本。因此,在此类请求中,提示文本的角色为 user,回答文本的角色为 model。
  • 系统指令:提示的前言,用于控制模型的行为并相应地修改输出。例如,您可以为生成的回答添加角色,或指示模型以特定方式设置输出文本的格式。对于多轮回答生成,您必须为每一轮提供系统指令。如需了解详情,请参阅使用系统指令。

  • 接地来源:回答所依据的来源,可以是以下一项或多项:

    • Google 搜索:依托 Google 搜索结果为回答接地。当接地来源为 Google 搜索时,您可以指定具有动态检索阈值的动态检索配置。如需了解详情,请参阅动态检索。

    • 内嵌文本:根据请求中提供的事实文本来回答问题。事实文本是用户提供的陈述,对于给定请求,该陈述被视为事实。模型不会检查事实文本的真实性。每个内嵌文本来源中最多可以提供 100 个事实文本。事实文本可以使用元属性(例如标题、作者和 URI)进行支持。在引用支持回答的文本块时,这些元属性会在响应中返回。

    • Agent Search 数据存储区:依据 Agent Search 数据存储区中的文档回答问题。您不能将网站搜索数据存储区指定为接地来源。

    在给定请求中,您可以同时提供内嵌文本来源和代理搜索数据存储区来源。您无法将 Google 搜索与其中任何一个来源结合使用。因此,如果您想使用 Google 搜索结果作为回答的依据,则必须发送单独的请求,并将 Google 搜索指定为唯一的依据来源。

    您最多可以提供 10 个接地来源,顺序不限。例如,假设您按以下顺序提供以下数量的接地来源,以获得总共 10 个接地来源:

    • 三个内嵌文本来源,每个来源最多可包含 100 个事实文本
    • 六个 Agent Search 数据存储区
    • 一个内嵌文本来源,最多包含 100 个事实文本

    系统会按照每个来源在请求中的指定顺序为其分配一个索引。例如,如果您在请求中指定了来源组合,则系统会按下表所示分配来源索引:

    依据来源 索引
    内嵌文本 1 0
    内嵌文本 2 1
    Agent Search 数据存储区 #1 2
    内嵌文本 3 3
    Agent Search 数据存储区 #2 4

    此索引在回答中引用,在跟踪来源时很有用。

  • 生成规范:模型配置的规范,包含以下信息:

    • 模型 ID:指定用于回答生成的 Vertex AI Gemini 模型。如需查看可用于生成接地回答的 Gemini 模型列表,请参阅 Gemini 模型。

    • 模型参数:指定可为您选择使用的模型设置的参数。这些参数包括:语言、温度、Top-P 和 Top-K。如需详细了解这些参数,请参阅 Gemini 模型参数。

  • 语言代码:生成的回答的语言通常设置为与提示的语言一致。如果提示中没有单一语言(例如,如果提示非常简短,并且在多种语言中都有效),则语言代码字段会决定回答的语言。

    如需查看语言代码列表,请参阅语言。

  • 纬度和经度:指定用户的纬度和经度。 如果查询包含特定于位置的问题(例如“查找我附近的咖啡店”),则会使用这些字段。如果无法确定查询语言,并且未设置语言代码,则系统会使用经纬度来确定回答的语言。

输出数据

模型生成的回答称为候选回答,其中包含以下数据。输出中可能不会显示所有字段。

  • 角色:接地回答的发送者。回答始终包含接地回答文本。因此,回答中的角色始终是模型。

  • 文本:接地的回答。

  • 接地分数:一个介于 [0, 1] 之间的浮点值,用于指示回答与给定来源的关联程度。

  • 接地元数据:有关接地来源的元数据。接地元数据包含以下信息:

    • 支持块:支持回答的块列表。每个支持分块都会分配一个支持分块索引,这在跟踪来源时很有用。每个支持分块都包含以下内容:

      • 分块文本:从来源中逐字引用的文本部分,回答或回答的一部分(称为声明文本)就是从中提取的。此字段不一定会出现在响应中。
      • 来源:请求中分配给来源的索引。
      • 来源元数据:有关数据块的元数据。根据来源,来源元数据可以是以下任一项:

        • 对于内嵌来源,元数据可以是请求中指定的其他详细信息,例如标题、作者或 URI。
        • 对于代理搜索数据存储区,元数据可以是文档 ID、文档标题、URI(Cloud Storage 位置)或页码。
        • 对于“依托 Google 搜索进行接地”,生成接地结果后,元数据会包含一个 URI,该 URI 会重定向到用于生成接地结果的内容的发布商。元数据还包含发布商的网域。在生成接地结果后,提供的 URI 最多可在 30 天内访问。
    • 接地支持:回答中某个主张的接地信息。接地支持包含以下信息:

      • 主张文本:由支持块文本证实的部分或全部回答。
      • 支持块索引:按照支持块在支持块列表中出现的顺序,为支持块分配的索引。
      • 网页搜索查询:Google 搜索建议的建议搜索查询。
      • 搜索建议:如果您收到包含 Google 搜索建议的回答,则该回答是“接地结果”,受“依托 Google 搜索进行接地”的服务条款约束。如需了解详情,请参阅服务条款。 searchEntryPoint 字段中的 renderedContent 字段是为实现 Google 搜索建议而提供的代码。如需使用 Google 搜索建议,请参阅使用 Google 搜索建议。

在单轮对话中生成接地回答

本部分介绍了如何生成基于以下来源的回答:

以 Agent Search 数据存储区中的内嵌文本和数据作为回答依据

以下示例展示了如何通过指定内嵌文本和 Agent Search 数据存储区作为接地来源来发送提示文本。您无法将网站搜索数据存储区指定为接地来源。 此示例使用 generateGroundedContent 方法。

REST

  1. 在以下 curl 请求中发送提示。

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_NUMBER/locations/global:generateGroundedContent" \
    -d '
    {
    "contents": [
     {
       "role": "user",
       "parts": [
         {
           "text": "PROMPT_TEXT"
         }
       ]
     }
    ],
    "systemInstruction": {
       "parts": {
           "text": "SYSTEM_INSTRUCTION"
       }
    },
    "groundingSpec": {
     "groundingSources": [
       {
         "inlineSource": {
           "groundingFacts": [
             {
               "factText": "FACT_TEXT_1",
               "attributes": {
                 "title": "TITLE_1",
                 "uri": "URI_1",
                 "author": "AUTHOR_1"
               }
             }
           ]
         }
       },
       {
         "inlineSource": {
           "groundingFacts": [
             {
               "factText": "FACT_TEXT_2",
               "attributes": {
                 "title": "TITLE_2",
                 "uri": "URI_2"
               }
             },
             {
               "factText": "FACT_TEXT_3",
               "attributes": {
                 "title": "TITLE_3",
                 "uri": "URI_3"
               }
             }
           ]
         }
       },
       {
         "searchSource": {
           "servingConfig": "projects/PROJECT_NUMBER/locations/global/collections/default_collection/engines/APP_ID_1/servingConfigs/default_search"
         }
       },
       {
         "searchSource": {
           "servingConfig": "projects/PROJECT_NUMBER/locations/global/collections/default_collection/engines/APP_ID_2/servingConfigs/default_search"
         }
       }
      ]
    },
    "generationSpec": {
      "modelId": "MODEL_ID",
      "temperature": TEMPERATURE,
      "topP": TOP_P,
      "topK": TOP_K
    },
    "user_context": {
      "languageCode: "LANGUAGE_CODE",
      "latLng": {
        "latitude": LATITUDE,
        "longitude": LONGITUDE
     },
    }
    }'
    

    替换以下内容:

    • PROJECT_NUMBER:您的 Google Cloud 项目编号。
    • PROMPT_TEXT:用户的提示。
    • SYSTEM_INSTRUCTION:一个可选字段,用于提供预置指令或一些额外的上下文。
    • FACT_TEXT_N:用于接地回答的内嵌文本。您最多可以提供 100 个事实文本。
    • TITLE_N:一个可选字段,用于为内嵌文本设置标题元属性。
    • URI_N:一个可选字段,用于为内嵌文本设置 URI 元属性。
    • AUTHOR_N:一个可选字段,用于为内嵌文本设置作者元属性。
    • APP_ID_N:Agent Search 应用的 ID。
    • MODEL_ID:一个可选字段,用于设置您要用来生成接地答案的 Gemini 模型的模型 ID。如需查看可用模型 ID 的列表,请参阅 Vertex AI 上的生成式 AI 产品文档中的 Gemini 模型。
    • TEMPERATURE:可选字段,用于设置采样温度。Google 建议将温度设置为 0.0。如需了解详情,请参阅 Gemini 模型参数。
    • TOP_P:可选字段,用于设置模型的 top-P 值。如需了解详情,请参阅 Gemini 模型参数。
    • TOP_K:一个可选字段,用于设置模型的 top-K 值。如需了解详情,请参阅 Gemini 模型参数。
    • LANGUAGE_CODE:一个可选字段,可用于设置生成的回答和返回的文本块的语言。如果无法根据查询确定语言,则使用此字段。默认值为 en。如需查看语言代码列表,请参阅语言。
    • LATITUDE:用于设置纬度的可选字段。以十进制度为单位输入值,例如 -25.34。
    • LONGITUDE:用于设置经度的可选字段。以十进制度为单位输入值,例如 131.04。

以单轮回答生成为例,该回答以单行文本和智能体搜索为依据

在以下示例中,请求指定了以下接地来源:一个内嵌文本事实和一个 Agent Search 数据存储区。此示例使用 generateGroundedContent 方法。此示例还使用系统指令,让回答以笑脸表情符号结尾。

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://discoveryengine.googleapis.com/v1/projects/123456/locations/global:generateGroundedContent" \
-d '
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "text": "How did Google do in 2020? Where can I find BigQuery docs?"
        }
      ]
    }
  ],
  "systemInstruction": {
      "parts": {
          "text": "Add a smiley emoji after the answer."
      }
  },
  "groundingSpec": {
    "groundingSources": [
      {
        "inline_source": {
          "grounding_facts": [
            {
              "fact_text": "The BigQuery documentation can be found at https://cloud.google.com/bigquery/docs/introduction",
              "attributes": {
                "title": "BigQuery Overview",
                "uri": "https://cloud.google.com/bigquery/docs/introduction"
              }
            }
          ]
        }
      },
      {
        "searchSource": {
          "servingConfig": "projects/123456/locations/global/collections/default_collection/engines/app_id_example/servingConfigs/default_search"
        }
      }
    ]
  },
  "generationSpec": {
    "modelId": "gemini-2.5-flash"
  },
  "user_context": {
    "languageCode: "en",
    "latLng": {
       "latitude": 37.422131,
       "longitude": -122.084801
    }
  }
}'

Python

from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_number = "YOUR_PROJECT_NUMBER"
# engine_id = "YOUR_ENGINE_ID"

client = discoveryengine.GroundedGenerationServiceClient()

request = discoveryengine.GenerateGroundedContentRequest(
    # The full resource name of the location.
    # Format: projects/{project_number}/locations/{location}
    location=client.common_location_path(project=project_number, location="global"),
    generation_spec=discoveryengine.GenerateGroundedContentRequest.GenerationSpec(
        model_id="gemini-2.5-flash",
    ),
    # Conversation between user and model
    contents=[
        discoveryengine.GroundedGenerationContent(
            role="user",
            parts=[
                discoveryengine.GroundedGenerationContent.Part(
                    text="How did Google do in 2020? Where can I find BigQuery docs?"
                )
            ],
        )
    ],
    system_instruction=discoveryengine.GroundedGenerationContent(
        parts=[
            discoveryengine.GroundedGenerationContent.Part(
                text="Add a smiley emoji after the answer."
            )
        ],
    ),
    # What to ground on.
    grounding_spec=discoveryengine.GenerateGroundedContentRequest.GroundingSpec(
        grounding_sources=[
            discoveryengine.GenerateGroundedContentRequest.GroundingSource(
                inline_source=discoveryengine.GenerateGroundedContentRequest.GroundingSource.InlineSource(
                    grounding_facts=[
                        discoveryengine.GroundingFact(
                            fact_text=(
                                "The BigQuery documentation can be found at https://cloud.google.com/bigquery/docs/introduction"
                            ),
                            attributes={
                                "title": "BigQuery Overview",
                                "uri": "https://cloud.google.com/bigquery/docs/introduction",
                            },
                        ),
                    ]
                ),
            ),
            discoveryengine.GenerateGroundedContentRequest.GroundingSource(
                search_source=discoveryengine.GenerateGroundedContentRequest.GroundingSource.SearchSource(
                    # The full resource name of the serving config for a Vertex AI Search App
                    serving_config=f"projects/{project_number}/locations/global/collections/default_collection/engines/{engine_id}/servingConfigs/default_search",
                ),
            ),
        ]
    ),
)
response = client.generate_grounded_content(request)

# Handle the response
print(response)

使用 Google 搜索生成接地回答

您可以使用公开提供的 Web 数据作为生成回答的依据。

动态检索

您可以在请求中使用动态检索,以选择何时关闭“依托 Google 搜索进行接地”。当提示不需要依托 Google 搜索进行接地的回答,并且模型也能够基于自身知识在不进行接地的情况下提供回答时,就可以利用这项功能。这有助于您更有效地管理延迟时间、回答质量和费用。

动态检索预测得分和阈值

当您发送生成有依据的回答的请求时,Agent Search 会为提示分配预测分数。预测得分是一个介于 [0,1] 范围内的浮点值。其值取决于提示是否可以从依托 Google 搜索中的最新信息进行接地中受益。因此,如果提示需要基于网络上的最新事实给出回答,则预测分数较高;如果提示只需要模型生成的回答,则预测分数较低。

以下是一些提示及其预测分数的示例。

提示 预测得分 评论
“写一首关于牡丹的诗” 0.13 模型可以依靠自身知识,回答不需要接地
“为 2 岁儿童推荐一款玩具” 0.36 模型可以依靠自身知识,回答不需要接地
“你能提供一份亚洲风味牛油果酱的食谱吗?” 0.55 Google 搜索可以提供接地回答,但接地并非严格必需;模型知识可能已经足够
“什么是 Agent Search?Agent Search 中的接地功能如何计费? 0.72 需要 Google 搜索才能生成具有良好接地程度的回答
“谁赢得了最近的 F1 大奖赛?” 0.97 需要 Google 搜索才能生成具有良好接地程度的回答

在接地回答生成请求中,您可以指定具有阈值的动态检索配置。阈值是一个在 [0,1] 范围内的浮点值,默认为 0.7。如果阈值为零,则回答始终依托 Google 搜索进行接地。对于阈值的所有其他值,以下内容适用:

  • 如果预测分数大于或等于阈值,则答案会依托 Google 搜索进行接地。阈值越低,意味着使用“依托 Google 搜索进行接地”功能生成回答的提示越多。
  • 如果预测分数低于阈值,模型可能仍会生成回答,但不会依托 Google 搜索进行接地。

如需找到适合您业务需求的良好阈值,您可以创建一组您预计会遇到的代表性查询。然后,您可以根据响应中的预测分数对查询进行排序,并为您的应用场景选择一个合适的阈值。

以 Google 搜索作为回答依据

以下示例展示了如何通过将 Google 搜索指定为接地来源,根据提示生成接地回答。此示例使用 generateGroundedContent 方法。

REST

  1. 在以下 curl 请求中发送提示。

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_NUMBER/locations/global:generateGroundedContent" \
    -d '
    {
    "contents": [
     {
       "role": "user",
       "parts": [
         {
           "text": "PROMPT_TEXT"
         }
       ]
     }
    ],
    "systemInstruction": {
       "parts": {
           "text": "SYSTEM_INSTRUCTION"
       }
    },
    "groundingSpec": {
     "groundingSources": [
     {
         "googleSearchSource": {
              "dynamicRetrievalConfig": {
                  "predictor":{
                      "threshold": DYNAMIC_RETRIEVAL_THRESHOLD
                  }
              }
         }
     }
    ]
    },
    "generationSpec": {
     "modelId": "MODEL_ID",
     "temperature": TEMPERATURE,
     "topP": TOP_P,
     "topK": TOP_K
    },
    "user_context": {
     "languageCode: "LANGUAGE_CODE",
     "latLng": {
       "latitude": LATITUDE,
       "longitude": LONGITUDE
     },
    }
    }'
    

    替换以下内容:

    • PROJECT_NUMBER:您的 Google Cloud 项目编号。
    • PROMPT_TEXT:用户的提示。
    • SYSTEM_INSTRUCTION:一个可选字段,用于提供预置指令或一些额外的上下文。
    • DYNAMIC_RETRIEVAL_THRESHOLD:可选字段,用于设置调用动态检索配置的阈值。该值是一个介于 [0,1] 范围内的浮点值。如果您添加了 dynamicRetrievalConfig 字段,但未设置 predictor 或 threshold 字段,则阈值默认为 0.7。如果您未设置 dynamicRetrievalConfig 字段,则回答始终会接地。
    • MODEL_ID:一个可选字段,用于设置您要用来生成接地答案的 Gemini 模型的模型 ID。如需查看可用模型 ID 的列表,请参阅 Vertex AI 上的生成式 AI 产品文档中的 Gemini 模型。
    • TEMPERATURE:可选字段,用于设置采样温度。Google 建议将温度设置为 0.0。如需了解详情,请参阅 Gemini 模型参数。
    • TOP_P:可选字段,用于设置模型的 top-P 值。如需了解详情,请参阅 Gemini 模型参数。
    • TOP_K:一个可选字段,用于设置模型的 top-K 值。如需了解详情,请参阅 Gemini 模型参数。
    • LANGUAGE_CODE:一个可选字段,可用于设置生成的回答和返回的文本块的语言。如果无法根据查询确定语言,则使用此字段。默认值为 en。如需查看语言代码列表,请参阅语言。
    • LATITUDE:用于设置纬度的可选字段。以十进制度为单位输入值,例如 -25.34。
    • LONGITUDE:用于设置经度的可选字段。以十进制度为单位输入值,例如 131.04。

Python

from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_number = "YOUR_PROJECT_NUMBER"

client = discoveryengine.GroundedGenerationServiceClient()

request = discoveryengine.GenerateGroundedContentRequest(
    # The full resource name of the location.
    # Format: projects/{project_number}/locations/{location}
    location=client.common_location_path(project=project_number, location="global"),
    generation_spec=discoveryengine.GenerateGroundedContentRequest.GenerationSpec(
        model_id="gemini-2.5-flash",
    ),
    # Conversation between user and model
    contents=[
        discoveryengine.GroundedGenerationContent(
            role="user",
            parts=[
                discoveryengine.GroundedGenerationContent.Part(
                    text="How much is Google stock?"
                )
            ],
        )
    ],
    system_instruction=discoveryengine.GroundedGenerationContent(
        parts=[
            discoveryengine.GroundedGenerationContent.Part(text="Be comprehensive.")
        ],
    ),
    # What to ground on.
    grounding_spec=discoveryengine.GenerateGroundedContentRequest.GroundingSpec(
        grounding_sources=[
            discoveryengine.GenerateGroundedContentRequest.GroundingSource(
                google_search_source=discoveryengine.GenerateGroundedContentRequest.GroundingSource.GoogleSearchSource(
                    # Optional: For Dynamic Retrieval
                    dynamic_retrieval_config=discoveryengine.GenerateGroundedContentRequest.DynamicRetrievalConfiguration(
                        predictor=discoveryengine.GenerateGroundedContentRequest.DynamicRetrievalConfiguration.DynamicRetrievalPredictor(
                            threshold=0.7
                        )
                    )
                )
            ),
        ]
    ),
)
response = client.generate_grounded_content(request)

# Handle the response
print(response)

在以下示例中,请求将 Google 搜索指定为接地来源。此示例使用 generateGroundedContent 方法。此示例还使用系统指令,让回答以笑脸表情符号结尾。

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://discoveryengine.googleapis.com/v1/projects/123456/locations/global:generateGroundedContent" \
-d '
{
"contents": [{
  "role": "user",
  "parts": [{
    "text": "What is Agent Search?"
}]
}],
"systemInstruction": {
   "parts": {
      "text": "Add a smiley emoji after the answer."
   }
},
"groundingSpec": {
  "groundingSources": [
  {
      "googleSearchSource": {
        "dynamicRetrievalConfig": {
               "predictor":{
                   "threshold": 0.6
               }
           }
      }
  }
 ]
},
"generationSpec": {
  "modelId": "gemini-2.5-flash"
}
}
'

在多轮对话中生成有依据的回答

在多轮回答生成中,您必须在每个请求中发送用户与模型在之前所有轮次中交换的所有文本。这样可以确保连续性并保持上下文,以便为最新提示生成回答。

如需通过多轮回答生成功能获取有依据的回答,请执行以下操作:

REST

以下示例展示了如何通过多轮对话发送后续提示文本。这些示例使用 generateGroundedContent 方法,并使用 Google 搜索对答案进行接地。您可以按照类似步骤,使用其他接地来源生成接地回答。

  1. 在以下 curl 请求中发送第一个提示。

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_NUMBER/locations/global:generateGroundedContent" \
    -d '
    {
    "contents": [
     {
       "role": "user",
       "parts": [
         {
           "text": "PROMPT_TEXT_TURN_1"
         }
       ]
     }
    ],
    "systemInstruction": {
       "parts": {
           "text": "SYSTEM_INSTRUCTION_TURN_1"
       }
    },
    "groundingSpec": {
     "groundingSources": [
       {
         "googleSearchSource": {}
       }
     ]
    },
    "generationSpec": {
     "modelId": "MODEL_ID",
     "temperature": TEMPERATURE,
     "topP": TOP_P,
     "topK": TOP_K
    },
    "user_context": {
     "languageCode: "LANGUAGE_CODE",
     "latLng": {
       "latitude": LATITUDE,
       "longitude": LONGITUDE
     },
    }
    }'
    

    替换以下内容:

    • PROJECT_NUMBER:您的 Google Cloud 项目编号。
    • PROMPT_TEXT_TURN_1:第一轮中来自用户的提示文本。
    • SYSTEM_INSTRUCTION_TURN_1:一个可选字段,用于提供预置指令或一些额外的上下文。对于多轮回答生成,您必须为每一轮提供系统指令。
    • MODEL_ID:一个可选字段,用于设置您要用来生成接地答案的 Gemini 模型的模型 ID。如需查看可用模型 ID 的列表,请参阅 Vertex AI 上的生成式 AI 产品文档中的 Gemini 模型。
    • TEMPERATURE:可选字段,用于设置采样温度。Google 建议将温度设置为 0.0。如需了解详情,请参阅 Gemini 模型参数。
    • TOP_P:可选字段,用于设置模型的 top-P 值。如需了解详情,请参阅 Gemini 模型参数。
    • TOP_K:一个可选字段,用于设置模型的 top-K 值。如需了解详情,请参阅 Gemini 模型参数。
    • LANGUAGE_CODE:一个可选字段,可用于设置生成的回答和返回的文本块的语言。如果无法根据查询确定语言,则使用此字段。默认值为 en。如需查看语言代码列表,请参阅语言。
    • LATITUDE:用于设置纬度的可选字段。以十进制度为单位输入值,例如 -25.34。
    • LONGITUDE:用于设置经度的可选字段。以十进制度为单位输入值,例如 131.04。
  2. 发送第二个提示作为后续提示。添加用户的第一个提示,后跟模型提供的相应回答,作为上下文。

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_NUMBER/locations/global:generateGroundedContent" \
    -d '
    {
    "contents": [
     {
       "role": "user",
       "parts": [
         {
           "text": "PROMPT_TEXT_TURN_1"
         }
       ]
     },
     {
       "role": "model",
       "parts": [
         {
           "text": "ANSWER_TEXT_TURN_1"
         }
       ]
     },
     {
       "role": "user",
       "parts": [
         {
           "text": "PROMPT_TEXT_TURN_2"
         }
       ]
     }
    ],
    "systemInstruction": {
       "parts": {
           "text": "SYSTEM_INSTRUCTION_TURN_2"
       }
    },
    "groundingSpec": {
     "groundingSources": [
       {
         "googleSearchSource": {}
       }
     ]
    },
    "generationSpec": {
     "modelId": "MODEL_ID",
     "temperature": TEMPERATURE,
     "topP": TOP_P,
     "topK": TOP_K
    },
    "user_context": {
     "languageCode: "LANGUAGE_CODE",
     "latLng": {
       "latitude": LATITUDE,
       "longitude": LONGITUDE
     },
    }
    }'
    

    替换以下内容:

    • PROJECT_NUMBER:您的 Google Cloud 项目编号。
    • PROMPT_TEXT_TURN_1:第一轮中来自用户的提示文本。
    • ANSWER_TEXT_TURN_1:模型在第一轮对话中给出的回答文本。
    • PROMPT_TEXT_TURN_2:用户在第二轮对话中输入的提示文本。
    • SYSTEM_INSTRUCTION_TURN_2:一个可选字段,用于提供预置指令或一些额外的上下文。对于多轮回答生成,您必须为每一轮提供系统指令。
    • MODEL_ID:一个可选字段,用于设置您要用来生成接地答案的 Gemini 模型的模型 ID。如需查看可用模型 ID 的列表,请参阅 Vertex AI 上的生成式 AI 产品文档中的 Gemini 模型。
    • TEMPERATURE:可选字段,用于设置采样温度。Google 建议将温度设置为 0.0。如需了解详情,请参阅 Gemini 模型参数。
    • TOP_P:可选字段,用于设置模型的 top-P 值。如需了解详情,请参阅 Gemini 模型参数。
    • TOP_K:一个可选字段,用于设置模型的 top-K 值。如需了解详情,请参阅 Gemini 模型参数。
    • LANGUAGE_CODE:一个可选字段,可用于设置生成的回答和返回的文本块的语言。如果无法根据查询确定语言,则使用此字段。默认值为 en。如需查看语言代码列表,请参阅语言。
    • LATITUDE:用于设置纬度的可选字段。以十进制度为单位输入值,例如 -25.34。
    • LONGITUDE:用于设置经度的可选字段。以十进制度为单位输入值,例如 131.04。
  3. 重复此过程,即可获得更多后续回答。在每个轮次中,添加用户之前的所有提示,后跟模型中的相应回答。

多轮回答生成示例

在以下示例中,请求指定了三个内嵌事实文本作为依据来源,以生成两轮对话的回答。此示例使用 generateGroundedContent 方法。此示例还使用系统指令,在第一轮对话中以笑脸表情符号结束回答。

REST

  1. 在以下 curl 请求中发送第一个提示。

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/123456/locations/global:generateGroundedContent" \
    -d '
    {
    "contents": [
     {
       "role": "user",
       "parts": [
         {
           "text": "Summarize what happened in 2023 in one paragraph."
         }
       ]
     }
    ],
    "systemInstruction": {
      "parts": {
          "text": "Add a smiley emoji after the answer."
      }
    },
    "grounding_spec": {
     "grounding_sources": [
       {
         "inline_source": {
           "grounding_facts": [
             {
               "fact_text": "In 2023, the world population surpassed 8 billion. This milestone marked a significant moment in human history, highlighting both the rapid growth of our species and the challenges of resource management and sustainability in the years to come.",
               "attributes": {
                 "title": "title_1",
                 "uri": "some-uri-1"
               }
             }
           ]
         }
       },
       {
         "inline_source": {
           "grounding_facts": [
             {
               "fact_text": "In 2023, global e-commerce sales reached an estimated $5.7 trillion. The continued rise of online shopping solidified its position as a dominant force in retail, with major implications for traditional brick-and-mortar stores and the logistics networks supporting worldwide deliveries.",
               "attributes": {
                 "title": "title_2",
                 "uri": "some-uri-2"
               }
             }
           ]
         }
       },
       {
         "inline_source": {
           "grounding_facts": [
             {
               "fact_text": "In 2023, the global average surface temperature was approximately 0.2 degrees Celsius higher than the 20th-century average. This continued the worrying trend of global warming, underscoring the urgency of worldwide climate initiatives, carbon reduction efforts, and investment in renewable energy sources.",
               "attributes": {
                 "title": "title_3",
                 "uri": "some-uri-3"
               }
             }
           ]
         }
       }
     ]
    },
    "generationSpec": {
     "modelId": "gemini-2.5-flash"
    }
    }'
    
  2. 发送第二个提示作为后续提示。添加用户的第一个提示,后跟模型提供的相应回答,作为上下文。

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/123456/locations/global:generateGroundedContent" \
    -d '
    {
    "contents": [
     {
       "role": "user",
       "parts": [
         {
           "text": "Summarize what happened in 2023 in one paragraph."
         }
       ]
     },
     {
       "role": "model",
       "parts": [
         {
           "text": "In 2023, the global average surface temperature increased, the world population surpassed 8 billion, and global e-commerce sales reached an estimated $5.7 trillion.  😊 \n"
         }
       ]
     },
     {
       "role": "user",
       "parts": [
         {
           "text": "Rephrase the answer in an abstracted list."
         }
       ]
     }
    ],
    "grounding_spec": {
     "grounding_sources": [
       {
         "inline_source": {
           "grounding_facts": [
             {
               "fact_text": "In 2023, the world population surpassed 8 billion. This milestone marked a significant moment in human history, highlighting both the rapid growth of our species and the challenges of resource management and sustainability in the years to come.",
               "attributes": {
                 "title": "title_1",
                 "uri": "some-uri-1"
               }
             }
           ]
         }
       },
       {
         "inline_source": {
           "grounding_facts": [
             {
               "fact_text": "In 2023, global e-commerce sales reached an estimated $5.7 trillion. The continued rise of online shopping solidified its position as a dominant force in retail, with major implications for traditional brick-and-mortar stores and the logistics networks supporting worldwide deliveries.",
               "attributes": {
                 "title": "title_2",
                 "uri": "some-uri-2"
               }
             }
           ]
         }
       },
       {
         "inline_source": {
           "grounding_facts": [
             {
               "fact_text": "In 2023, the global average surface temperature was approximately 0.2 degrees Celsius higher than the 20th-century average. This continued the worrying trend of global warming, underscoring the urgency of worldwide climate initiatives, carbon reduction efforts, and investment in renewable energy sources.",
               "attributes": {
                 "title": "title_3",
                 "uri": "some-uri-3"
               }
             }
           ]
         }
       }
     ]
    },
    "generationSpec": {
     "modelId": "gemini-2.5-flash"
    }
    }'
    

逐字逐句给出基于事实的回答

您可以选择以流式传输的方式获取模型的回答。在回答特别长且一次性发送整个回答会导致严重延迟的使用场景中,此功能非常有用。流式传输回答会将回答分解为包含回答文本的连续部分的多个候选回答。

如需获取流式、有依据的回答,请执行以下操作:

REST

以下示例展示了如何流式传输接地回答。 此示例使用 streamGenerateGroundedContent 方法,并在不使用动态检索配置的情况下,通过 Google 搜索为回答提供依据。您可以使用类似的步骤,通过其他接地来源生成接地答案。

  1. 在以下 curl 请求中发送提示。

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1alpha/projects/PROJECT_NUMBER/locations/global:streamGenerateGroundedContent" \
    -d '
    [
    {
     "contents": [
       {
         "role": "user",
         "parts": [
           {
             "text": "PROMPT_TEXT"
           }
         ]
       }
     ],
     "systemInstruction": {
         "parts": {
             "text": "SYSTEM_INSTRUCTION"
         }
     },
     "groundingSpec": {
       "groundingSources": [
         {
           "googleSearchSource": {}
         }
       ]
     },
    "generationSpec": {
     "modelId": "MODEL_ID",
     "temperature": TEMPERATURE,
     "topP": TOP_P,
     "topK": TOP_K
    },
    "user_context": {
     "languageCode: "LANGUAGE_CODE",
     "latLng": {
       "latitude": LATITUDE,
       "longitude": LONGITUDE
     },
    }
    }
    ]'
    

    替换以下内容:

    • PROJECT_NUMBER:您的 Google Cloud 项目编号。
    • PROMPT_TEXT:用户的提示。
    • SYSTEM_INSTRUCTION:一个可选字段,用于提供预置指令或一些额外的上下文。
    • MODEL_ID:一个可选字段,用于设置您要用来生成接地答案的 Gemini 模型的模型 ID。如需查看可用模型 ID 的列表,请参阅 Vertex AI 上的生成式 AI 产品文档中的 Gemini 模型。
    • TEMPERATURE:可选字段,用于设置采样温度。Google 建议将温度设置为 0.0。如需了解详情,请参阅 Gemini 模型参数。
    • TOP_P:可选字段,用于设置模型的 top-P 值。如需了解详情,请参阅 Gemini 模型参数。
    • TOP_K:一个可选字段,用于设置模型的 top-K 值。如需了解详情,请参阅 Gemini 模型参数。
    • LANGUAGE_CODE:一个可选字段,可用于设置生成的回答和返回的文本块的语言。如果无法根据查询确定语言,则使用此字段。默认值为 en。如需查看语言代码列表,请参阅语言。
    • LATITUDE:用于设置纬度的可选字段。以十进制度为单位输入值,例如 -25.34。
    • LONGITUDE:用于设置经度的可选字段。以十进制度为单位输入值,例如 131.04。

Python

from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"

client = discoveryengine.GroundedGenerationServiceClient()

request = discoveryengine.GenerateGroundedContentRequest(
    # The full resource name of the location.
    # Format: projects/{project_number}/locations/{location}
    location=client.common_location_path(project=project_number, location="global"),
    generation_spec=discoveryengine.GenerateGroundedContentRequest.GenerationSpec(
        model_id="gemini-2.5-flash",
    ),
    # Conversation between user and model
    contents=[
        discoveryengine.GroundedGenerationContent(
            role="user",
            parts=[
                discoveryengine.GroundedGenerationContent.Part(
                    text="Summarize how to delete a data store in Vertex AI Agent Builder?"
                )
            ],
        )
    ],
    grounding_spec=discoveryengine.GenerateGroundedContentRequest.GroundingSpec(
        grounding_sources=[
            discoveryengine.GenerateGroundedContentRequest.GroundingSource(
                google_search_source=discoveryengine.GenerateGroundedContentRequest.GroundingSource.GoogleSearchSource()
            ),
        ]
    ),
)
responses = client.stream_generate_grounded_content(iter([request]))

for response in responses:
    # Handle the response
    print(response)

流式传输有依据的回答的示例

在以下示例中,请求将 Google 搜索指定为接地来源,以便在不使用动态检索配置的情况下流式传输回答。流式回答分布在多个候选回答中。此示例使用 streamGenerateGroundedContent 方法。

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://discoveryengine.googleapis.com/v1alpha/projects/123456/locations/global:streamGenerateGroundedContent" \
-d '
[
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "text": "Summarize How to delete a data store in Agent Search?"
        }
      ]
    }
  ],
  "groundingSpec": {
    "groundingSources": [
      {
        "googleSearchSource": {}
      }
    ]
  },
  "generationSpec": {
    "modelId": "gemini-2.5-flash"
  }
}
]'

后续步骤

了解如何将接地生成方法与其他 RAG API 搭配使用,以根据非结构化数据生成接地回答。