您可以透過搜尋 API 連結 Gemini 和外部資料來源。這樣一來,您就能使用任何搜尋服務做為 Gemini 的基礎來源,確保回應內容是根據系統中最新且最相關的資訊提供。這項功能對於非公開的企業專屬資料特別實用。
本頁面說明如何使用 Gemini 搭配任何搜尋 API 設定及使用 grounding。
如何使用搜尋 API 進行接地
當您使用搜尋 API 做為回覆依據時,Gemini 可以查詢您提供的外部 API 端點。這樣一來,Gemini 就能使用自訂搜尋功能,提升回覆品質。這可讓互動更具動態性和情境感知能力,因為模型可在需要時從指定的資料來源尋找資訊。
在產生要求期間,Gemini 可以使用搜尋查詢呼叫外部 API 端點。您的 API 應該會傳回相關資料片段。Gemini 會使用這些片段做為真相來源,生成更準確且有依據的回覆。
您可以將使用搜尋 API 的基準與其他基準來源 (例如 Google 搜尋) 結合。生成要求最多可支援 10 個基準來源和多工具查詢,Gemini 可利用不同的資訊來源,產生最佳答案。
支援的模型
以下型號支援與 API 連線:
詳情請參閱Gemini 模型。
事前準備
如要使用搜尋 API 的接地功能,請按照下列步驟操作:
- 確認 Google Cloud專案已啟用 Vertex AI API。
- 如果您打算按照詳細設定指南建立新的搜尋 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 的 Grounding 支援使用 API 金鑰,可確保 API 端點的安全性。Gemini 會將這組 API 金鑰做為名為 key
的查詢參數傳送。
使用相容端點的搜尋 API 建立基準
如果您已擁有符合結構定義和驗證要求的 API 端點,可以直接在 Gemini API 呼叫中進行設定。
設定 externalApi
工具
向 Gemini API 提出要求時,請在工具參數中加入為 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>
的形式附加至端點網址。
REST
使用任何要求資料之前,請先替換以下項目:
- LOCATION:處理要求的地區,例如
us-central1
。 - PROJECT_ID:您的 Google Cloud 專案 ID。
- 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 函式設定範例 (Python)
這個範例使用硬式編碼的產品清單做為示範。您必須將資料擷取邏輯替換為對實際搜尋系統的呼叫。
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)
requirements.py
functions-framework>=3.0.0 Flask>=2.0.0
部署:前往包含
main.py
和requirements.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
。
- 將 YOUR_REGION 替換為您選擇的 Google Cloud 區域,例如
使用 API 閘道和 API 金鑰保護 Cloud Functions
API Gateway 可提供安全的 Cloud Functions 管理進入點,並讓您強制執行 API 金鑰驗證。
詳情請參閱 API Gateway 說明文件。
建立 OpenAPI 規格 (
openapi-spec.yaml
):這個檔案會定義 API Gateway 公開 Cloud Functions 的方式。這會指定閘道預期POST
要求會傳送至/v0/search
路徑,並要求以名為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
部署 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
建立及限制 API 金鑰:您必須建立 Gemini 用於存取 API Gateway 端點的 API 金鑰。詳情請參閱「管理 API 金鑰」。
如要建立及限制 API 金鑰,請按照下列步驟操作:
在 Google Cloud 控制台中,前往「API Gateway / Enable APIs」頁面。
如果尚未啟用 API Gateway API,請依序按一下「Launch」和「Enable」。
選取「憑證」。
按一下「建立憑證」,然後選取「API 金鑰」。
按一下「顯示金鑰」,然後複製產生的 API 金鑰。將金鑰儲存在安全的位置。這組金鑰由 Gemini 使用。
按一下「編輯 API 金鑰」或金鑰名稱。
在「API 限制」專區中,執行下列操作:
選取「Restrict key」(限制金鑰) 選項。
選取 API Gateway 代管服務。必須以您的 API 命名,例如
Custom Search API for Gemini Grounding API
。如果未納入金鑰,或是您想使用此金鑰的 API 管理閘道,請務必選取 API Gateway API (
apigateway.googleapis.com
)。如要進行驗證,金鑰必須能存取由 API Gateway 代管的特定 API 服務。
按一下 [儲存]。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 產生可靠回應的能力造成負面影響。