Mendapatkan hasil penelusuran

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

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

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 AI Applications.

    Aplikasi AI

  2. Klik nama aplikasi yang ingin Anda edit.

  3. Klik Pratinjau.

  4. Buka halaman Pratinjau di konsol.

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

  6. Ketik kueri penelusuran.

    Jika Anda mengaktifkan pelengkapan otomatis, daftar saran pelengkapan otomatis akan muncul di bawah kotak penelusuran saat Anda mengetik.

  7. Tekan Enter untuk mengirimkan kueri.

    • Daftar hasil penelusuran akan muncul di bawah kotak penelusuran.
    • Setiap hasil berisi judul, cuplikan, dan URL.
    • Mengklik hasil akan membuka URL tersebut.
    • Jika Fitur LLM lanjutan diaktifkan untuk aplikasi, jawaban yang dihasilkan juga dapat muncul.

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 AI Applications.

      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 kueri.
    • 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: Default 10, Maksimum 25
      • Situs dengan pengindeksan lanjutan: Default 25, Maksimum 50
      • Lainnya: Default 50, Maksimum 100
    • OFFSET: indeks awal hasil. Nilai defaultnya adalah 0.

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

    • ORDER_BY: urutan hasil disusun. Atribut yang akan diurutkan harus memiliki interpretasi numerik—misalnya, date. Untuk mengetahui 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 Mesin Penelusuran yang Dapat Diprogram.

    • 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 Anda menggunakan ekspresi filter. Nilai defaultnya adalah string kosong. Untuk mengetahui informasi selengkapnya tentang cara menggunakan kolom filter, lihat Memfilter penelusuran situs.

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

      • BOOST: bilangan floating point dalam rentang [-1,1]. Jika nilainya negatif, hasil akan diturunkan (hasil muncul lebih rendah dalam hasil). Jika nilainya positif, hasil akan dipromosikan (muncul lebih tinggi dalam hasil).
      • CONDITION: ekspresi filter teks untuk memilih dokumen yang akan diterapkan peningkatannya. Filter harus dievaluasi ke nilai boolean. Untuk mempelajari cara meningkatkan penelusuran terstruktur, lihat Meningkatkan hasil penelusuran.
    • RESULT_MODE: menentukan apakah hasil penelusuran ditampilkan sebagai dokumen lengkap atau dalam potongan. Untuk mendapatkan potongan, penyimpanan data harus mengaktifkan pemotongan dokumen. Nilai yang diterima adalah documents dan chunks. Jika chunking diaktifkan untuk penyimpanan data, nilai defaultnya adalah chunks. Jika tidak, defaultnya adalah documents. Untuk informasi tentang pemecahan dokumen, lihat Mengurai dan memecah 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 dicari. Gunakan dataStoreSpecs jika aplikasi penelusuran Anda terhubung ke beberapa penyimpanan data, tetapi Anda menginginkan hasil dari penyimpanan data tertentu. Untuk mengetahui informasi selengkapnya, lihat DataStoreSpec.

C#

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API C# Aplikasi AI.

Untuk melakukan autentikasi ke Aplikasi AI, 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 Aplikasi AI.

Untuk melakukan autentikasi ke Aplikasi AI, 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 Aplikasi AI.

Untuk melakukan autentikasi ke Aplikasi AI, 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 Aplikasi AI.

Untuk melakukan autentikasi ke Aplikasi AI, 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 Aplikasi AI.

Untuk melakukan autentikasi ke Aplikasi AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat 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 Aplikasi AI.

Untuk melakukan autentikasi ke Aplikasi AI, 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

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 metode ini hanya dapat digunakan untuk menelusuri situs publik.

Metode searchLite sangat cocok dalam kondisi berikut:

  • Anda memiliki situs statis yang penyiapan 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 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 AI Applications.

      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 kueri.

    • QUERY: teks kueri yang akan ditelusuri.

Python

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Aplikasi AI.

Untuk melakukan autentikasi ke Aplikasi AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat 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 Google Cloud konsol atau mendapatkan hasil penelusuran menggunakan API.

Konsol

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

  1. Buka halaman Pratinjau di konsol.
  2. Ketik kueri penelusuran.

    Jika Anda mengaktifkan pelengkapan otomatis, daftar saran pelengkapan otomatis akan muncul di bawah kotak penelusuran saat Anda mengetik.

  3. (Opsional) Jika Anda menghubungkan beberapa penyimpanan data ke aplikasi, tetapi hanya ingin mendapatkan hasil dari penyimpanan data tertentu, pilih penyimpanan data untuk mendapatkan hasil.

  4. Tekan Enter untuk mengirimkan kueri.

    Daftar hasil penelusuran akan muncul di bawah kotak penelusuran.

    Untuk data terstruktur, hal berikut berlaku:

    • Jika pemetaan atribut tidak ditentukan di Konfigurasi > Konfigurasi kolom dalam hasil, hasil penelusuran akan ditampilkan sebagai daftar nama dan nilai atribut mentah.

    • Jika pemetaan atribut disimpan di Konfigurasi > Konfigurasi kolom dalam hasil, hasil penelusuran akan ditampilkan dengan cara yang sama seperti yang Anda lihat di pratinjau halaman Konfigurasi.

    • Jika ada aspek yang ditentukan di Konfigurasi > Setelan aspek, aspek tersebut akan ditampilkan dengan cara yang sama.

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 AI Applications.

      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 Google Cloud project Anda.
    • APP_ID: ID aplikasi Vertex AI Search yang ingin Anda kueri.
    • QUERY: teks kueri yang akan ditelusuri.
    • USER_PSEUDO_ID: optional. Ini adalah ID yang disamarkan 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 mengidentifikasi pengunjung secara unik 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 peristiwanya 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: Default 10, Maksimum 25
      • Situs dengan pengindeksan lanjutan: Default 25, Maksimum 50
      • Lainnya: Default 50, Maksimum 100
    • OFFSET: optional. Indeks awal hasil. Nilai defaultnya adalah 0.

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

    • ORDER_BY: optional. Urutan hasil disusun.

    • FILTER: optional. Kolom teks untuk memfilter penelusuran Anda 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 mengetahui informasi selengkapnya, lihat Memfilter penelusuran untuk data terstruktur atau tidak terstruktur.

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

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

      Untuk mempelajari cara meningkatkan penelusuran terstruktur, lihat Meningkatkan hasil penelusuran.

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

    • QUERY_EXPANSION_SPEC: optional. Spesifikasi untuk menentukan kondisi yang memungkinkan perluasan kueri terjadi. Defaultnya adalah DISABLED.

    • SPELL_CORRECTION_SPEC: optional. Spesifikasi untuk menentukan kondisi saat koreksi ejaan harus terjadi. Defaultnya adalah AUTO.

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

    • DATA_STORE_SPEC: filter untuk penyimpanan data tertentu yang akan dicari. 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 dengan menggunakan beberapa kunci dan nilai atribut sebagai filter.

      Dalam contoh respons ini, warna hijau digunakan untuk mempersempit hasil penelusuran dengan mengirimkan 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# Aplikasi AI.

Untuk melakukan autentikasi ke Aplikasi AI, 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 Aplikasi AI.

Untuk melakukan autentikasi ke Aplikasi AI, 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 Aplikasi AI.

Untuk melakukan autentikasi ke Aplikasi AI, 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 Aplikasi AI.

Untuk melakukan autentikasi ke Aplikasi AI, 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 Aplikasi AI.

Untuk melakukan autentikasi ke Aplikasi AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat 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 Aplikasi AI.

Untuk melakukan autentikasi ke Aplikasi AI, 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

Mendapatkan skor relevansi dokumen dengan hasil penelusuran

Skor relevansi dokumen didasarkan pada kemiripan kueri dengan dokumen. Skor dimasukkan ke dalam 11 bucket dalam rentang: 0, 0,1, 0,2, … hingga 1,0. Makin tinggi skornya, makin relevan dokumen tersebut.

Pertimbangkan skor relevansi dokumen untuk kasus penggunaan berikut:

  • Pemfilteran pasca-penelusuran berdasarkan skor relevansi untuk menghapus hasil yang tidak relevan

  • Peringkat pasca-penelusuran atau sebagai input ke aplikasi lain

  • Proses debug: skor relevansi dapat memberikan insight tentang alasan beberapa hasil penelusuran ditampilkan

Untuk setiap hasil penelusuran, skor relevansi dapat ditampilkan:

  "results": [
    {
      "id": "DOCUMENT_ID",
      "document": {
      ...
      },
      "modelScores": {
        "relevance_score": {
          "values": [
            DOCUMENT-RELEVANCE-SCORE
          ]
        }
      }
    },
    ...

Lihat juga contoh perintah dalam prosedur di bawah.

Sebelum memulai: Pastikan aplikasi penelusuran dikaitkan dengan penyimpanan data terstruktur atau tidak terstruktur. Artinya, skor relevansi dokumen tidak dapat ditampilkan untuk aplikasi penelusuran situs.

REST

Untuk meminta agar skor relevansi dokumen ditampilkan dengan hasil penelusuran, gunakan metode engines.servingConfigs.search sebagai berikut:

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

    1. Di konsol Google Cloud , buka halaman AI Applications.

      Buka Aplikasi

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

  2. Jalankan perintah curl berikut untuk mendapatkan skor yang ditampilkan dengan 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",
         "relevanceScoreSpec": {
           "returnRelevanceScore": true
         }
    }'
    
    • PROJECT_ID: ID Google Cloud project Anda.
    • APP_ID: ID aplikasi Vertex AI Search yang ingin Anda kueri.
    • QUERY: teks kueri yang akan ditelusuri.

Ringkasan penelusuran berbeda menurut model

Jika Anda membuat ringkasan penelusuran untuk kueri, Anda mungkin melihat bahwa ringkasan berbeda antara hasil konsol dan hasil API. Jika Anda melihat pesan ini, 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 UI (hanya didukung untuk aplikasi penelusuran lanjutan dan aplikasi layanan kesehatan).

    1. Buka halaman Konfigurasi aplikasi Anda > tab UI.
    2. Pilih Jenis Penelusuran:

      • Pilih Telusuri dengan jawaban untuk menampilkan ringkasan generatif di atas hasil penelusuran.
      • Pilih Penelusuran dengan kueri lanjutan untuk mengaktifkan penelusuran percakapan dengan ringkasan generatif dan pertanyaan lanjutan.
    3. Di bagian Model bahasa besar untuk ringkasan, pilih model.

  • Untuk panggilan metode, model stabil adalah model default. Untuk menggunakan model LLM selain model stabil, lihat Menentukan model ringkasan dan Menentukan model jawaban.

    Langkah berikutnya

  • Tambahkan widget penelusuran ke halaman web.

  • Gunakan Search API untuk menjelajahi data di aplikasi penelusuran umum Anda.