获取搜索结果

本页介绍了如何使用 Google Cloud 控制台预览搜索结果,以及如何使用 API 获取搜索结果。

此外,您还可以进行 API 调用并将其集成到您的服务器或应用中,而不是创建要添加到网页中的搜索微件。本页包含代码示例,介绍如何使用 gRPC 客户端库搭配服务账号发出搜索查询。

搜索摘要因设备型号而异

如果您为查询生成搜索摘要,可能会发现控制台结果和 API 结果中的摘要有所不同。如果您看到此消息,可能是因为控制台使用的 LLM 模型与 API 使用的 LLM 模型不同。本页中的 curl 和代码示例使用的是稳定的 LLM 模型。

  • 如需更改或查看界面预览页面中使用的 LLM 模型,请前往应用的配置页面 > 界面标签页。

  • 对于方法调用,如需使用稳定模型以外的 LLM 模型,请参阅指定总结模型

获取包含网站数据的应用的搜索结果

控制台

如需使用 Google Cloud 控制台预览包含网站数据的应用的搜索结果,请按以下步骤操作:

  1. 在 Google Cloud 控制台中,前往 Agent Builder 页面。

    Agent Builder

  2. 点击要修改的应用的名称。

  3. 点击预览

  4. 在控制台中打开预览页面。

  5. 可选:如果您已将多个数据存储区连接到您的应用,但只希望从特定数据存储区获取结果,请选择要从中获取结果的数据存储区。

  6. 输入搜索查询。

    1. 如果您启用了自动补全功能,则在输入内容时,搜索栏下方会显示自动补全建议列表。
  7. 点击 Enter 键提交查询。

    1. 搜索栏下方会显示搜索结果列表。
    2. 每个结果均包含标题、摘要和网址。
    3. 点击相应结果即可打开该网址。
  8. 点击结果列表下方的箭头,即可加载下一页结果。

REST

如需使用此 API 获取包含网站数据的应用的搜索结果,请使用 engines.servingConfigs.search 方法:

  1. 找到您的应用 ID。如果您已经有应用 ID,请跳至下一步。

    1. 在 Google Cloud 控制台中,前往 Agent Builder 页面。

      前往“应用”

    2. 应用页面上,找到应用的名称,然后从 ID 列中获取应用的 ID。

  2. 获取搜索结果。

    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:search" \
    -d '{
    "servingConfig": "projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search",
    "query": "QUERY",
    "pageSize": "PAGE_SIZE",
    "offset": "OFFSET",
    "orderBy": "ORDER_BY",
    "params": {"user_country_code": "USER_COUNTRY_CODE",
    "searchType": "SEARCH_TYPE"},
    "filter": "FILTER",
    "boostSpec": "BOOST_SPEC",
    "contentSearchSpec": {
       "searchResultMode": "RESULT_MODE"
     },
     "dataStoreSpecs": [{"DATA_STORE_SPEC"}]
    }'
    

    替换以下内容:

    • PROJECT_ID:您的 Google Cloud 项目的 ID。
    • APP_ID:您要查询的 Vertex AI Search 应用的 ID。
    • QUERY:要搜索的查询文本。
    • PAGE_SIZE:搜索返回的结果数。 允许的最大页面大小取决于数据类型。大于最大值的页面大小会被强制转换为最大值。

      • 采用基本索引的网站:默认 10,上限 25
      • 启用了高级索引编制的网站:默认 25,上限 50
      • 其他:默认 50,最大 100
    • OFFSET:结果的起始索引。默认值为 0。

      例如,如果偏移量为 2,页面大小为 10,并且要返回 15 个结果,则第一页会返回第 2 条到第 12 条结果。

    • ORDER_BY:结果的排列顺序。用于排序的属性必须具有数值解释,例如 date。如需了解详情,请参阅对网页搜索结果进行排序

    • USER_COUNTRY_CODE:用户的位置。此键值对是 params 映射字段唯一支持的条目。默认值为空。如需了解可接受的值,请参阅可编程搜索引擎 JSON API 参考文档中的国家/地区代码

    • SEARCH_TYPE:要执行的搜索类型。文档搜索的默认值为 0。图片搜索的另一个支持的值为 1。

    • FILTER:一个文本字段,用于使用过滤条件表达式过滤搜索结果。默认值为空字符串。如需详细了解如何使用 filter 字段,请参阅过滤网站搜索

    • BOOST_SPEC:可选。用于提升或隐藏文档的规范。值:

      • BOOST:[-1,1] 范围内的浮点数。当该值为负时,相应结果会被降级(在结果中显示在更低的位置)。当该值为正时,系统会提升结果的排名(即在搜索结果中显示在更高的位置)。
      • CONDITION:一个文本过滤表达式,用于选择要应用权重功能的文档。过滤条件的求值结果必须为布尔值。 如需了解如何为结构化搜索结果提升排名,请参阅提升搜索结果排名
    • RESULT_MODE:确定搜索结果是作为完整文档还是分块返回。如需获取分块,数据存储区必须启用文档分块。可接受的值为 documentschunks。为数据存储区启用分块时,默认值为 chunks。否则,默认值为 documents。如需了解文档分块,请参阅解析和分块文档。此字段处于公开预览阶段;如需使用它,请在 curl 命令中将 v1 更改为 v1alpha

    • DATA_STORE_SPEC:用于搜索特定数据存储区的过滤条件。如果您的搜索应用连接到多个数据存储区,但您希望从特定数据存储区获取结果,请使用 dataStoreSpecs

C#

如需了解详情,请参阅 Vertex AI Agent Builder C# API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

using Google.Api.Gaxs="devsite-xref-link" href="https://cloud.google.com/dotnet/docs/reference/Google.Protobuf/latest/Google.Protobuf.WellKnownTypes.Api.html" track-type="exampleCode" track-nam<e="xref>Link" track-metada<ta-lang=>"DOTNET" <track-m>etadata-modifier="Google.Protobuf.WellKnownTypes" track-metadata-href="https://cloud.google.com/dotnet/docs/reference/Google.Protobuf/latest/Google.Protobuf.WellKnownTypes.Api.html">Api.Gax;
using Google.Cloud.DiscoveryEngine.V1Beta;
using Google.Protobuf.WellKnownTypes;
using System;

public sealed partial class GeneratedSearchServiceClientSnippets
{
    /// summarySnippet for Search/summary
    /// remarks
    /// This< snippet> has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/refere"nce/help/"cl"ient-confi"gu"ration#endpo"in"t.
    /// /rema"rks
    public void SearchRequestObject()
    {
        // Create client
        S"earchServ"ic"eClient se"ar"chServiceCli"en"t = Sear"chServiceClient.Create("");
        // Initialize request argument(s)
  ""      SearchRequest requ""est = new SearchRequest
        {
            ServingConfigAsServingConfigName = ServingConfigName.FromProjectLocationDataStoreServingConfig([PROJECT], [LOCATION], [DATA_STORE], [SERVING_CONFIG])"",
            BranchAsBranchName = BranchName.FromProjectLocationDataStoreBranch([PROJECT], [LOCATION], [DATA_STORE], [BRANCH]),
            Query = ,
            Offset = 0,
            Filter = ,
         ""   OrderBy = ,
            FacetSpecs =
            {
                new SearchRequest.Types.FacetSpec(),
            },
            BoostSpec = new SearchRequest.T""yp""es.BoostSpec(),
            Params = { { , new Value() }, },
            QueryExpansionSpec = new SearchRequest.Types.QueryExpansionSpec(),
            SpellCorrectionSpec = new SearchR""equest.Types.SpellCorrectionSpec(),
            UserPseudoId = ,
            ImageQuery = new SearchRequest.Types.ImageQuery(),
            SafeSearc""h = false,
            UserInfo = new UserInfo(),
            UserLabels = { { ,  }, },
            EmbeddingSpec = new SearchRequest.Types.EmbeddingSpec(),
            ContentSearchSpec = new SearchRequest.Types.ContentSearc""hSpec(),
            Rankin""gExpression = ,
            NaturalLanguageQueryUnderstandingSpec = new SearchRequest".Types.Na"tu"ralLanguag"eQ"ueryUndersta"nd"ingSpec()",
            CanonicalFilter = ,
            SearchAsYouTypeSpec = new SearchRequest.Types.SearchAsYouTypeSpec(),
            DataStoreSpecs =
            {
                new SearchRequest.Types.DataStoreSpec(),
            },
            LanguageCode = ,
            RegionCode = ,
            SessionAsSessionName = Session<Name.FromProjectLocationDataStoreSession([PROJECT>], [LOCATION], [DATA_STORE], [SESSION]),
            SessionSpec = new SearchRequest.Types.SessionSpec(),
            RelevanceThreshold = SearchRequest.Types.RelevanceThreshold.Unspecified,
            PersonalizationSpec = new SearchRequest.Types.PersonalizationSpec(),
            OneBoxPageSize = 0,
        };
        // Make the request
        PagedEnumerableSearchResponse, SearchResponse.Types.SearchResult response = searchServiceClient.Search(request);

        // Iterate over all response items, lazily performing RPCs as required
 "       foreach (Se"archResponse.Types.SearchResult item in response)
        {
            // Do something with each item
            Console.WriteLine(item);
        }

        // Or iterate over pages (of server-defined size), performing one RPC per page
        foreach (Searc'hResponse page in response.AsRawResponses())
        {
            // Do something with each p<age of items
            Console.>WriteLine(A page of results:);
            foreach (SearchResponse.Types.SearchResult item in page)
            {
   "             // Do something with each 'item
             "   Console.WriteLine(item);
            }
        }

        // Or retrieve a single page of known size (unless its the final page), performing as many RPCs as required
        int pageSize = 10;
        PageSearchResponse.Types.SearchResult singlePage = response.ReadPage(pageSize);
        // Do something with the page of items
        Console.WriteLine($A page of {pageSize} results (unless its the final page):);
        foreach (SearchResponse.Types.SearchResult item in singlePage)
        {
            // Do something with each item
            Console.WriteLine(item);
        }
        // Store the pageToken, for when the next page is required.
        string nextPageToken = singlePage.NextPageToken;
    }
}

Java

如需了解详情,请参阅 Vertex AI Agent Builder Java API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.discoveryengine.v1.SearchRequest;
import com.google.cloud.discoveryengine.v1.SearchResponse;
import com.google.cloud.discoveryengine.v1.SearchServiceClient;
import com.google.cloud.discoveryengine.v1.SearchServiceSettings;
import com.google.cloud.discoveryengine.v1.ServingConfigName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class Search {
  public static void main() throws IOException, ExecutionException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "PROJECT_ID";
    // Location of the data store. Options: "global", "us", "eu"
    String location = "global";
    // Collection containing the data store.
    String collectionId = "default_collection";
    // Data store ID.
    String dataStoreId = "DATA_STORE_ID";
    // Serving configuration. Options: "default_search"
    String servingConfigId = "default_search";
    // Search Query for the data store.
    String searchQuery = "Google";
    search(projectId, location, collectionId, dataStoreId, servingConfigId, searchQuery);
  }

  /** Performs a search on a given datastore. */
  public static void search(
      String projectId,
      String location,
      String collectionId,
      String dataStoreId,
      String servingConfigId,
      String searchQuery)
      throws IOException, ExecutionException {
    // For more information, refer to:
    // https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
    String endpoint = (location.equals("global")) 
        ? String.format("discoveryengine.googleapis.com:443", location) 
        : String.format("%s-discoveryengine.googleapis.com:443", location);
    SearchServiceSettings settings =
        SearchServiceSettings.newBuilder().setEndpoint(endpoint).build();
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `searchServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (SearchServiceClient searchServiceClient = SearchServiceClient.create(settings)) {
      SearchRequest request =
          SearchRequest.newBuilder()
              .setServingConfig(
                  ServingConfigName.formatProjectLocationCollectionDataStoreServingConfigName(
                      projectId, location, collectionId, dataStoreId, servingConfigId))
              .setQuery(searchQuery)
              .setPageSize(10)
              .build();
      SearchResponse response = searchServiceClient.search(request).getPage().getResponse();
      for (SearchResponse.SearchResult element : response.getResultsList()) {
        System.out.println("Response content: " + element);
      }
    }
  }
}

Node.js

如需了解详情,请参阅 Vertex AI Agent Builder Node.js API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'YOUR_LOCATION';              // Options: 'global', 'us', 'eu'
// const collectionId = 'default_collection';     // Options: 'default_collection'
// const dataStoreId = 'YOUR_DATA_STORE_ID'       // Create in Cloud Console
// const servingConfigId = 'default_config';      // Options: 'default_config'
// const searchQuery = 'Google';

const {SearchServiceClient} = require('@google-cloud/discoveryengine').v1beta;

// For more information, refer to:
// https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
const apiEndpoint =
  location === 'global'
    ? 'discoveryengine.googleapis.com'
    : `${location}-discoveryengine.googleapis.com`;

// Instantiates a client
const client = new SearchServiceClient({apiEndpoint: apiEndpoint});

async function search() {
  // The full resource name of the search engine serving configuration.
  // Example: projects/{projectId}/locations/{location}/collections/{collectionId}/dataStores/{dataStoreId}/servingConfigs/{servingConfigId}
  // You must create a search engine in the Cloud Console first.
  const name = client.projectLocationCollectionDataStoreServingConfigPath(
    projectId,
    location,
    collectionId,
    dataStoreId,
    servingConfigId
  );

  const request = {
    pageSize: 10,
    query: searchQuery,
    servingConfig: name,
  };

  const IResponseParams = {
    ISearchResult: 0,
    ISearchRequest: 1,
    ISearchResponse: 2,
  };

  // Perform search request
  const response = await client.search(request, {
    // Warning: Should always disable autoPaginate to avoid iterate through all pages.
    //
    // By default NodeJS SDK returns an iterable where you can iterate through all
    // search results instead of only the limited number of results requested on
    // pageSize, by sending multiple sequential search requests page-by-page while
    // iterating, until it exhausts all the search results. This will be unexpected and
    // may cause high Search API usage and long wait time, especially when the matched
    // document numbers are huge.
    autoPaginate: false,
  });
  const results = response[IResponseParams.ISearchResponse].results;

  for (const result of results) {
    console.log(result);
  }
}

PHP

如需了解详情,请参阅 Vertex AI Agent Builder PHP API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\DiscoveryEngine\V1beta\Client\SearchServiceClient;
use Google\Cloud\DiscoveryEngine\V1beta\SearchRequest;
use Google\Cloud\DiscoveryEngine\V1beta\SearchResponse\SearchResult;

/**
 * Performs a search.
 *
 * @param string $formattedServingConfig The resource name of the Search serving config, such as
 *                                       `projects/&#42;/locations/global/collections/default_collection/engines/&#42;/servingConfigs/default_serving_config`,
 *                                       or
 *                                       `projects/&#42;/locations/global/collections/default_collection/dataStores/default_data_store/servingConfigs/default_serving_config`.
 *                                       This field is used to identify the serving configuration name, set
 *                                       of models used to make the search. Please see
 *                                       {@see SearchServiceClient::servingConfigName()} for help formatting this field.
 */
function search_sample(string $formattedServingConfig): void
{
    // Create a client.
    $searchServiceClient = new SearchServiceClient();

    // Prepare the request message.
    $request = (new SearchRequest())
        ->setServingConfig($formattedServingConfig);

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $searchServiceClient->search($request);

        /** @var SearchResult $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedServingConfig = SearchServiceClient::servingConfigName(
        '[PROJECT]',
        '[LOCATION]',
        '[DATA_STORE]',
        '[SERVING_CONFIG]'
    );

    search_sample($formattedServingConfig);
}

Python

如需了解详情,请参阅 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"
# search_query = "YOUR_SEARCH_QUERY"


def search_sample(
    project_id: str,
    location: str,
    engine_id: str,
    search_query: str,
) -> discoveryengine.services.search_service.pagers.SearchPager:
    #  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.SearchServiceClient(client_options=client_options)

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

    # Optional - only supported for unstructured data: Configuration options for search.
    # Refer to the `ContentSearchSpec` reference for all supported fields:
    # https://cloud.google.com/python/docs/reference/discoveryengine/latest/google.cloud.discoveryengine_v1.types.SearchRequest.ContentSearchSpec
    content_search_spec = discoveryengine.SearchRequest.ContentSearchSpec(
        # For information about snippets, refer to:
        # https://cloud.google.com/generative-ai-app-builder/docs/snippets
        snippet_spec=discoveryengine.SearchRequest.ContentSearchSpec.SnippetSpec(
            return_snippet=True
        ),
        # For information about search summaries, refer to:
        # https://cloud.google.com/generative-ai-app-builder/docs/get-search-summaries
        summary_spec=discoveryengine.SearchRequest.ContentSearchSpec.SummarySpec(
            summary_result_count=5,
            include_citations=True,
            ignore_adversarial_query=True,
            ignore_non_summary_seeking_query=True,
            model_prompt_spec=discoveryengine.SearchRequest.ContentSearchSpec.SummarySpec.ModelPromptSpec(
                preamble="YOUR_CUSTOM_PROMPT"
            ),
            model_spec=discoveryengine.SearchRequest.ContentSearchSpec.SummarySpec.ModelSpec(
                version="stable",
            ),
        ),
    )

    # Refer to the `SearchRequest` reference for all supported fields:
    # https://cloud.google.com/python/docs/reference/discoveryengine/latest/google.cloud.discoveryengine_v1.types.SearchRequest
    request = discoveryengine.SearchRequest(
        serving_config=serving_config,
        query=search_query,
        page_size=10,
        content_search_spec=content_search_spec,
        query_expansion_spec=discoveryengine.SearchRequest.QueryExpansionSpec(
            condition=discoveryengine.SearchRequest.QueryExpansionSpec.Condition.AUTO,
        ),
        spell_correction_spec=discoveryengine.SearchRequest.SpellCorrectionSpec(
            mode=discoveryengine.SearchRequest.SpellCorrectionSpec.Mode.AUTO
        ),
        # Optional: Use fine-tuned model for this request
        # custom_fine_tuning_spec=discoveryengine.CustomFineTuningSpec(
        #     enable_search_adaptor=True
        # ),
    )

    page_result = client.search(request)

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

    return page_result

Ruby

如需了解详情,请参阅 Vertex AI Agent Builder Ruby API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/discovery_engine/v1beta"

##
# Snippet for the search call in the SearchService service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::DiscoveryEngine::V1beta::SearchService::Client#search.
#
def search
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::DiscoveryEngine::V1beta::SearchService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::DiscoveryEngine::V1beta::SearchRequest.new

  # Call the search method.
  result = client.search request

  # The returned object is of type Gapic::PagedEnumerable. You can iterate
  # over elements, and API calls will be issued to fetch pages as needed.
  result.each do |item|
    # Each element is of type ::Google::Cloud::DiscoveryEngine::V1beta::SearchResponse::SearchResult.
    p item
  end
end

获取包含网站数据的应用的搜索结果(API 密钥)

如果您想使用 API 密钥(而不是通过服务账号或用户账号使用 OAuth 2.0)对搜索方法调用进行身份验证,请按照以下使用 searchLite 方法的步骤操作。searchLite 方法与 search 方法具有相同的功能,但只能用于搜索公开网站。

searchLite 方法在以下情况下特别适用:

  • 您有一个静态网站,无法通过服务账号或用户账号设置 OAuth 2.0。

  • 您已从可编程搜索引擎的 Custom Search Site Restricted JSON API 迁移到 Vertex AI Search。

  • 您不想使用搜索微件。

准备工作

您需要先拥有 API 密钥,然后才能调用 servingConfigs.searchLite 方法。如果您没有 API 密钥,请完成部署搜索应用(API 密钥)中的第 1 步。

过程

REST

如需使用此 API 获取使用 API 密钥进行身份验证的公共网站数据的应用的搜索结果,请使用 engines.servingConfigs.searchLite 方法:

  1. 找到您的应用 ID。如果您已经有应用 ID,请跳至下一步。

    1. 在 Google Cloud 控制台中,前往 Agent Builder 页面。

      前往“应用”

    2. 应用页面上,找到应用的名称,然后从 ID 列中获取应用的 ID。

  2. 运行以下 curl 命令可获取搜索结果:

    curl -X POST -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:searchLite?key=API_KEY" \
    -d '{
    "servingConfig": "projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search",
    "query": "QUERY",
    }'
    

    替换以下内容:

    • PROJECT_ID:您的 Google Cloud 项目的 ID。

    • API_KEY:您的 API 密钥字符串。

    • PROJECT_ID:您的 Google Cloud 项目的 ID。

    • APP_ID:您要查询的 Vertex AI Search 应用的 ID。

    • QUERY:要搜索的查询文本。

Python

如需了解详情,请参阅 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"
# api_key = "YOUR_API_KEY"
# search_query = "YOUR_SEARCH_QUERY"


def search_lite_sample(
    project_id: str,
    location: str,
    engine_id: str,
    api_key: str,
    search_query: str,
) -> discoveryengine.services.search_service.pagers.SearchLitePager:

    client_options = ClientOptions(
        # For information on API Keys, refer to:
        # https://cloud.google.com/generative-ai-app-builder/docs/migrate-from-cse#api-key-deploy
        api_key=api_key,
        #  For more information, refer to:
        # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
        api_endpoint=(
            f"{location}-discoveryengine.googleapis.com"
            if location != "global"
            else None
        ),
    )

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

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

    # Refer to the `SearchRequest` reference for all supported fields:
    # https://cloud.google.com/python/docs/reference/discoveryengine/latest/google.cloud.discoveryengine_v1.types.SearchRequest
    request = discoveryengine.SearchRequest(
        serving_config=serving_config,
        query=search_query,
    )

    page_result = client.search_lite(request)

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

    return page_result

获取包含结构化数据或非结构化数据的应用的搜索结果

您可以通过 Google Cloud 控制台预览搜索结果,也可以使用 API 获取搜索结果。

控制台

如需使用 Google Cloud 控制台预览包含结构化或非结构化数据的应用的搜索结果,请按以下步骤操作:

  1. 在控制台中打开预览页面。
  2. 输入搜索查询。
    1. 如果您在第 1 步中启用了自动补全功能,则在输入内容时,搜索栏下方会显示自动补全建议列表。
  3. (可选)如果您已将多个数据存储区连接到您的应用,但只希望从特定数据存储区获取结果,请选择要从中获取结果的数据存储区。
  4. 点击 Enter 键提交查询。
    1. 搜索栏下方会显示搜索结果列表。
    2. 如果未在配置页面中定义任何属性映射,则每个搜索结果都会显示为原始属性名称和值的列表。
    3. 如果您在配置页面中保存了任何属性映射,搜索结果中会显示与配置页面预览中相同的图片。
  5. 如果您在配置页面中指定了任何切面,它们也会以相同的方式显示。
  6. 点击结果列表下方的箭头,即可加载下一页结果。

REST

如需使用此 API 获取包含结构化或非结构化数据的应用的搜索结果,请使用 engines.servingConfigs.search 方法:

  1. 找到您的应用 ID。如果您已经有应用 ID,请跳至下一步。

    1. 在 Google Cloud 控制台中,前往 Agent Builder 页面。

      前往“应用”

    2. 应用页面上,找到应用的名称,然后从 ID 列中获取应用的 ID。

  2. 获取搜索结果。

    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:search" \
    -d '{
    "query": "QUERY",
    "userPseudoId": "USER_PSEUDO_ID",
    "pageSize": "PAGE_SIZE",
    "offset": "OFFSET",
    "orderBy": "ORDER_BY",
    "filter": "FILTER",
    "boostSpec": "BOOST_SPEC",
    "facetSpec": "FACET_SPEC",
    "queryExpansionSpec": "QUERY_EXPANSION_SPEC",
    "spellCorrectionSpec": "SPELL_CORRECTION_SPEC",
    "contentSearchSpec": "CONTENT_SEARCH_SPEC",
    "dataStoreSpecs": [{"DATA_STORE_SPEC"}],
    }'
    

    替换以下内容:

    • PROJECT_ID:您的 Google Cloud 项目的 ID。
    • PROJECT_ID:您的 Google Cloud 项目的 ID。
    • APP_ID:您要查询的 Vertex AI Search 应用的 ID。
    • QUERY:要搜索的查询文本。
    • USER_PSEUDO_ID:可选。这是一个经过假名化处理的标识符,用于跟踪搜索访问者。Google 强烈建议使用此字段,因为这有助于提升模型效果和个性化质量。您可以为此字段使用 HTTP Cookie,该 Cookie 可唯一标识单个设备上的访问者。访问者登录或退出网站时,此标识符不会发生变化。请勿为多位用户将此字段设置为相同的标识符,否则系统会合并他们的事件历史记录,从而降低模型质量。请勿在此字段中包含个人身份信息 (PII)。
    • PAGE_SIZE:搜索返回的结果数。允许的最大页面大小取决于数据类型。大于最大值的页面大小会被强制转换为最大值。

      • 采用基本索引的网站:默认 10,上限 25
      • 启用了高级索引编制的网站:默认 25,上限 50
      • 其他:默认 50,最大 100
    • OFFSET:可选。结果的起始索引。 默认值为 0。

      例如,如果偏移量为 2,页面大小为 10,并且要返回 15 条结果,则第一页会返回第 2 条到第 11 条结果。

    • ORDER_BY:可选。结果的排列顺序。

    • FILTER:可选。一个文本字段,用于使用过滤表达式过滤搜索结果。默认值为空字符串,表示不应用任何过滤条件。

      示例:color: ANY("red", "blue") AND score: IN(*, 100.0e)

      如需了解详情,请参阅过滤结构化或非结构化数据的搜索

    • BOOST_SPEC:可选。用于提升或隐藏文档的规范。值:

      • BOOST:[-1,1] 范围内的浮点数。当该值为负时,相应结果会被降级(在结果中显示在更低的位置)。当该值为正时,系统会提升结果的排名(即在结果中显示在更高的位置)。
      • CONDITION:一个文本过滤表达式,用于选择要应用该增强功能的文档。过滤条件的求值结果必须为布尔值。

      如需了解如何为结构化搜索结果提升排名,请参阅提升搜索结果排名

    • FACET_SPEC:可选。用于执行分面搜索的 facet 规范。

    • QUERY_EXPANSION_SPEC:可选。用于确定应在何种情况下进行查询展开的规范。默认值为 DISABLED

    • SPELL_CORRECTION_SPEC:可选。用于确定应在何种情况下进行拼写检查的规范。默认值为 AUTO

    • CONTENT_SEARCH_SPEC:可选。用于获取摘要、提取式回答、提取式片段和搜索摘要。仅适用于非结构化数据。有关详情,请参阅:

    • DATA_STORE_SPEC:用于搜索特定数据存储区的过滤条件。如果您的搜索应用连接到多个数据存储区,则可以使用此方法。

    • 在搜索响应中查看引导式搜索结果:

      系统会在结构化搜索和非结构化搜索的搜索响应中返回引导式搜索结果。引导式搜索结果包含根据搜索结果文档提取的属性键值对列表。这样,用户就可以使用某些属性键和值作为过滤条件来优化搜索结果。

      在此示例响应中,系统使用了绿色,通过发出将过滤字段指定为 _gs.color: ANY("green") 的新搜索请求来优化搜索结果:

      {
      "guidedSearchResult": {
        "refinementAttributes": [
          {
            "attributeKey": "_gs.color",
            "attributeValue" : "green"
          },
          {
            "attributeKey": "_gs.category",
            "attributeValue" : "shoe"
          }
        ]
      }
      }
      

C#

如需了解详情,请参阅 Vertex AI Agent Builder C# API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

using Google.Api.Gaxs="devsite-xref-link" href="https://cloud.google.com/dotnet/docs/reference/Google.Protobuf/latest/Google.Protobuf.WellKnownTypes.Api.html" track-type="exampleCode" track-nam<e="xref>Link" track-metada<ta-lang=>"DOTNET" <track-m>etadata-modifier="Google.Protobuf.WellKnownTypes" track-metadata-href="https://cloud.google.com/dotnet/docs/reference/Google.Protobuf/latest/Google.Protobuf.WellKnownTypes.Api.html">Api.Gax;
using Google.Cloud.DiscoveryEngine.V1Beta;
using Google.Protobuf.WellKnownTypes;
using System;

public sealed partial class GeneratedSearchServiceClientSnippets
{
    /// summarySnippet for Search/summary
    /// remarks
    /// This< snippet> has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/refere"nce/help/"cl"ient-confi"gu"ration#endpo"in"t.
    /// /rema"rks
    public void SearchRequestObject()
    {
        // Create client
        S"earchServ"ic"eClient se"ar"chServiceCli"en"t = Sear"chServiceClient.Create("");
        // Initialize request argument(s)
  ""      SearchRequest requ""est = new SearchRequest
        {
            ServingConfigAsServingConfigName = ServingConfigName.FromProjectLocationDataStoreServingConfig([PROJECT], [LOCATION], [DATA_STORE], [SERVING_CONFIG])"",
            BranchAsBranchName = BranchName.FromProjectLocationDataStoreBranch([PROJECT], [LOCATION], [DATA_STORE], [BRANCH]),
            Query = ,
            Offset = 0,
            Filter = ,
         ""   OrderBy = ,
            FacetSpecs =
            {
                new SearchRequest.Types.FacetSpec(),
            },
            BoostSpec = new SearchRequest.T""yp""es.BoostSpec(),
            Params = { { , new Value() }, },
            QueryExpansionSpec = new SearchRequest.Types.QueryExpansionSpec(),
            SpellCorrectionSpec = new SearchR""equest.Types.SpellCorrectionSpec(),
            UserPseudoId = ,
            ImageQuery = new SearchRequest.Types.ImageQuery(),
            SafeSearc""h = false,
            UserInfo = new UserInfo(),
            UserLabels = { { ,  }, },
            EmbeddingSpec = new SearchRequest.Types.EmbeddingSpec(),
            ContentSearchSpec = new SearchRequest.Types.ContentSearc""hSpec(),
            Rankin""gExpression = ,
            NaturalLanguageQueryUnderstandingSpec = new SearchRequest".Types.Na"tu"ralLanguag"eQ"ueryUndersta"nd"ingSpec()",
            CanonicalFilter = ,
            SearchAsYouTypeSpec = new SearchRequest.Types.SearchAsYouTypeSpec(),
            DataStoreSpecs =
            {
                new SearchRequest.Types.DataStoreSpec(),
            },
            LanguageCode = ,
            RegionCode = ,
            SessionAsSessionName = Session<Name.FromProjectLocationDataStoreSession([PROJECT>], [LOCATION], [DATA_STORE], [SESSION]),
            SessionSpec = new SearchRequest.Types.SessionSpec(),
            RelevanceThreshold = SearchRequest.Types.RelevanceThreshold.Unspecified,
            PersonalizationSpec = new SearchRequest.Types.PersonalizationSpec(),
            OneBoxPageSize = 0,
        };
        // Make the request
        PagedEnumerableSearchResponse, SearchResponse.Types.SearchResult response = searchServiceClient.Search(request);

        // Iterate over all response items, lazily performing RPCs as required
 "       foreach (Se"archResponse.Types.SearchResult item in response)
        {
            // Do something with each item
            Console.WriteLine(item);
        }

        // Or iterate over pages (of server-defined size), performing one RPC per page
        foreach (Searc'hResponse page in response.AsRawResponses())
        {
            // Do something with each p<age of items
            Console.>WriteLine(A page of results:);
            foreach (SearchResponse.Types.SearchResult item in page)
            {
   "             // Do something with each 'item
             "   Console.WriteLine(item);
            }
        }

        // Or retrieve a single page of known size (unless its the final page), performing as many RPCs as required
        int pageSize = 10;
        PageSearchResponse.Types.SearchResult singlePage = response.ReadPage(pageSize);
        // Do something with the page of items
        Console.WriteLine($A page of {pageSize} results (unless its the final page):);
        foreach (SearchResponse.Types.SearchResult item in singlePage)
        {
            // Do something with each item
            Console.WriteLine(item);
        }
        // Store the pageToken, for when the next page is required.
        string nextPageToken = singlePage.NextPageToken;
    }
}

Java

如需了解详情,请参阅 Vertex AI Agent Builder Java API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.discoveryengine.v1.SearchRequest;
import com.google.cloud.discoveryengine.v1.SearchResponse;
import com.google.cloud.discoveryengine.v1.SearchServiceClient;
import com.google.cloud.discoveryengine.v1.SearchServiceSettings;
import com.google.cloud.discoveryengine.v1.ServingConfigName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class Search {
  public static void main() throws IOException, ExecutionException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "PROJECT_ID";
    // Location of the data store. Options: "global", "us", "eu"
    String location = "global";
    // Collection containing the data store.
    String collectionId = "default_collection";
    // Data store ID.
    String dataStoreId = "DATA_STORE_ID";
    // Serving configuration. Options: "default_search"
    String servingConfigId = "default_search";
    // Search Query for the data store.
    String searchQuery = "Google";
    search(projectId, location, collectionId, dataStoreId, servingConfigId, searchQuery);
  }

  /** Performs a search on a given datastore. */
  public static void search(
      String projectId,
      String location,
      String collectionId,
      String dataStoreId,
      String servingConfigId,
      String searchQuery)
      throws IOException, ExecutionException {
    // For more information, refer to:
    // https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
    String endpoint = (location.equals("global")) 
        ? String.format("discoveryengine.googleapis.com:443", location) 
        : String.format("%s-discoveryengine.googleapis.com:443", location);
    SearchServiceSettings settings =
        SearchServiceSettings.newBuilder().setEndpoint(endpoint).build();
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `searchServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (SearchServiceClient searchServiceClient = SearchServiceClient.create(settings)) {
      SearchRequest request =
          SearchRequest.newBuilder()
              .setServingConfig(
                  ServingConfigName.formatProjectLocationCollectionDataStoreServingConfigName(
                      projectId, location, collectionId, dataStoreId, servingConfigId))
              .setQuery(searchQuery)
              .setPageSize(10)
              .build();
      SearchResponse response = searchServiceClient.search(request).getPage().getResponse();
      for (SearchResponse.SearchResult element : response.getResultsList()) {
        System.out.println("Response content: " + element);
      }
    }
  }
}

Node.js

如需了解详情,请参阅 Vertex AI Agent Builder Node.js API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'YOUR_LOCATION';              // Options: 'global', 'us', 'eu'
// const collectionId = 'default_collection';     // Options: 'default_collection'
// const dataStoreId = 'YOUR_DATA_STORE_ID'       // Create in Cloud Console
// const servingConfigId = 'default_config';      // Options: 'default_config'
// const searchQuery = 'Google';

const {SearchServiceClient} = require('@google-cloud/discoveryengine').v1beta;

// For more information, refer to:
// https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
const apiEndpoint =
  location === 'global'
    ? 'discoveryengine.googleapis.com'
    : `${location}-discoveryengine.googleapis.com`;

// Instantiates a client
const client = new SearchServiceClient({apiEndpoint: apiEndpoint});

async function search() {
  // The full resource name of the search engine serving configuration.
  // Example: projects/{projectId}/locations/{location}/collections/{collectionId}/dataStores/{dataStoreId}/servingConfigs/{servingConfigId}
  // You must create a search engine in the Cloud Console first.
  const name = client.projectLocationCollectionDataStoreServingConfigPath(
    projectId,
    location,
    collectionId,
    dataStoreId,
    servingConfigId
  );

  const request = {
    pageSize: 10,
    query: searchQuery,
    servingConfig: name,
  };

  const IResponseParams = {
    ISearchResult: 0,
    ISearchRequest: 1,
    ISearchResponse: 2,
  };

  // Perform search request
  const response = await client.search(request, {
    // Warning: Should always disable autoPaginate to avoid iterate through all pages.
    //
    // By default NodeJS SDK returns an iterable where you can iterate through all
    // search results instead of only the limited number of results requested on
    // pageSize, by sending multiple sequential search requests page-by-page while
    // iterating, until it exhausts all the search results. This will be unexpected and
    // may cause high Search API usage and long wait time, especially when the matched
    // document numbers are huge.
    autoPaginate: false,
  });
  const results = response[IResponseParams.ISearchResponse].results;

  for (const result of results) {
    console.log(result);
  }
}

PHP

如需了解详情,请参阅 Vertex AI Agent Builder PHP API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\DiscoveryEngine\V1beta\Client\SearchServiceClient;
use Google\Cloud\DiscoveryEngine\V1beta\SearchRequest;
use Google\Cloud\DiscoveryEngine\V1beta\SearchResponse\SearchResult;

/**
 * Performs a search.
 *
 * @param string $formattedServingConfig The resource name of the Search serving config, such as
 *                                       `projects/&#42;/locations/global/collections/default_collection/engines/&#42;/servingConfigs/default_serving_config`,
 *                                       or
 *                                       `projects/&#42;/locations/global/collections/default_collection/dataStores/default_data_store/servingConfigs/default_serving_config`.
 *                                       This field is used to identify the serving configuration name, set
 *                                       of models used to make the search. Please see
 *                                       {@see SearchServiceClient::servingConfigName()} for help formatting this field.
 */
function search_sample(string $formattedServingConfig): void
{
    // Create a client.
    $searchServiceClient = new SearchServiceClient();

    // Prepare the request message.
    $request = (new SearchRequest())
        ->setServingConfig($formattedServingConfig);

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $searchServiceClient->search($request);

        /** @var SearchResult $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedServingConfig = SearchServiceClient::servingConfigName(
        '[PROJECT]',
        '[LOCATION]',
        '[DATA_STORE]',
        '[SERVING_CONFIG]'
    );

    search_sample($formattedServingConfig);
}

Python

如需了解详情,请参阅 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"
# search_query = "YOUR_SEARCH_QUERY"


def search_sample(
    project_id: str,
    location: str,
    engine_id: str,
    search_query: str,
) -> discoveryengine.services.search_service.pagers.SearchPager:
    #  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.SearchServiceClient(client_options=client_options)

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

    # Optional - only supported for unstructured data: Configuration options for search.
    # Refer to the `ContentSearchSpec` reference for all supported fields:
    # https://cloud.google.com/python/docs/reference/discoveryengine/latest/google.cloud.discoveryengine_v1.types.SearchRequest.ContentSearchSpec
    content_search_spec = discoveryengine.SearchRequest.ContentSearchSpec(
        # For information about snippets, refer to:
        # https://cloud.google.com/generative-ai-app-builder/docs/snippets
        snippet_spec=discoveryengine.SearchRequest.ContentSearchSpec.SnippetSpec(
            return_snippet=True
        ),
        # For information about search summaries, refer to:
        # https://cloud.google.com/generative-ai-app-builder/docs/get-search-summaries
        summary_spec=discoveryengine.SearchRequest.ContentSearchSpec.SummarySpec(
            summary_result_count=5,
            include_citations=True,
            ignore_adversarial_query=True,
            ignore_non_summary_seeking_query=True,
            model_prompt_spec=discoveryengine.SearchRequest.ContentSearchSpec.SummarySpec.ModelPromptSpec(
                preamble="YOUR_CUSTOM_PROMPT"
            ),
            model_spec=discoveryengine.SearchRequest.ContentSearchSpec.SummarySpec.ModelSpec(
                version="stable",
            ),
        ),
    )

    # Refer to the `SearchRequest` reference for all supported fields:
    # https://cloud.google.com/python/docs/reference/discoveryengine/latest/google.cloud.discoveryengine_v1.types.SearchRequest
    request = discoveryengine.SearchRequest(
        serving_config=serving_config,
        query=search_query,
        page_size=10,
        content_search_spec=content_search_spec,
        query_expansion_spec=discoveryengine.SearchRequest.QueryExpansionSpec(
            condition=discoveryengine.SearchRequest.QueryExpansionSpec.Condition.AUTO,
        ),
        spell_correction_spec=discoveryengine.SearchRequest.SpellCorrectionSpec(
            mode=discoveryengine.SearchRequest.SpellCorrectionSpec.Mode.AUTO
        ),
        # Optional: Use fine-tuned model for this request
        # custom_fine_tuning_spec=discoveryengine.CustomFineTuningSpec(
        #     enable_search_adaptor=True
        # ),
    )

    page_result = client.search(request)

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

    return page_result

Ruby

如需了解详情,请参阅 Vertex AI Agent Builder Ruby API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/discovery_engine/v1beta"

##
# Snippet for the search call in the SearchService service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::DiscoveryEngine::V1beta::SearchService::Client#search.
#
def search
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::DiscoveryEngine::V1beta::SearchService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::DiscoveryEngine::V1beta::SearchRequest.new

  # Call the search method.
  result = client.search request

  # The returned object is of type Gapic::PagedEnumerable. You can iterate
  # over elements, and API calls will be issued to fetch pages as needed.
  result.each do |item|
    # Each element is of type ::Google::Cloud::DiscoveryEngine::V1beta::SearchResponse::SearchResult.
    p item
  end
end

对于媒体搜索,Vertex AI Agent Builder 提供两种搜索行为:

  • 用户输入搜索查询,然后按 Enter 键。这是默认行为,与在微件中搜索和搜索非媒体(通用)应用的行为相同。请参阅获取包含结构化数据或非结构化数据的应用的搜索结果

  • 用户输入每个字母后,系统都会返回新的搜索结果。这称为“边输入边搜索”,对于通过电视遥控器等不太方便的界面输入搜索查询的用户来说,这一功能尤为有用。

如需为媒体应用获取“边输入边搜索”结果,请执行以下操作:

控制台

如需使用 Google Cloud 控制台为 widget 应用启用“边输入边搜索”功能,请执行以下操作:

  1. 在 Google Cloud 控制台中,前往 Agent Builder 页面。

    Agent Builder

  2. 点击您要为其启用“边输入边搜索”功能的媒体搜索应用的名称。

  3. 点击配置

  4. 点击界面标签页。

  5. 点击启用即输即搜切换开关。

  6. 预览窗格中,开始输入查询。

    搜索结果会在每次按键后更新。

  7. 如要保留“边输入边搜索”设置,请点击保存并发布

REST

使用 dataStores.servingConfigs.search 方法获取媒体应用的搜索结果:

  1. 找到您的应用 ID。如果您已经有应用 ID,请跳至下一步。

    1. 在 Google Cloud 控制台中,前往 Agent Builder 页面。

      前往“应用”

    2. 应用页面上,找到应用的名称,然后从 ID 列中获取应用的 ID。

  2. 运行以下 curl 命令可获取“边输入边搜索”结果。

    contentSearchSpec 之外的所有字段都可以与 searchAsYouTypeSpec 字段结合使用。为清楚起见,我们已从 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:search" \
    -d '{
    "query": "QUERY",
    "searchAsYouTypeSpec": {"condition": "ENABLED"}
    }'
    

    替换以下内容:

    • PROJECT_ID:您的 Google Cloud 项目的 ID。
    • PROJECT_ID:您的 Google Cloud 项目的 ID。
    • APP_ID:您要查询的 Vertex AI Search 应用的 ID。
    • QUERY:要搜索的查询文本。

    点击此处查看 curl 命令示例。

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)"
    -H "Content-Type: application/json"
    "https://discoveryengine.googleapis.com/v1/projects/12345/locations/global/collections/default_collection/engines/my-app_4321/servingConfigs/default_search:search"
    -d '{
         "query": "midsummer night",
         "searchAsYouTypeSpec": {"condition": "ENABLED"}
        }'

后续步骤