Mendapatkan hasil penelusuran

Halaman ini menunjukkan cara melihat pratinjau hasil penelusuran menggunakan konsol Google Cloud dan mendapatkan hasil penelusuran menggunakan API.

Selain itu, daripada membuat widget penelusuran untuk ditambahkan ke halaman web, Anda dapat melakukan panggilan API dan mengintegrasikan panggilan tersebut ke server atau aplikasi Anda. Halaman ini menyertakan contoh kode tentang cara membuat kueri penelusuran menggunakan library klien gRPC dengan akun layanan.

Ringkasan penelusuran berbeda-beda menurut model

Jika membuat ringkasan penelusuran untuk kueri, Anda mungkin melihat bahwa ringkasan antara hasil konsol dan hasil API berbeda. Jika Anda melihatnya, kemungkinan alasannya adalah konsol menggunakan model LLM yang berbeda dari API. Contoh curl dan kode di halaman ini menggunakan model LLM yang stabil.

  • Untuk mengubah atau melihat model LLM yang digunakan di halaman Pratinjau pada UI, buka halaman Konfigurasi > tab UI untuk aplikasi Anda.

  • Untuk panggilan metode, guna menggunakan model LLM selain model stabil, lihat Menentukan model ringkasan.

Mendapatkan hasil penelusuran untuk aplikasi dengan data situs

Konsol

Untuk menggunakan konsol Google Cloud guna melihat pratinjau hasil penelusuran untuk aplikasi dengan data situs, ikuti langkah-langkah berikut:

  1. Di konsol Google Cloud, buka halaman Agent Builder.

    Agent Builder

  2. Klik nama aplikasi yang ingin Anda edit.

  3. Klik Pratinjau.

  4. Buka halaman Preview di konsol.

  5. Opsional: Jika Anda menghubungkan beberapa penyimpanan data ke aplikasi, tetapi hanya ingin mendapatkan hasil dari penyimpanan data tertentu, pilih penyimpanan data tempat hasil akan diperoleh.

  6. Ketik kueri penelusuran.

    1. Jika mengaktifkan pelengkapan otomatis, Anda akan melihat daftar sugesti pelengkapan otomatis di bawah kotak penelusuran saat mengetik.
  7. Klik Enter untuk mengirimkan kueri.

    1. Daftar hasil penelusuran akan muncul di bawah kotak penelusuran.
    2. Setiap hasil berisi judul, cuplikan, dan URL.
    3. Mengklik hasil akan membuka URL tersebut.
  8. Klik panah di bawah daftar hasil untuk memuat halaman hasil berikutnya.

REST

Untuk menggunakan API guna mendapatkan hasil penelusuran untuk aplikasi dengan data situs, gunakan metode engines.servingConfigs.search:

  1. Temukan ID aplikasi Anda. Jika Anda sudah memiliki ID aplikasi, lanjutkan ke langkah berikutnya.

    1. Di konsol Google Cloud, buka halaman Agent Builder.

      Buka Aplikasi

    2. Di halaman Aplikasi, temukan nama aplikasi Anda dan dapatkan ID aplikasi dari kolom ID.

  2. Mendapatkan hasil penelusuran.

    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"}]
    }'
    

    Ganti kode berikut:

    • PROJECT_ID: ID Google Cloud project Anda.
    • APP_ID: ID aplikasi Vertex AI Search yang ingin Anda buat kuerinya.
    • QUERY: teks kueri yang akan ditelusuri.
    • PAGE_SIZE: jumlah hasil yang ditampilkan oleh penelusuran. Ukuran halaman maksimum yang diizinkan bergantung pada jenis data. Ukuran halaman di atas nilai maksimum akan dikonversi menjadi nilai maksimum.

      • Situs dengan pengindeksan dasar: 10 Default, 25 Maksimum
      • Situs dengan pengindeksan lanjutan: 25 Default, 50 Maksimum
      • Lainnya: Default 50, Maksimum 100
    • OFFSET: indeks awal hasil. Nilai defaultnya adalah 0.

      Misalnya, jika offset adalah 2, ukuran halaman adalah 10, dan ada 15 hasil yang akan ditampilkan, hasil 2 hingga 12 akan ditampilkan di halaman pertama.

    • ORDER_BY: urutan pengaturan hasil. Atribut yang akan diurutkan harus memiliki interpretasi numerik—misalnya, date. Untuk informasi selengkapnya, lihat Mengurutkan hasil penelusuran web.

    • USER_COUNTRY_CODE: lokasi pengguna. Pasangan nilai kunci ini adalah satu-satunya entri yang didukung untuk kolom peta params. Nilai defaultnya kosong. Untuk nilai yang dapat diterima, lihat Kode Negara dalam dokumentasi referensi JSON API Programmable Search Engine.

    • SEARCH_TYPE: jenis penelusuran yang akan dilakukan. Nilai defaultnya adalah 0 untuk penelusuran dokumen. Nilai lain yang didukung adalah 1 untuk penelusuran gambar.

    • FILTER: kolom teks untuk memfilter penelusuran menggunakan ekspresi filter. Nilai defaultnya adalah string kosong. Untuk mengetahui informasi selengkapnya tentang penggunaan kolom filter, lihat Memfilter penelusuran situs.

    • BOOST_SPEC: optional. Spesifikasi untuk meningkatkan atau menyembunyikan dokumen. Nilai:

      • BOOST: bilangan floating point dalam rentang [-1,1]. Jika nilainya negatif, hasil akan diturunkan (muncul lebih rendah dalam hasil). Jika nilainya positif, hasil akan dipromosikan (muncul lebih tinggi di hasil).
      • CONDITION: ekspresi filter teks untuk memilih dokumen yang akan diberi boost. Filter harus dievaluasi ke nilai boolean. Untuk mempelajari peningkatan untuk penelusuran terstruktur, lihat Meningkatkan hasil penelusuran.
    • RESULT_MODE: menentukan apakah hasil penelusuran ditampilkan sebagai dokumen lengkap atau dalam potongan. Untuk mendapatkan bagian, penyimpanan data harus mengaktifkan pengelompokan dokumen. Nilai yang diterima adalah documents dan chunks. Jika pengelompokan diaktifkan untuk penyimpanan data, nilai defaultnya adalah chunks. Jika tidak, defaultnya adalah documents. Untuk informasi tentang pengelompokan dokumen, lihat Mengurai dan mengelompokkan dokumen. Kolom ini dalam Pratinjau publik; untuk menggunakannya, ubah v1 menjadi v1alpha dalam perintah curl.

    • DATA_STORE_SPEC: filter untuk penyimpanan data tertentu yang akan ditelusuri. Gunakan dataStoreSpecs jika aplikasi penelusuran Anda terhubung ke beberapa penyimpanan data, tetapi Anda menginginkan hasil dari penyimpanan data tertentu.

C#

Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API C# Vertex AI Agent Builder.

Untuk melakukan autentikasi ke Vertex AI Agent Builder, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

using Google.Api.Gax;
using Google.Cloud.DiscoveryEngine.V1Beta;
using Google.Protobuf.WellKnownTypes;
using System;

public sealed partial class GeneratedSearchServiceClientSnippets
{
    /// <summary>Snippet 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/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void SearchRequestObject()
    {
        // Create client
        SearchServiceClient searchServiceClient = SearchServiceClient.Create();
        // Initialize request argument(s)
        SearchRequest request = 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.Types.BoostSpec(),
            Params = { { "", new Value() }, },
            QueryExpansionSpec = new SearchRequest.Types.QueryExpansionSpec(),
            SpellCorrectionSpec = new SearchRequest.Types.SpellCorrectionSpec(),
            UserPseudoId = "",
            ImageQuery = new SearchRequest.Types.ImageQuery(),
            SafeSearch = false,
            UserInfo = new UserInfo(),
            UserLabels = { { "", "" }, },
            EmbeddingSpec = new SearchRequest.Types.EmbeddingSpec(),
            ContentSearchSpec = new SearchRequest.Types.ContentSearchSpec(),
            RankingExpression = "",
            NaturalLanguageQueryUnderstandingSpec = new SearchRequest.Types.NaturalLanguageQueryUnderstandingSpec(),
            CanonicalFilter = "",
            SearchAsYouTypeSpec = new SearchRequest.Types.SearchAsYouTypeSpec(),
            DataStoreSpecs =
            {
                new SearchRequest.Types.DataStoreSpec(),
            },
            LanguageCode = "",
            RegionCode = "",
            SessionAsSessionName = SessionName.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
        PagedEnumerable<SearchResponse, SearchResponse.Types.SearchResult> response = searchServiceClient.Search(request);

        // Iterate over all response items, lazily performing RPCs as required
        foreach (SearchResponse.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 (SearchResponse page in response.AsRawResponses())
        {
            // Do something with each page 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 it's the final page), performing as many RPCs as required
        int pageSize = 10;
        Page<SearchResponse.Types.SearchResult> singlePage = response.ReadPage(pageSize);
        // Do something with the page of items
        Console.WriteLine($"A page of {pageSize} results (unless it's 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

Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Java Vertex AI Agent Builder.

Untuk melakukan autentikasi ke Vertex AI Agent Builder, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Node.js Vertex AI Agent Builder.

Untuk melakukan autentikasi ke Vertex AI Agent Builder, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * 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

Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API PHP Vertex AI Agent Builder.

Untuk melakukan autentikasi ke Vertex AI Agent Builder, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Python Vertex AI Agent Builder.

Untuk melakukan autentikasi ke Vertex AI Agent Builder, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Ruby Vertex AI Agent Builder.

Untuk melakukan autentikasi ke Vertex AI Agent Builder, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Mendapatkan hasil penelusuran untuk aplikasi dengan data situs (kunci API)

Jika Anda ingin mengautentikasi panggilan metode penelusuran dengan kunci API, bukan menggunakan OAuth 2.0 melalui akun layanan atau akun pengguna, ikuti prosedur ini, yang menggunakan metode searchLite. Metode searchLite memiliki fitur yang sama dengan metode search, kecuali bahwa metode ini hanya dapat digunakan untuk menelusuri situs publik.

Metode searchLite sangat cocok dalam kondisi berikut:

  • Anda memiliki situs statis yang menyiapkan OAuth 2.0 melalui akun layanan atau akun pengguna tidak praktis.

  • Anda telah bermigrasi ke Vertex AI Search dari Custom Search Site Restricted JSON API Programmable Search Engine.

  • Anda tidak ingin menggunakan widget penelusuran.

Sebelum memulai

Sebelum dapat memanggil metode servingConfigs.searchLite, Anda memerlukan kunci API. Jika Anda tidak memiliki kunci API, selesaikan langkah 1 dari Men-deploy aplikasi penelusuran (kunci API).

Prosedur

REST

Untuk menggunakan API guna mendapatkan hasil penelusuran untuk aplikasi dengan data situs publik yang diautentikasi dengan kunci API, gunakan metode engines.servingConfigs.searchLite:

  1. Temukan ID aplikasi Anda. Jika Anda sudah memiliki ID aplikasi, lanjutkan ke langkah berikutnya.

    1. Di konsol Google Cloud, buka halaman Agent Builder.

      Buka Aplikasi

    2. Di halaman Aplikasi, temukan nama aplikasi Anda dan dapatkan ID aplikasi dari kolom ID.

  2. Jalankan perintah curl berikut untuk mendapatkan hasil penelusuran:

    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",
    }'
    

    Ganti kode berikut:

    • PROJECT_ID: ID Google Cloud project Anda.

    • API_KEY: string kunci API Anda.

    • PROJECT_ID: ID Google Cloud project Anda.

    • APP_ID: ID aplikasi Vertex AI Search yang ingin Anda buat kuerinya.

    • QUERY: teks kueri yang akan ditelusuri.

Python

Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Python Vertex AI Agent Builder.

Untuk melakukan autentikasi ke Vertex AI Agent Builder, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Mendapatkan hasil penelusuran untuk aplikasi dengan data terstruktur atau tidak terstruktur

Anda dapat melihat pratinjau hasil penelusuran dari konsol Google Cloud atau mendapatkan hasil penelusuran menggunakan API.

Konsol

Untuk menggunakan konsol Google Cloud guna melihat pratinjau hasil penelusuran untuk aplikasi dengan data terstruktur atau tidak terstruktur, ikuti langkah-langkah berikut:

  1. Buka halaman Preview di konsol.
  2. Ketik kueri penelusuran.
    1. Jika Anda mengaktifkan pelengkapan otomatis di langkah 1, Anda akan melihat daftar saran pelengkapan otomatis di bawah kotak penelusuran saat mengetik.
  3. (Opsional) Jika Anda menghubungkan beberapa penyimpanan data ke aplikasi, tetapi hanya ingin mendapatkan hasil dari penyimpanan data tertentu, pilih penyimpanan data tempat hasil akan diambil.
  4. Klik Enter untuk mengirimkan kueri.
    1. Daftar hasil penelusuran akan muncul di bawah kotak penelusuran.
    2. Jika tidak ada pemetaan atribut yang ditentukan di halaman Konfigurasi, setiap hasil penelusuran akan muncul sebagai daftar nama dan nilai atribut mentah.
    3. Jika pemetaan atribut disimpan di halaman Konfigurasi, hasil penelusuran akan menampilkan gambar yang sama dengan yang Anda lihat di pratinjau halaman Konfigurasi.
  5. Jika ada aspek yang ditentukan di halaman Konfigurasi, aspek tersebut akan ditampilkan dengan cara yang sama.
  6. Klik panah di bawah daftar hasil untuk memuat halaman hasil berikutnya.

REST

Untuk menggunakan API guna mendapatkan hasil penelusuran untuk aplikasi dengan data terstruktur atau tidak terstruktur, gunakan metode engines.servingConfigs.search:

  1. Temukan ID aplikasi Anda. Jika Anda sudah memiliki ID aplikasi, lanjutkan ke langkah berikutnya.

    1. Di konsol Google Cloud, buka halaman Agent Builder.

      Buka Aplikasi

    2. Di halaman Aplikasi, temukan nama aplikasi Anda dan dapatkan ID aplikasi dari kolom ID.

  2. Mendapatkan hasil penelusuran.

    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"}],
    }'
    

    Ganti kode berikut:

    • PROJECT_ID: ID Google Cloud project Anda.
    • PROJECT_ID: ID project Google Cloud Anda.
    • APP_ID: ID aplikasi Vertex AI Search yang ingin Anda buat kuerinya.
    • QUERY: teks kueri yang akan ditelusuri.
    • USER_PSEUDO_ID: optional. Ini adalah ID pseudonim untuk melacak pengunjung penelusuran. Google sangat merekomendasikan penggunaan kolom ini, yang meningkatkan performa model dan kualitas personalisasi. Anda dapat menggunakan cookie HTTP untuk kolom ini, yang secara unik mengidentifikasi pengunjung di satu perangkat. ID ini tidak berubah saat pengunjung login atau logout dari situs. Jangan tetapkan kolom ini ke ID yang sama untuk beberapa pengguna—tindakan ini akan menggabungkan histori peristiwa mereka dan menurunkan kualitas model. Jangan sertakan informasi identitas pribadi (PII) di kolom ini.
    • PAGE_SIZE: jumlah hasil yang ditampilkan oleh penelusuran. Ukuran halaman maksimum yang diizinkan bergantung pada jenis data. Ukuran halaman di atas nilai maksimum akan dikonversi menjadi nilai maksimum.

      • Situs dengan pengindeksan dasar: 10 Default, 25 Maksimum
      • Situs dengan pengindeksan lanjutan: 25 Default, 50 Maksimum
      • Lainnya: Default 50, Maksimum 100
    • OFFSET: optional. Indeks awal hasil. Nilai defaultnya adalah 0.

      Misalnya, jika offset adalah 2, ukuran halaman adalah 10, dan ada 15 hasil yang akan ditampilkan, hasil 2 hingga 11 akan ditampilkan di halaman pertama.

    • ORDER_BY: optional. Urutan pengaturan hasil.

    • FILTER: optional. Kolom teks untuk memfilter penelusuran menggunakan ekspresi filter. Nilai defaultnya adalah string kosong, yang berarti tidak ada filter yang diterapkan.

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

      Untuk informasi selengkapnya, lihat Memfilter penelusuran untuk data terstruktur atau tidak terstruktur.

    • BOOST_SPEC: optional. Spesifikasi untuk meningkatkan atau menyembunyikan dokumen. Nilai:

      • BOOST: bilangan floating point dalam rentang [-1,1]. Jika nilainya negatif, hasil akan diturunkan (muncul lebih rendah dalam hasil). Jika nilainya positif, hasil akan dipromosikan (muncul lebih tinggi di hasil).
      • CONDITION: ekspresi filter teks untuk memilih dokumen yang akan diberi boost. Filter harus dievaluasi ke nilai boolean.

      Untuk mempelajari peningkatan untuk penelusuran terstruktur, lihat Meningkatkan hasil penelusuran.

    • FACET_SPEC: optional. Spesifikasi faset untuk melakukan penelusuran dengan faset.

    • QUERY_EXPANSION_SPEC: optional. Spesifikasi untuk menentukan kondisi perluasan kueri yang harus terjadi. Setelan defaultnya adalah DISABLED.

    • SPELL_CORRECTION_SPEC: optional. Spesifikasi untuk menentukan kondisi yang harus dipenuhi agar koreksi ejaan terjadi. Setelan defaultnya adalah AUTO.

    • CONTENT_SEARCH_SPEC: optional. Untuk mendapatkan cuplikan, jawaban ekstraktif, segmen ekstraktif, dan ringkasan penelusuran. Khusus untuk data tidak terstruktur. Untuk informasi selengkapnya, lihat:

    • DATA_STORE_SPEC: filter untuk penyimpanan data tertentu yang akan ditelusuri. Hal ini dapat digunakan jika aplikasi penelusuran Anda terhubung ke beberapa penyimpanan data.

    • Melihat hasil penelusuran terpandu dalam respons penelusuran:

      Hasil penelusuran terpandu ditampilkan dengan respons penelusuran untuk penelusuran terstruktur dan tidak terstruktur. Hasil penelusuran terpandu berisi daftar pasangan nilai kunci atribut yang diekstrak berdasarkan dokumen hasil penelusuran. Hal ini memungkinkan pengguna menyaring hasil penelusuran mereka menggunakan beberapa kunci dan nilai atribut sebagai filter.

      Dalam contoh respons ini, warna hijau digunakan untuk menyaring hasil penelusuran dengan mengeluarkan permintaan penelusuran baru dengan kolom filter yang ditentukan sebagai _gs.color: ANY("green"):

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

C#

Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API C# Vertex AI Agent Builder.

Untuk melakukan autentikasi ke Vertex AI Agent Builder, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

using Google.Api.Gax;
using Google.Cloud.DiscoveryEngine.V1Beta;
using Google.Protobuf.WellKnownTypes;
using System;

public sealed partial class GeneratedSearchServiceClientSnippets
{
    /// <summary>Snippet 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/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void SearchRequestObject()
    {
        // Create client
        SearchServiceClient searchServiceClient = SearchServiceClient.Create();
        // Initialize request argument(s)
        SearchRequest request = 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.Types.BoostSpec(),
            Params = { { "", new Value() }, },
            QueryExpansionSpec = new SearchRequest.Types.QueryExpansionSpec(),
            SpellCorrectionSpec = new SearchRequest.Types.SpellCorrectionSpec(),
            UserPseudoId = "",
            ImageQuery = new SearchRequest.Types.ImageQuery(),
            SafeSearch = false,
            UserInfo = new UserInfo(),
            UserLabels = { { "", "" }, },
            EmbeddingSpec = new SearchRequest.Types.EmbeddingSpec(),
            ContentSearchSpec = new SearchRequest.Types.ContentSearchSpec(),
            RankingExpression = "",
            NaturalLanguageQueryUnderstandingSpec = new SearchRequest.Types.NaturalLanguageQueryUnderstandingSpec(),
            CanonicalFilter = "",
            SearchAsYouTypeSpec = new SearchRequest.Types.SearchAsYouTypeSpec(),
            DataStoreSpecs =
            {
                new SearchRequest.Types.DataStoreSpec(),
            },
            LanguageCode = "",
            RegionCode = "",
            SessionAsSessionName = SessionName.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
        PagedEnumerable<SearchResponse, SearchResponse.Types.SearchResult> response = searchServiceClient.Search(request);

        // Iterate over all response items, lazily performing RPCs as required
        foreach (SearchResponse.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 (SearchResponse page in response.AsRawResponses())
        {
            // Do something with each page 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 it's the final page), performing as many RPCs as required
        int pageSize = 10;
        Page<SearchResponse.Types.SearchResult> singlePage = response.ReadPage(pageSize);
        // Do something with the page of items
        Console.WriteLine($"A page of {pageSize} results (unless it's 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

Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Java Vertex AI Agent Builder.

Untuk melakukan autentikasi ke Vertex AI Agent Builder, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Node.js Vertex AI Agent Builder.

Untuk melakukan autentikasi ke Vertex AI Agent Builder, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * 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

Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API PHP Vertex AI Agent Builder.

Untuk melakukan autentikasi ke Vertex AI Agent Builder, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Python Vertex AI Agent Builder.

Untuk melakukan autentikasi ke Vertex AI Agent Builder, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Ruby Vertex AI Agent Builder.

Untuk melakukan autentikasi ke Vertex AI Agent Builder, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Untuk penelusuran media, Vertex AI Agent Builder menawarkan dua jenis perilaku penelusuran:

  • Pengguna mengetik kueri penelusuran dan menekan enter. Ini adalah setelan default dan memiliki perilaku yang sama dengan penelusuran di widget dan penelusuran untuk aplikasi non-media (generik). Lihat Mendapatkan hasil penelusuran untuk aplikasi dengan data terstruktur atau tidak terstruktur.

  • Hasil penelusuran baru ditampilkan setelah setiap huruf yang dimasukkan pengguna. Hal ini disebut penelusuran saat mengetik dan sangat membantu bagi pengguna yang memasukkan kueri penelusuran melalui antarmuka yang lebih canggung seperti remote control untuk televisi.

Untuk mendapatkan hasil penelusuran saat mengetik untuk aplikasi media:

Konsol

Untuk menggunakan konsol Google Cloud guna mengaktifkan penelusuran saat mengetik untuk aplikasi widget:

  1. Di konsol Google Cloud, buka halaman Agent Builder.

    Agent Builder

  2. Klik nama aplikasi penelusuran media yang ingin Anda gunakan untuk penelusuran saat mengetik.

  3. Klik Configurations.

  4. Klik tab UI.

  5. Klik tombol Aktifkan telusuri-sambil-kata-diketik.

  6. Di panel Preview, mulai ketik kueri.

    Hasil penelusuran diperbarui setelah setiap penekanan tombol.

  7. Untuk mempertahankan setelan penelusuran saat mengetik, klik Simpan dan publikasikan.

REST

Gunakan metode dataStores.servingConfigs.search untuk mendapatkan hasil penelusuran untuk aplikasi media:

  1. Temukan ID aplikasi Anda. Jika Anda sudah memiliki ID aplikasi, lanjutkan ke langkah berikutnya.

    1. Di konsol Google Cloud, buka halaman Agent Builder.

      Buka Aplikasi

    2. Di halaman Aplikasi, temukan nama aplikasi Anda dan dapatkan ID aplikasi dari kolom ID.

  2. Jalankan perintah curl berikut untuk mendapatkan hasil penelusuran saat Anda mengetik.

    Semua kolom kecuali contentSearchSpec dapat digunakan bersama dengan kolom searchAsYouTypeSpec. Agar lebih jelas, kolom opsional telah dihilangkan dari perintah curl. Untuk kolom opsional, lihat Mendapatkan hasil penelusuran untuk aplikasi dengan data terstruktur atau tidak terstruktur.

    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"}
    }'
    

    Ganti kode berikut:

    • PROJECT_ID: ID Google Cloud project Anda.
    • PROJECT_ID: ID Google Cloud project Anda.
    • APP_ID: ID aplikasi Vertex AI Search yang ingin Anda buat kuerinya.
    • QUERY: teks kueri yang akan ditelusuri.

    Klik untuk melihat contoh perintah 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"}
        }'

Langkah berikutnya