Grounding the response from a text-generation model using Vertex AI Search or Google Search

This sample demonstrates how to use Vertex AI's Grounding API. Grounding lets you provide additional information to the model, such as documents or URLs, which can improve the accuracy and relevance of the generated response. This specific example showcases the use of Vertex AI Search (your data) or Google Search (web search across the Internet) as a grounding source. A grounded text response and citations are returned.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

Python

Before trying this sample, follow the Python setup instructions in the Vertex AI quickstart using client libraries. For more information, see the Vertex AI Python API reference documentation.

To authenticate to Vertex AI, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import vertexai

from vertexai.language_models import GroundingSource, TextGenerationModel

# TODO(developer): Update project_id and location
vertexai.init(project=PROJECT_ID, location="us-central1")

# TODO developer - override these parameters as needed:
parameters = {
    "temperature": 0.7,  # Temperature controls the degree of randomness in token selection.
    "max_output_tokens": 256,  # Token limit determines the maximum amount of text output.
    "top_p": 0.8,  # Tokens are selected from most probable to least until the sum of their probabilities equals the top_p value.
    "top_k": 40,  # A top_k of 1 means the selected token is the most probable among all tokens.
}

model = TextGenerationModel.from_pretrained("text-bison@002")

# TODO(developer): Update values for data_store_location, data_store_id
# data_store_id = ""
# data_store_location = ""
if data_store_id and data_store_location:
    # Use Vertex AI Search data store
    grounding_source = GroundingSource.VertexAISearch(
        data_store_id=data_store_id, location=data_store_location
    )
else:
    # Use Google Search for grounding (Private Preview)
    grounding_source = GroundingSource.WebSearch()

response = model.predict(
    "What are the price, available colors, and storage size options of a Pixel Tablet?",
    grounding_source=grounding_source,
    **parameters,
)
print(f"Response from Model: {response.text}")
print(f"Grounding Metadata: {response.grounding_metadata}")

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.