通过搜索 API 接地

您可以通过搜索 API 进行接地,将 Gemini 连接到外部数据源。这使您能将任何搜索服务用作 Gemini 的接地来源,有助于确保其回答是基于您系统中的最新、最相关信息。这对于非公开的企业专属数据尤其有用。

本页面介绍了如何通过 Gemini 配置和使用任意搜索 API 进行接地。

“通过搜索 API 接地”功能的运作方式

当您通过搜索 API 进行接地时,Gemini 可以查询您所提供的外部 API 端点。这允许 Gemini 将您的自定义搜索功能作为一种工具来增强其回答。由于模型能够在需要时从您指定的数据源中查找信息,因此可以实现更具动态性和情境感知能力的交互。

在一次生成请求期间,Gemini 可以通过一个搜索查询来调用该外部 API 端点。您的 API 随后应返回相关的数据片段。Gemini 会将这些片段作为可信来源,以生成更准确、更具事实依据的回答。

您可以将通过搜索 API 接地与其他接地来源(如 Google 搜索)结合使用。一次生成请求最多支持 10 个接地来源,并支持多工具查询,通过这种方式,Gemini 可以利用不同的信息来源来生成尽可能最佳的回答。

支持的模型

本部分列出了支持“通过搜索 API 接地”的模型。

准备工作

如需使用“通过搜索 API 接地”,请执行以下操作:

  1. 确保已在 Google Cloud项目中启用 Vertex AI API
  2. 如果您计划按照详细的设置指南创建新的搜索 API 端点,请确保您已安装并初始化 Google Cloud CLI

搜索 API 要求

如需将您的现有搜索基础架构与 Gemini 搭配使用,您的 API 端点必须满足以下要求:

API 架构

  • HTTP 方法POST
  • 请求正文(从 Gemini 到您的 API)

    {
      "query": "the user's search query string"
    }
    
  • 响应正文(从您的 API 到 Gemini):一个 JSON 对象数组。每个对象代表一条搜索结果,且必须包含 snippet 和 uri 字段。

    [
      {
        "snippet": "A text snippet containing the answer or relevant information.",
        "uri": "A URI/URL linking to the source of the information, or a relevant identifier."
      },
      {
        "snippet": "Another piece of information.",
        "uri": "https://example.com/another-source"
      }
    ]
    

如果未找到任何结果,您的 API 端点应返回一个空数组。

身份验证

“通过搜索 API 接地”支持使用 API 密钥,以保护您的 API 端点安全。Gemini 会将此 API 密钥作为名为 key 的查询参数发送。

将“通过搜索 API 接地”与兼容端点搭配使用

如果您已有一个符合架构和身份验证要求的 API 端点,则可以直接在 Gemini API 调用中配置该端点。

配置 externalApi 工具

向 Gemini API 发出请求时,请添加 tools 参数,并为其配置一个用于 externalApi 的检索工具。关键字段包括:

  • api_spec: "SIMPLE_SEARCH":这会告知 Gemini 使用预定义的输入和输出架构。
  • endpoint:API Gateway 端点的完整网址,例如 https://YOUR_GATEWAY_HOSTNAME/v0/search
  • apiAuth.apiKeyConfig.apiKeyString:Gemini 用于向您的 API 进行身份验证的 API 密钥。Gemini 会将此密钥以 ?key=<YOUR_API_KEY> 的形式附加到端点网址的末尾。

Python

安装

pip install --upgrade google-genai

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

  from google import genai
  from google.genai.types import (
      GenerateContentConfig,
      ExternalApi,
      Retrieval,
      Tool,
      HttpOptions,
  )

  client = genai.Client(http_options=HttpOptions(api_version="v1"))

  # Replace with your API details
  EXTERNAL_API_ENDPOINT = "YOUR_EXTERNAL_API_ENDPOINT"  # e.g., https://YOUR_GATEWAY_HOSTNAME/v0/search
  EXTERNAL_API_KEY = "YOUR_EXTERNAL_API_KEY"

  tool = Tool(
      retrieval=Retrieval(
          external_api=ExternalApi(
              api_spec="SIMPLE_SEARCH",
              endpoint=EXTERNAL_API_ENDPOINT,
              api_auth={
                  "apiKeyConfig": {
                      "apiKeyString": EXTERNAL_API_KEY
                  }
              }
          )
      )
  )

  response = client.models.generate_content(
      model="gemini-2.5-flash",  # Or another supported model
      contents="What can you tell me about product Y based on my API?", # Your query
      config=GenerateContentConfig(
          tools=[tool],
      ),
  )

  print(response.text)

REST

在使用任何请求数据之前,请先进行以下替换:

  • LOCATION:处理请求的区域。如需使用全球端点,请清除端点名称中的相应位置,并将资源位置配置为 global
  • PROJECT_ID:您的 Google Cloud 项目 ID。
  • MODEL_ID:兼容的 Gemini 模型的模型 ID,例如 gemini-2.0-flash-001
  • PROMPT:要包含在提示中的文本说明。
  • EXTERNAL_API_ENDPOINT:Gemini 调用的安全 API Gateway 端点的完整网址,例如 https://YOUR_GATEWAY_HOSTNAME/v0/search。此端点必须遵循指定的 API 架构。
  • EXTERNAL_API_KEY:您为 API Gateway 生成和配置的 API 密钥。Gemini 会使用此密钥向您的端点进行身份验证。

    HTTP 方法和网址:

    POST https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent
    

    请求 JSON 正文:

      {
      "contents": [{
          "role": "user",
          "parts": [{
              "text": "PROMPT"
          }]
      }],
      "tools": [{
          "retrieval": {
            "externalApi": {
              "api_spec": "SIMPLE_SEARCH",
              "endpoint": "EXTERNAL_API_ENDPOINT",
              "apiAuth": {
                "apiKeyConfig": {
                  "apiKeyString": "EXTERNAL_API_KEY"
                }
              }
            }
          }
      }]
    }
    

    如需发送您的请求,请使用以下方式之一:

    curl

    以下命令假定您已使用自己的用户账号通过以下方法登录 gcloud CLI:运行 gcloud CLI init 或 gcloud CLI auth login 命令;或者通过使用 Cloud Shell,这会自动将您登录 gcloud CLI。您可以运行 gcloud CLI auth list 来检查活跃账号。

    将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    -d @request.json \
    "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent"
    

    Powershell

    以下命令假定您已使用自己的用户账号通过运行 gcloud CLI init 或 gcloud CLI auth login 登录 gcloud CLI。您可以运行 gcloud CLI auth list 来检查活跃账号。

    将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }
    
    Invoke-WebRequest `
      -Method POST `
      -Headers $headers `
      -ContentType: "application/json; charset=utf-8" `
      -InFile request.json `
      -Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent" | Select-Object -Expand Content
    

    您应该收到类似以下内容的 JSON 响应:

    {
      "candidates": [
        {
          "content": {
            "role": "model",
            "parts": [
              {
                "text": "You can make an appointment on the website https://dmv.gov/"
              }
            ]
          },
          "finishReason": "STOP",
          "safetyRatings": [
            "..."
          ],
          "groundingMetadata": {
            "retrievalQueries": [
              "How to make appointment to renew driving license?"
            ],
            "groundingChunks": [
              {
                "retrievedContext": {
                  "uri": "https://...",
                  "snippet": "Snippet text about driving license renewal"
                }
              }
            ],
            "groundingSupport": [
              {
                "segment": {
                  "startIndex": 25,
                  "endIndex": 147
                },
                "segment_text": "ipsum lorem ...",
                "supportChunkIndices": [1, 2],
                "confidenceScore": [0.9541752, 0.97726375]
              },
              {
                "segment": {
                  "startIndex": 294,
                  "endIndex": 439
                },
                "segment_text": "ipsum lorem ...",
                "supportChunkIndices": [1],
                "confidenceScore": [0.9541752, 0.9325467]
              }
            ]
          }
        }
      ],
      "usageMetadata": {
        "..."
      }
    }
    

设置搜索 API 端点

如果您没有符合要求的现有 API 端点,本部分将指导您使用 Cloud Functions 和 API Gateway 设置一个。

使用 Cloud Functions 函数创建外部 API 封装容器

Cloud Functions 函数可以充当中间媒介,从 Gemini 接收查询,向您现有的搜索基础架构(例如数据库、内部搜索引擎或向量搜索)发出相应的查询,然后以 Gemini 可理解的架构设置结果格式。

如需了解详情,请参阅 Cloud Run functions 文档

Cloud Functions 函数设置示例 (Python)

此示例使用硬编码的产品列表进行演示。您需要将数据检索逻辑替换为对实际搜索系统的调用。

  1. main.py

    import functions_framework
    import json
    from flask import jsonify
    
    @functions_framework.http
    def custom_search_wrapper(request):
        """
        HTTP Cloud Function to provide a minimal, fixed response for Gemini grounding.
        """
        if request.method != 'POST':
            return 'Only POST requests are accepted', 405
    
        request_json = request.get_json(silent=True)
    
        if not request_json or 'query' not in request_json:
            return jsonify({"error": "Invalid request. JSON body with 'query' field is required."}), 400
    
        user_query = request_json['query']
        print(f"Received query: '{user_query}'. Responding with fixed data.")
    
        # --- FIXED RESPONSE ---
        # This is a hardcoded response. In a real scenario, you would
        # use the 'user_query' to fetch relevant data.
        fixed_results = [
            {
                "snippet": "This is a fixed snippet from your custom Search API. The original query was: " + user_query,
                "uri": "https://example.com/docs/fixed-test-data"
            },
            {
                "snippet": "Another piece of fixed information to demonstrate the list format.",
                "uri": "https://example.com/another-fixed-source"
            }
        ]
        # --- END OF FIXED RESPONSE ---
    
        return jsonify(fixed_results)
    
  2. requirements.py

    functions-framework>=3.0.0
    Flask>=2.0.0
    
  3. 部署:前往包含 main.pyrequirements.txt 的目录,然后运行以下命令:

    gcloud functions deploy custom_search_wrapper \
      --runtime python311 \
      --trigger-http \
      --entry-point custom_search_wrapper \
      --region YOUR_REGION \
      --allow-unauthenticated \
      --gen2
    
    • 将 YOUR_REGION 替换为您选择的 Google Cloud 区域,例如 us-central1
    • 这里指定了 --allow-unauthenticated,因为 API Gateway 会处理身份验证。

使用 API Gateway 和 API 密钥保护 Cloud Functions

API Gateway 可为您的 Cloud Functions 提供安全的受管入口点,并允许您强制执行 API 密钥身份验证。

如需了解详情,请参阅 API Gateway 文档

  1. 创建 OpenAPI 规范 (openapi-spec.yaml):此文件定义了 API Gateway 如何公开您的 Cloud Functions。它规定了网关应接收一个指向 /v0/search 路径的 POST 请求,并要求以名为 key 的查询参数形式发送 API 密钥。

    swagger: '2.0'
    info:
      title: Custom Search API for Gemini Grounding
      description: Wraps an internal search function, secured by API Key for Gemini.
      version: 1.0.0
    schemes:
      - https
    produces:
      - application/json
    consumes:
      - application/json
    paths:
      /v0/search: # TODO: This will be part of API endpoint URL change if necessary
        post:
          summary: Custom search endpoint for Gemini
          operationId: customSearchForGemini # TODO: Change if needed
          x-google-backend:
            address: YOUR_CLOUD_FUNCTION_TRIGGER_URL # TODO: Replace with your Cloud Function trigger URL
          parameters:
            - name: body
              in: body
              required: true
              schema:
                type: object
                properties:
                  query:
                    type: string
          security:
            - api_key_query: []
          responses:
            '200':
              description: Search results
              schema:
                type: array
                items:
                  type: object
                  properties:
                    snippet:
                      type: string
                    uri:
                      type: string
            '400':
              description: Invalid request
            '401':
              description: Unauthorized (Missing or invalid API key)
            '500':
              description: Internal server error
    securityDefinitions:
      api_key_query:
        type: apiKey
        name: key # Gemini will send its API key using this query parameter name
        in: query
    
  2. 部署 API Gateway:替换以下变量后,执行 gcloud CLI 命令:

    • YOUR_PROJECT_ID:您的 Google Cloud 项目 ID。
    • YOUR_REGION:您用于 Cloud Functions 的 Google Cloud 区域,例如 us-central1
    # 1. Create an API
    gcloud api-gateway apis create custom-search-gemini-api --project=YOUR_PROJECT_ID
    
    # 2. Create an API Config from your OpenAPI spec
    gcloud api-gateway api-configs create v1 \
      --api=custom-search-gemini-api \
      --openapi-spec=openapi-spec.yaml \
      --project=YOUR_PROJECT_ID \
      --display-name="Version 1"
    
    # 3. Create a Gateway
    gcloud api-gateway gateways create custom-search-gateway \
      --api=custom-search-gemini-api \
      --api-config=v1 \
      --location=YOUR_REGION \
      --project=YOUR_PROJECT_ID
    

    部署后,主机名(网关网址)的格式如下:

    https://custom-search-gateway-UNIQUE_ID.nw.gateway.dev

    您可以使用主机名来构建 Gemini 的完整端点网址。例如:

    https://custom-search-gateway-UNIQUE_ID.nw.gateway.dev/v0/search

  3. 创建并限制 API 密钥:您必须创建一个 API 密钥,供 Gemini 用于访问您的 API Gateway 端点。如需了解详情,请参阅管理 API 密钥

    如需创建和限制 API 密钥,请执行以下操作:

    1. 在 Google Cloud 控制台中,前往 API Gateway/启用 API 页面。

      前往 API Gateway API/启用 API

    2. 如果 API Gateway API 尚未启用,请点击启动,然后点击启用

    3. 选择凭证

    4. 点击创建凭证,然后选择 API 密钥

    5. 点击显示密钥,然后复制生成的 API 密钥。请将密钥保存在一个安全的位置。此密钥由 Gemini 使用。

    6. 点击修改 API 密钥,或点击密钥名称。

    7. API 限制部分中,执行以下操作:

      1. 选择限制密钥选项。

      2. 选择您的 API Gateway 托管式服务。它必须以您的 API 命名,例如 Custom Search API for Gemini Grounding API

      3. 如果未添加密钥,或者您打算使用此密钥通过 API 管理网关,请确保已勾选 API Gateway API (apigateway.googleapis.com)。为了实现接地,密钥需要访问由 API Gateway 托管的特定 API 服务。

    8. 点击保存。您的 API Gateway 端点现已受到保护,当您使用 API Gateway 端点时,必须将 API 密钥作为查询参数传递。例如:

      https://custom-search-gateway-UNIQUE_ID.nw.gateway.dev/v0/search?key=YOUR_GENERATED_API_KEY

使用搜索 API 的注意事项

请查看以下注意事项,以便您选择合适的搜索 API:

  • 选段质量:您的 API 返回的文本选段至关重要。它应该简洁明了,但又要有足够的信息量,以便 Gemini 将其用作回答的事实依据。
  • 延迟时间:搜索 API 应能快速响应。API 中的高延迟会增加 Gemini 的整体响应时间。
  • 错误处理:在 Cloud Functions 或搜索 API 中实现稳健的错误处理机制。如果您的 API 经常出错或超时,则会严重影响 Gemini 生成接地回答的能力。

后续步骤