回答とフォローアップを取得する

このページでは、Vertex AI Search の回答とフォローアップによる検索について説明します。また、メソッド呼び出しを使用して汎用検索アプリに実装する方法についても説明します。

回答とフォローアップによる検索は、answer メソッドに基づいています。answer メソッドは、古い search メソッドの要約機能と、非推奨の converse メソッドのすべての機能を置き換えます。 answer メソッドには、複雑なクエリを処理する機能など、重要な追加機能もあります。

answer メソッドの特徴

answer メソッドの主な機能は次のとおりです。

  • 複雑なクエリに対する回答を生成できる能力。たとえば、answer メソッドでは、次のような複合クエリを複数の小さなクエリに分割して、より良い結果を返すことができます。これにより、より良い回答が得られます。

    • 「2024 年の Google Cloud と Google 広告の収益はそれぞれいくらですか?」
    • 「Google は創業から何年後に収益 10 億米ドルに達しましたか?」
  • 各ターンで answer メソッドを呼び出して、マルチターンの会話で検索と回答の生成を組み合わせる機能。

  • search メソッドと組み合わせて検索レイテンシを短縮する機能。search メソッドと answer メソッドを別々に呼び出し、検索結果と回答を異なる iframe に異なるタイミングでレンダリングできます。つまり、検索結果(10 個の青いリンク)を数ミリ秒以内にユーザーに表示できます。回答が生成されるのを待たずに、検索結果を表示できます。

回答とフォローアップの機能は、クエリ、検索、回答の 3 つのフェーズに分けられます。

回答と検索を使用するタイミング

Vertex AI Search には、アプリのクエリに使用される 2 つのメソッドがあります。機能は異なりますが、重複する部分もあります。

answer メソッドは、次の場合に使用します。

  • 検索結果の AI 生成の回答(またはサマリー)が必要な場合。

  • マルチターン検索(コンテキストを保持してフォローアップの質問を可能にする検索)が必要な場合。

search メソッドは、次の場合に使用します。

  • 生成された回答ではなく、検索結果のみが必要。

  • 検索結果(「青色リンク」)を 10 件より多く表示したい。

  • 次のいずれかがある。

    • メディアまたは医療データ
    • 独自のエンベディング
    • 類義語またはリダイレクト コントロール
    • ファセット
    • ユーザーの国コード

次の場合は、answer メソッドと search メソッドを併用します。

  • 10 件を超える検索結果を返す必要があり、かつ、生成された回答が必要な場合。

  • レイテンシの問題があり、生成された回答が返される前に検索結果をすばやく返して表示したい場合。

クエリフェーズの機能

回答とフォローアップ機能は、自然言語クエリ処理をサポートしています。

このセクションでは、クエリの言い換えと分類のさまざまなオプションについて説明します。

クエリの言い換え

クエリの言い換えはデフォルトでオンになっています。この機能は、検索結果を改善するために、クエリを自動的に言い換える最善の方法を選択します。この機能は、言い換えを必要としないクエリも処理できます。

  • 複雑なクエリを複数のクエリに分割し、同期サブクエリを実行します。

    たとえば、複雑なクエリを 4 つの小さく単純なクエリに分割します。

    ユーザー入力 複雑なクエリから作成されたサブクエリ
    Andie Ram と Arnaud Clément は、どのような仕事と趣味が共通していますか?
    • Andie Ram の職業
    • Arnaud Clément の職業
    • Andie Ram の趣味
    • Arnaud Clément の趣味
  • マルチターンのクエリを合成して、フォローアップの質問をコンテキスト認識型でステートフルにします。

    例: 各ターンのユーザー入力から合成されたクエリは次のようになります。

    ユーザー入力 合成されたクエリ
    ターン 1: 学校用ノートパソコン 学校用ノートパソコン
    ターン 2: Mac 以外 Mac 以外の学校用ノートパソコン
    ターン 3: 大画面かつワイヤレス キーボードとマウスも必要 ワイアレス キーボードとマウス付きの、Mac 以外の大画面の学校用ノートパソコン
    ターン 4: それにパソコン用のバックパック ワイアレス キーボードとマウスとバックパック付きの、Mac 以外の大画面の学校用ノートパソコン
  • 長いクエリを簡素化して、取得を改善します。

    たとえば、長いクエリが単純なクエリに短縮されます。

    ユーザー入力 簡素化されたクエリ
    ウェブサイトの [カートに追加] ボタンが正しく機能しない理由を調べています。ユーザーがボタンをクリックしても、商品がカートに追加されず、エラー メッセージが表示されるようです。コードを確認しましたが、正しいようです。問題が何なのかわかりません。この問題のトラブルシューティングをお手伝いいただけますか? ウェブサイトで [カートに追加] ボタンが機能しません。
  • 複数ステップの推論を行う

    マルチステップ推論は ReACT(理由 + 行動)パラダイムに基づいており、LLM が自然言語推論を使用して複雑なタスクを解決できるようにします。 デフォルトでは、ステップ数の上限は 5 です。

    例:

    ユーザー入力 回答を生成するための 2 つのステップ
    Google は創業から何年後に収益 10 億ドルに達しましたか。 ステップ 1:
    [思考]: Google の創立日を知る必要があります。そうすれば、それ以降の収益をクエリできます。
    [行動] 検索: Google はいつ設立されましたか?[検索結果の確認]:「1998 年」

    ステップ 2:
    [思考]: 次は、1998 年以降の Google の年間収益を調べて、初めて 10 億ドルを超えたのはいつかを確認する必要があります。
    [行動] 検索: 1998 年以降の Google の収益
    [検索結果の確認] 1998 年の Google の収益、1999 年の Google の収益
    [回答]: Google は、2003 年に 10 億米ドル以上の収益を達成しました [1]、1998 年の創業から 5 年後です [2]。

クエリの分類

クエリ分類オプションは、敵対的なクエリと回答を求めていないクエリを特定します。デフォルトでは、クエリ分類オプションは無効になっています。

敵対的クエリと回答を求めていないクエリの詳細については、敵対的クエリを無視するサマリーを求めていないクエリを無視するをご覧ください。

検索フェーズの機能

検索の場合、answer メソッドには search メソッドと同じオプションがあります。次に例を示します。

回答フェーズの機能

回答フェーズでは、検索結果から回答が生成されたときに、search メソッドと同じ機能を有効にできます。例:

始める前に

アプリの種類に応じて、次の要件を完了します。

  • 構造化または非構造化の検索アプリを使用している場合は、[高度な LLM 機能] がオンになっていることを確認します。

  • ウェブサイト検索アプリを使用している場合は、次の機能がオンになっていることを確認します。

  • 統合検索アプリ(複数のデータストアに接続されているアプリ)をお持ちの場合は、Google アカウント チームに連絡し、統合検索を使用した Answer API の許可リストに追加するよう依頼してください。

検索と回答(基本)

次のコマンドは、answer メソッドを呼び出して、生成された回答と、ソースへのリンクを含む検索結果のリストを返す方法を示しています。

このコマンドは、必要な入力のみを表示します。オプションはデフォルトのままにします。

RESTPython

生成された回答を含む結果を検索して取得する手順は次のとおりです。

  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 データベースを比較するには?」などです。
    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": "Which database is faster, bigquery or spanner?"}}'
            
    { "answer": { "state": "SUCCEEDED", "answerText": "The provided sources do not directly compare the speed of BigQuery and Spanner. However, they do highlight the performance capabilities of each database. BigQuery is described as having strong query performance, particularly for short and complex queries. It also offers a serverless architecture that provides consistent performance regardless of query complexity. Spanner is described as having high performance at virtually unlimited scale, with single-digit millisecond latency for strongly-consistent reads and writes. It also offers a five-nines availability SLA. Ultimately, the best database for a particular use case will depend on the specific requirements of the application. \n", "steps": [ { "state": "SUCCEEDED", "description": "Rephrase the query and search.", "actions": [ { "searchAction": { "query": " What is the performance of BigQuery?" }, "observation": { "searchResults": [ { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/9ab3ef91bcfde1fcd091efe9df7c699c", "uri": "https://cloud.google.com/bigquery/docs/best-practices-performance-overview", "title": "Introduction to optimizing query performance | BigQuery | Google Cloud", "snippetInfo": [ { "snippet": "After a query begins execution, \u003cb\u003eBigQuery\u003c/b\u003e calculates how many slots each query stage uses based on the stage size and complexity and the number of slots ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/4e545c5cb69b06b251265114d9099cb4", "uri": "https://cloud.google.com/bigquery/docs/query-insights", "title": "Get query performance insights | BigQuery | Google Cloud", "snippetInfo": [ { "snippet": "This document describes how to use the query execution graph to diagnose query \u003cb\u003eperformance\u003c/b\u003e issues, and to see query \u003cb\u003eperformance\u003c/b\u003e insights. \u003cb\u003eBigQuery\u003c/b\u003e offers ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/d34672d877eefe596f9c7d1a3d7076b1", "uri": "https://cloud.google.com/bigquery/docs/best-practices-performance-compute", "title": "Optimize query computation | BigQuery | Google Cloud", "snippetInfo": [ { "snippet": "After addressing the query \u003cb\u003eperformance\u003c/b\u003e insights, you can further optimize your query by performing the following tasks: Reduce data that is to be processed ...", "snippetStatus": "SUCCESS" } ] }, ... { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/75ce2f05833683e60ddc21a11ce0466f", "uri": "https://cloud.google.com/blog/products/data-analytics/troubleshoot-and-optimize-your-bigquery-analytics-queries-with-query-execution-graph/", "title": "Troubleshoot and optimize your BigQuery analytics queries with query execution graph | Google Cloud Blog", "snippetInfo": [ { "snippet": "Since query \u003cb\u003eperformance\u003c/b\u003e is multi-faceted, \u003cb\u003eperformance\u003c/b\u003e insights might only provide a partial picture of the overall query \u003cb\u003eperformance\u003c/b\u003e. Execution graph. When ...", "snippetStatus": "SUCCESS" } ] } ] } }, { "searchAction": { "query": " What is the performance of Spanner?" }, "observation": { "searchResults": [ { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/f3d036b60379873acf7c73081c5e5b5c", "uri": "https://cloud.google.com/spanner/docs/performance", "title": "Performance overview | Spanner | Google Cloud", "snippetInfo": [ { "snippet": "These \u003cb\u003eperformance\u003c/b\u003e improvements should result in higher throughput and better latency in \u003cb\u003eSpanner\u003c/b\u003e nodes in both regional and multi-region instance configurations.", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/422496248ade354c73b4c906b8eb9b5f", "uri": "https://cloud.google.com/blog/products/databases/announcing-cloud-spanner-price-performance-updates", "title": "Announcing Cloud Spanner price-performance updates | Google Cloud Blog", "snippetInfo": [ { "snippet": "Alongside lower costs, Cloud \u003cb\u003eSpanner\u003c/b\u003e provides single-digit ms latencies and strong consistency across multiple availability zones in the same region.", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/53c2a1a6990480ba4aa05cc6b4404562", "uri": "https://cloud.google.com/blog/topics/developers-practitioners/understanding-cloud-spanner-performance-metrics-scale-key-visualizer", "title": "Understanding Cloud Spanner performance metrics at scale with Key Visualizer | Google Cloud Blog", "snippetInfo": [ { "snippet": "Designed for \u003cb\u003eperformance\u003c/b\u003e tuning and instance sizing, you can use Key Visualizer today in the web-based Cloud Console for all \u003cb\u003eSpanner\u003c/b\u003e databases at no additional ...", "snippetStatus": "SUCCESS" } ] }, ... { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/a6501ecd5d6391e3ade49097bab0ad3a", "uri": "https://cloud.google.com/blog/products/databases/a-technical-overview-of-cloud-spanners-query-optimizer", "title": "A technical overview of Cloud Spanner's query optimizer | Google Cloud Blog", "snippetInfo": [ { "snippet": "... performance. Typically, a join will ... Google is continuously improving out-of-the-box \u003cb\u003eperformance of Spanner\u003c/b\u003e and reducing the need for manual tuning.", "snippetStatus": "SUCCESS" } ] } ] } } ] } ] }, "answerQueryToken": "NMwKDAj1_d62BhC72_X_AhIkNjZkN2I4YWEtMDAwMC0yYTdiLWIxMmMtMDg5ZTA4MjhlNzY0" }

    この例では、クエリは「Spanner のパフォーマンスは?」と「BigQuery のパフォーマンスは?」という部分に分解されています。

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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
    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
    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-1.5-flash-001/answer_gen/v2",  # 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 メソッドを呼び出して、生成された回答と検索結果のリストを返す方法を示しています。言い換えオプションが無効になっているため、回答が前の回答と異なる場合があります。

RESTPython

クエリの言い換えを適用せずに検索して生成された回答を含む結果を取得する手順は次のとおりです。

  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 データベースを比較するには?」などです。
    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": "Which database is faster, bigquery or spanner?"},
          "queryUnderstandingSpec": { "queryRephraserSpec": { "disable": true } }
        }'
        
    { "answer": { "state": "SUCCEEDED", "answerText": "The sources provided do not directly compare the speed of BigQuery and Spanner. They do mention that Spanner is optimized for transactional workloads and BigQuery is optimized for analytical workloads. Spanner is a fully managed relational database that provides seamless replication across regions in Google Cloud. BigQuery is a serverless, highly scalable, and cost-effective multi-cloud data warehouse. Spanner is designed to scale horizontally across multiple regions and continents. BigQuery is designed for business agility. \n", "steps": [ { "state": "SUCCEEDED", "description": "Rephrase the query and search.", "actions": [ { "searchAction": { "query": "Which database is faster, bigquery or spanner?" }, "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": "A federated \u003cb\u003equery\u003c/b\u003e might not be as \u003cb\u003efast\u003c/b\u003e as querying local \u003cb\u003eBigQuery tables\u003c/b\u003e. There may be higher latency because of the small wait time for the source \u003cb\u003edatabase\u003c/b\u003e to ...", "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": "... \u003cb\u003equick\u003c/b\u003e lookup on \u003cb\u003edata\u003c/b\u003e that's in \u003cb\u003eSpanner\u003c/b\u003e -- you can ... Set up an external \u003cb\u003edata\u003c/b\u003e source for the \u003cb\u003eSpanner\u003c/b\u003e shopping \u003cb\u003edatabase\u003c/b\u003e in \u003cb\u003eBigQuery\u003c/b\u003e. ... The \u003cb\u003equery\u003c/b\u003e is executed in ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/f3d036b60379873acf7c73081c5e5b5c", "uri": "https://cloud.google.com/spanner/docs/performance", "title": "Performance overview | Spanner | Google Cloud", "snippetInfo": [ { "snippet": "The information on this page applies to both GoogleSQL and PostgreSQL \u003cb\u003edatabases\u003c/b\u003e. Note: We are in the process of rolling out \u003cb\u003eperformance\u003c/b\u003e and storage changes that ...", "snippetStatus": "SUCCESS" } ] }, ... { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/47b09cb5ad5e3ab3b1eb93d99ecb0896", "uri": "https://cloud.google.com/blog/products/databases/rewe-uses-cloud-spanner-to-optimize-for-speed-and-performance", "title": "REWE uses Cloud Spanner to optimize for speed and performance | Google Cloud Blog", "snippetInfo": [ { "snippet": "As a fully managed relational \u003cb\u003edatabase\u003c/b\u003e, \u003cb\u003eSpanner\u003c/b\u003e provides unlimited scale, strong consistency, and up to 99.999% availability. By choosing this approach to ...", "snippetStatus": "SUCCESS" } ] } ] } } ] } ] }, "answerQueryToken": "M8gKCwjp_t62BhC7wOFMEiQ2NmQ3YjhhZS0wMDAwLTJhN2ItYjEyYy0wODllMDgyOGU3NjQ" }

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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
    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
    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-1.5-flash-001/answer_gen/v2",  # 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 メソッドを呼び出して、生成された回答と検索結果のリストを返す方法を示しています。言い換えステップの数が増えているため、回答が前の回答とは異なっています。

RESTPython

最大 5 回の言い換えステップを許可する生成された回答を含む結果を検索して取得する手順は次のとおりです。

  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 になります。
    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": "How much longer does it take to train a recommendations model than a search model"},
            "queryUnderstandingSpec": {
                "queryRephraserSpec": {
                "maxRephraseSteps": 5
                 }
             }
          }'
          

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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
    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
    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-1.5-flash-001/answer_gen/v2",  # 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 メソッドを呼び出して、クエリが敵対的、回答を求めていない、またはどちらでもないかを問い合わせる方法を示しています。

レスポンスにはクエリの分類タイプが含まれますが、回答自体は分類の影響を受けません。 クエリタイプに応じて回答動作を変更する場合は、回答フェーズで変更できます。敵対的クエリを無視するサマリーを求めていないクエリを無視するをご覧ください。

RESTPython

クエリが敵対的なものか、回答を求めていないものかを判断するには、次の操作を行います。

  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、またはその両方)。
    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": "Hello!"},
              "queryUnderstandingSpec": {
                 "queryClassificationSpec": {
                 "types": ["ADVERSARIAL_QUERY", "NON_ANSWER_SEEKING_QUERY"]
                  }
              }
    }'
    
    { "answer": { "state": "SUCCEEDED", "answerText": "A user reported that their Google Voice account was randomly sending \"Hello!\" replies to incoming texts. The user was frustrated because they did not want to send these replies and found the behavior random. The user was unable to find any linked accounts, Google extensions, or other settings that could be causing the issue. The user confirmed that Google Voice does not have auto-reply functions. The user was seeking help to stop the automatic replies. \n", "steps": [ { "state": "SUCCEEDED", "description": "Rephrase the query and search.", "actions": [ { "searchAction": { "query": "Hello!" }, "observation": { "searchResults": [ { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/69e92e5b1de5b1e583fbe95f94dd4cbf", "uri": "https://support.google.com/voice/thread/152245405/google-voice-is-randomly-automatically-sending-hello-replies-to-incoming-texts?hl=en", "title": "Google voice is randomly/automatically sending \"Hello!\" replies to incoming texts", "snippetInfo": [ { "snippet": "There IS a new "Smart reply" feature on the Android or iOS client apps, but you'd have to a) receive a SMS/MMS, b) open it up, c) look at the three suggested ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/44fb313bcc09877e7239f3810ddb132b", "uri": "https://support.google.com/mail/thread/58174131/gmail-sends-random-email-saying-hello-to-my-emails-without-me-touching-it?hl=en", "title": "Gmail sends random email saying \"Hello!!\" to my emails without me touching it", "snippetInfo": [ { "snippet": "Gmail sends random email saying "\u003cb\u003eHello\u003c/b\u003e!!" to my emails without me touching it. Whenever I email somebody and they reply, a random email from my Gmail is sent to ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/16d65e2af7fa854d1a00995525646dc3", "uri": "https://support.google.com/voice/thread/112990484/google-voice-sending-hello-in-response-to-text-messages?hl=en", "title": "Google Voice sending \"Hello,\" in response to text messages", "snippetInfo": [ { "snippet": "When I receive text messages, a reply is instantly sent out reading "\u003cb\u003eHello\u003c/b\u003e," and I cannot figure out how this is happening. I have no linked accounts, ...", "snippetStatus": "SUCCESS" } ] }, ... { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/a828eb8f442f1dfbdda06dbeb52841b0", "uri": "https://support.google.com/a/thread/161821861/hello-hello-the-lost-phone?hl=en", "title": "Hello.Hello the lost phone - Google Workspace Admin Community", "snippetInfo": [ { "snippet": "\u003cb\u003eHello\u003c/b\u003e the lost phone. My wife lost her phone but she cannot remember her emails pasward to help track .", "snippetStatus": "SUCCESS" } ] } ] } } ] } ], "queryUnderstandingInfo": { "queryClassificationInfo": [ { "type": "ADVERSARIAL_QUERY" }, { "type": "NON_ANSWER_SEEKING_QUERY", "positive": true } ] } }, "answerQueryToken": "NMwKDAjVloK3BhCdt8u9AhIkNjZkYmFhNWItMDAwMC0yZTBkLTg0ZDAtMDg5ZTA4MmRjYjg0" }

    この例では、クエリ「hello」は敵対的ではありませんが、回答を求めていないものとして分類されます。

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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
    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
    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-1.5-flash-001/answer_gen/v2",  # 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 メソッドを呼び出して、検索結果を返す方法に関するさまざまなオプションを指定する方法を示しています。(検索結果は回答とは関係ありません)。

RESTPython

検索結果が返される内容と方法に関連するさまざまなオプションを設定するには、次の操作を行います。

  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 です。
    • FILTER: クエリ対象のドキュメントを指定します。ドキュメントのメタデータがフィルタ仕様に合致すると、そのドキュメントに対してクエリが実行されます。フィルタ構文など、詳細については、構造化データまたは非構造化データの一般的な検索をフィルタするをご覧ください。
    • BOOST_SPEC: ブースト仕様を使用すると、検索結果で特定のドキュメントをブーストできます。これにより、回答に影響する可能性があります。 ブースト仕様の構文など、詳細については、検索結果をブーストするをご覧ください。
    • ORDER_BY: ドキュメントが返される順序。ドキュメントは、Document オブジェクトのフィールドで並べ替えることができます。orderBy 式では大文字と小文字が区別されます。 このフィールドが認識できない場合、INVALID_ARGUMENT が返されます。
    • SEARCH_RESULT_MODE: 検索結果モード(DOCUMENTS または CHUNKS)を指定します。詳細については、ドキュメントを解析してチャンクするContentSearchSpec をご覧ください。このフィールドは、API の v1alpha バージョンでのみ使用できます。
    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": "Does spanner database have an API?"},
              "searchSpec": {
              "searchParams": { "maxReturnResults": 3 }
              }
        }'
        
    { "answer": { "state": "SUCCEEDED", "answerText": "Spanner database has an API that provides programmatic access to the database. The API is available through client libraries, RPC, and REST. The client libraries allow you to interact with Spanner in your preferred language. The RPC API and REST API provide programmatic access to Spanner. The Cloud Spanner API is a managed, mission-critical, globally consistent and scalable relational database service. \n", "steps": [ { "state": "SUCCEEDED", "description": "Rephrase the query and search.", "actions": [ { "searchAction": { "query": "Does spanner database have an API?" }, "observation": { "searchResults": [ { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/d135b46c4a44d0cc6b652538c1887f4d", "uri": "https://cloud.google.com/spanner/docs/apis", "title": "APIs & reference | Spanner | Google Cloud", "snippetInfo": [ { "snippet": "The client libraries, the RPC \u003cb\u003eAPI\u003c/b\u003e, and the REST \u003cb\u003eAPI\u003c/b\u003e provide programmatic access to \u003cb\u003eSpanner\u003c/b\u003e. \u003cb\u003eSpanner\u003c/b\u003e client libraries. \u003cb\u003eGet\u003c/b\u003e started with \u003cb\u003eSpanner\u003c/b\u003e in your language ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/7a744d43e61ccd33539de74d5c1f6313", "uri": "https://cloud.google.com/spanner/docs/reference/rest", "title": "Cloud Spanner API", "snippetInfo": [ { "snippet": "Returns permissions that the caller \u003cb\u003ehas\u003c/b\u003e on the specified \u003cb\u003edatabase\u003c/b\u003e or backup resource. updateDdl, PATCH /v1/{\u003cb\u003edatabase\u003c/b\u003e=projects/*/instances/*/\u003cb\u003edatabases\u003c/b\u003e/*}/ddl", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/70834ebf4b72b6dc69e06c44ee80f90b", "uri": "https://cloud.google.com/spanner/docs/reference/rpc", "title": "Cloud Spanner API", "snippetInfo": [ { "snippet": "ChangeQuorum \u003cb\u003eis\u003c/b\u003e strictly restricted to \u003cb\u003edatabases\u003c/b\u003e ... Returns the schema of a Cloud \u003cb\u003eSpanner database\u003c/b\u003e ... Returns permissions that the caller \u003cb\u003ehas\u003c/b\u003e on the specified ...", "snippetStatus": "SUCCESS" } ] } ] } } ] } ] }, "answerQueryToken": "NMwKDAj2l4K3BhCqiv66ARIkNjZkYmFhNmMtMDAwMC0yZTBkLTg0ZDAtMDg5ZTA4MmRjYjg0" }

    この例では、返されるドキュメントの数は 3 に制限されています。

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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
    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
    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-1.5-flash-001/answer_gen/v2",  # 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 メソッドを呼び出すときに、敵対的クエリや回答を求めていないクエリに回答しないようにする方法を示しています。

RESTPython

敵対的または回答を求めていないクエリへの回答をスキップするには、次の操作を行います。

  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: 質問または検索クエリを含む自由形式の文字列。
    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": "Hello"},
          "answerGenerationSpec": {
              "ignoreAdversarialQuery": true,
              "ignoreNonAnswerSeekingQuery": true }
            }'
            
    { "answer": { "state": "SUCCEEDED", "answerText": "A summary could not be generated for your search query. Here are some search results.", "steps": [ { "state": "SUCCEEDED", "description": "Rephrase the query and search.", "actions": [ { "searchAction": { "query": "Hello" }, "observation": { "searchResults": [ { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/69e92e5b1de5b1e583fbe95f94dd4cbf", "uri": "https://support.google.com/voice/thread/152245405/google-voice-is-randomly-automatically-sending-hello-replies-to-incoming-texts?hl=en", "title": "Google voice is randomly/automatically sending \"Hello!\" replies to incoming texts", "snippetInfo": [ { "snippet": "There IS a new "Smart reply" feature on the Android or iOS client apps, but you'd have to a) receive a SMS/MMS, b) open it up, c) look at the three suggested ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/16d65e2af7fa854d1a00995525646dc3", "uri": "https://support.google.com/voice/thread/112990484/google-voice-sending-hello-in-response-to-text-messages?hl=en", "title": "Google Voice sending \"Hello,\" in response to text messages", "snippetInfo": [ { "snippet": "When I receive text messages, a reply is instantly sent out reading "\u003cb\u003eHello\u003c/b\u003e," and I cannot figure out how this is happening. I have no linked accounts, ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/b3bdde4957f588a1458c533269626d09", "uri": "https://support.google.com/voice/thread/4307458/lately-an-automatic-text-response-saying-hello-is-going-out-how-do-i-stop-this?hl=en", "title": "Lately an automatic text response saying, \"Hello\" is going out. How do I stop this? - Google Voice Community", "snippetInfo": [ { "snippet": "You need to find out what app is causing it and deactivate or delete it. Last edited Apr 16, 2019.", "snippetStatus": "SUCCESS" } ] }, ... { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/a828eb8f442f1dfbdda06dbeb52841b0", "uri": "https://support.google.com/a/thread/161821861/hello-hello-the-lost-phone?hl=en", "title": "Hello.Hello the lost phone - Google Workspace Admin Community", "snippetInfo": [ { "snippet": "\u003cb\u003eHello\u003c/b\u003e the lost phone. My wife lost her phone but she cannot remember her emails pasward to help track .", "snippetStatus": "SUCCESS" } ] } ] } } ] } ], "answerSkippedReasons": [ "NON_ANSWER_SEEKING_QUERY_IGNORED" ] }, "answerQueryToken": "NMwKDAjFgN-2BhDlsKaZARIkNjZkN2I0NmItMDAwMC0yZmQ5LTkwMDktZjQwMzA0M2E5YTg4" }

    この例では、クエリが回答を求めていないと判断されるため、回答は生成されません。

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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
    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
    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-1.5-flash-001/answer_gen/v2",  # 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 メソッドを呼び出したときに、関連性のない結果の場合にフォールバック回答を返す方法を示しています。

RESTPython

関連する結果が見つからない場合にフォールバック回答を返すには、次の操作を行います。

  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: 質問または検索クエリを含む自由形式の文字列。
    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": "foobar"}, "answerGenerationSpec": {
           "ignoreLowRelevantContent": true
        } }'
        
    { "answer": { "state": "SUCCEEDED", "answerText": "We do not have a summary for your query.", "steps": [ { "state": "SUCCEEDED", "description": "Rephrase the query and search.", "actions": [ { "searchAction": { "query": "foobar" }, "observation": { "searchResults": [ { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/719b79786f0c143717c569eade5305d9", "uri": "https://support.google.com/websearch/thread/261714267/google-foobar-bug-console-disappeared?hl=en", "title": "Google Foobar Bug - Console Disappeared", "snippetInfo": [ { "snippet": "Google \u003cb\u003eFoobar\u003c/b\u003e Bug - Console Disappeared. After I logged in today the top bar says "The \u003cb\u003eFoobar\u003c/b\u003e Challenge will be turned down on 1 April 2024. If you run out of ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/932369826585ff45f6ab3eba01ba6933", "uri": "https://support.google.com/websearch/thread/95251114/unable-to-contact-foobar-recruiter?hl=en", "title": "Unable to contact Foobar Recruiter - Google Search Community", "snippetInfo": [ { "snippet": "Access is by invitation only so you will need to have the proper credentials to login. You can always reach out using the contact us button, but there is no ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/fb736a30ff90d058be755f0a04a522a8", "uri": "https://support.google.com/websearch/thread/121151780/foobar-challenge-appeared-to-me-then-disappeared?hl=en", "title": "Foobar challenge appeared to me then disappeared - Google Search Community", "snippetInfo": [ { "snippet": "Hi. I got the \u003cb\u003efoobar\u003c/b\u003e challenge some months ago. But then it disappeared immediately, maybe by misclick (though I don't think I misclicked).", "snippetStatus": "SUCCESS" } ] }, ... { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/f56f2656b0d02b839509d0e67e60c1c9", "uri": "https://support.google.com/chrome/thread/159931759/cannot-access-google-foobar-challenge?hl=en", "title": "Cannot Access Google FooBar Challenge", "snippetInfo": [ { "snippet": "I knew I wouldn't have time for it today, so I just kept the tab in the background. Tonight, I went to go close all my tabs, but the page had changed. It said " ...", "snippetStatus": "SUCCESS" } ] } ] } } ] } ], "answerSkippedReasons": [ "NO_RELEVANT_CONTENT" ] }, "answerQueryToken": "M8gKCwiokvy2BhDtv8EDEiQ2NmQ5NDQxZC0wMDAwLTIxMGQtOWU2Yi1mNDAzMDQ1ZGJkMzA" }

    この例では、結果がクエリに十分に関連していないと判断されたため、生成された回答と結果の代わりにフォールバック回答が返されました。

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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
    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
    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-1.5-flash-001/answer_gen/v2",  # 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

回答モデルを指定する

次のコマンドは、回答の生成に使用されるモデル バージョンを変更する方法を示しています。

サポートされているモデルについては、回答生成モデルのバージョンとライフサイクルをご覧ください。

RESTPython

デフォルト モデルとは異なるモデルを使用して回答を生成する手順は次のとおりです。

  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: 回答の生成に使用するモデル バージョン。詳細については、回答生成モデルのバージョンとライフサイクルをご覧ください。
    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?"},   "answerGenerationSpec": {
         "modelSpec": {
         "modelVersion": "preview",
         }
       } }'
       
    { "answer": { "state": "SUCCEEDED", "answerText": "Cloud Spanner is a fully managed relational database optimized for transactional workloads. BigQuery is a serverless, highly scalable, and cost-effective multi-cloud data warehouse designed for business agility. BigQuery is optimized for ad-hoc analysis and reporting. Both Spanner and BigQuery are built on Google's distributed storage system, Colossus, and their internal cluster management system, Borg. They are also built on Jupiter, Google's in-house custom network hardware and software.\n\nBigQuery can query data stored in Spanner in real time without moving or copying the data. This is possible with BigQuery's query federation support. To run a federated query, you need to configure an external data source in BigQuery that points to the intended Spanner instance. You can then write queries that can be used to populate a BigQuery table on demand or scheduled to run as needed. You can also join the query with another BigQuery result set dynamically.\n\nYou can also use Dataflow to copy data from Spanner to BigQuery. Dataflow is a service that can be used to ingest Spanner data into BigQuery. This is useful for more complex transformations or external dependencies. For example, an online gaming company might use Spanner to store game data and BigQuery to perform analytics on player behavior. They can replicate data from Spanner into BigQuery and perform analytics against local data, or they can use federated queries to retrieve data from Spanner on-demand.\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/648c220055c1d2ac369165007d9f6650", "uri": "https://cloud.google.com/blog/products/databases/choosing-cloud-spanner-for-game-development", "title": "Choosing Cloud Spanner for game development | Google Cloud Blog", "snippetInfo": [ { "snippet": "To get started with \u003cb\u003eSpanner\u003c/b\u003e, create a \u003cb\u003edatabase\u003c/b\u003e, or try it out with a \u003cb\u003eSpanner\u003c/b\u003e Qwiklab. ... AlloyDB \u003cb\u003evs\u003c/b\u003e. ... SQL for SQL Server to \u003cb\u003eBigQuery\u003c/b\u003e. By Alexander ...", "snippetStatus": "SUCCESS" } ] } ] } } ] } ] }, "answerQueryToken": "NMwKDAivmvy2BhCxnsqdARIkNjZkOTQ0NWEtMDAwMC0yMTBkLTllNmItZjQwMzA0NWRiZDMw" }

    この例では、デフォルト モデルではなく、モデルのプレビュー版を使用しています。

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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
    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
    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-1.5-flash-001/answer_gen/v2",  # 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 など)などのカスタマイズをリクエストできます。たとえば、プリアンブルは「10 歳の子どもに説明するように説明して」などです。

RESTPython

デフォルト モデルとは異なるモデルを使用して回答を生成する手順は次のとおりです。

  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 を試します。
    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": "what is bigquery?"},
              "answerGenerationSpec": {
                 "promptSpec": {
                    "preamble": "Explain like you are a ten years old
                    kid",
         }
      }
    }'
    
    { "answer": { "state": "SUCCEEDED", "answerText": "BigQuery is like a super-powered storage space for your data, but it's in the cloud, not on your computer. It's like a giant warehouse for all your information, but you don't have to build or manage it yourself. You can use BigQuery to find patterns and insights in your data, like figuring out what people like to buy or how many people visited your website. It's like having a super-smart assistant that can help you understand your data better. BigQuery is really good at working with lots of data, even billions of pieces of information. \n", "steps": [ { "state": "SUCCEEDED", "description": "Rephrase the query and search.", "actions": [ { "searchAction": { "query": "What is BigQuery?" }, "observation": { "searchResults": [ { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/2d032dc582689e8c0ecea7fc7bfa3189", "uri": "https://cloud.google.com/bigquery", "title": "BigQuery enterprise data warehouse | Google Cloud", "snippetInfo": [ { "snippet": "\u003cb\u003eBigQuery\u003c/b\u003e is a fully managed, AI-ready data analytics platform that helps you maximize value from your data and is designed to be multi-engine, multi-format, ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/4474f4a5a18ecd611dedfe323dfe55d9", "uri": "https://cloud.google.com/bigquery/docs/introduction", "title": "BigQuery overview | Google Cloud", "snippetInfo": [ { "snippet": "\u003cb\u003eBigQuery\u003c/b\u003e is a fully managed, AI-ready data platform that helps you manage and analyze your data with built-in features like machine learning, search, ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/c840fdef90d86328f13bbedbdbf0ac10", "uri": "https://cloud.google.com/bigquery/docs/query-overview", "title": "Overview of BigQuery analytics | Google Cloud", "snippetInfo": [ { "snippet": "\u003cb\u003eBigQuery\u003c/b\u003e lets you save queries and share queries with others. When you save a query, it can be private (visible only to you), shared at the project level ( ...", "snippetStatus": "SUCCESS" } ] }, ... { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/5cbfab8ce1d5f6ffe45fef22900c9a00", "uri": "https://cloud.google.com/curated-resources/bigquery", "title": "Guides BigQuery | Google Cloud", "snippetInfo": [ { "snippet": "\u003cb\u003eBigQuery\u003c/b\u003e is Google Cloud's fully managed and serverless enterprise data warehouse solution, designed to help you make informed decisions quickly, so you can ...", "snippetStatus": "SUCCESS" } ] } ] } } ] } ] }, "answerQueryToken": "NMwKDAi8hN-2BhC0jMCPARIkNjZkN2I4MzItMDAwMC0yMTliLTkxN2EtMDg5ZTA4MjA0YjFj" }

    この例では、プリアンブルはデフォルトよりもシンプルな回答をリクエストします。

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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
    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
    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-1.5-flash-001/answer_gen/v2",  # 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

引用を含める

次のコマンドは、回答に引用を含めるようにリクエストする方法を示しています。

RESTPython

デフォルト モデルとは異なるモデルを使用して回答を生成する手順は次のとおりです。

  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 です。
    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": "What is SQL"},   "answerGenerationSpec": {
        "includeCitations": true
    }
    }'
    
    { "answer": { "state": "SUCCEEDED", "answerText": "SQL stands for Structured Query Language and is a programming language used to manage, query, and retrieve data in a relational database. It is the standard language used by relational database management systems (RDBMS) such as PostgreSQL, SQL Server, MySQL, and Oracle Database. SQL statements are written in a statement format for queries and other database operations, allowing users to manipulate data in relational database tables. SQL is used to create and update the structure of tables, read and write data, manage user permissions, and perform administrative tasks. While originally created for relational databases, SQL is now a foundation for many technology capabilities, making SQL knowledge essential for many technology roles. \n", "citations": [ { "endIndex": "137", "sources": [ { "referenceId": "0" }, { "referenceId": "1" } ] }, { "startIndex": "138", "endIndex": "437", "sources": [ { "referenceId": "3" } ] }, { "startIndex": "438", "endIndex": "575", "sources": [ { "referenceId": "2" } ] }, { "startIndex": "576", "endIndex": "742", "sources": [ { "referenceId": "3" } ] } ], "references": [ { "chunkInfo": { "content": "There may be a second table that stores visit information. A relational database uses a unique ID for each row to maintain the linked patient information across the two tables. This way, you can quickly look up the visits of each patient. Sign up for a free trial for any of Google Cloud's SQL databases, which include AlloyDB, Cloud SQL, and Spanner. Get started for free What is SQL? SQL (Structured Query Language) is a programming language used to store, retrieve, and manage data in a relational database. SQL statements are English-like, making the language accessible to software developers, data analysts, and other practitioners. Benefits of SQL databases Enterprises choose SQL databases for being: Efficient. Relational databases are incredibly efficient in managing complex queries. Fast. SQL databases can retrieve large amounts of data, quickly. This makes them highly desirable for real-time transactional data. Reliable. SQL databases provide a high degree of data integrity and are ACID-compliant. SQL database engines There are numerous SQL database engines (products) used to build software applications. Some of the most popular include PostgreSQL, MySQL, SQL Server, and Oracle. Some database engines are open source while others are commercial offerings. ", "relevanceScore": 0.9, "documentMetadata": { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/7218ff4f57328d86059246d4af3a9953", "uri": "https://cloud.google.com/discover/what-are-sql-databases", "title": "SQL Databases | Google Cloud" } } }, { "chunkInfo": { "content": "PostgreSQL vs. SQL Server: What's the difference? | Google Cloud Page Contents Topics PostgreSQL vs. SQL PostgreSQL vs SQL Server: What are the key differences? Trying to find the right database for your applications? When it comes to choosing a database technology, the most common SQL options to consider are PostgreSQL vs. SQL Server. While both systems share many core features, there are some key differences—the major one being that PostgreSQL is open source and SQL Server is owned by Microsoft. Today, it is more vital than ever for companies to be able to manage, store, and activate data for modern business operations. With the growing assortment of databases available to choose from, it can be overwhelming to pick the right one for your applications. The most important thing to remember is that no single database will be a good match for every project requirement, so it's critical to understand the option that will work best for your specific use case. So, what is PostgreSQL vs. SQL Server? In this short guide, we'll discuss the basic differences between PostgreSQL and SQL Server. Get started for freeStay informed What is SQL? Structured Query Language or SQL, as it's more commonly known, is a programming language used to manage, query, and retrieve data in a relational database. ", "relevanceScore": 0.8, "documentMetadata": { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/f7cd9afab1282a9f57cdcee1885bb4c6", "uri": "https://cloud.google.com/learn/postgresql-vs-sql", "title": "PostgreSQL vs. SQL Server: What's the difference? | Google Cloud" } } }, { "chunkInfo": { "content": "SQL Databases | Google Cloud Page Contents Topics What are SQL databases? What are SQL databases? A SQL database, also known as a relational database, is a system that stores and organizes data into highly structured tables of rows and columns. These databases offer Structured Query Language (SQL) to read and write the data, and are categorized as relational database management systems (RDBMS). SQL statements are used to create and update the structure of tables, read and write data, manage user permissions, and perform administrative tasks. For example, a CREATE statement is used to create a table, an INSERT statement adds a new row to a table, and a SELECT statement performs a database query. Statements that make structural or administrative changes are usually reserved for software developers and administrators, while read and write operations are performed by end-user applications. A relational database maintains the ability to link information across multiple tables. This format makes it easy to quickly gain insights about the relationships between various columns or data points in these tables. A relational database can create indexes for particular columns for faster lookups. For example, a healthcare facility might maintain a table containing rows of patient information, where each row is one patient and the columns contain data points, such as the patient's name, insurance information, and contact details. ", "relevanceScore": 0.8, "documentMetadata": { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/7218ff4f57328d86059246d4af3a9953", "uri": "https://cloud.google.com/discover/what-are-sql-databases", "title": "SQL Databases | Google Cloud" } } }, { "chunkInfo": { "content": "It is the standard language used by relational database management systems (RDBMS), including PostgreSQL, SQL Server, MySQL, and Oracle Database. SQL typically uses commands written in statement format for queries and other database operations, which allow users to manipulate data in relational database tables. While originally created for relational databases, SQL acts as a foundation for many of today's technology capabilities, making SQL knowledge an essential skill for many technology roles today, including data analysts, database engineers, and even backend programming. However, you will find that there are different variants of SQL depending on the database or database management system that you choose. What is Microsoft SQL Server? SQL Server is a leading RDBMS that is built on top of SQL and developed by Microsoft. It is used to manage and store data to support numerous enterprise use cases for business intelligence, transaction processing, data analytics, and machine learning services. SQL Server has a row-based table structure that allows you to connect related data elements from different tables without having to store data multiple times in a database. In general, Microsoft SQL Server is known for its high availability, fast performance when handling large workloads, and easy integration with other applications to gain business intelligence across your entire data estate. For more information, we recommend reviewing the official SQL Server documentation. ", "relevanceScore": 0.8, "documentMetadata": { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/f7cd9afab1282a9f57cdcee1885bb4c6", "uri": "https://cloud.google.com/learn/postgresql-vs-sql", "title": "PostgreSQL vs. SQL Server: What's the difference? | Google Cloud" } } }, { "chunkInfo": { "content": "Send feedback The GoogleSQL language in Spanner bookmark_borderbookmark Stay organized with collections Save and categorize content based on your preferences. Dismiss Got it GoogleSQL is the new name for Google Standard SQL! New name, same great SQL dialect. This page provides an overview of supported statements in GoogleSQL. GoogleSQL is an ANSI compliant Structured Query Language (SQL) which includes the following types of supported statements: Query statements, also known as Data Query Language (DQL) statements, are the primary method to analyze data in Spanner. They scan one or more tables or expressions and return the computed result rows. Data Definition Language (DDL) statements let you create and modify database objects such as tables, views, and database roles. Data Manipulation Language (DML) statements enable you to update, insert, and delete data from your Spanner tables. Data Access Control statements let you grant and revoke access privileges at the table and column level. Transaction Control statements allow you to manage transactions for data modifications. Was this helpful? Send feedback Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates. ", "relevanceScore": 0.7, "documentMetadata": { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/0c5c094170756eeb6bdfec6eb5c7d081", "uri": "https://cloud.google.com/spanner/docs/reference/standard-sql/overview", "title": "The GoogleSQL language in Spanner | Google Cloud" } } }, { "chunkInfo": { "content": "FAQ Expand all What is Cloud SQL? Cloud SQL is a service that delivers fully managed relational databases in the cloud. It offers MySQL, PostgreSQL, and SQL Server database engines. How is Cloud SQL different from other cloud databases? Cloud SQL is valued for its openness, ease of use, security, cost-efficiency, and Google Cloud integration—in fact, more than 95% of Google Cloud's top 100 customers use it. If you're comparing PostgreSQL options on Google Cloud, view our comparison chart. What's the difference between the Enterprise and Enterprise Plus editions? For PostgreSQL, the Enterprise Plus edition brings enhanced availability, performance, and data protection capabilities. Specifically, it provides a 99.99% availability SLA with near-zero downtime maintenance, optimized hardware and software configurations, intelligent data caching for read-intensive transactional workloads, a configurable data cache option and 35 days of log retention. For MySQL, the Enterprise Plus edition brings enhanced availability, performance, and data protection capabilities. Specifically, it provides a 99.99% availability SLA with near-zero downtime maintenance, optimized hardware and software configurations, intelligent data caching for read-intensive transactional workloads, a configurable data cache option, 35 days of log retention and advanced disaster recovery capabilities like orchestrated failover and switchback. ", "relevanceScore": 0.7, "documentMetadata": { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/931f2c8e19ed54a407857f1cad3b5aaa", "uri": "https://cloud.google.com/sql", "title": "Cloud SQL for MySQL, PostgreSQL, and SQL Server | Google Cloud" } } }, { "chunkInfo": { "content": "PostgreSQL versus SQL PostgreSQL is an open-source, object-relational database (ORDBMS) designed for enterprise-level performance and is valued for its reliability and robust features. Its long history of development and its use of SQL makes it one of the most popular open source databases worldwide. Its default procedural language is an extension of pgSQL (PL/pgSQL), with procedural language extensions of Tcl, Perl, and Python included in the standard distribution (written as PL/Tcl, PL/Perl, and PL/Python). Many more languages are supported through extensions, including Java, Ruby, C, C++, Delphi, and JavaScript. For a more in-depth comparison, visit our PostgreSQL versus SQL guide. MySQL versus SQL MySQL is a popular open source relational database created in 1995 and currently sponsored by Oracle. It supports SQL queries and can be administered either through a graphical user interface (GUI) or a command line. MySQL can be deployed manually on a physical machine or through a cloud service provider. Enterprises are increasingly choosing fully managed services to reduce the maintenance burden of their databases. What is SQL Server? SQL Server is a Microsoft-owned database that runs SQL queries. Dive into the differences between PostgreSQL and SQL Server. ", "relevanceScore": 0.6, "documentMetadata": { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/7218ff4f57328d86059246d4af3a9953", "uri": "https://cloud.google.com/discover/what-are-sql-databases", "title": "SQL Databases | Google Cloud" } } }, { "chunkInfo": { "content": "Send feedback On this page BigQuery SQL dialects Changing from the default dialect What's next Introduction to SQL in BigQuery bookmark_borderbookmark Stay organized with collections Save and categorize content based on your preferences. Dismiss Got it GoogleSQL is the new name for Google Standard SQL! New name, same great SQL dialect. This document provides an overview of supported statements and SQL dialects in BigQuery. GoogleSQL is an ANSI compliant Structured Query Language (SQL) which includes the following types of supported statements: Query statements, also known as Data Query Language (DQL) statements, are the primary method to analyze data in BigQuery. They scan one or more tables or expressions and return the computed result rows. Procedural language statements are procedural extensions to GoogleSQL that allow you to execute multiple SQL statements in one request. Procedural statements can use variables and control-flow statements, and can have side effects. Data Definition Language (DDL) statements let you create and modify database objects such as tables, views, functions, and row-level access policies. Data Manipulation Language (DML) statements enable you to update, insert, and delete data from your BigQuery tables. Data Control Language (DCL) statements let you control BigQuery system resources such as access and capacity. Transaction Control Language (TCL) statements allow you to manage transactions for data modifications. ", "relevanceScore": 0.6, "documentMetadata": { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/2f6fc3e29873518196cb50195d7ded45", "uri": "https://cloud.google.com/bigquery/docs/introduction-sql", "title": "Introduction to SQL in BigQuery | Google Cloud" } } }, { "chunkInfo": { "content": "Database administration Cloud SQL pricing Connect to a Cloud SQL managed database Cloud SQL updates Configuration updates System updates What's next Home Cloud SQL Documentation Guides Was this helpful? Send feedback Cloud SQL overview bookmark_borderbookmark Stay organized with collections Save and categorize content based on your preferences. Dismiss Got it On this page Database configurations with Cloud SQL Use cases for Cloud SQL What Cloud SQL provides What is a Cloud SQL instance? Database administration Cloud SQL pricing Connect to a Cloud SQL managed database Cloud SQL updates Configuration updates System updates What's next Cloud SQL is a fully managed relational database service for MySQL, PostgreSQL, and SQL Server. This frees you from database administration tasks so that you have more time to manage your data. This page discusses basic concepts and terminology for Cloud SQL, which provides SQL data storage for Google Cloud. For a more in-depth explanation of key concepts, see the key terms and features pages. For information about how Cloud SQL databases compare with one another, see Cloud SQL feature support by database engine. Database configurations with Cloud SQL The following video shows you the benefits of using Cloud SQL. ", "relevanceScore": 0.6, "documentMetadata": { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/4098ae11bfa400e8f1b8e9ba59d2b71b", "uri": "https://cloud.google.com/sql/docs/introduction", "title": "Cloud SQL overview" } } }, { "chunkInfo": { "content": "Cloud SQL documentation View all product documentation Cloud SQL is a fully-managed database service that helps you set up, maintain, manage, and administer your relational databases on Google Cloud Platform. You can use Cloud SQL with MySQL, PostgreSQL, or SQL Server. Not sure what database option is right for you? Learn more about our database services. Learn more about Cloud SQL. Documentation resources Find quickstarts and guides, review key references, and get help with common issues. format_list_numbered Guides Cloud SQL overview Database engine feature support MySQL PostgreSQL SQL Server find_in_page Reference gcloud commands REST API Client libraries info Resources Pricing Release notes Resources Try Cloud SQL for yourself Create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads. Try Cloud SQL free Was this helpful? Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates. Last updated 2024-08-29 UTC. ", "relevanceScore": 0.5, "documentMetadata": { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/37935181d99a6ad3b4897e673a7a7986", "uri": "https://cloud.google.com/sql/docs", "title": "Cloud SQL documentation" } } } ], "steps": [ { "state": "SUCCEEDED", "description": "Rephrase the query and search.", "actions": [ { "searchAction": { "query": "What is SQL?" }, "observation": { "searchResults": [ { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/7218ff4f57328d86059246d4af3a9953", "uri": "https://cloud.google.com/discover/what-are-sql-databases", "title": "SQL Databases | Google Cloud", "snippetInfo": [ { "snippet": "\u003cb\u003eSQL\u003c/b\u003e (Structured Query Language) is a programming language used to store, retrieve, and manage data in a relational database. \u003cb\u003eSQL\u003c/b\u003e statements are English-like, ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/f7cd9afab1282a9f57cdcee1885bb4c6", "uri": "https://cloud.google.com/learn/postgresql-vs-sql", "title": "PostgreSQL vs. SQL Server: What's the difference? | Google Cloud", "snippetInfo": [ { "snippet": "\u003cb\u003eSQL\u003c/b\u003e typically uses commands written in statement format for queries and other database operations, which allow users to manipulate data in relational database ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/3afdede140d0906c2146a2f2b3a7821e", "uri": "https://cloud.google.com/blog/topics/developers-practitioners/what-cloud-sql", "title": "What is Cloud SQL? | Google Cloud Blog", "snippetInfo": [ { "snippet": "It is a fully managed relational database for MySQL, PostgreSQL and \u003cb\u003eSQL\u003c/b\u003e Server. It reduces maintenance cost and automates database provisioning, storage ...", "snippetStatus": "SUCCESS" } ] }, ... { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/0c5c094170756eeb6bdfec6eb5c7d081", "uri": "https://cloud.google.com/spanner/docs/reference/standard-sql/overview", "title": "The GoogleSQL language in Spanner | Google Cloud", "snippetInfo": [ { "snippet": "\u003cb\u003eGoogleSQL\u003c/b\u003e is the new name for Google Standard \u003cb\u003eSQL\u003c/b\u003e! New name, same great \u003cb\u003eSQL\u003c/b\u003e dialect. This page provides an overview of supported statements in \u003cb\u003eGoogleSQL\u003c/b\u003e.", "snippetStatus": "SUCCESS" } ] } ] } } ] } ] }, "answerQueryToken": "NMwKDAiFm_y2BhC_nfrYAxIkNjZkYjg3NjItMDAwMC0yZTBkLTg0ZDAtMDg5ZTA4MmRjYjg0" }

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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
    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
    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-1.5-flash-001/answer_gen/v2",  # 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

回答の言語コードを設定する

次のコマンドは、回答の言語コードを設定する方法を示しています。

RESTPython

デフォルト モデルとは異なるモデルを使用して回答を生成する手順は次のとおりです。

  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: Tags for Identifying Languages で定義されている言語タグを使用します。
    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": "What is SQL"},   "answerGenerationSpec": {
      "answerLanguageCode": "es"
         }
    }'
    
    { "answer": { "state": "SUCCEEDED", "answerText": "SQL, que significa Structured Query Language, es un lenguaje de programación utilizado para almacenar, recuperar y administrar datos en una base de datos relacional. Las instrucciones de SQL son similares al inglés, lo que hace que el lenguaje sea accesible para desarrolladores de software, analistas de datos y otros profesionales. Las bases de datos SQL se utilizan para administrar y almacenar datos para apoyar numerosos casos de uso empresariales, como la inteligencia empresarial, el procesamiento de transacciones, el análisis de datos y los servicios de aprendizaje automático. SQL es el lenguaje estándar utilizado por los sistemas de gestión de bases de datos relacionales (RDBMS), incluidos PostgreSQL, SQL Server, MySQL y Oracle Database. SQL se utiliza para crear y actualizar la estructura de las tablas, leer y escribir datos, administrar los permisos de los usuarios y realizar tareas administrativas. \n", "steps": [ { "state": "SUCCEEDED", "description": "Rephrase the query and search.", "actions": [ { "searchAction": { "query": "What is SQL?" }, "observation": { "searchResults": [ { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/7218ff4f57328d86059246d4af3a9953", "uri": "https://cloud.google.com/discover/what-are-sql-databases", "title": "SQL Databases | Google Cloud", "snippetInfo": [ { "snippet": "\u003cb\u003eSQL\u003c/b\u003e (Structured Query Language) is a programming language used to store, retrieve, and manage data in a relational database. \u003cb\u003eSQL\u003c/b\u003e statements are English-like, ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/f7cd9afab1282a9f57cdcee1885bb4c6", "uri": "https://cloud.google.com/learn/postgresql-vs-sql", "title": "PostgreSQL vs. SQL Server: What's the difference? | Google Cloud", "snippetInfo": [ { "snippet": "\u003cb\u003eSQL\u003c/b\u003e typically uses commands written in statement format for queries and other database operations, which allow users to manipulate data in relational database ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/3afdede140d0906c2146a2f2b3a7821e", "uri": "https://cloud.google.com/blog/topics/developers-practitioners/what-cloud-sql", "title": "What is Cloud SQL? | Google Cloud Blog", "snippetInfo": [ { "snippet": "It is a fully managed relational database for MySQL, PostgreSQL and \u003cb\u003eSQL\u003c/b\u003e Server. It reduces maintenance cost and automates database provisioning, storage ...", "snippetStatus": "SUCCESS" } ] }, ... { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/0c5c094170756eeb6bdfec6eb5c7d081", "uri": "https://cloud.google.com/spanner/docs/reference/standard-sql/overview", "title": "The GoogleSQL language in Spanner | Google Cloud", "snippetInfo": [ { "snippet": "\u003cb\u003eGoogleSQL\u003c/b\u003e is the new name for Google Standard \u003cb\u003eSQL\u003c/b\u003e! New name, same great \u003cb\u003eSQL\u003c/b\u003e dialect. This page provides an overview of supported statements in \u003cb\u003eGoogleSQL\u003c/b\u003e.", "snippetStatus": "SUCCESS" } ] } ] } } ] } ] }, "answerQueryToken": "NMwKDAjim_y2BhDftIjEAhIkNjZkOTQ0NWQtMDAwMC0yMTBkLTllNmItZjQwMzA0NWRiZDMw" }

    この例では、ソースドキュメントは英語ですが、回答はスペイン語で提供されています。

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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
    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
    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-1.5-flash-001/answer_gen/v2",  # 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 メソッドで関連する質問を提示することもできます。ユーザーは、独自のフォローアップの質問を入力する代わりに、提示された質問を選択できます。

前のセクションで説明した回答とフォローアップの機能(引用、フィルタ、セーフサーチ、特定の種類のクエリの無視、プリアンブルを使用した回答のカスタマイズなど)はすべて、フォローアップとともに適用できます。

フォローアップ セッションの例

フォローアップを含むセッションの例を次に示します。メキシコでの休暇について調べたいとします。

  • ターン 1:

    • お客様: メキシコで休暇を過ごすのに最適な時期はいつですか?

    • フォローアップ付きの回答: メキシコで休暇を過ごすのに最適な時期は乾季です。これは 11 月から 4 月までです。

  • ターン 2:

    • お客様: 為替レートはいくらですか?

    • フォローアップ付きの回答: 1 米ドルは約 17.65 メキシコペソに相当します。

  • ターン 3:

    • お客様: 12 月の平均気温はどれくらいですか?

    • フォローアップ付きの回答: 平均気温は華氏 70~78 度です。 カンクンの平均気温は華氏 77 度までです。

フォローアップなしでは、「為替レートはいくらですか?」という質問に回答できません。通常の検索では、メキシコの為替レートが求められていることを認識できないためです。同様に、フォローアップなしでは、特にメキシコの温度を示すために必要なコンテキストがありません。

「メキシコで休暇を過ごすのに最適な時期はいつですか?」という質問をするときに、質問への回答に加えて、回答とフォローアップでは、「メキシコで休暇を過ごすのに最も安い月はいつですか?」や「メキシコの観光シーズンはいつですか?」など、質問する可能性のある他の質問を提示できます。

関連する質問の機能が有効になると、質問は ConverseConversationResponse で文字列として返されます。

セッションについて

Vertex AI Search でのフォローアップの仕組みを理解するには、セッションについて理解する必要があります。

セッションは、ユーザーが提供するテキスト クエリと Vertex AI Search が提供するレスポンスで構成されます。

これらのクエリとレスポンスのペアは、ターンと呼ばれることもあります。上の例では、2 番目のターンは「為替レートはいくらですか?」と「1 米ドルは約 17.65 メキシコペソです」で構成されています。

セッションはアプリとともに保存されます。アプリでは、セッションはセッション リソースで表されます。

クエリ メッセージとレスポンス メッセージに加えて、セッション リソースには次のものも含まれます。

  • 一意の名前(セッション ID)。

  • ステータス(進行中または完了)。

  • ユーザー疑似 ID(ユーザーを追跡する訪問者 ID)。プログラムで割り当てることができます。

  • 開始時刻と終了時刻。

  • ターン(クエリと回答のペア)。

セッション情報を保存してレスポンスを取得する

コマンドラインを使用して検索レスポンスと回答を生成し、各クエリとともにセッションに保存できます。

RESTPython

コマンドラインを使用してセッションを作成し、ユーザー入力からレスポンスを生成する手順は次のとおりです。

  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: 検索訪問者をトラッキングするための固有識別子。たとえば、HTTP Cookie を使用して、1 台のデバイス上の訪問者を一意に識別できます。

    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. JSON レスポンスの name: フィールドの末尾にある数字であるセッション ID をメモします。次の例の場合、ID は 5386462384953257772 です。 この値は次のステップで必要になります。

  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。これは、手順 2 でメモした name: フィールドの末尾にある数字です。セッションでは、すべてのターンで同じセッション 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 を繰り返します。

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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 メソッドを呼び出してデータストアからセッションを取得する方法を示しています。

RESTPython

データストアからセッションを取得する手順は次のとおりです。

  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。

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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 呼び出しを使用して削除します。

RESTPython

アプリからセッションを削除する手順は次のとおりです。

  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。
    curl -X DELETE -H "Authorization: Bearer $(gcloud auth print-access-token)"
    -H "Content-Type: application/json"
    "https://discoveryengine.googleapis.com/v1/projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/16002628354770206943"
        
    {}

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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 メソッドを呼び出してデータストア内のセッションを更新する方法を示しています。

RESTPython

アプリからセッションを更新する手順は次のとおりです。

  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 など)。
    curl -X PATCH -H "Authorization: Bearer $(gcloud auth print-access-token)"
    -H "Content-Type: application/json"
    "https://discoveryengine.googleapis.com/v1/projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/16002628354770206943?updateMask=state"
    -d '{
    "state": "IN_PROGRESS"
    }'
        
    { "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:49:41.579151Z" }

    この例では、セッションの状態をオープン(進行中)に変更します。同様の方法で userPseudoId を更新します。

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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 メソッドを呼び出して、データストア内のセッションを一覧表示する方法を示しています。

RESTPython

アプリのセッションを一覧表示する手順は次のとおりです。

  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。
    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)"
    -H "Content-Type: application/json"
    "https://discoveryengine.googleapis.com/v1/projects/123456/locations/global/collections/default_collection/engines/my-app/sessions"
        
    { "sessions": [ { "name": "projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/10000135306311111817", "state": "IN_PROGRESS", "turns": [ { "query": { "queryId": "projects/123456/locations/global/questions/10000135306311114276", "text": "bugs reported by tiktok on grounding" } } ], "startTime": "2024-09-03T00:38:40.338623Z", "endTime": "2024-09-03T00:38:40.338623Z" }, { "name": "projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/10000827040519035859", "state": "IN_PROGRESS", "turns": [ { "query": { "queryId": "projects/123456/locations/global/questions/10000827040519033518", "text": "GDM models" } } ], "startTime": "2024-07-19T15:53:06.521775Z" }, { "name": "projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/10003910515245149877", "state": "IN_PROGRESS", "turns": [ { "query": { "queryId": "projects/123456/locations/global/questions/10003910515245148378", "text": "gyorgyattila" }, "answer": "projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/10003910515245149877/answers/17036357111873257990" } ], "startTime": "2024-08-08T11:40:04.632463Z", "endTime": "2024-08-08T11:40:04.632463Z" }, ... { "name": "projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/10198752942940073431", "state": "IN_PROGRESS", "turns": [ { "query": { "queryId": "projects/123456/locations/global/questions/10198752942940071818", "text": "hello" }, "answer": "projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/10198752942940073431/answers/13411441797796265380" } ], "startTime": "2024-08-14T17:30:21.203439Z", "endTime": "2024-08-14T17:30:21.203439Z" } ], "nextPageToken": "IDEDgIwL_vuieLC" }

    レスポンスには、セッションのリストと nextPageToken が含まれます。nextPageToken が返されない場合、一覧表示するセッションはありません。デフォルトのページサイズは 50 です。

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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 メソッドを呼び出して、ユーザーまたは訪問者に関連付けられたセッションを一覧表示する方法を示しています。

RESTPython

ユーザーまたは訪問者に関連付けられたセッションを一覧表示するには、次の操作を行います。

  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。
    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)"
    -H "Content-Type: application/json"
    "https://discoveryengine.googleapis.com/v1/projects/123456/locations/global/collections/default_collection/engines/my-app/sessions?filter=userPseudoId=test_user"
        
    { "sessions": [ { "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:49:41.579151Z" } ] }

    この例では、test_user に関連付けられているセッションが 1 つあります。セッションのクエリと回答が一覧表示されます。

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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 メソッドを呼び出して、特定のユーザーの特定の状態のセッションを一覧表示する方法を示しています。

RESTPython

オープンまたはクローズしていて、特定のユーザーまたは訪問者に関連付けられているユーザーのセッションを一覧表示するには、次の操作を行います。

  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(オープン)。
    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)"
    -H "Content-Type: application/json"
    "https://discoveryengine.googleapis.com/v1/projects/123456/locations/global/collections/default_collection/engines/my-app/sessions?filter=userPseudoId=test_user%20AND%20state=IN_PROGRESS"
        
    { "sessions": [ { "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:49:41.579151Z" } ] }

    予想される結果は空のレスポンスです。

詳細については、Vertex AI Agent Builder Python API のリファレンス ドキュメントをご覧ください。

Vertex AI Agent Builder に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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