利用 Search API 建立基準

您可以透過搜尋 API 進行基礎訓練,將 Gemini 連結至外部資料來源。這樣一來,您就能將任何搜尋服務做為 Gemini 的基礎來源,確保回覆內容是根據系統中的最新和最相關資訊生成。這項功能特別適合用於企業專屬的非公開資料。

本頁面說明如何使用任何搭載 Gemini 的搜尋 API 設定及使用基礎功能。

如何使用搜尋 API 進行基礎處理

以搜尋 API 做為回覆依據時,Gemini 可以查詢您提供的外部 API 端點。Gemini 就能使用自訂搜尋功能做為工具,提升回覆品質。因為模型可在需要時從指定資料來源尋找資訊,因此能提供更動態且符合情境的互動。

在生成要求期間,Gemini 可以使用搜尋查詢呼叫外部 API 端點。然後,API 應傳回相關的資料片段。Gemini 會將這些摘要視為事實來源,生成更準確且有依據的回覆。

您可以結合使用搜尋 API 建立基準,以及其他基準來源 (例如 Google 搜尋)。生成要求最多支援 10 個基準化來源和多工具查詢,Gemini 可運用不同資訊來源生成最佳答案。

支援的模型

下列模型支援透過 API 進行基礎化:

詳情請參閱「Gemini 模型」一文。

事前準備

如要在 Search API 中使用基礎功能,請按照下列步驟操作:

  1. 確認 Google Cloud專案已啟用 Vertex AI API
  2. 如果您打算按照詳細設定指南建立新的搜尋 API 端點,請務必安裝並初始化 Google Cloud CLI

Search API 規定

如要搭配 Gemini 使用現有的搜尋基礎架構,API 端點必須符合下列需求:

API 結構定義

  • HTTP 方法POST
  • 要求主體 (從 Gemini 到您的 API)

    {
      "query": "the user's search query string"
    }
    
  • 回覆主體 (從 API 傳送至 Gemini):JSON 物件陣列。每個物件代表一項搜尋結果,且必須包含摘要和 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 會以名為 key 的查詢參數形式傳送這組 API 金鑰。

使用與相容端點搭配的 Search 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 驗證的金鑰。Gemini 會將這個金鑰附加至端點網址,做為 ?key=<YOUR_API_KEY>

REST

使用任何要求資料之前,請先替換以下項目:

  • LOCATION:處理要求的地區,例如 us-central1
  • PROJECT_ID:您的專案 ID。 Google Cloud
  • MODEL_ID:相容 Gemini 模型的模型 ID,例如 gemini-2.0-flash-001
  • USER_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/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent

JSON 要求內文:

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

如要傳送要求,請選擇以下其中一個選項:

curl

下列指令假設您已執行 gcloud CLI init 或 gcloud CLI auth login,或使用 Cloud Shell (會自動登入 gcloud CLI),透過使用者帳戶登入 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 Function 可做為中介服務,接收 Gemini 的查詢、向現有搜尋基礎架構 (例如資料庫、內部搜尋引擎或向量搜尋) 發出適當的查詢,然後將結果格式化為 Gemini 可解讀的結構定義。

詳情請參閱 Cloud Run 函式說明文件

Cloud Functions 設定範例 (Python)

本範例使用硬式編碼產品清單進行示範。您需要將資料擷取邏輯替換為對實際搜尋系統的呼叫。

  1. main.py

    import functions_framework
    import json
    from flask import jsonify
    
    @functions_framework.http
    def custom_search_wrapper_minimal(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
    • 因為 API Gateway 會處理驗證。--allow-unauthenticated

使用 API 閘道和 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 / Enable APIs」(API 閘道/啟用 API) 頁面。

      前往 API Gateway API / 啟用 API

    2. 如果 API Gateway API 尚未啟用,請按一下「啟動」,然後按一下「啟用」

    3. 選取「憑證」

    4. 按一下「建立憑證」,然後選取「API 金鑰」

    5. 按一下「顯示金鑰」,然後複製產生的 API 金鑰。將金鑰存放在安全的地方,Gemini 會使用這組金鑰。

    6. 按一下「編輯 API 金鑰」,或按一下金鑰名稱。

    7. 在「API 限制」部分執行下列操作:

      1. 選取「Restrict key」(限制金鑰) 選項。

      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 金鑰做為查詢參數傳遞。例如:

      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 生成有根據的回覆時就會受到負面影響。

後續步驟