取得 StreamAssist 的搜尋結果

在網頁應用程式中,您可以透過串流回覆的形式取得問題解答。本文說明如何使用 REST API 取得答案。如要使用 Gemini Enterprise 網頁應用程式,請參閱「與助理對話」。

StreamAssist 總覽

StreamAssist 提供強大的互動方式,可處理使用者查詢。這項功能以串流方式運作,可進行即時來回互動。

API 的主要功能包括:

  • 維持對話脈絡:使用工作階段維持對話脈絡,確保能理解先前互動範圍內的後續查詢。

  • 整合提供的檔案:將附加檔案做為背景資訊,提供更精確、更相關的回覆。

  • 完美整合:與各種代理和工具整合,滿足各種使用者要求。

事前準備

請確認您已備妥下列項目:

  • Google Cloud已啟用 Discovery Engine API。您可以在Google Cloud 控制台的「Discovery Engine API」頁面啟用。

    前往 Discovery Engine API

  • 呼叫使用者或工作負載主體具備 Discovery Engine 使用者 (roles/discoveryengine.user) 或 Gemini Enterprise 使用者 (roles/discoveryengine.agentspaceUser,包含 roles/discoveryengine.user) Identity and Access Management (IAM) 角色。或者,您也可以授予包含 discoveryengine.assistants.assist 的自訂角色 (如果應用程式搜尋附加的資料儲存庫,則為 discoveryengine.servingConfigs.search)。如果呼叫端使用自訂角色傳送 X-Goog-User-Project 標頭 (例如使用 ADC 或聯合憑證),也請在配額專案中加入 serviceusage.services.use,或授予服務使用情形消費者角色 (roles/serviceusage.serviceUsageConsumer),以免發生 403 USER_PROJECT_DENIED。

  • 每位人類使用者都獲派有效的 Gemini Enterprise 授權 (或應用程式已啟用自動指派授權功能)。詳情請參閱「Gemini Enterprise 授權」。

  • 現有的 Gemini Enterprise 應用程式。如要建立應用程式,請參閱「建立應用程式」。

驗證自訂 UI 的使用者和工作負載

從自訂網頁應用程式或後端服務呼叫 StreamAssist 時,Authorization 標頭中的不記名權杖會決定 Gemini Enterprise 使用的身分,以便檢查授權、強制執行每位使用者的文件存取控制清單 (ACL),以及評估代理共用權限。

選擇與呼叫端身分相符的驗證模式:

來電者類型 驗證流程 個別使用者的 ACL 和授權
真人使用者 (Google Identity) 透過 Google OAuth 2.0 登入使用者,並使用 https://www.googleapis.com/auth/cloud-platform 範圍,然後在 Authorization: Bearer 標頭中傳遞使用者的 OAuth 2.0 存取權杖。 對已登入的 Google 使用者強制執行。
人類使用者 (員工身分聯盟) 將使用者登入外部身分識別資訊提供者 (IdP),例如 Microsoft Entra ID、Okta 或 Ping Identity。使用員工身分集區 (workforcePools),在安全權杖服務 (STS) 交換使用者的 OIDC 或 SAML 權杖,取得聯合存取權杖。在 Authorization: Bearer 標頭中傳遞聯合權杖。 強制對聯合員工使用者執行。
非人類服務和機器人 (Workload Identity Federation) 使用 workload identity pool (workloadIdentityPools) 在 STS 交換工作負載憑證。在 Authorization: Bearer 標頭中傳遞 STS 存取權杖。 而非每位使用者。使用共用工作負載主體,且不會強制執行個別使用者 ACL 或授權。

如要代表聯合員工使用者呼叫 StreamAssist,請在 STS 交換使用者的外部 IdP 權杖,並透過 X-Goog-User-Project 標頭傳遞產生的存取權杖:

REST

# 1. Exchange the external IdP OIDC token for a federated Google access token
STS_TOKEN=$(curl -s -X POST "https://sts.googleapis.com/v1/token" \
  -H "Content-Type: application/json" \
  -d '{
    "audience": "//iam.googleapis.com/locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID",
    "grantType": "urn:ietf:params:oauth:grant-type:token-exchange",
    "requestedTokenType": "urn:ietf:params:oauth:token-type:access_token",
    "scope": "https://www.googleapis.com/auth/cloud-platform",
    "subjectTokenType": "urn:ietf:params:oauth:token-type:id_token",
    "subjectToken": "EXTERNAL_IDP_TOKEN"
  }' | python3 -c "import sys, json; print(json.load(sys.stdin)['access_token'])")

# 2. Call StreamAssist with the federated access token
curl -X POST \
  -H "Authorization: Bearer ${STS_TOKEN}" \
  -H "Content-Type: application/json" \
  -H "X-Goog-User-Project: PROJECT_ID" \
  "https://ENDPOINT_LOCATION-discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/collections/default_collection/engines/APP_ID/assistants/default_assistant:streamAssist" \
  -d '{
    "query": {
      "text": "QUERY_TEXT"
    }
  }'

更改下列內容:

  • WORKFORCE_POOL_ID:員工身分集區的 ID。員工身分集區是全域 IAM 資源,因此無論 Gemini Enterprise 應用程式位置為何 (global、us 或 eu),audience 路徑一律使用 locations/global。
  • PROVIDER_ID:員工身分集區提供者的 ID。
  • EXTERNAL_IDP_TOKEN:外部 IdP 核發的使用者 OIDC ID 權杖。如果是 SAML 宣告,請將 subjectTokenType 設為 urn:ietf:params:oauth:token-type:saml2。
  • PROJECT_ID: Google Cloud 專案的 ID。
  • ENDPOINT_LOCATION:API 要求適用的多區域。請指定下列其中一個值:
    • us 適用於美國多區域
    • eu 代表歐盟多區域
    • global 適用於全域位置
    詳情請參閱「為資料儲存庫指定多區域」。
  • LOCATION:資料儲存庫的多區域:global、us 或 eu。
  • APP_ID:Gemini Enterprise 應用程式的專屬 ID。
  • QUERY_TEXT:搜尋查詢文字。

Python

在試用這個範例之前,請先按照「使用用戶端程式庫的 Gemini Enterprise 快速入門導覽課程」中的 Python 設定說明操作。詳情請參閱 Gemini Enterprise Python API 參考文件。

如要向 Gemini Enterprise 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

import requests

# Replace these placeholder values with your project, app, and pool details.
project_id = "YOUR_PROJECT_ID"
location = "YOUR_LOCATION"  # "global", "us", or "eu"
engine_id = "YOUR_APP_ID"
workforce_pool_id = "YOUR_WORKFORCE_POOL_ID"
provider_id = "YOUR_PROVIDER_ID"
external_idp_token = "EXTERNAL_IDP_OIDC_TOKEN"
query = "What is Gemini Enterprise?"


def stream_assist_with_workforce_identity(
    project_id: str,
    location: str,
    engine_id: str,
    workforce_pool_id: str,
    provider_id: str,
    external_idp_token: str,
    query: str,
):
    # 1. Exchange the external IdP token at Google Cloud STS.
    sts_response = requests.post(
        "https://sts.googleapis.com/v1/token",
        json={
            "audience": (
                f"//iam.googleapis.com/locations/global/"
                f"workforcePools/{workforce_pool_id}/providers/{provider_id}"
            ),
            "grantType": "urn:ietf:params:oauth:grant-type:token-exchange",
            "requestedTokenType": "urn:ietf:params:oauth:token-type:access_token",
            "scope": "https://www.googleapis.com/auth/cloud-platform",
            "subjectTokenType": "urn:ietf:params:oauth:token-type:id_token",
            "subjectToken": external_idp_token,
        },
        timeout=30,
    )
    sts_response.raise_for_status()
    federated_access_token = sts_response.json()["access_token"]

    # 2. Call StreamAssist with the federated access token.
    host = (
        "discoveryengine.googleapis.com"
        if location == "global"
        else f"{location}-discoveryengine.googleapis.com"
    )
    endpoint = (
        f"https://{host}/v1/projects/{project_id}/locations/{location}/"
        f"collections/default_collection/engines/{engine_id}/"
        "assistants/default_assistant:streamAssist"
    )
    response = requests.post(
        endpoint,
        headers={
            "Authorization": f"Bearer {federated_access_token}",
            "Content-Type": "application/json",
            "X-Goog-User-Project": project_id,
        },
        json={"query": {"text": query}},
        timeout=90,
    )
    response.raise_for_status()
    print(response.json())

取得搜尋結果

您可以使用 streamAssist 方法,向 Gemini Enterprise 查詢並取得答案。下列 curl 指令會列出必填欄位。

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://ENDPOINT_LOCATION-discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/collections/default_collection/engines/APP_ID/assistants/default_assistant:streamAssist" \
  -d '
{
  "query": {
    "text": "QUERY_TEXT_1"
  }
}'

更改下列內容:

  • ENDPOINT_LOCATION:API 要求適用的多區域。請指定下列其中一個值:
    • us 適用於美國多區域
    • eu 代表歐盟多區域
    • global 適用於全域位置
    詳情請參閱「為資料儲存庫指定多區域」。
  • PROJECT_ID: Google Cloud 專案的 ID。
  • APP_ID:Gemini Enterprise 應用程式的專屬 ID。
  • LOCATION:資料儲存庫的多區域:global、us 或 eu
  • QUERY_TEXT_1:搜尋查詢文字。

如要進一步瞭解欄位和傳回的內容,請參閱「回應主體」。

Python

在試用這個範例之前,請先按照「使用用戶端程式庫的 Gemini Enterprise 快速入門導覽課程」中的 Python 設定說明操作。詳情請參閱 Gemini Enterprise Python API 參考文件。

如要向 Gemini Enterprise 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Update these variables before running the sample.
project_id = "YOUR_PROJECT_ID"
location = "YOUR_LOCATION"
engine_id = "YOUR_APP_ID"
query = "What is Gemini Enterprise?"


def stream_assist_sample(
    project_id: str,
    location: str,
    engine_id: str,
    query: str,
):
    # For more information, refer to:
    # https://docs.cloud.google.com/gemini/enterprise/docs/locations#specify_a_multi-region_for_your_data_store
    client_options = (
        ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
        if location != "global"
        else None
    )

    client = discoveryengine.AssistantServiceClient(client_options=client_options)

    request = discoveryengine.StreamAssistRequest(
        name=client.assistant_path(
            project=project_id,
            location=location,
            collection="default_collection",
            engine=engine_id,
            assistant="default_assistant",
        ),
        query=discoveryengine.Query(text=query),
    )

    # Make the request
    stream = client.stream_assist(request=request)

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

使用相同工作階段取得搜尋結果

如要在現有工作階段中繼續對話,並取得 Gemini Enterprise 的回覆,請使用 streamAssist 方法。下列程式碼範例顯示必填欄位:

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://ENDPOINT_LOCATION-discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/collections/default_collection/engines/APP_ID/assistants/default_assistant:streamAssist" \
  -d '
{
  "session": "projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions/SESSION_ID",
  "query": {
    "text": "QUERY_TEXT_2"
  }
}'

更改下列內容:

  • ENDPOINT_LOCATION:API 要求適用的多區域。請指定下列其中一個值:
    • us 適用於美國多區域
    • eu 代表歐盟多區域
    • global 適用於全域位置
    詳情請參閱「為資料儲存庫指定多區域」。
  • PROJECT_ID: Google Cloud 專案的 ID。
  • APP_ID:Gemini Enterprise 應用程式的專屬 ID。
  • LOCATION:資料儲存庫的多區域:global、us 或 eu
  • QUERY_TEXT_2:搜尋查詢文字。
  • SESSION_ID:先前對話或查詢的工作階段 ID。

如要進一步瞭解欄位和傳回的內容,請參閱「回應主體」。

Python

在試用這個範例之前,請先按照「使用用戶端程式庫的 Gemini Enterprise 快速入門導覽課程」中的 Python 設定說明操作。詳情請參閱 Gemini Enterprise Python API 參考文件。

如要向 Gemini Enterprise 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Update these variables before running the sample.
project_id = "YOUR_PROJECT_ID"
location = "YOUR_LOCATION"
engine_id = "YOUR_APP_ID"
session = "projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions/SESSION_ID" # From previous session
query = "What is Gemini Enterprise?"


def stream_assist_session_sample(
    project_id: str,
    location: str,
    engine_id: str,
    session: str,
    query: str,
):
    # For more information, refer to:
    # https://docs.cloud.google.com/gemini/enterprise/docs/locations#specify_a_multi-region_for_your_data_store
    client_options = (
        ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
        if location != "global"
        else None
    )

    client = discoveryengine.AssistantServiceClient(client_options=client_options)

    request = discoveryengine.StreamAssistRequest(
        name=client.assistant_path(
            project=project_id,
            location=location,
            collection="default_collection",
            engine=engine_id,
            assistant="default_assistant",
        ),
        session=session,
        query=discoveryengine.Query(text=query),
    )

    # Make the request
    stream = client.stream_assist(request=request)

    # Handle the response
    for response in stream:
        print(response.answer)
        # Get Session ID
        print(response.session_info.session)

依據特定資料儲存庫或連接器建立基準答案

如果 Gemini Enterprise 應用程式附加了多個資料儲存庫或連結的資料來源,您可以傳遞 toolsSpec.vertexAiSearchSpec.dataStoreSpecs,將 StreamAssist 要求限制在特定資料儲存庫子集。Gemini Enterprise 只會搜尋指定的資料儲存庫,並針對經過驗證的呼叫者強制執行個別使用者的 ACL。

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-H "X-Goog-User-Project: PROJECT_ID" \
"https://ENDPOINT_LOCATION-discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/collections/default_collection/engines/APP_ID/assistants/default_assistant:streamAssist" \
  -d '{
  "query": {
    "text": "QUERY_TEXT"
  },
  "toolsSpec": {
    "vertexAiSearchSpec": {
      "dataStoreSpecs": [
        {
          "dataStore": "projects/PROJECT_NUMBER/locations/LOCATION/collections/COLLECTION_ID/dataStores/DATA_STORE_ID"
        }
      ]
    }
  }
}'

更改下列內容:

  • ENDPOINT_LOCATION:API 要求適用的多區域。請指定下列其中一個值:
    • us 適用於美國多區域
    • eu 代表歐盟多區域
    • global 適用於全域位置
    詳情請參閱「為資料儲存庫指定多區域」。
  • PROJECT_ID: Google Cloud 專案的 ID。
  • PROJECT_NUMBER: Google Cloud 專案的編號。dataStore 資源路徑需要數字專案編號,不接受專案 ID。
  • LOCATION:資料儲存庫的多區域:global、us 或 eu。
  • APP_ID:Gemini Enterprise 應用程式的專屬 ID。
  • COLLECTION_ID:資料儲存庫所在集合的 ID (標準資料儲存庫請使用 default_collection,連結的資料來源則使用連接器集合 ID)。
  • DATA_STORE_ID:要搜尋的資料儲存庫 ID。
  • QUERY_TEXT:搜尋查詢文字。

Python

在試用這個範例之前,請先按照「使用用戶端程式庫的 Gemini Enterprise 快速入門導覽課程」中的 Python 設定說明操作。詳情請參閱 Gemini Enterprise Python API 參考文件。

如要向 Gemini Enterprise 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine_v1 as discoveryengine

# Replace these placeholder values with your project, app, and data store details.
project_id = "YOUR_PROJECT_ID"
project_number = "YOUR_PROJECT_NUMBER"  # Numeric project number required by dataStore
location = "YOUR_LOCATION"
engine_id = "YOUR_APP_ID"
collection_id = "YOUR_COLLECTION_ID"
data_store_id = "YOUR_DATA_STORE_ID"
query = "Summarize my latest project notes."


def stream_assist_scoped_data_store_sample(
    project_id: str,
    project_number: str,
    location: str,
    engine_id: str,
    collection_id: str,
    data_store_id: str,
    query: str,
):
    client_options = (
        ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
        if location != "global"
        else None
    )

    client = discoveryengine.AssistantServiceClient(client_options=client_options)

    data_store_name = (
        f"projects/{project_number}/locations/{location}/"
        f"collections/{collection_id}/dataStores/{data_store_id}"
    )

    request = discoveryengine.StreamAssistRequest(
        name=client.assistant_path(
            project=project_id,
            location=location,
            collection="default_collection",
            engine=engine_id,
            assistant="default_assistant",
        ),
        query=discoveryengine.Query(text=query),
        tools_spec=discoveryengine.StreamAssistRequest.ToolsSpec(
            vertex_ai_search_spec=discoveryengine.StreamAssistRequest.ToolsSpec.VertexAiSearchSpec(
                data_store_specs=[
                    discoveryengine.SearchRequest.DataStoreSpec(
                        data_store=data_store_name
                    )
                ]
            )
        ),
    )

    for response in client.stream_assist(request=request):
        print(response)

上傳檔案並取得搜尋結果 (預先發布版)

如要提供更多背景資訊給助理,請將檔案上傳至工作階段,然後查詢檔案內容。步驟如下:

  1. 使用 addContextFile 方法將檔案上傳至工作階段。

    REST

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://ENDPOINT_LOCATION-discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/collections/default_collection/engines/APP_ID/sessions/SESSION_ID:addContextFile" \
      -d '
    {
      "fileName": "FILE_NAME",
      "mimeType": "MIME_TYPE",
      "fileContents": "BASE64_ENCODED_FILE"
    }'
    

    更改下列內容:

    • ENDPOINT_LOCATION:API 要求適用的多區域。請指定下列其中一個值:
      • us 適用於美國多區域
      • eu 代表歐盟多區域
      • global 適用於全域位置
      詳情請參閱「為資料儲存庫指定多區域」。
    • PROJECT_ID: Google Cloud 專案的 ID。
    • LOCATION:資料儲存庫的多區域:global、us 或 eu
    • APP_ID:Gemini Enterprise 應用程式的專屬 ID。
    • SESSION_ID:先前對話或查詢的工作階段 ID。
    • FILE_NAME:檔案名稱。
    • MIME_TYPE:檔案的 MIME 類型,例如 text/plain 或 application/pdf。如要進一步瞭解不同的媒體類型,請參閱「媒體類型」。
    • BASE64_ENCODED_FILE:檔案的 Base64 編碼表示法。

    如要進一步瞭解欄位和傳回的內容,請參閱「回應主體」。

  2. 使用同一個工作階段,詢問有關您透過 streamAssist 方法上傳的檔案的問題。

    REST

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://ENDPOINT_LOCATION-discoveryengine.googleapis.com/v1alpha/projects/PROJECT_ID/locations/LOCATION/collections/default_collection/engines/APP_ID/assistants/default_assistant:streamAssist" \
      -d '
    {
      "session": "projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions/SESSION_ID",
      "fileIds": ["FILE_ID"],
      "query": {
        "text": "QUERY_TEXT_3"
      }
    }'
    
    

    更改下列內容:

    • ENDPOINT_LOCATION:API 要求適用的多區域。請指定下列其中一個值:
      • us 適用於美國多區域
      • eu 代表歐盟多區域
      • global 適用於全域位置
      詳情請參閱「為資料儲存庫指定多區域」。
    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:Gemini Enterprise 應用程式的專屬 ID。
    • LOCATION:資料儲存庫的多區域:global、us 或 eu
    • QUERY_TEXT_3:搜尋查詢文字。
    • SESSION_ID:先前對話或查詢的工作階段 ID。
    • FILE_ID:上傳至助理的檔案 ID。

    如要進一步瞭解欄位和傳回的內容,請參閱「回應主體」。