In your web app, you can get answers to your questions in the form of streaming responses. This document shows you how to use the REST API to get answers. If you want to use the Gemini Enterprise web app, see Chat with the assistant.
StreamAssist overview
StreamAssist provides a powerful, interactive way to handle user
queries. It operates in a streaming fashion, enabling real-time, back-and-forth
interactions.
The key capabilities of the API include the following:
Maintaining conversational context: it uses sessions to maintain conversational context, ensuring it understands follow-up queries within the scope of previous interactions.
Incorporating provided files: it includes the attached files as context for more informed and relevant responses.
Seamless integration: it integrates with various agents and tools to fulfill a wide range of user requests.
Before you begin
Ensure that you have the following:
The Discovery Engine API enabled for your Google Cloud. You can enable it on the Discovery Engine API page in the Google Cloud console.
The Discovery Engine User (
roles/discoveryengine.user) or Gemini Enterprise User (roles/discoveryengine.agentspaceUser, which includesroles/discoveryengine.user) Identity and Access Management (IAM) role granted to the calling user or workload principal. Alternatively, grant a custom role that includesdiscoveryengine.assistants.assist(anddiscoveryengine.servingConfigs.searchif the app searches attached data stores). If callers using a custom role send theX-Goog-User-Projectheader (for example, with ADC or federated credentials), also includeserviceusage.services.useon the quota project—or grant the Service Usage Consumer role (roles/serviceusage.serviceUsageConsumer)—to avoid403 USER_PROJECT_DENIED.An active Gemini Enterprise license assigned to each human end user (or automatic license assignment enabled for your app). For more information, see Gemini Enterprise licenses.
An existing Gemini Enterprise app. To create an app, see Create an app.
Authenticate end users and workloads for custom UIs
When you call StreamAssist from a custom web application or backend service,
the bearer token in the Authorization header determines the identity that
Gemini Enterprise uses to check licenses, enforce per-user document access
control lists (ACLs), and evaluate agent sharing permissions.
Choose the authentication pattern that matches your caller identity:
| Caller type | Authentication flow | Per-user ACLs and licenses |
|---|---|---|
| Human end users (Google Identity) | Sign the user in through Google OAuth 2.0 with the
https://www.googleapis.com/auth/cloud-platform scope, and
pass the user's OAuth 2.0 access token in the
Authorization: Bearer header. |
Enforced for the signed-in Google user. |
| Human end users (Workforce Identity Federation) |
Sign the user in to your external identity provider (IdP), such as
Microsoft Entra ID, Okta, or Ping Identity. Exchange the user's OIDC or
SAML token at the
Security Token Service
(STS) for a federated access token using a
workforce identity
pool (workforcePools). Pass the federated token in the
Authorization: Bearer header.
|
Enforced for the federated workforce user. |
| Non-human services and bots (Workload Identity Federation) |
Exchange a workload credential at STS using a
workload identity
pool (workloadIdentityPools). Pass the STS access token
in the Authorization: Bearer header.
|
Not per-user. Uses the shared workload principal and doesn't enforce individual end-user ACLs or licenses. |
To call StreamAssist on behalf of a federated workforce user, exchange the
user's external IdP token at STS and pass the resulting access token with the
X-Goog-User-Project header:
REST
# 1. Exchange the external IdP OIDC token for a federated Google access token
STS_TOKEN=$(curl -s -X POST "https://sts.googleapis.com/v1/token" \
-H "Content-Type: application/json" \
-d '{
"audience": "//iam.googleapis.com/locations/global/workforcePools/WORKFORCE_POOL_ID/providers/PROVIDER_ID",
"grantType": "urn:ietf:params:oauth:grant-type:token-exchange",
"requestedTokenType": "urn:ietf:params:oauth:token-type:access_token",
"scope": "https://www.googleapis.com/auth/cloud-platform",
"subjectTokenType": "urn:ietf:params:oauth:token-type:id_token",
"subjectToken": "EXTERNAL_IDP_TOKEN"
}' | python3 -c "import sys, json; print(json.load(sys.stdin)['access_token'])")
# 2. Call StreamAssist with the federated access token
curl -X POST \
-H "Authorization: Bearer ${STS_TOKEN}" \
-H "Content-Type: application/json" \
-H "X-Goog-User-Project: PROJECT_ID" \
"https://ENDPOINT_LOCATION-discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/collections/default_collection/engines/APP_ID/assistants/default_assistant:streamAssist" \
-d '{
"query": {
"text": "QUERY_TEXT"
}
}'
Replace the following:
- WORKFORCE_POOL_ID: the ID of your workforce identity pool.
Workforce identity pools are global IAM resources, so the
audiencepath always useslocations/globalregardless of your Gemini Enterprise app location (global,us, oreu). - PROVIDER_ID: the ID of your workforce identity pool provider.
- EXTERNAL_IDP_TOKEN: the end user's OIDC ID token issued by your
external IdP. For SAML assertions, set
subjectTokenTypetourn:ietf:params:oauth:token-type:saml2. - PROJECT_ID: the ID of your Google Cloud project.
- ENDPOINT_LOCATION: the multi-region for your API request. Specify one of the following
values:
usfor the US multi-regioneufor the EU multi-regionglobalfor the Global location
- LOCATION: the multi-region of your data store:
global,us, oreu. - APP_ID: the unique identifier for the Gemini Enterprise app.
- QUERY_TEXT: the search query text.
Python
Before trying this sample, follow the Python setup instructions in the Gemini Enterprise quickstart using client libraries. For more information, see the Gemini Enterprise Python API reference documentation.
To authenticate to Gemini Enterprise, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
import requests
# Replace these placeholder values with your project, app, and pool details.
project_id = "YOUR_PROJECT_ID"
location = "YOUR_LOCATION" # "global", "us", or "eu"
engine_id = "YOUR_APP_ID"
workforce_pool_id = "YOUR_WORKFORCE_POOL_ID"
provider_id = "YOUR_PROVIDER_ID"
external_idp_token = "EXTERNAL_IDP_OIDC_TOKEN"
query = "What is Gemini Enterprise?"
def stream_assist_with_workforce_identity(
project_id: str,
location: str,
engine_id: str,
workforce_pool_id: str,
provider_id: str,
external_idp_token: str,
query: str,
):
# 1. Exchange the external IdP token at Google Cloud STS.
sts_response = requests.post(
"https://sts.googleapis.com/v1/token",
json={
"audience": (
f"//iam.googleapis.com/locations/global/"
f"workforcePools/{workforce_pool_id}/providers/{provider_id}"
),
"grantType": "urn:ietf:params:oauth:grant-type:token-exchange",
"requestedTokenType": "urn:ietf:params:oauth:token-type:access_token",
"scope": "https://www.googleapis.com/auth/cloud-platform",
"subjectTokenType": "urn:ietf:params:oauth:token-type:id_token",
"subjectToken": external_idp_token,
},
timeout=30,
)
sts_response.raise_for_status()
federated_access_token = sts_response.json()["access_token"]
# 2. Call StreamAssist with the federated access token.
host = (
"discoveryengine.googleapis.com"
if location == "global"
else f"{location}-discoveryengine.googleapis.com"
)
endpoint = (
f"https://{host}/v1/projects/{project_id}/locations/{location}/"
f"collections/default_collection/engines/{engine_id}/"
"assistants/default_assistant:streamAssist"
)
response = requests.post(
endpoint,
headers={
"Authorization": f"Bearer {federated_access_token}",
"Content-Type": "application/json",
"X-Goog-User-Project": project_id,
},
json={"query": {"text": query}},
timeout=90,
)
response.raise_for_status()
print(response.json())
Get search results
You can use the streamAssist
method to query and get answers from
Gemini Enterprise. The following curl command lists the mandatory fields.
REST
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://ENDPOINT_LOCATION-discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/collections/default_collection/engines/APP_ID/assistants/default_assistant:streamAssist" \
-d '
{
"query": {
"text": "QUERY_TEXT_1"
}
}'
Replace the following:
- ENDPOINT_LOCATION: the multi-region for your API request. Specify one of the following
values:
usfor the US multi-regioneufor the EU multi-regionglobalfor the Global location
- PROJECT_ID: the ID of your Google Cloud project.
- APP_ID: the unique identifier for the Gemini Enterprise app.
- LOCATION: the multi-region of your data store:
global,us, oreu - QUERY_TEXT_1: the search query text.
For more information on the fields and what is returned, see Response body.
Python
Before trying this sample, follow the Python setup instructions in the Gemini Enterprise quickstart using client libraries. For more information, see the Gemini Enterprise Python API reference documentation.
To authenticate to Gemini Enterprise, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine_v1 as discoveryengine
# TODO(developer): Update these variables before running the sample.
project_id = "YOUR_PROJECT_ID"
location = "YOUR_LOCATION"
engine_id = "YOUR_APP_ID"
query = "What is Gemini Enterprise?"
def stream_assist_sample(
project_id: str,
location: str,
engine_id: str,
query: str,
):
# For more information, refer to:
# https://docs.cloud.google.com/gemini/enterprise/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
)
client = discoveryengine.AssistantServiceClient(client_options=client_options)
request = discoveryengine.StreamAssistRequest(
name=client.assistant_path(
project=project_id,
location=location,
collection="default_collection",
engine=engine_id,
assistant="default_assistant",
),
query=discoveryengine.Query(text=query),
)
# Make the request
stream = client.stream_assist(request=request)
# Handle the response
for response in stream:
print(response)
Get search results using the same session
To continue a conversation and get answers from Gemini Enterprise within an
existing session, use the
streamAssist method. The following
code sample shows the mandatory fields:
REST
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://ENDPOINT_LOCATION-discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/collections/default_collection/engines/APP_ID/assistants/default_assistant:streamAssist" \
-d '
{
"session": "projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions/SESSION_ID",
"query": {
"text": "QUERY_TEXT_2"
}
}'
Replace the following:
- ENDPOINT_LOCATION: the multi-region for your API request. Specify one of the following
values:
usfor the US multi-regioneufor the EU multi-regionglobalfor the Global location
- PROJECT_ID: the ID of your Google Cloud project.
- APP_ID: the unique identifier for the Gemini Enterprise app.
- LOCATION: the multi-region of your data store:
global,us, oreu - QUERY_TEXT_2: the search query text.
- SESSION_ID: the ID of a session from a previous conversation or query.
For more information on the fields and what is returned, see Response body.
Python
Before trying this sample, follow the Python setup instructions in the Gemini Enterprise quickstart using client libraries. For more information, see the Gemini Enterprise Python API reference documentation.
To authenticate to Gemini Enterprise, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine_v1 as discoveryengine
# TODO(developer): Update these variables before running the sample.
project_id = "YOUR_PROJECT_ID"
location = "YOUR_LOCATION"
engine_id = "YOUR_APP_ID"
session = "projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions/SESSION_ID" # From previous session
query = "What is Gemini Enterprise?"
def stream_assist_session_sample(
project_id: str,
location: str,
engine_id: str,
session: str,
query: str,
):
# For more information, refer to:
# https://docs.cloud.google.com/gemini/enterprise/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
)
client = discoveryengine.AssistantServiceClient(client_options=client_options)
request = discoveryengine.StreamAssistRequest(
name=client.assistant_path(
project=project_id,
location=location,
collection="default_collection",
engine=engine_id,
assistant="default_assistant",
),
session=session,
query=discoveryengine.Query(text=query),
)
# Make the request
stream = client.stream_assist(request=request)
# Handle the response
for response in stream:
print(response.answer)
# Get Session ID
print(response.session_info.session)
Ground answers on specific data stores or connectors
When your Gemini Enterprise app has multiple data stores or connected data
sources attached, you can restrict a StreamAssist request to a specific subset
of data stores by passing toolsSpec.vertexAiSearchSpec.dataStoreSpecs.
Gemini Enterprise searches only the specified data stores and enforces
per-user ACLs for the authenticated caller.
REST
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-H "X-Goog-User-Project: PROJECT_ID" \
"https://ENDPOINT_LOCATION-discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/collections/default_collection/engines/APP_ID/assistants/default_assistant:streamAssist" \
-d '{
"query": {
"text": "QUERY_TEXT"
},
"toolsSpec": {
"vertexAiSearchSpec": {
"dataStoreSpecs": [
{
"dataStore": "projects/PROJECT_NUMBER/locations/LOCATION/collections/COLLECTION_ID/dataStores/DATA_STORE_ID"
}
]
}
}
}'
Replace the following:
- ENDPOINT_LOCATION: the multi-region for your API request. Specify one of the following
values:
usfor the US multi-regioneufor the EU multi-regionglobalfor the Global location
- PROJECT_ID: the ID of your Google Cloud project.
- PROJECT_NUMBER: the number of your Google Cloud project. The
dataStoreresource path requires the numeric project number and doesn't accept a project ID. - LOCATION: the multi-region of your data store:
global,us, oreu. - APP_ID: the unique identifier for the Gemini Enterprise app.
- COLLECTION_ID: the ID of the collection containing the data store
(use
default_collectionfor standard data stores, or the connector collection ID for connected data sources). - DATA_STORE_ID: the ID of the data store to search.
- QUERY_TEXT: the search query text.
Python
Before trying this sample, follow the Python setup instructions in the Gemini Enterprise quickstart using client libraries. For more information, see the Gemini Enterprise Python API reference documentation.
To authenticate to Gemini Enterprise, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine_v1 as discoveryengine
# Replace these placeholder values with your project, app, and data store details.
project_id = "YOUR_PROJECT_ID"
project_number = "YOUR_PROJECT_NUMBER" # Numeric project number required by dataStore
location = "YOUR_LOCATION"
engine_id = "YOUR_APP_ID"
collection_id = "YOUR_COLLECTION_ID"
data_store_id = "YOUR_DATA_STORE_ID"
query = "Summarize my latest project notes."
def stream_assist_scoped_data_store_sample(
project_id: str,
project_number: str,
location: str,
engine_id: str,
collection_id: str,
data_store_id: str,
query: str,
):
client_options = (
ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
if location != "global"
else None
)
client = discoveryengine.AssistantServiceClient(client_options=client_options)
data_store_name = (
f"projects/{project_number}/locations/{location}/"
f"collections/{collection_id}/dataStores/{data_store_id}"
)
request = discoveryengine.StreamAssistRequest(
name=client.assistant_path(
project=project_id,
location=location,
collection="default_collection",
engine=engine_id,
assistant="default_assistant",
),
query=discoveryengine.Query(text=query),
tools_spec=discoveryengine.StreamAssistRequest.ToolsSpec(
vertex_ai_search_spec=discoveryengine.StreamAssistRequest.ToolsSpec.VertexAiSearchSpec(
data_store_specs=[
discoveryengine.SearchRequest.DataStoreSpec(
data_store=data_store_name
)
]
)
),
)
for response in client.stream_assist(request=request):
print(response)
Upload a file and get search results (Preview)
To give the assistant more context, upload a file to a session and then query its content. Follow these steps:
Upload a file to a session using the
addContextFilemethod.REST
curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ "https://ENDPOINT_LOCATION-discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/collections/default_collection/engines/APP_ID/sessions/SESSION_ID:addContextFile" \ -d ' { "fileName": "FILE_NAME", "mimeType": "MIME_TYPE", "fileContents": "BASE64_ENCODED_FILE" }'Replace the following:
- ENDPOINT_LOCATION: the multi-region for your API request. Specify one of the following
values:
usfor the US multi-regioneufor the EU multi-regionglobalfor the Global location
- PROJECT_ID: the ID of your Google Cloud project.
- LOCATION: the multi-region of your data store:
global,us, oreu - APP_ID: the unique identifier for the Gemini Enterprise app.
- SESSION_ID: the ID of a session from a previous conversation or query.
- FILE_NAME: the name of the file.
- MIME_TYPE: the MIME type of the file, for example,
text/plainorapplication/pdf. For more information on the different media types, see Media Types. - BASE64_ENCODED_FILE: the base64-encoded representation of the file.
For more information on the fields and what is returned, see Response body.
- ENDPOINT_LOCATION: the multi-region for your API request. Specify one of the following
values:
Use the same session to ask a question about the file you uploaded using the
streamAssistmethod.REST
curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ "https://ENDPOINT_LOCATION-discoveryengine.googleapis.com/v1alpha/projects/PROJECT_ID/locations/LOCATION/collections/default_collection/engines/APP_ID/assistants/default_assistant:streamAssist" \ -d ' { "session": "projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions/SESSION_ID", "fileIds": ["FILE_ID"], "query": { "text": "QUERY_TEXT_3" } }'Replace the following:
- ENDPOINT_LOCATION: the multi-region for your API request. Specify one of the following
values:
usfor the US multi-regioneufor the EU multi-regionglobalfor the Global location
- PROJECT_ID: the ID of your Google Cloud project.
- APP_ID: the unique identifier for the Gemini Enterprise app.
- LOCATION: the multi-region of your data store:
global,us, oreu - QUERY_TEXT_3: the search query text.
- SESSION_ID: the ID of a session from a previous conversation or query.
- FILE_ID: the ID of the file you uploaded to the assistant.
For more information on the fields and what is returned, see Response body.
- ENDPOINT_LOCATION: the multi-region for your API request. Specify one of the following
values: