Generate grounded answers with RAG

As part of your Retrieval Augmented Generation (RAG) experience in Vertex AI Agent Builder, you can generate grounded answers to prompts based on the following grounding sources:

  • Google Search: Use Grounding with Google Search if you want to connect the model with world knowledge, a wide range of topics, or up-to-date information on the internet. Grounding with Google Search supports dynamic retrieval that gives you the option to generate Grounded Results with Google Search only when necessary. Therefore, the dynamic retrieval configuration evaluates whether a prompt requires knowledge about recent events and enables Grounding with Google Search. For more information, see Dynamic retrieval.
  • Inline text: Use grounding with inline text to ground the answer in pieces of text called fact text that are provided in the request. A fact text is a user-provided statement that is considered to be factual for a given request. The model doesn't check the authenticity of the fact text.
  • Vertex AI Search data stores: Use grounding with Vertex AI Search if you want to connect the model to your enterprise documents from Vertex AI Search data stores.

This page describes how to generate grounded answers based on these grounding sources using the following approaches:

Additionally, you can choose to stream the answers from the model. Generating a grounded answer by streaming is an Experimental feature.

You can use other methods to generate grounded answers, to suit your application. For more information, see Vertex AI APIs for building search and RAG experiences.

Terminology

Before you use the grounded answer generation method, it helps to understand the inputs and outputs, how to structure your request, and RAG-related terminology.

RAG terms

RAG is a methodology that enables Large Language Models (LLMs) to generate responses that are grounded to your data source of choice. There are two stages in RAG:

  1. Retrieval: Getting the most relevant facts quickly can be a common search problem. With RAG, you can quickly retrieve the facts that are important to generate an answer.
  2. Generation: The retrieved facts are used by the LLM to generate a grounded response.

Therefore, the grounded answer generation method retrieves the facts from the grounding source and generates a grounded answer.

Input data

The grounded answer generation method requires the following inputs in the request:

  • Role: The sender of a given text that's either a user (user) or a model (model).

  • Text: When the role is user, the text is a prompt and when the role is model, the text is a grounded answer. How you specify the role and text in a request is determined as follows:

    • For a single-turn answer generation, the user sends the prompt text in the request and the model sends the answer text in the response.
    • For a multi-turn answer generation, the request contains the prompt-answer pair for all the previous turns and the prompt text from the user for the current turn. Therefore, in such a request, the role is user for a prompt text and it is model for the answer text.
  • System instruction: A preamble to your prompt that governs the behavior of the model and modifies the output accordingly. For example, you can add a persona to the generated answer or instruct the model to format the output text a certain way. For multi-turn answer generation, you must provide the system instructions for every turn. For more information, see Use system instructions.

  • Grounding source: The source in which the answer is grounded and can be one or more of the following:

    • Google Search: Ground the answers with Google Search results. When the grounding source is Google Search, you can specify a dynamic retrieval configuration with a dynamic retrieval threshold. For more information, see Dynamic retrieval.

    • Inline text: Ground the answer in fact text that is provided in the request. A fact text is a user-provided statement that is considered to be factual for a given request. The model doesn't check the authenticity of the fact text. You can provide a maximum of 100 fact texts in each inline text source. The fact texts can be supported using meta attributes, such as title, author and URI. These meta attributes are returned in the response when quoting the chunks that support the answer.

    • Vertex AI Search data stores: Ground the answer in the documents from Vertex AI Search data stores. You can't specify a website search data store as the grounding source.

    In a given request, you can provide both an inline text source and a Vertex AI Search data store source. You can't combine Google Search with either of these sources. Therefore, if you want to ground your answers with Google Search results, you must send a separate request specifying Google Search as the only grounding source.

    You can provide a maximum of 10 grounding sources in any order. For example, suppose that you provide the grounding sources with the following count, in the following order to obtain a total of 10 grounding sources:

    • Three inline text sources, each of which can contain a maximum of 100 fact texts
    • Six Vertex AI Search data stores
    • Four inline text sources, each of which can contain a maximum of 100 fact texts

    Each source is assigned an index in the order in which it is specified in the request. For example, if you have specified a combination of sources in your request, then the source index is assigned as illustrated in the following table:

    Grounding source Index
    Inline text #1 0
    Inline text #2 1
    Vertex AI Search data store #1 2
    Inline text #3 3
    Vertex AI Search data store #2 4

    This index is cited in the response and is helpful when tracing the provenance.

  • Generation specifications: The specifications for model configuration that consist of the following information:

    • Model ID: Specifies the Vertex AI Gemini model to use for answer generation. For a list of models that you can use to generate grounded answers, see Supported models.
    • Model parameters: Specify the parameters that you can set for the model that you choose to use. These parameters are: language, temperature, top-P, and top-K. For details about these parameters, see Gemini model parameters.

Output data

The response that the model generates is called a candidate and it contains the following data. Not all fields might be present in the output.

  • Role: The sender of the grounded answer. The response always contains the grounded answer text. Therefore, the role in a response is always a model.

  • Text: A grounded answer.

  • Grounding score: A float value in the range [0, 1] that indicates how well an answer is grounded in the given sources.

  • Grounding metadata: Metadata about the grounding source. Grounding metadata contains the following information:

    • Support chunks: A list of chunks that support the answer. Each support chunk is assigned a support chunk index that is helpful when tracing the provenance. Each support chunk contains the following:

      • Chunk text: A portion of text quoted verbatim from the source from which the answer or a part of answer (called the claim text) is extracted. This might not always be present in the response.
      • Source: An index assigned to the source in the request.
      • Source metadata: Metadata about the chunk. Depending on the source, the source metadata can be any of the following:

        • For an inline source, the metadata can be the additional details that were specified in the request such as title, author, or URI.
        • For the Vertex AI Search data store, the metadata can be the document ID, document title, the URI (Cloud Storage location), or the page number.
        • For Grounding with Google Search, when a grounded result is generated, the metadata contains a URI that redirects to the publisher of the content that was used to generate the grounded result. The metadata also contains the publisher's domain. The provided URIs remain accessible for up to 30 days after the grounded result is generated.
    • Grounding support: Grounding information for a claim in the answer. Grounding support contains the following information:

      • Claim text: The answer or a part of the answer that is substantiated with the support chunk text.
      • Support chunk index: An index assigned to the support chunk in the order in which the chunk appears in the list of support chunks.
      • Web search queries: The suggested search queries for the Google Search Suggestions.
      • Search Suggestions: If you receive Google Search Suggestions with a response, that response is a "Grounded Result" subject to the service terms for Grounding with Google Search. For more information, see For more information, see Service Terms . The renderedContent field within the searchEntryPoint field is the provided code for implementing Google Search Suggestions. To use Google Search Suggestions, see Use Google Search Suggestions.

Generate a grounded answer in a single turn

This section describes how to generate answers grounded in the following sources:

Ground the answer in inline text and Vertex AI Search data store

The following sample shows how to send prompt text by specifying an inline text and a Vertex AI Search data store as the grounding source. You can't specify a website search data store as the grounding source. This sample uses the generateGroundedContent method.

REST

  1. Send the prompt in the following curl request.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_NUMBER/locations/global:generateGroundedContent" \
    -d '
    {
    "contents": [
     {
       "role": "user",
       "parts": [
         {
           "text": "PROMPT_TEXT"
         }
       ]
     }
    ],
    "systemInstruction": {
       "parts": {
           "text": "SYSTEM_INSTRUCTION"
       }
    },
    "groundingSpec": {
     "groundingSources": [
       {
         "inlineSource": {
           "groundingFacts": [
             {
               "factText": "FACT_TEXT_1",
               "attributes": {
                 "title": "TITLE_1",
                 "uri": "URI_1",
                 "author": "AUTHOR_1"
               }
             }
           ]
         }
       },
       {
         "inlineSource": {
           "groundingFacts": [
             {
               "factText": "FACT_TEXT_2",
               "attributes": {
                 "title": "TITLE_2",
                 "uri": "URI_2"
               }
             },
             {
               "factText": "FACT_TEXT_3",
               "attributes": {
                 "title": "TITLE_3",
                 "uri": "URI_3"
               }
             }
           ]
         }
       },
       {
         "searchSource": {
           "servingConfig": "projects/PROJECT_NUMBER/locations/global/collections/default_collection/engines/APP_ID_1/servingConfigs/default_search"
         }
       },
       {
         "searchSource": {
           "servingConfig": "projects/PROJECT_NUMBER/locations/global/collections/default_collection/engines/APP_ID_2/servingConfigs/default_search"
         }
       }
      ]
    },
    "generationSpec": {
      "modelId": "MODEL_ID",
      "temperature": TEMPERATURE,
      "topP": TOP_P,
      "topK": TOP_K
    }
    }'
    

    Replace the following:

    • PROJECT_NUMBER: the number of your Google Cloud project.
    • PROMPT_TEXT: the prompt from the user.
    • SYSTEM_INSTRUCTION: an optional field to provide a preamble or some additional context.
    • FACT_TEXT_N: the inline text to ground the answer. You can provide a maximum of 100 fact texts.
    • TITLE_N: an optional field to set the title meta attribute for the inline text.
    • URI_N: an optional field to set the URI meta attribute for the inline text.
    • AUTHOR_N: an optional field to set the author meta attribute for the inline text.
    • APP_ID_N: the ID of the Vertex AI Search app.
    • MODEL_ID: an optional field to set the model ID of the Gemini model that you'd like to use to generate the grounded answer. For a list of available model IDs, see Supported models.
    • TEMPERATURE: an optional field to set the temperature used for sampling. Google recommends a temperature of 0.0. For more information, see Gemini model parameters.
    • TOP_P: an optional field to set the top-P value for the model. For more information, see Gemini model parameters.
    • TOP_K: an optional field to set the top-K value for the model. For more information, see Gemini model parameters.

Python

from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_number = "YOUR_PROJECT_NUMBER"
# engine_id = "YOUR_ENGINE_ID"

client = discoveryengine.GroundedGenerationServiceClient()

request = discoveryengine.GenerateGroundedContentRequest(
    # The full resource name of the location.
    # Format: projects/{project_number}/locations/{location}
    location=client.common_location_path(project=project_number, location="global"),
    generation_spec=discoveryengine.GenerateGroundedContentRequest.GenerationSpec(
        model_id="gemini-1.5-flash",
    ),
    # Conversation between user and model
    contents=[
        discoveryengine.GroundedGenerationContent(
            role="user",
            parts=[
                discoveryengine.GroundedGenerationContent.Part(
                    text="How did Google do in 2020? Where can I find BigQuery docs?"
                )
            ],
        )
    ],
    system_instruction=discoveryengine.GroundedGenerationContent(
        parts=[
            discoveryengine.GroundedGenerationContent.Part(
                text="Add a smiley emoji after the answer."
            )
        ],
    ),
    # What to ground on.
    grounding_spec=discoveryengine.GenerateGroundedContentRequest.GroundingSpec(
        grounding_sources=[
            discoveryengine.GenerateGroundedContentRequest.GroundingSource(
                inline_source=discoveryengine.GenerateGroundedContentRequest.GroundingSource.InlineSource(
                    grounding_facts=[
                        discoveryengine.GroundingFact(
                            fact_text=(
                                "The BigQuery documentation can be found at https://cloud.google.com/bigquery/docs/introduction"
                            ),
                            attributes={
                                "title": "BigQuery Overview",
                                "uri": "https://cloud.google.com/bigquery/docs/introduction",
                            },
                        ),
                    ]
                ),
            ),
            discoveryengine.GenerateGroundedContentRequest.GroundingSource(
                search_source=discoveryengine.GenerateGroundedContentRequest.GroundingSource.SearchSource(
                    # The full resource name of the serving config for a Vertex AI Search App
                    serving_config=f"projects/{project_number}/locations/global/collections/default_collection/engines/{engine_id}/servingConfigs/default_search",
                ),
            ),
        ]
    ),
)
response = client.generate_grounded_content(request)

# Handle the response
print(response)

Example for single-turn answer generation grounded in inline text and Vertex AI Search

In the following example, the request specifies the following grounding sources: one inline text fact and one Vertex AI Search data store. This sample uses the generateGroundedContent method. This example also uses a system instruction to end the answer with a smiley emoji.

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://discoveryengine.googleapis.com/v1/projects/123456/locations/global:generateGroundedContent" \
-d '
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "text": "How did google do in 2020? Where can I find Bigquery docs?"
        }
      ]
    }
  ],
  "systemInstruction": {
      "parts": {
          "text": "Add a smiley emoji after the answer."
      }
  },
  "groundingSpec": {
    "groundingSources": [
      {
        "inline_source": {
          "grounding_facts": [
            {
              "fact_text": "The BigQuery documentation can be found at https://cloud.google.com/bigquery/docs/introduction",
              "attributes": {
                "title": "BigQuery Overview",
                "uri": "https://cloud.google.com/bigquery/docs/introduction"
              }
            }
          ]
        }
      },
      {
        "searchSource": {
          "servingConfig": "projects/123456/locations/global/collections/default_collection/engines/app_id_example/servingConfigs/default_search"
        }
      }
    ]
  },
  "generationSpec": {
    "modelId": "gemini-1.5-flash"
  }
}'

Generate grounded answer with Google Search

You can ground the generated responses with publicly available web data.

Dynamic retrieval

You can use dynamic retrieval in your request to choose when to turn off grounding with Google Search. This is useful when the prompt doesn't require an answer grounded with Google Search and the supported models can provide an answer based on their knowledge without grounding. This helps you manage latency, quality, and cost more effectively.

Dynamic retrieval prediction score and threshold

When you send a request to generate a grounded answer, Vertex AI Agent Builder assigns a prediction score to the prompt. The prediction score is a floating point value in the range [0,1]. Its value depends on whether the prompt can benefit from grounding the answer with the most up-to-date information from Google Search. Therefore, a prompt that requires an answer grounded in the most recent facts on the web has a higher prediction score, and a prompt for which a model-generated answer is sufficient has a lower prediction score.

Here are examples of some prompts and their prediction scores.

Prompt Prediction score Comment
"Write a poem about peonies" 0.13 The model can rely on its knowledge and the answer doesn't need grounding
"Suggest a toy for a 2yo child" 0.36 The model can rely on its knowledge and the answer doesn't need grounding
"Can you give a recipe for an asian-inspired guacamole?" 0.55 Google Search can give a grounded answer, but grounding is not strictly required; the model knowledge might be sufficient
"What's Agent Builder? How is grounding billed in Agent Builder?" 0.72 Requires Google Search to generate a well-grounded answer
"Who won the latest F1 grand prix?" 0.97 Requires Google Search to generate a well-grounded answer

In your grounded answer generation request, you can specify a dynamic retrieval configuration with a threshold. The threshold is a floating point value in the range [0,1] and defaults to 0.7. If the threshold value is zero, the response is always grounded in Google Search. For all other values of threshold, the following is applicable:

  • If the prediction score is greater than or equal to the threshold, the answer is grounded with Google Search. A lower threshold implies that more prompts have responses that are generated using Grounding with Google Search.
  • If the prediction score is less than the threshold, the model may still generate the answer, but it isn't grounded with Google Search.

To find a good threshold that suits your business needs, you can create a representative set of queries that you expect to encounter. Then, you can sort the queries according to the prediction score in the response and select a good threshold for your use case.

Ground the answer with Google Search

The following sample shows how to generate a grounded answer from a prompt by specifying Google Search as the grounding source. This sample uses the generateGroundedContent method.

REST

  1. Send the prompt in the following curl request.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_NUMBER/locations/global:generateGroundedContent" \
    -d '
    {
    "contents": [
     {
       "role": "user",
       "parts": [
         {
           "text": "PROMPT_TEXT"
         }
       ]
     }
    ],
    "systemInstruction": {
       "parts": {
           "text": "SYSTEM_INSTRUCTION"
       }
    },
    "groundingSpec": {
     "groundingSources": [
     {
         "googleSearchSource": {
              "dynamicRetrievalConfig": {
                  "predictor":{
                      "threshold": DYNAMIC_RETRIEVAL_THRESHOLD
                  }
              }
         }
     }
    ]
    },
    "generationSpec": {
     "modelId": "MODEL_ID",
     "temperature": TEMPERATURE,
     "topP": TOP_P,
     "topK": TOP_K
    }
    }'
    

    Replace the following:

    • PROJECT_NUMBER: the number of your Google Cloud project.
    • PROMPT_TEXT: the prompt from the user.
    • SYSTEM_INSTRUCTION: an optional field to provide a preamble or some additional context.
    • MODEL_ID: an optional field to set the model ID of the Gemini model that you'd like to use to generate the grounded answer. For a list of available model IDs, see Supported models.
    • TEMPERATURE: an optional field to set the temperature used for sampling. Google recommends a temperature of 0.0. For more information, see Gemini model parameters.
    • TOP_P: an optional field to set the top-P value for the model. For more information, see Gemini model parameters.
    • TOP_K: an optional field to set the top-K value for the model. For more information, see Gemini model parameters.
    • DYNAMIC_RETRIEVAL_THRESHOLD: an optional field to set the threshold to invoke the dynamic retrieval configuration. It is floating point value in the range [0,1]. If you add the dynamicRetrievalConfig field, but you don't set the predictor or threshold field, the threshold value defaults to 0.7. If you don't set the dynamicRetrievalConfig field, the answer is always grounded.

Python

from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_number = "YOUR_PROJECT_NUMBER"

client = discoveryengine.GroundedGenerationServiceClient()

request = discoveryengine.GenerateGroundedContentRequest(
    # The full resource name of the location.
    # Format: projects/{project_number}/locations/{location}
    location=client.common_location_path(project=project_number, location="global"),
    generation_spec=discoveryengine.GenerateGroundedContentRequest.GenerationSpec(
        model_id="gemini-1.5-flash",
    ),
    # Conversation between user and model
    contents=[
        discoveryengine.GroundedGenerationContent(
            role="user",
            parts=[
                discoveryengine.GroundedGenerationContent.Part(
                    text="How much is Google stock?"
                )
            ],
        )
    ],
    system_instruction=discoveryengine.GroundedGenerationContent(
        parts=[
            discoveryengine.GroundedGenerationContent.Part(text="Be comprehensive.")
        ],
    ),
    # What to ground on.
    grounding_spec=discoveryengine.GenerateGroundedContentRequest.GroundingSpec(
        grounding_sources=[
            discoveryengine.GenerateGroundedContentRequest.GroundingSource(
                google_search_source=discoveryengine.GenerateGroundedContentRequest.GroundingSource.GoogleSearchSource(
                    # Optional: For Dynamic Retrieval
                    dynamic_retrieval_config=discoveryengine.GenerateGroundedContentRequest.DynamicRetrievalConfiguration(
                        predictor=discoveryengine.GenerateGroundedContentRequest.DynamicRetrievalConfiguration.DynamicRetrievalPredictor(
                            threshold=0.7
                        )
                    )
                )
            ),
        ]
    ),
)
response = client.generate_grounded_content(request)

# Handle the response
print(response)

In the following example, the request specifies Google Search as the grounding source. This sample uses the generateGroundedContent method. This example also uses a system instruction to end the answer with a smiley emoji.

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://discoveryengine.googleapis.com/v1/projects/123456/locations/global:generateGroundedContent" \
-d '
{
"contents": [{
  "role": "user",
  "parts": [{
    "text": "What is vertex ai agent builder?"
}]
}],
"systemInstruction": {
   "parts": {
      "text": "Add a smiley emoji after the answer."
   }
},
"groundingSpec": {
  "groundingSources": [
  {
      "googleSearchSource": {
        "dynamicRetrievalConfig": {
               "predictor":{
                   "threshold": 0.6
               }
           }
      }
  }
 ]
},
"generationSpec": {
  "modelId": "gemini-1.5-flash"
}
}
'

Generate a grounded answer in multiple turns

In multi-turn answer generation, in each request you must send all the text exchanged between the user and the model in all the previous turns. This ensures continuity and maintains context to generate the answer for the latest prompt.

To obtain a grounded answer by multi-turn answer generation, do the following:

REST

The following samples show how to send follow-up prompt text over multiple turns. These samples use the generateGroundedContent method and ground the answers with Google Search. You can use similar steps to generate grounded answers using other grounding sources.

  1. Send the first prompt in the following curl request.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_NUMBER/locations/global:generateGroundedContent" \
    -d '
    {
    "contents": [
     {
       "role": "user",
       "parts": [
         {
           "text": "PROMPT_TEXT_TURN_1"
         }
       ]
     }
    ],
    "systemInstruction": {
       "parts": {
           "text": "SYSTEM_INSTRUCTION_TURN_1"
       }
    },
    "groundingSpec": {
     "groundingSources": [
       {
         "googleSearchSource": {}
       }
     ]
    },
    "generationSpec": {
     "modelId": "MODEL_ID",
     "temperature": TEMPERATURE,
     "topP": TOP_P,
     "topK": TOP_K
    }
    }'
    

    Replace the following:

    • PROJECT_NUMBER: the number of your Google Cloud project.
    • PROMPT_TEXT_TURN_1: the prompt text from the user in the first turn.
    • SYSTEM_INSTRUCTION_TURN_1: an optional field to provide a preamble or some additional context. For multi-turn answer generation, you must provide the system instructions for every turn.
    • MODEL_ID: an optional field to set the model ID of the Gemini model that you'd like to use to generate the grounded answer. For a list of available model IDs, see Supported models.
    • TEMPERATURE: an optional field to set the temperature used for sampling. Google recommends a temperature of 0.0. For more information, see Gemini model parameters.
    • TOP_P: an optional field to set the top-P value for the model. For more information, see Gemini model parameters.
    • TOP_K: an optional field to set the top-K value for the model. For more information, see Gemini model parameters.
  2. Send the second prompt as a follow-up. Add the first prompt from the user followed by its corresponding answer from the model for context.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_NUMBER/locations/global:generateGroundedContent" \
    -d '
    {
    "contents": [
     {
       "role": "user",
       "parts": [
         {
           "text": "PROMPT_TEXT_TURN_1"
         }
       ]
     },
     {
       "role": "model",
       "parts": [
         {
           "text": "ANSWER_TEXT_TURN_1"
         }
       ]
     },
     {
       "role": "user",
       "parts": [
         {
           "text": "PROMPT_TEXT_TURN_2"
         }
       ]
     }
    ],
    "systemInstruction": {
       "parts": {
           "text": "SYSTEM_INSTRUCTION_TURN_2"
       }
    },
    "groundingSpec": {
     "groundingSources": [
       {
         "googleSearchSource": {}
       }
     ]
    },
    "generationSpec": {
     "modelId": "MODEL_ID",
     "temperature": TEMPERATURE,
     "topP": TOP_P,
     "topK": TOP_K
    }
    }'
    

    Replace the following:

    • PROJECT_NUMBER: the number of your Google Cloud project.
    • PROMPT_TEXT_TURN_1: the prompt text from the user in the first turn.
    • ANSWER_TEXT_TURN_1: the answer text from the model in the first turn.
    • PROMPT_TEXT_TURN_2: the prompt text from the user in the second turn.
    • SYSTEM_INSTRUCTION_TURN_2: an optional field to provide a preamble or some additional context. For multi-turn answer generation, you must provide the system instructions for every turn.
    • MODEL_ID: an optional field to set the model ID of the Gemini model that you'd like to use to generate the grounded answer. For a list of available model IDs, see Supported models.
    • TEMPERATURE: an optional field to set the temperature used for sampling. Google recommends a temperature of 0.0. For more information, see Gemini model parameters.
    • TOP_P: an optional field to set the top-P value for the model. For more information, see Gemini model parameters.
    • TOP_K: an optional field to set the top-K value for the model. For more information, see Gemini model parameters.
  3. Repeat this process to get further follow-up answers. In each turn, add all the previous prompts from the user followed by their corresponding answers from the model.

Example for multi-turn answer generation

In the following example, the request specifies three inline fact texts as the grounding source to generate answers over two turns. This sample uses the generateGroundedContent method. This example also uses a system instruction to end the answer in the first turn with a smiley emoji.

REST

  1. Send the first prompt in the following curl request.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/123456/locations/global:generateGroundedContent" \
    -d '
    {
    "contents": [
     {
       "role": "user",
       "parts": [
         {
           "text": "Summarize what happened in 2023 in one paragraph."
         }
       ]
     }
    ],
    "systemInstruction": {
      "parts": {
          "text": "Add a smiley emoji after the answer."
      }
    },
    "grounding_spec": {
     "grounding_sources": [
       {
         "inline_source": {
           "grounding_facts": [
             {
               "fact_text": "In 2023, the world population surpassed 8 billion. This milestone marked a significant moment in human history, highlighting both the rapid growth of our species and the challenges of resource management and sustainability in the years to come.",
               "attributes": {
                 "title": "title_1",
                 "uri": "some-uri-1"
               }
             }
           ]
         }
       },
       {
         "inline_source": {
           "grounding_facts": [
             {
               "fact_text": "In 2023, global e-commerce sales reached an estimated $5.7 trillion. The continued rise of online shopping solidified its position as a dominant force in retail, with major implications for traditional brick-and-mortar stores and the logistics networks supporting worldwide deliveries.",
               "attributes": {
                 "title": "title_2",
                 "uri": "some-uri-2"
               }
             }
           ]
         }
       },
       {
         "inline_source": {
           "grounding_facts": [
             {
               "fact_text": "In 2023, the global average surface temperature was approximately 0.2 degrees Celsius higher than the 20th-century average. This continued the worrying trend of global warming, underscoring the urgency of worldwide climate initiatives, carbon reduction efforts, and investment in renewable energy sources.",
               "attributes": {
                 "title": "title_3",
                 "uri": "some-uri-3"
               }
             }
           ]
         }
       }
     ]
    },
    "generationSpec": {
     "modelId": "gemini-1.5-flash"
    }
    }'
    
  2. Send the second prompt as a follow-up. Add the first prompt from the user followed by its corresponding answer from the model for context.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/123456/locations/global:generateGroundedContent" \
    -d '
    {
    "contents": [
     {
       "role": "user",
       "parts": [
         {
           "text": "Summarize what happened in 2023 in one paragraph."
         }
       ]
     },
     {
       "role": "model",
       "parts": [
         {
           "text": "In 2023, the global average surface temperature increased, the world population surpassed 8 billion, and global e-commerce sales reached an estimated $5.7 trillion.  😊 \n"
         }
       ]
     },
     {
       "role": "user",
       "parts": [
         {
           "text": "Rephrase the answer in an abstracted list."
         }
       ]
     }
    ],
    "grounding_spec": {
     "grounding_sources": [
       {
         "inline_source": {
           "grounding_facts": [
             {
               "fact_text": "In 2023, the world population surpassed 8 billion. This milestone marked a significant moment in human history, highlighting both the rapid growth of our species and the challenges of resource management and sustainability in the years to come.",
               "attributes": {
                 "title": "title_1",
                 "uri": "some-uri-1"
               }
             }
           ]
         }
       },
       {
         "inline_source": {
           "grounding_facts": [
             {
               "fact_text": "In 2023, global e-commerce sales reached an estimated $5.7 trillion. The continued rise of online shopping solidified its position as a dominant force in retail, with major implications for traditional brick-and-mortar stores and the logistics networks supporting worldwide deliveries.",
               "attributes": {
                 "title": "title_2",
                 "uri": "some-uri-2"
               }
             }
           ]
         }
       },
       {
         "inline_source": {
           "grounding_facts": [
             {
               "fact_text": "In 2023, the global average surface temperature was approximately 0.2 degrees Celsius higher than the 20th-century average. This continued the worrying trend of global warming, underscoring the urgency of worldwide climate initiatives, carbon reduction efforts, and investment in renewable energy sources.",
               "attributes": {
                 "title": "title_3",
                 "uri": "some-uri-3"
               }
             }
           ]
         }
       }
     ]
    },
    "generationSpec": {
     "modelId": "gemini-1.5-flash"
    }
    }'
    

Stream grounded answers

You can choose to stream the answers from the model. This is useful in those use cases where the answer is especially long and sending the entire response all at once causes a significant delay. Streaming the answer breaks down the response into an array of several candidates that contain sequential parts of the answer text.

To obtain a streamed, grounded answer, do the following:

REST

The following sample shows how to stream a grounded answer. This sample uses the streamGenerateGroundedContent method and grounds the answer with Google Search without the dynamic retrieval configuration. You can use similar steps to generate grounded answers using other grounding sources.

  1. Send the prompt in the following curl request.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1alpha/projects/PROJECT_NUMBER/locations/global:streamGenerateGroundedContent" \
    -d '
    [
    {
     "contents": [
       {
         "role": "user",
         "parts": [
           {
             "text": "PROMPT_TEXT"
           }
         ]
       }
     ],
     "systemInstruction": {
         "parts": {
             "text": "SYSTEM_INSTRUCTION"
         }
     },
     "groundingSpec": {
       "groundingSources": [
         {
           "googleSearchSource": {}
         }
       ]
     },
    "generationSpec": {
     "modelId": "MODEL_ID",
     "temperature": TEMPERATURE,
     "topP": TOP_P,
     "topK": TOP_K
    }
    }
    ]'
    

    Replace the following:

    • PROJECT_NUMBER: the number of your Google Cloud project.
    • PROMPT_TEXT: the prompt from the user.
    • SYSTEM_INSTRUCTION: an optional field to provide a preamble or some additional context.
    • MODEL_ID: an optional field to set the model ID of the Gemini model that you'd like to use to generate the grounded answer. For a list of available model IDs, see Supported models.
    • TEMPERATURE: an optional field to set the temperature used for sampling. Google recommends a temperature of 0.0. For more information, see Gemini model parameters.
    • TOP_P: an optional field to set the top-P value for the model. For more information, see Gemini model parameters.
    • TOP_K: an optional field to set the top-K value for the model. For more information, see Gemini model parameters.

Python

from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"

client = discoveryengine.GroundedGenerationServiceClient()

request = discoveryengine.GenerateGroundedContentRequest(
    # The full resource name of the location.
    # Format: projects/{project_number}/locations/{location}
    location=client.common_location_path(project=project_number, location="global"),
    generation_spec=discoveryengine.GenerateGroundedContentRequest.GenerationSpec(
        model_id="gemini-1.5-flash",
    ),
    # Conversation between user and model
    contents=[
        discoveryengine.GroundedGenerationContent(
            role="user",
            parts=[
                discoveryengine.GroundedGenerationContent.Part(
                    text="Summarize how to delete a data store in Vertex AI Agent Builder?"
                )
            ],
        )
    ],
    grounding_spec=discoveryengine.GenerateGroundedContentRequest.GroundingSpec(
        grounding_sources=[
            discoveryengine.GenerateGroundedContentRequest.GroundingSource(
                google_search_source=discoveryengine.GenerateGroundedContentRequest.GroundingSource.GoogleSearchSource()
            ),
        ]
    ),
)
responses = client.stream_generate_grounded_content(iter([request]))

for response in responses:
    # Handle the response
    print(response)

Example for streaming grounded answers

In the following example, the request specifies Google Search as the grounding source to stream an answer without the dynamic retrieval configuration. The streamed answer is distributed over several response candidates. This sample uses the streamGenerateGroundedContent method.

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://discoveryengine.googleapis.com/v1alpha/projects/123456/locations/global:streamGenerateGroundedContent" \
-d '
[
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "text": "Summarize How to delete a data store in Vertex AI Agent Builder?"
        }
      ]
    }
  ],
  "groundingSpec": {
    "groundingSources": [
      {
        "googleSearchSource": {}
      }
    ]
  },
  "generationSpec": {
    "modelId": "gemini-1.5-flash"
  }
}
]'

Supported models

The following models support grounding:

  • Gemini 1.5 Pro with text input only
  • Gemini 1.5 Flash with text input only
  • Gemini 1.0 Pro with text input only

To learn more about these Gemini models, see Gemini model versions and lifecycle.

When you call the generateGroundedContent method, you can use the following model IDs:

Model ID Auto-updated
default Yes
gemini-1.0-pro Yes
gemini-1.0-pro-001 No
gemini-1.0-pro-002 No
gemini-1.5-flash Yes
gemini-1.5-flash-001 No
gemini-1.5-pro Yes
gemini-1.5-pro-001 No

What's next

Learn how to use the grounded generation method with other RAG APIs to generate grounded answers from unstructured data.