AI Applications client libraries Stay organized with collections Save and categorize content based on your preferences.
This page shows how to get started with the Cloud Client Libraries for theAI Applications API. Client libraries make it easier to accessGoogle Cloud APIs from a supported language. Although you can useGoogle Cloud APIs directly by making raw requests to the server, clientlibraries provide simplifications that significantly reduce the amount of codeyou need to write.
Read more about the Cloud Client Librariesand the older Google API Client Libraries inClient libraries explained.
Important: AI Applications uses the Discovery Engine API and client libraries.Install the client library
C#
Install-Package Google.Cloud.DiscoveryEngine.V1Beta -Pre
For more information, seeSetting Up a C# Development Environment.
Java
If you are usingMaven, addthe following to yourpom.xml
file. For more information aboutBOMs, seeThe Google Cloud Platform Libraries BOM.
<dependencyManagement><dependencies><dependency><groupId>com.google.cloud</groupId><artifactId>libraries-bom</artifactId><version>26.61.0</version><type>pom</type><scope>import</scope></dependency> </dependencies></dependencyManagement><dependencies> <dependency> <groupId>com.google.cloud</groupId><artifactId>google-cloud-discoveryengine</artifactId></dependency></dependencies>
If you are usingGradle,add the following to your dependencies:
implementation'com.google.cloud:google-cloud-discoveryengine:0.63.0'
If you are usingsbt, addthe following to your dependencies:
libraryDependencies+="com.google.cloud"%"google-cloud-discoveryengine"%"0.63.0"
If you're using Visual Studio Code, IntelliJ, or Eclipse, you can add client libraries to your project using the following IDE plugins:
The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.
Note: Cloud Java client libraries do not currently support Android.For more information, seeSetting Up a Java Development Environment.
Node.js
npm install @google-cloud/discoveryengine
For more information, seeSetting Up a Node.js Development Environment.
PHP
composer require google/cloud-discoveryengine
For more information, seeUsing PHP on Google Cloud.
Python
pip install --upgrade google-cloud-discoveryengine
For more information, seeSetting Up a Python Development Environment.
Ruby
gem install google-cloud-discovery_engine-v1beta
For more information, seeSetting Up a Ruby Development Environment.
Set up authentication
To authenticate calls to Google Cloud APIs, client libraries supportApplication Default Credentials (ADC);the libraries look for credentials in a set of defined locations and use those credentialsto authenticate requests to the API. With ADC, you can makecredentials available to your application in a variety of environments, such as localdevelopment or production, without needing to modify your application code.For production environments, the way you set up ADC depends on the serviceand context. For more information, seeSet up Application Default Credentials.
For a local development environment, you can set up ADC with the credentialsthat are associated with your Google Account:
Afterinstalling the Google Cloud CLI,initialize it by running the following command:
gcloudinit
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
A sign-in screen appears. After you sign in, your credentials are stored in the local credential file used by ADC.
Use the client library
The following example shows how to use the client library.
C#
usingGoogle.Api.Gax;usingGoogle.Cloud.DiscoveryEngine.V1Beta;usingGoogle.Protobuf.WellKnownTypes;usingSystem;publicsealedpartialclassGeneratedSearchServiceClientSnippets{/// <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>publicvoidSearchRequestObject(){// Create clientSearchServiceClientsearchServiceClient=SearchServiceClient.Create();// Initialize request argument(s)SearchRequestrequest=newSearchRequest{ServingConfigAsServingConfigName=ServingConfigName.FromProjectLocationDataStoreServingConfig("[PROJECT]","[LOCATION]","[DATA_STORE]","[SERVING_CONFIG]"),BranchAsBranchName=BranchName.FromProjectLocationDataStoreBranch("[PROJECT]","[LOCATION]","[DATA_STORE]","[BRANCH]"),Query="",Offset=0,Filter="",OrderBy="",FacetSpecs={newSearchRequest.Types.FacetSpec(),},BoostSpec=newSearchRequest.Types.BoostSpec(),Params={{"",newValue()},},QueryExpansionSpec=newSearchRequest.Types.QueryExpansionSpec(),SpellCorrectionSpec=newSearchRequest.Types.SpellCorrectionSpec(),UserPseudoId="",ImageQuery=newSearchRequest.Types.ImageQuery(),SafeSearch=false,UserInfo=newUserInfo(),UserLabels={{"",""},},EmbeddingSpec=newSearchRequest.Types.EmbeddingSpec(),ContentSearchSpec=newSearchRequest.Types.ContentSearchSpec(),RankingExpression="",NaturalLanguageQueryUnderstandingSpec=newSearchRequest.Types.NaturalLanguageQueryUnderstandingSpec(),CanonicalFilter="",SearchAsYouTypeSpec=newSearchRequest.Types.SearchAsYouTypeSpec(),DataStoreSpecs={newSearchRequest.Types.DataStoreSpec(),},LanguageCode="",RegionCode="",SessionAsSessionName=SessionName.FromProjectLocationDataStoreSession("[PROJECT]","[LOCATION]","[DATA_STORE]","[SESSION]"),SessionSpec=newSearchRequest.Types.SessionSpec(),RelevanceThreshold=SearchRequest.Types.RelevanceThreshold.Unspecified,PersonalizationSpec=newSearchRequest.Types.PersonalizationSpec(),OneBoxPageSize=0,};// Make the requestPagedEnumerable<SearchResponse,SearchResponse.Types.SearchResult>response=searchServiceClient.Search(request);// Iterate over all response items, lazily performing RPCs as requiredforeach(SearchResponse.Types.SearchResultiteminresponse){// Do something with each itemConsole.WriteLine(item);}// Or iterate over pages (of server-defined size), performing one RPC per pageforeach(SearchResponsepageinresponse.AsRawResponses()){// Do something with each page of itemsConsole.WriteLine("A page of results:");foreach(SearchResponse.Types.SearchResultiteminpage){// Do something with each itemConsole.WriteLine(item);}}// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as requiredintpageSize=10;Page<SearchResponse.Types.SearchResult>singlePage=response.ReadPage(pageSize);// Do something with the page of itemsConsole.WriteLine($"A page of {pageSize} results (unless it's the final page):");foreach(SearchResponse.Types.SearchResultiteminsinglePage){// Do something with each itemConsole.WriteLine(item);}// Store the pageToken, for when the next page is required.stringnextPageToken=singlePage.NextPageToken;}}
Java
importcom.google.cloud.discoveryengine.v1.SearchRequest;importcom.google.cloud.discoveryengine.v1.SearchResponse;importcom.google.cloud.discoveryengine.v1.SearchServiceClient;importcom.google.cloud.discoveryengine.v1.SearchServiceSettings;importcom.google.cloud.discoveryengine.v1.ServingConfigName;importjava.io.IOException;importjava.util.concurrent.ExecutionException;publicclassSearch{publicstaticvoidmain()throwsIOException,ExecutionException{// TODO(developer): Replace these variables before running the sample.// Project ID or project number of the Cloud project you want to use.StringprojectId="PROJECT_ID";// Location of the data store. Options: "global", "us", "eu"Stringlocation="global";// Collection containing the data store.StringcollectionId="default_collection";// Data store ID.StringdataStoreId="DATA_STORE_ID";// Serving configuration. Options: "default_search"StringservingConfigId="default_search";// Search Query for the data store.StringsearchQuery="Google";search(projectId,location,collectionId,dataStoreId,servingConfigId,searchQuery);}/** Performs a search on a given datastore. */publicstaticvoidsearch(StringprojectId,Stringlocation,StringcollectionId,StringdataStoreId,StringservingConfigId,StringsearchQuery)throwsIOException,ExecutionException{// For more information, refer to:// https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_storeStringendpoint=(location.equals("global"))?String.format("discoveryengine.googleapis.com:443",location):String.format("%s-discoveryengine.googleapis.com:443",location);SearchServiceSettingssettings=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(SearchServiceClientsearchServiceClient=SearchServiceClient.create(settings)){SearchRequestrequest=SearchRequest.newBuilder().setServingConfig(ServingConfigName.formatProjectLocationCollectionDataStoreServingConfigName(projectId,location,collectionId,dataStoreId,servingConfigId)).setQuery(searchQuery).setPageSize(10).build();SearchResponseresponse=searchServiceClient.search(request).getPage().getResponse();for(SearchResponse.SearchResultelement:response.getResultsList()){System.out.println("Response content: "+element);}}}}
Node.js
/** * 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_storeconstapiEndpoint=location==='global'?'discoveryengine.googleapis.com':`${location}-discoveryengine.googleapis.com`;// Instantiates a clientconstclient=newSearchServiceClient({apiEndpoint:apiEndpoint});asyncfunctionsearch(){// 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.constname=client.projectLocationCollectionDataStoreServingConfigPath(projectId,location,collectionId,dataStoreId,servingConfigId);constrequest={pageSize:10,query:searchQuery,servingConfig:name,};constIResponseParams={ISearchResult:0,ISearchRequest:1,ISearchResponse:2,};// Perform search requestconstresponse=awaitclient.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,});constresults=response[IResponseParams.ISearchResponse].results;for(constresultofresults){console.log(result);}}
PHP
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/*/locations/global/collections/default_collection/engines/*/servingConfigs/default_serving_config`, * or * `projects/*/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
fromgoogle.api_core.client_optionsimportClientOptionsfromgoogle.cloudimportdiscoveryengine_v1asdiscoveryengine# 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"defsearch_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_storeclient_options=(ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")iflocation!="global"elseNone)# Create a clientclient=discoveryengine.SearchServiceClient(client_options=client_options)# The full resource name of the search app serving configserving_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.ContentSearchSpeccontent_search_spec=discoveryengine.SearchRequest.ContentSearchSpec(# For information about snippets, refer to:# https://cloud.google.com/generative-ai-app-builder/docs/snippetssnippet_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-summariessummary_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.SearchRequestrequest=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 responseforresponseinpage_result:print(response)returnpage_result
Ruby
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.#defsearch# 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.searchrequest# 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.eachdo|item|# Each element is of type ::Google::Cloud::DiscoveryEngine::V1beta::SearchResponse::SearchResult.pitemendend
Additional resources
C#
The following list contains links to more resources related to theclient library for C#:
Java
The following list contains links to more resources related to theclient library for Java:
Node.js
The following list contains links to more resources related to theclient library for Node.js:
PHP
The following list contains links to more resources related to theclient library for PHP:
Python
The following list contains links to more resources related to theclient library for Python:
Ruby
The following list contains links to more resources related to theclient library for Ruby:
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-07-16 UTC.