取得解答和後續追蹤

本頁面將介紹 Vertex AI Search 的搜尋功能,包括提供答案和後續動作,並說明如何使用方法呼叫,為一般搜尋應用程式實作這項功能。

搜尋答案和後續問題的結果,取決於回答方法。答案方法取代舊版 search 方法的摘要功能,以及已淘汰的 converse 方法的所有功能。答案方法也提供一些重要的額外功能,例如處理複雜查詢的能力。

回覆方法的特色

答案方法的主要功能如下:

  • 產生複雜查詢的答案。舉例來說,答案方法可將複合查詢 (例如下列查詢) 分解為多個較小的查詢,以便傳回更優質的結果,進而提供更精確的答案:

    • 「Google Cloud 和 Google Ads 在 2024 年的分別營收為何?」
    • 「Google 成立多少年後,收益達到 10 億美元?」
  • 在每個回合中呼叫答案方法,藉此在多回合對話中結合搜尋和答案產生功能。

  • 可與搜尋方法搭配使用,以縮短搜尋延遲時間。您可以分別呼叫搜尋方法和回覆方法,並在不同時間點以不同的 iframe 顯示搜尋結果和回覆。也就是說,您可以在幾毫秒內向使用者顯示搜尋結果 (10 個藍色連結)。您不必等到答案產生,就能顯示搜尋結果。

答案和後續動作的功能可分為三個階段:查詢、搜尋和答案:

何時使用 Answer,何時使用 Search

Vertex AI Search 有兩種方法可用於查詢應用程式。兩者功能相似,但有些重疊。

請在下列情況下使用 answer 方法:

  • 您希望搜尋結果包含 AI 產生的答案 (或摘要)。

  • 您需要多輪搜尋功能,也就是保留上下文的搜尋功能,以便進行後續問題。

請在下列情況下使用 search 方法:

  • 你只需要搜尋結果,不需要生成的答案。

  • 您有下列任一情況:

    • 媒體或醫療照護資料
    • 您自己的嵌入
    • 同義詞或重新導向控制項
    • facet
    • 使用者國家/地區代碼

請在下列情況下同時使用回答和搜尋方法:

  • 您想傳回超過十個搜尋結果,並且希望系統產生答案。

  • 您遇到延遲問題,希望在產生的答案傳回前,快速傳回並顯示搜尋結果。

查詢階段功能

答案和後續追蹤功能支援自然語言查詢處理。

本節將說明及示範各種查詢重述和分類選項。

查詢重寫

根據預設,系統會開啟查詢重述功能。這項功能會自動選擇最佳方式重新表達查詢,以改善搜尋結果。這項功能也能處理不需要重新表達的查詢。

  • 將複雜查詢拆分為多項查詢,並執行同步子查詢。

    例如:將複雜的查詢拆解為四個較簡單的查詢。

    使用者輸入內容 從複雜查詢建立的子查詢
    Andie Ram 和 Arnaud Clément 有哪些共同的工作和興趣?
    • Andie Ram 職業
    • Arnaud Clément 職業
    • Andie Ram 興趣
    • Arnaud Clément 的興趣
  • 彙整多輪查詢,讓後續問題能根據情境提供有狀態的回覆。

    舉例來說,每次輪到使用者輸入時,系統合成的查詢可能會像這樣:

    使用者輸入內容 已合成的查詢
    第一步:學校適用的筆記型電腦 學校適用的筆記型電腦
    Turn 2: not mac 學校適用的筆電 (非 Mac)
    轉換 3:螢幕更大,我還需要無線鍵盤和滑鼠 學校使用的大螢幕筆記型電腦 (非 Mac),搭配無線鍵盤和滑鼠
    第 4 回合:以及一個背包 學校使用的大螢幕筆電 (非 Mac),內含無線鍵盤和滑鼠,以及筆電背包
  • 簡化長查詢,改善擷取結果 (需要進階 LLM 功能)。

    例如:將長查詢縮短為簡單查詢。

    使用者輸入內容 簡化查詢
    我正在嘗試找出網站上的「Add to Cart」按鈕為何無法正常運作。使用者點選按鈕時,商品似乎不會加入購物車,且會收到錯誤訊息。我已檢查程式碼,似乎沒有問題,可以幫我排解這個問題嗎? 「Add to Cart」按鈕無法在網站上運作。
  • 進行多步驟推論

    多步驟推論是根據 ReAct (reason + act) 模式,可讓大型語言模型透過自然語言推論解決複雜任務。根據預設,步驟數量上限為五個。

    例如:

    使用者輸入內容 產生答案的兩個步驟
    Google 成立多少年後,才達到 10 億美元的營收? 步驟 1:
    [思考過程]: 我需要知道 Google 成立的時間,才能查詢 Google 自成立以來的收益。
    [行動] 搜尋:Google 成立於何時?[觀察搜尋結果]:「1998 年」

    步驟 2:
    [思考]:現在我需要查看 Google 自 1998 年以來的年收入,並找出首次超過 10 億的時間。
    [Act] 搜尋:Google 自 1998 年以來的收益
    [Observe Search Results] Google 在 1998 年的收益、Google 在 1999 年的收益……
    [答案]:Google 在 1998 年成立後的 5 年 [2],於 2003 年 [1] 達到超過 10 億美元的收益。

    多步驟推論功能需要進階 LLM 功能

查詢分類

查詢分類選項可用於識別惡意查詢和非答案查詢。根據預設,查詢分類選項會關閉。

如要進一步瞭解對抗性和非答案查詢,請參閱「忽略對抗性查詢」和「忽略非摘要查詢」。

搜尋階段功能

在搜尋方面,回答方法與搜尋方法的選項相同。例如:

答案階段功能

在回答階段,當系統從搜尋結果產生答案時,您可以啟用與搜尋方法相同的功能。例如:

搜尋方法中無法使用的其他答案階段功能如下:

  • 為每項主張 (產生答案中的句子) 取得支援分數。支援分數是介於 0 到 1 之間的浮點值,用於指出聲明在資料儲存庫中的資料中有多可靠。詳情請參閱「返回接地支援分數」。

  • 取得答案的綜合支援分數。支援分數可顯示答案與資料儲存庫中的資料相符程度。詳情請參閱「退回接地支援分數」。

  • 只回傳有根據的答案。您可以選擇只傳回符合特定支援分數門檻的答案。詳情請參閱「只顯示有根據的答案」。

  • 在查詢中加入個人化資訊,以便為個別使用者提供客製化答案。詳情請參閱「個人化答案」。

如要收到包含文字、圖表或圖片的多模式答案,請使用下列選項:

  • 取得包含圖表和圖形的答案,以便繪製答案中包含的資料。詳情請參閱「為答案產生圖表」。

  • 從資料儲存庫擷取圖片。如果資料儲存庫包含圖片,答案方法就能在答案中傳回圖片。如果要求引用資料,資料儲存庫中的圖片也可以在參考資料中傳回。詳情請參閱「從資料儲存庫擷取現有圖片」。

事前準備

視應用程式類型而定,請完成下列要求:

  • 如果您有結構化、非結構化或網站搜尋應用程式,請開啟下列選項:

    • Enterprise 版功能:可使用核心生成式回答功能。這包括所有答案產生功能,但不包括進階生成式答案功能,例如相關問題、查詢簡化、多回合查詢,以及傳回圖片和圖表的多模態答案。
    • 進階 LLM 功能:您可以使用進階生成式答案功能,這類功能需要多步驟推理、查詢簡化、多輪查詢、相關問題,以及傳回圖片和圖表的多模態答案。
  • 此外,如果您有網站搜尋資料儲存庫,請啟用進階網站索引建立功能

  • 如果您有混合搜尋應用程式 (也就是連結至多個資料儲存庫的應用程式),請與 Google 帳戶團隊聯絡,要求將您的應用程式加入答案 API 的混合搜尋許可清單。

搜尋和回答 (基本)

以下指令說明如何呼叫 answer 方法,並傳回已產生的答案和搜尋結果清單,以及來源連結。

這個指令只會顯示必要的輸入內容。這些選項會保留預設值。

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_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"}
          }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:您要查詢的 Vertex AI Search 應用程式 ID。
    • QUERY:包含問題或搜尋查詢的自由文字字串。例如:「比較 BigQuery 和 Spanner 資料庫?」

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

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

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/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
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
            model_version="gemini-2.0-flash-001/answer_gen/v1",  # Optional: Model to use for answer generation
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

查詢階段指令

本節說明如何為 answer 方法呼叫的查詢階段指定選項。

搜尋與回答 (已停用重述功能)

以下指令說明如何呼叫 answer 方法,並傳回生成的答案和搜尋結果清單。由於重寫選項已停用,因此答案可能與先前的答案不同。

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_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "queryUnderstandingSpec": {
               "queryRephraserSpec": {
                  "disable": true
            }
        }
          }'
    
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:Vertex AI Search 應用程式 ID。
    • QUERY:包含問題或搜尋查詢的自由文字字串。例如:「比較 BigQuery 和 Spanner 資料庫?」。

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

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

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/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
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
            model_version="gemini-2.0-flash-001/answer_gen/v1",  # Optional: Model to use for answer generation
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

搜尋及回答 (指定步驟上限)

以下指令說明如何呼叫 answer 方法,並傳回已產生的答案和搜尋結果清單。由於重述步驟數量增加,因此答案與前述答案不同。

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_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "queryUnderstandingSpec": {
                "queryRephraserSpec": {
                    "maxRephraseSteps": MAX_REPHRASE
                 }
             }
          }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:您要查詢的 Vertex AI Search 應用程式 ID。
    • QUERY:包含問題或搜尋查詢的自由文字字串。例如:「比較 BigQuery 和 Spanner 資料庫?」
    • MAX_REPHRASE:重述步驟的上限。允許的最大值為 5。如果未設定或設定的值小於 1,則採用預設值 1

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

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

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/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
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
            model_version="gemini-2.0-flash-001/answer_gen/v1",  # Optional: Model to use for answer generation
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

使用查詢分類功能搜尋及回答

以下指令說明如何呼叫 answer 方法,以便查詢查詢是否為對抗性、非答案搜尋,或兩者皆非。

回應會包含查詢的分類類型,但答案本身不會受到分類影響。如果您想根據查詢類型變更答案行為,可以在答案階段執行這項操作。請參閱「忽略對立查詢」和「忽略非摘要查詢」。

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_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "queryUnderstandingSpec": {
                "queryClassificationSpec": {
                    "types": ["QUERY_CLASSIFICATION_TYPE"]
                 }
             }
          }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:您要查詢的 Vertex AI Search 應用程式 ID。
    • QUERY:包含問題或搜尋查詢的自由文字字串。例如「hello」。
    • QUERY_CLASSIFICATION_TYPE:您要識別的查詢類型:ADVERSARIAL_QUERYNON_ANSWER_SEEKING_QUERY,或兩者皆是。

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

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

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/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
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
            model_version="gemini-2.0-flash-001/answer_gen/v1",  # Optional: Model to use for answer generation
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

搜尋階段指令:使用搜尋結果選項搜尋及回答

本節說明如何為 answer 方法呼叫的搜尋階段部分指定選項,例如設定傳回文件數量上限、提升和篩選,以及在您提供自己的搜尋結果時如何取得答案。

下列指令說明如何呼叫 answer 方法,並指定各種選項,以便返回搜尋結果。(搜尋結果與答案無關)。

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_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
              "searchSpec": {
              "searchParams": {
                "maxReturnResults": MAX_RETURN_RESULTS,
                "filter": "FILTER",
                "boostSpec": BOOST_SPEC,
                "orderBy": "ORDER_BY",
                "searchResultMode": SEARCH_RESULT_MODE
               }
             }
          }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:您要查詢的 Vertex AI Search 應用程式 ID。
    • QUERY:包含問題或搜尋查詢的自由文字字串。例如:「比較 BigQuery 和 Spanner 資料庫?」
    • MAX_RETURN_RESULTS:要傳回的搜尋結果數量。預設值為 10。最大值為 25
    • FILTER:篩選器會指定要查詢哪些文件。如果文件的中繼資料符合篩選器規格,系統就會查詢該文件。如需進一步瞭解篩選器語法等資訊,請參閱「篩選結構化或非結構化資料的一般搜尋結果」。
    • BOOST_SPEC:您可以使用提升規格,在搜尋結果中提升特定文件的排名,這可能會影響答案。如需進一步瞭解 (包括提升規範的語法),請參閱「提升搜尋結果」。
    • ORDER_BY:文件的傳回順序。文件可依 Document 物件中的欄位排序。orderBy 運算式會區分大小寫。如果這個欄位無法辨識,系統會傳回 INVALID_ARGUMENT
    • SEARCH_RESULT_MODE:指定搜尋結果模式:DOCUMENTSCHUNKS。詳情請參閱「剖析及分割文件」和「ContentSearchSpec」。這個欄位僅適用於 API 的 v1alpha 版。

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

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

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/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
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
            model_version="gemini-2.0-flash-001/answer_gen/v1",  # Optional: Model to use for answer generation
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

答案階段指令

本節將說明如何自訂 answer 方法呼叫。您可以視需要結合下列選項。

忽略對抗查詢和非尋答查詢

下列指令說明如何在呼叫 answer 方法時,避免回答對抗性查詢和非尋答查詢。

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_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "answerGenerationSpec": {
               "ignoreAdversarialQuery": true,
               "ignoreNonAnswerSeekingQuery": true
            }
          }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:您要查詢的 Vertex AI Search 應用程式 ID。
    • QUERY:包含問題或搜尋查詢的自由文字字串。

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

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

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/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
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
            model_version="gemini-2.0-flash-001/answer_gen/v1",  # Optional: Model to use for answer generation
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

只顯示相關的答案

Vertex AI Search 可以評估結果與查詢的關聯性。如果系統判定沒有任何結果與查詢相符,您可以選擇傳回備用答案「We do not have a summary for your query.」,而不是從不相符或相符程度不高的結果產生答案。

以下指令說明如何在呼叫 answer 方法時,針對不相關的結果傳回備用答案。

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_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "answerGenerationSpec": {
               "ignoreLowRelevantContent": true
            }
          }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:您要查詢的 Vertex AI Search 應用程式 ID。
    • QUERY:包含問題或搜尋查詢的自由文字字串。

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

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

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/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
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
            model_version="gemini-2.0-flash-001/answer_gen/v1",  # Optional: Model to use for answer generation
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

傳回基準分數

以下指令說明如何傳回答案和主張的基礎支持分數。

如要進一步瞭解 Vertex AI 中的基準,請參閱「使用 RAG 檢查基準」一文。答案方法會呼叫 groundingConfigs.check 方法。

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_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "groundingSpec": {
               "includeGroundingSupports": true,
            }
          }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:您要查詢的 Vertex AI Search 應用程式 ID。
    • QUERY:包含問題或搜尋查詢的自由文字字串。

只顯示有根據的答案

下列指令說明如何只傳回系統認為與字典 (資料儲存庫中的資訊) 相符的答案。系統會篩除不切實際的答案。

您可以為地線支援分數選擇低或高等級門檻。接著,只有在達到或超過該等級時,系統才會傳回答案。您可以嘗試使用兩個篩選器門檻和沒有門檻的情況,判斷哪種篩選器等級最有可能為使用者提供最佳結果。

如要進一步瞭解 Vertex AI 中的基準,請參閱「使用 RAG 檢查基準」。答案方法會呼叫 groundingConfigs.check 方法。

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_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "groundingSpec": {
               "filteringLevel": "FILTER_LEVEL"
            }
          }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:您要查詢的 Vertex AI Search 應用程式 ID。
    • QUERY:包含問題或搜尋查詢的自由文字字串。
    • FILTER_LEVEL:根據基礎支援分數篩選答案的列舉。選項包括:FILTERING_LEVEL_LOWFILTERING_LEVEL_HIGH。如果未納入 filteringLevel,則系統不會對答案套用支援分數篩選器。

指定答案模型

下列指令說明如何變更用於產生答案的模型版本。

如要瞭解支援的模型,請參閱「答案產生模型版本和生命週期」。

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_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "answerGenerationSpec": {
               "modelSpec": {
                  "modelVersion": "MODEL_VERSION",
               }
             }
          }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:您要查詢的 Vertex AI Search 應用程式 ID。
    • QUERY:包含問題或搜尋查詢的自由文字字串。
    • MODEL_VERSION:您要用來產生答案的模型版本。詳情請參閱「答案產生模型版本和生命週期」。

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

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

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/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
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
            model_version="gemini-2.0-flash-001/answer_gen/v1",  # Optional: Model to use for answer generation
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

指定自訂前置文字

下列指令說明如何為產生的答案設定前置文字。前言包含用於自訂答案的自然語言指示。您可以要求自訂內容,例如長度、詳細程度、輸出樣式 (例如「簡單」)、輸出語言、答案重點和格式 (例如表格、項目符號和 XML)。舉例來說,前言可以是「請用十歲小孩的語氣解釋」。

前置文字會對產生的答案品質造成重大影響。如要瞭解前置文字的內容,以及良好前置文字的範例,請參閱「關於自訂前置文字」。

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_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "answerGenerationSpec": {
               "promptSpec": {
                   "preamble": "PREAMBLE",
               }
            }
          }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:您要查詢的 Vertex AI Search 應用程式 ID。
    • QUERY:包含問題或搜尋查詢的自由文字字串。
    • PREAMBLE:用於自訂答案的自然語言指示。例如,請嘗試使用 show the answer format in an ordered listgive a very detailed answer

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

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

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/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
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
            model_version="gemini-2.0-flash-001/answer_gen/v1",  # Optional: Model to use for answer generation
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

納入參考資料

以下指令顯示如何要求在答案中加入參考資料。

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_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "answerGenerationSpec": {
               "includeCitations": INCLUDE_CITATIONS
            }
          }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:您要查詢的 Vertex AI Search 應用程式 ID。
    • QUERY:包含問題或搜尋查詢的自由文字字串。
    • INCLUDE_CITATIONS:指定是否要在答案中加入引文中繼資料。預設值為 false

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

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

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/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
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
            model_version="gemini-2.0-flash-001/answer_gen/v1",  # Optional: Model to use for answer generation
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

設定答案語言代碼

下列指令說明如何設定答案的語言代碼。

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_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "answerGenerationSpec": {
               "answerLanguageCode": "ANSWER_LANGUAGE_CODE"
               }
          }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:您要查詢的 Vertex AI Search 應用程式 ID。
    • QUERY:包含問題或搜尋查詢的自由文字字串。
    • ANSWER_LANGUAGE_CODE:答案的語言代碼。請使用 BCP47:用於識別語言的標記 定義的語言標記。

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

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

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/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
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
            model_version="gemini-2.0-flash-001/answer_gen/v1",  # Optional: Model to use for answer generation
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

提供個人化答案

如果有可用的使用者特定資訊 (例如個人資料中的資料),您可以在 endUserMetadata 物件中指定該資訊,以便為使用者提供個人化搜尋結果。

舉例來說,如果已登入的使用者搜尋有關升級手機的資訊,系統會根據使用者個人資料中的資訊 (例如目前的手機型號和行動網路方案),提供可個人化產生的答案。

如要新增查詢使用者的個人資訊,並產生考量個人資訊的答案,請執行下列操作:

  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_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
    -d '{
        "query": { "text": "QUERY"},
        "endUserSpec": {
           "endUserMetadata": [
             {
               "chunkInfo": {
                  "content": "PERSONALIZED_INFO",
                  "documentMetadata":  { "title": "INFO_DESCRIPTION"}
               }
             }
           ]
        }
      }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:您要查詢的 Vertex AI Search 應用程式 ID。
    • QUERY:包含問題或搜尋查詢的自由文字字串。
    • PERSONALIZATION_INFO:包含查詢使用者專屬資訊的字串。例如:This customer has a Pixel 6 Pro purchased over a period of 24-months starting 2023-01-15. This customer is on the Business Plus International plan. No payment is due at this time. 這個字串的長度上限為 8,000 個字元。
    • INFO_DESCRIPTION:簡要說明個人化資訊的字串,例如 Customer profile data, including model, plan, and billing status.。模型在為查詢產生自訂答案時,會同時使用這項說明和個人化資訊。

為答案產生圖表

answer 方法可產生圖表,並將圖表做為查詢答案的一部分傳回。

您可以明確要求答案包含圖表,例如「使用現有資料繪製小型企業支付交易的年度成長率」。如果系統判定資料量足夠,就會傳回圖表。通常會一併傳回部分答案文字。

此外,如果有足夠的資料可用於建立圖表,即使查詢未明確要求圖表,答案方法仍可傳回圖表。例如:「2010 年至 2020 年間,人類發展指標的改善程度與更容易取得乾淨飲用水之間的關聯為何?」

每個答案只會產生一張圖表。不過,圖表可能為複合圖表,包含其他較小的圖表。複合圖表範例:

複合圖表包含四個較小的圖表

限制

查詢必須以英文輸入。

常見的失敗情況

系統不會一律在回覆中附上圖片。如果資料不足,就無法產生圖表。

其他失敗情況包括程式碼執行失敗和逾時。如果發生上述任一情況,請重新表達查詢,然後再試一次。

事前準備

執行要求產生圖表的查詢前,請先完成下列步驟:

程序

REST

如要傳回可包含資料儲存庫中資料所產生圖表的答案,請呼叫 answer 方法,如下所示:

  1. 執行下列 curl 指令:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1beta/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "answerGenerationSpec": {
              "model_spec": {
                 "model_version": "MODEL_VERSION"
             },
              "multimodalSpec": {
                 "imageSource": "IMAGE_SOURCE"
                 }
            }
          }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:您要查詢的 Vertex AI Search 應用程式 ID。
    • QUERY:包含問題或搜尋查詢的英文自由文字字串。
    • MODEL_VERSION:模型版本 gemini-2.0-flash-001/answer_gen/v1 以上。詳情請參閱「答案產生模型版本和生命週期」。
    • IMAGE_SOURCE:列舉項目,用於要求答案包含產生的圖表 FIGURE_GENERATION_ONLY,或是要求答案可以包含產生的圖表或資料儲存庫中的現有圖片 ALL_AVAILABLE_SOURCES

從資料儲存庫擷取現有圖片

您可以選擇讓資料儲存庫中的圖片隨回覆一併傳回,並在引文參考資料中顯示。資料儲存庫必須是已啟用版面配置剖析器的非結構化資料儲存庫。

如要在傳回的答案中取得圖表,您必須開啟 進階 LLM 功能

imageSourceCORPUS_IMAGE_ONLYALL_AVAILABLE_SOURCES 時,answer 方法就能視需要從資料儲存庫擷取圖片。不過,啟用這項功能並不代表系統一律會傳回圖片。

每個答案最多只能上傳一張圖片。參考資料可以包含多張圖片。

限制

  • 您使用的應用程式必須連結至非結構化資料儲存庫。系統無法從網站或結構化資料儲存庫傳回圖片。

  • 查詢必須以英文輸入。

  • 透過版面配置剖析器的圖片註解必須套用至資料儲存庫。如要瞭解版面配置剖析器,請參閱「剖析及分割文件」。

程序

REST

如要傳回可在答案中加入資料儲存庫圖片的答案,請呼叫 answer 方法,如下所示:

  1. 執行下列 curl 指令:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1beta/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "answerGenerationSpec": {
              "model_spec": {
                 "model_version": "MODEL_VERSION"
              },
              includeCitations: true,
              "multimodalSpec": {
                 "imageSource": "IMAGE_SOURCE"
                 }
            }
          }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:您要查詢的 Vertex AI Search 應用程式 ID。
    • QUERY:包含問題或搜尋查詢的英文自由文字字串。
    • MODEL_VERSION:模型版本 gemini-2.0-flash-001/answer_gen/v1 以上。詳情請參閱「答案產生模型版本和生命週期」。
    • IMAGE_SOURCE:列舉項目,用於要求答案包含資料儲存庫的圖片 (CORPUS_IMAGE_ONLY),或答案可包含資料儲存庫的圖片或產生的圖表 (ALL_AVAILABLE_SOURCES)。

後續問題的指令

後續追蹤是多輪查詢。在後續工作階段中進行第一次查詢後,後續的「輪次」會考量先前的互動。透過後續追蹤,回答方法也可以建議相關問題,讓使用者選擇這些問題,而不用自行輸入後續追蹤問題。如要取得相關問題的建議,請務必開啟進階 LLM 功能

您可以搭配後續動作使用前面各節所述的所有答案和後續動作功能,例如引文、篩選器、安全搜尋、忽略特定類型的查詢,以及使用前言自訂答案。

後續追蹤工作階段範例

以下是含有後續追蹤的會話範例。假設您想瞭解墨西哥的度假資訊:

  • 第 1 回合:

    • 你:在墨西哥度假的最佳時機是什麼時候?

    • 回答並追問:在墨西哥度假的最佳時機是乾季,也就是從 11 月到 4 月。

  • 第 2 回合:

    • 您:匯率是多少?

    • 回答並附上後續說明:1 美元約等於 17.65 墨西哥披索。

  • 第 3 回合:

    • 你:12 月的平均氣溫是多少?

    • 回答並附上後續說明:平均溫度介於華氏 70 到 78 度之間。坎昆的平均溫度約為華氏 77°。

如未進行後續追蹤,系統就無法回答「匯率是多少?」的問題,因為一般搜尋不會知道你想查詢墨西哥的匯率。同樣地,如果沒有後續追蹤,就無法提供特定墨西哥的溫度。

當你詢問「何時是前往墨西哥度假的最佳時機?」時,除了回答你的問題,答案和後續追蹤結果還會建議你可能會問的其他問題,例如「何時是前往墨西哥度假的最佳時機?」和「墨西哥的旅遊旺季是哪幾個月?」。

啟用相關問題功能後,系統會在 ConverseConversationResponse 中以字串的形式傳回問題。

關於工作階段

如要瞭解 Vertex AI Search 中的追蹤功能運作方式,您必須先瞭解工作階段。

一個工作階段由使用者提供的文字查詢和 Vertex AI Search 提供的回覆組成。

這些查詢和回應組合有時也稱為回合。在上述範例中,第二輪對話包含「匯率是多少?」和「1 美元約等於 17.65 墨西哥披索。」

工作階段會與應用程式一併儲存。在應用程式中,工作階段會以工作階段資源表示。

除了包含查詢和回應訊息之外,工作階段資源還包含下列項目:

  • 不重複的名稱 (工作階段 ID)。

  • 狀態 (進行中或已完成)。

  • 使用者虛擬 ID,也就是用來追蹤使用者的訪客 ID。可透過程式輔助方式指派。

  • 開始時間和結束時間。

  • 一個回合,也就是查詢答案組合。

事前準備

執行要求後續問題的查詢前,請先確認您已為應用程式啟用進階 LLM 功能

儲存工作階段資訊並取得回應

您可以使用命令列產生搜尋回應和答案,並將這些內容與會話中的每項查詢一併儲存。

REST

如要使用指令列建立工作階段,並根據使用者輸入內容產生回應,請按照下列步驟操作:

  1. 指定要儲存工作階段的應用程式:

    curl -X POST \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions" \
      -d '{
            "userPseudoId": "USER_PSEUDO_ID"
          }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。

    • APP_ID:Vertex AI Search 應用程式 ID。

    • USER_PSEUDO_ID:用於追蹤搜尋訪客的專屬 ID。例如,您可以使用 HTTP Cookie 實作這項功能,這樣就能明確識別單一裝置上的訪客。

    指令和結果範例

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)"
    -H "Content-Type: application/json"
    "https://discoveryengine.googleapis.com/v1/projects/my-project-123/locations/global/collections/default_collection/engines/my-app/sessions"
    -d '{
    "userPseudoId": "test_user"
    }'
    
    { "name": "projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/16002628354770206943", "state": "IN_PROGRESS", "userPseudoId": "test_user", "startTime": "2024-09-13T18:47:10.465311Z", "endTime": "2024-09-13T18:47:10.465311Z" }
  2. 請記下工作階段 ID,也就是 JSON 回應中 name: 欄位結尾的數字。在範例結果中,ID 為 5386462384953257772。在下一個步驟中會用到這個 ID。

  3. 產生答案並將其新增至應用程式的工作階段:

    curl -X POST \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "session": "projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions/SESSION_ID",
              "searchSpec":{ "searchParams": {"filter": "FILTER"} }
    }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:Vertex AI Search 應用程式 ID。
    • QUERY:包含問題或搜尋查詢的自由文字字串。
    • SESSION_ID:您在步驟 1 建立的工作階段 ID。這些是 name: 欄位結尾的數字,請參閱步驟 2。針對工作階段,請在每個回合中使用相同的工作階段 ID。
    • FILTER:使用篩選器運算式篩選搜尋結果的文字欄位。預設值為空白字串。您建構篩選器的方式會因資料類型而異,包括是否含有中繼資料的非結構化資料、結構化資料或網站資料。詳情請參閱「篩選一般搜尋結果,以便搜尋結構化或非結構化資料」和「篩選網站搜尋結果」。

    指令和結果範例

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)"
    -H "Content-Type: application/json"
    "https://discoveryengine.googleapis.com/v1/projects/my-project-123/locations/global/collections/default_collection/engines/my-app/servingConfigs/default_search:answer"
    -d '{
    "query": { "text": "Compare bigquery with spanner database?"},
    "session":  "projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/16002628354770206943",
    }'
        
    { "answer": { "name": "projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/16002628354770206943/answers/4861507376861383072", "state": "SUCCEEDED", "answerText": "BigQuery and Spanner are both powerful tools that can be used together to handle transactional and analytical workloads. Spanner is a fully managed relational database optimized for transactional workloads, while BigQuery is a serverless data warehouse designed for business agility. Spanner provides seamless replication across regions in Google Cloud and processes over 1 billion requests per second at peak. BigQuery analyzes over 110 terabytes of data per second. Users can leverage federated queries to read data from Spanner and write to a native BigQuery table. \n", "steps": [ { "state": "SUCCEEDED", "description": "Rephrase the query and search.", "actions": [ { "searchAction": { "query": "Compare bigquery with spanner database?" }, "observation": { "searchResults": [ { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/ecc0e7547253f4ca3ff3328ce89995af", "uri": "https://cloud.google.com/blog/topics/developers-practitioners/how-spanner-and-bigquery-work-together-handle-transactional-and-analytical-workloads", "title": "How Spanner and BigQuery work together to handle transactional and analytical workloads | Google Cloud Blog", "snippetInfo": [ { "snippet": "Using Cloud \u003cb\u003eSpanner\u003c/b\u003e and \u003cb\u003eBigQuery\u003c/b\u003e also allows customers to build their \u003cb\u003edata\u003c/b\u003e clouds using Google Cloud, a unified, open approach to \u003cb\u003edata\u003c/b\u003e-driven transformation ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/d7e238f73608a860e00b752ef80e2941", "uri": "https://cloud.google.com/blog/products/databases/cloud-spanner-gets-stronger-with-bigquery-federated-queries", "title": "Cloud Spanner gets stronger with BigQuery-federated queries | Google Cloud Blog", "snippetInfo": [ { "snippet": "As enterprises compete for market share, their need for real-time insights has given rise to increased demand for transactional \u003cb\u003edatabases\u003c/b\u003e to support \u003cb\u003edata\u003c/b\u003e ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/e10a5a3c267dc61579e7c00fefe656eb", "uri": "https://cloud.google.com/blog/topics/developers-practitioners/replicating-cloud-spanner-bigquery-scale", "title": "Replicating from Cloud Spanner to BigQuery at scale | Google Cloud Blog", "snippetInfo": [ { "snippet": "... \u003cb\u003eSpanner data\u003c/b\u003e into \u003cb\u003eBigQuery\u003c/b\u003e for analytics. In this post, you will learn how to efficiently use this feature to replicate large tables with high throughput ...", "snippetStatus": "SUCCESS" } ] }, ... { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/8100ad36e1cac149eb9fc180a41d8f25", "uri": "https://cloud.google.com/blog/products/gcp/from-nosql-to-new-sql-how-spanner-became-a-global-mission-critical-database", "title": "How Spanner became a global, mission-critical database | Google Cloud Blog", "snippetInfo": [ { "snippet": "... SQL \u003cb\u003evs\u003c/b\u003e. NoSQL dichotomy may no longer be relevant." The \u003cb\u003eSpanner\u003c/b\u003e SQL query processor, while recognizable as a standard implementation, has unique ...", "snippetStatus": "SUCCESS" } ] } ] } } ] } ] }, "session": { "name": "projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/16002628354770206943", "state": "IN_PROGRESS", "userPseudoId": "test_user", "turns": [ { "query": { "queryId": "projects/123456/locations/global/questions/741830", "text": "Compare bigquery with spanner database?" }, "answer": "projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/16002628354770206943/answers/4861507376861383072" } ], "startTime": "2024-09-13T18:47:10.465311Z", "endTime": "2024-09-13T18:47:10.465311Z" }, "answerQueryToken": "NMwKDAjFkpK3BhDU24uZAhIkNjZlNDIyZWYtMDAwMC0yMjVmLWIxMmQtZjQwMzA0M2FkYmNj" }
  4. 針對工作階段中的每個新查詢重複執行步驟 3。

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

from google.cloud import discoveryengine_v1 as discoveryengine


def create_session(
    project_id: str,
    location: str,
    engine_id: str,
    user_pseudo_id: str,
) -> discoveryengine.Session:
    """Creates a session.

    Args:
        project_id: The ID of your Google Cloud project.
        location: The location of the app.
        engine_id: The ID of the app.
        user_pseudo_id: A unique identifier for tracking visitors. For example, this
          could be implemented with an HTTP cookie, which should be able to
          uniquely identify a visitor on a single device.
    Returns:
        discoveryengine.Session: The newly created Session.
    """

    client = discoveryengine.ConversationalSearchServiceClient()

    session = client.create_session(
        # The full resource name of the engine
        parent=f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}",
        session=discoveryengine.Session(user_pseudo_id=user_pseudo_id),
    )

    # Send Session name in `answer_query()`
    print(f"Session: {session.name}")
    return session

從資料儲存庫取得工作階段

以下指令示範如何呼叫 get 方法,並從資料儲存庫取得工作階段。

REST

如要從資料儲存庫取得工作階段,請執行下列操作:

  1. 執行下列 curl 指令:

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions/SESSION_ID"
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:Vertex AI Search 應用程式 ID。
    • SESSION_ID:您要取得的工作階段 ID。

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

from google.cloud import discoveryengine_v1 as discoveryengine


def get_session(
    project_id: str,
    location: str,
    engine_id: str,
    session_id: str,
) -> discoveryengine.Session:
    """Retrieves a session.

    Args:
        project_id: The ID of your Google Cloud project.
        location: The location of the app.
        engine_id: The ID of the app.
        session_id: The ID of the session.
    """

    client = discoveryengine.ConversationalSearchServiceClient()

    # The full resource name of the session
    name = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/sessions/{session_id}"

    session = client.get_session(name=name)

    print(f"Session details: {session}")
    return session

從應用程式中刪除工作階段

以下指令示範如何呼叫 delete 方法,並從資料儲存庫中刪除工作階段。

根據預設,系統會自動刪除超過 60 天的會話。不過,如果您想刪除特定工作階段 (例如含有機密內容的工作階段),請使用這個 API 呼叫來刪除。

REST

如要刪除應用程式的工作階段,請按照下列步驟操作:

  1. 執行下列 curl 指令:

    curl -X DELETE -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions/SESSION_ID"
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:Vertex AI Search 應用程式的 ID。
    • SESSION_ID:您要刪除的工作階段 ID。

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

from google.cloud import discoveryengine_v1 as discoveryengine


def delete_session(
    project_id: str,
    location: str,
    engine_id: str,
    session_id: str,
) -> None:
    """Deletes a session.

    Args:
        project_id: The ID of your Google Cloud project.
        location: The location of the app.
        engine_id: The ID of the app.
        session_id: The ID of the session.
    """

    client = discoveryengine.ConversationalSearchServiceClient()

    # The full resource name of the session
    name = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/sessions/{session_id}"

    client.delete_session(name=name)

    print(f"Session {name} deleted.")

更新工作階段

您可能會因為以下原因而希望更新工作階段:例如,執行下列任一操作:

  • 將工作階段標示為已完成
  • 將一個工作階段的訊息合併到另一個工作階段
  • 變更使用者的虛擬 ID

以下指令顯示如何呼叫 patch 方法,並在資料儲存庫中更新工作階段。

REST

如要透過應用程式更新工作階段,請按照下列步驟操作:

  1. 執行下列 curl 指令:

    curl -X PATCH \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions/SESSION_ID?updateMask=state" \
      -d '{
            "state": "NEW_STATE"
          }'
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:Vertex AI Search 應用程式 ID。
    • SESSION_ID:您要更新的會話 ID。
    • NEW_STATE:狀態的新值,例如 IN_PROGRESS

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

from google.cloud import discoveryengine_v1 as discoveryengine
from google.protobuf import field_mask_pb2


def update_session(
    project_id: str,
    location: str,
    engine_id: str,
    session_id: str,
) -> discoveryengine.Session:
    """Updates a session.

    Args:
        project_id: The ID of your Google Cloud project.
        location: The location of the app.
        engine_id: The ID of the app.
        session_id: The ID of the session.
    Returns:
        discoveryengine.Session: The updated Session.
    """
    client = discoveryengine.ConversationalSearchServiceClient()

    # The full resource name of the session
    name = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/sessions/{session_id}"

    session = discoveryengine.Session(
        name=name,
        state=discoveryengine.Session.State.IN_PROGRESS,  # Options: IN_PROGRESS, STATE_UNSPECIFIED
    )

    # Fields to Update
    update_mask = field_mask_pb2.FieldMask(paths=["state"])

    session = client.update_session(session=session, update_mask=update_mask)
    print(f"Updated session: {session.name}")
    return session

列出所有工作階段

以下指令示範如何呼叫 list 方法,並在資料儲存庫中列出工作階段。

REST

如要列出應用程式的工作階段,請按照下列步驟操作:

  1. 執行下列 curl 指令:

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions"
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:Vertex AI Search 應用程式 ID。

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

from google.cloud import discoveryengine_v1 as discoveryengine


def list_sessions(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.ListSessionsResponse:
    """Lists all sessions associated with a data store.

    Args:
        project_id: The ID of your Google Cloud project.
        location: The location of the app.
        engine_id: The ID of the app.
    Returns:
        discoveryengine.ListSessionsResponse: The list of sessions.
    """

    client = discoveryengine.ConversationalSearchServiceClient()

    # The full resource name of the engine
    parent = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}"

    response = client.list_sessions(
        request=discoveryengine.ListSessionsRequest(
            parent=parent,
            filter='state="IN_PROGRESS"',  # Optional: Filter requests by userPseudoId or state
            order_by="update_time",  # Optional: Sort results
        )
    )

    print("Sessions:")
    for session in response.sessions:
        print(session)

    return response

列出使用者的工作階段

以下指令說明如何呼叫 list 方法,列出與使用者或訪客相關聯的工作階段。

REST

如要列出與使用者或訪客相關聯的工作階段,請按照下列步驟操作:

  1. 執行下列 curl 指令:

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions?filter=userPseudoId=USER_PSEUDO_ID"
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:Vertex AI Search 應用程式 ID。
    • USER_PSEUDO_ID:您要列出工作階段的使用者別名 ID。

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

from google.cloud import discoveryengine_v1 as discoveryengine


def list_sessions(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.ListSessionsResponse:
    """Lists all sessions associated with a data store.

    Args:
        project_id: The ID of your Google Cloud project.
        location: The location of the app.
        engine_id: The ID of the app.
    Returns:
        discoveryengine.ListSessionsResponse: The list of sessions.
    """

    client = discoveryengine.ConversationalSearchServiceClient()

    # The full resource name of the engine
    parent = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}"

    response = client.list_sessions(
        request=discoveryengine.ListSessionsRequest(
            parent=parent,
            filter='state="IN_PROGRESS"',  # Optional: Filter requests by userPseudoId or state
            order_by="update_time",  # Optional: Sort results
        )
    )

    print("Sessions:")
    for session in response.sessions:
        print(session)

    return response

列出使用者和狀態的工作階段

以下指令說明如何呼叫 list 方法,為特定使用者列出特定狀態的工作階段。

REST

如要列出使用者已開啟或已關閉,且與特定使用者或訪客相關聯的工作階段,請按照下列步驟操作:

  1. 執行下列 curl 指令:

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions?filter=userPseudoId=USER_PSEUDO_ID%20AND%20state=STATE"
    

    更改下列內容:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • APP_ID:Vertex AI Search 應用程式的 ID。
    • USER_PSEUDO_ID:您要列出工作階段的使用者別名 ID。
    • STATE:工作階段狀態:STATE_UNSPECIFIED (已關閉或不明) 或 IN_PROGRESS (已開啟)。

Python

詳情請參閱 AI Applications Python API 參考說明文件

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

from google.cloud import discoveryengine_v1 as discoveryengine


def list_sessions(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.ListSessionsResponse:
    """Lists all sessions associated with a data store.

    Args:
        project_id: The ID of your Google Cloud project.
        location: The location of the app.
        engine_id: The ID of the app.
    Returns:
        discoveryengine.ListSessionsResponse: The list of sessions.
    """

    client = discoveryengine.ConversationalSearchServiceClient()

    # The full resource name of the engine
    parent = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}"

    response = client.list_sessions(
        request=discoveryengine.ListSessionsRequest(
            parent=parent,
            filter='state="IN_PROGRESS"',  # Optional: Filter requests by userPseudoId or state
            order_by="update_time",  # Optional: Sort results
        )
    )

    print("Sessions:")
    for session in response.sessions:
        print(session)

    return response