The [VPC-SC security controls](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/security-controls.md.txt) and
CMEK are supported by RAG Engine on Gemini Enterprise Agent Platform. Data residency and AXT security controls aren't
supported.

> [!NOTE]
> To see an example of using RAG Engine on Gemini Enterprise Agent Platform with Agent Search,
> run the "RAG Engine with Agent Search" notebook in one of the following
> environments:
>
> [![](https://docs.cloud.google.com/static/vertex-ai/images/colab-logo-32px.png)Open in Colab](https://colab.research.google.com/github/GoogleCloudPlatform/generative-ai/blob/main/gemini/rag-engine/rag_engine_vertex_ai_search.ipynb)
>
>
> \|
>
> [![](https://docs.cloud.google.com/static/vertex-ai/images/colab-enterprise-logo-32px.png)Open in Colab Enterprise](https://console.cloud.google.com/agent-platform/colab/import/https%3A%2F%2Fraw.githubusercontent.com%2FGoogleCloudPlatform%2Fgenerative-ai%2Fmain%2Fgemini%2Frag-engine%2Frag_engine_vertex_ai_search.ipynb)
>
>
> \|
>
> [![](https://docs.cloud.google.com/static/vertex-ai/images/vertex-ai-workbench-logo-32px.png)Open
> in Agent Platform Workbench](https://console.cloud.google.com/agent-platform/workbench/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/generative-ai/main/gemini/rag-engine/rag_engine_vertex_ai_search.ipynb)
>
>
> \|
>
> [![](https://docs.cloud.google.com/static/vertex-ai/images/github-logo-32px.png)View on GitHub](https://github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/rag-engine/rag_engine_vertex_ai_search.ipynb)

This page introduces Agent Search integration with the
RAG Engine.

Agent Search provides a solution for retrieving and managing
data within your Gemini Enterprise Agent Platform RAG applications. By using
Agent Search as your retrieval backend, you can improve
performance, scalability, and ease of integration.

- **Enhanced performance and scalability**: Agent Search is
  designed to handle large volumes of data with exceptionally low latency. This
  translates to faster response times and improved performance for your RAG
  applications, especially when dealing with complex or extensive knowledge
  bases.

- **Simplified data management** : Import your data from various sources, such as
  websites, BigQuery datasets, and Cloud Storage buckets, that
  can streamline your [data ingestion process](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/rag-engine/rag-overview.md.txt).

- **Seamless integration**: Agent Platform provides built-in
  integration with Agent Search, which lets you select
  Agent Search as the corpus backend for your RAG
  application. This simplifies the integration process and helps to ensure
  optimal compatibility between components.

- **Improved LLM output quality**: By using the retrieval capabilities of
  Agent Search, you can help to ensure that your RAG
  application retrieves the most relevant information from your corpus, which
  leads to more accurate and informative LLM-generated outputs.

## Agent Search

[Agent Search](https://docs.cloud.google.com/generative-ai-app-builder/docs/enterprise-search-introduction)
brings together deep information retrieval, natural-language processing, and the
latest features in large language model (LLM) processing, which helps to
understand user intent and to return the most relevant results for the user.

With Agent Search, you can build a Google-quality search
application using data that you control.

### Configure Agent Search

To set up a Agent Search, do the following:

1. [Create a search data
   store](https://docs.cloud.google.com/generative-ai-app-builder/docs/create-data-store-es).

2. [Create a search
   application](https://docs.cloud.google.com/generative-ai-app-builder/docs/create-engine-es).

## Use the Agent Search as a retrieval backend for RAG Engine

Once the Agent Search is set up, follow these steps to set it
as the retrieval backend for the RAG application.

### Set the Agent Search as the retrieval backend to create a RAG corpus

These code samples show you how to configure Agent Search as
the retrieval backend for a RAG corpus.

### REST

To use the command line to create a RAG corpus, do the following:

1. Create a RAG corpus

   Replace the following variables used in the code sample:
   - **<var translate="no">PROJECT_ID</var>**: The ID of your Google Cloud project.
   - **<var translate="no">LOCATION</var>**: The region to process the request.
   - **<var translate="no">DISPLAY_NAME</var>**: The display name of the RAG corpus that you want to create.
   - **<var translate="no">ENGINE_NAME</var>** : The full resource name of the Agent Search engine or Agent Search Datastore. For example,

     `projects/PROJECT_NUMBER/locations/LOCATION/collections/default_collection/engines/ENGINE_NAME/servingConfigs/default_search`

   ```bash
   curl -X POST \
   -H "Authorization: Bearer $(gcloud auth print-access-token)" \
   -H "Content-Type: application/json" \
   "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/ragCorpora" \
   -d '{
     "display_name" : "DISPLAY_NAME",
     "vertex_ai_search_config" : {
       "serving_config": "ENGINE_NAME/servingConfigs/default_search"
     }
   }'
   ```
2. Monitor progress

   Replace the following variables used in the code sample:
   - **<var translate="no">PROJECT_ID</var>**: The ID of your Google Cloud project.
   - **<var translate="no">LOCATION</var>**: The region to process the request.
   - **<var translate="no">OPERATION_ID</var>**: The ID of the RAG corpus create operation.

   ```bash
   curl -X GET \
   -H "Authorization: Bearer $(gcloud auth print-access-token)" \
   -H "Content-Type: application/json" \
   "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID"
   ```

### Python


Before trying this sample, follow the Python setup instructions in the
[Agent Platform quickstart using
client libraries](https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/start/client-libraries).


To authenticate to Agent Platform, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt).

```python

import agentplatform
from agentplatform import types

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# vertex_ai_search_engine_name = "projects/{PROJECT_ID}/locations/{LOCATION}/collections/default_collection/engines/{ENGINE_ID}"
# display_name = "test_corpus"
# description = "Corpus Description"

# Initialize Agent Platform client once per session.
# See https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/rag-engine/rag-overview#supported-regions
client = agentplatform.Client(project=PROJECT_ID, location="us-east5")

# Configure Search
vertex_ai_search_config = types.VertexAiSearchConfig(
    serving_config=f"{vertex_ai_search_engine_name}/servingConfigs/default_search",
)

corpus = client.rag.create_corpus(
    rag_corpus=types.RagCorpus(
        display_name=display_name,
        description=description,
        vertex_ai_search_config=vertex_ai_search_config,
    ),
)
print(corpus)
# Example response:
# RagCorpus(name='projects/1234567890/locations/us-central1/ragCorpora/1234567890',
# display_name='test_corpus', description='Corpus Description'.
# ...
```

<br />

### Retrieve contexts using the RAG API

After the RAG corpus creation, relevant contexts can be retrieved from
Agent Search through the `RetrieveContexts` API.

### REST

This code sample demonstrates how to retrieve contexts using REST.

Replace the following variables used in the code sample:

- **<var translate="no">PROJECT_ID</var>**: The ID of your Google Cloud project.
- **<var translate="no">LOCATION</var>**: The region to process the request.
- **<var translate="no">RAG_CORPUS_RESOURCE</var>** : The name of the RAG corpus resource.

  Format:
  `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}.`
- **<var translate="no">TEXT</var>**: The query text to get relevant contexts.

```bash
curl -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION:retrieveContexts" \
  -d '{
    "vertex_rag_store": {
      "rag_resources": {
        "rag_corpus": "RAG_CORPUS_RESOURCE"
      }
    },
    "query": {
      "text": "TEXT"
    }
  }'
```

### Python

To learn how to install or update the Vertex AI SDK for Python, see [Install the Vertex AI SDK for Python](https://docs.cloud.google.com/vertex-ai/docs/start/use-vertex-ai-python-sdk).

For more information, see the
[Python API reference documentation](https://docs.cloud.google.com/python/docs/reference/aiplatform/latest.md.txt).


    import agentplatform

    from agentplatform import types
    from google.genai import types as genai_types

    # TODO(developer): Update and un-comment below lines
    # PROJECT_ID = "your-project-id"
    # corpus_name = "projects/[PROJECT_ID]/locations/us-east5/ragCorpora/[rag_corpus_id]"

    # Initialize Agent Platform client once per session.
    # See https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/rag-engine/rag-overview#supported-regions
    client = agentplatform.Client(project=PROJECT_ID, location="us-east5")

    response = client.rag.retrieve_contexts(
        vertex_rag_store=genai_types.VertexRagStore(
            rag_resources=[
                genai_types.VertexRagStoreRagResource(
                    rag_corpus=corpus_name,
                    # Optional: supply IDs from `rag.list_files()`.
                    # rag_file_ids=["rag-file-1", "rag-file-2", ...],
                )
            ],
        ),
        query=types.RagQuery(
            text="Hello World!",
            rag_retrieval_config=genai_types.RagRetrievalConfig(
                top_k=10,
                filter=genai_types.RagRetrievalConfigFilter(
                    vector_distance_threshold=0.5
                ),
            ),
        )
    )
    print(response)
    # Example response:
    # contexts {
    #   contexts {
    #     source_uri: "gs://your-bucket-name/file.txt"
    #     text: "....
    #   ....

<br />

### Generate content using Agent Platform Gemini API

### REST

To generate content using Gemini models, make a call to the
Agent Platform `GenerateContent` API. By specifying the
`RAG_CORPUS_RESOURCE` in the request, it automatically retrieves data from
Agent Search.

Replace the following variables used in the sample code:

- **<var translate="no">PROJECT_ID</var>**: The ID of your Google Cloud project.

- **<var translate="no">LOCATION</var>**: The region to process the request.

- **<var translate="no">MODEL_ID</var>** : LLM model for content generation. For
  example, `gemini-3.8-flash`.

- **<var translate="no">GENERATION_METHOD</var>** : LLM method for content generation.
  For example, `generateContent`, `streamGenerateContent`.

- **<var translate="no">INPUT_PROMPT</var>**: The text that is sent to the LLM for
  content generation. Try to use a prompt relevant to the documents in
  Agent Search.

- **<var translate="no">RAG_CORPUS_RESOURCE</var>** : The name of the RAG corpus
  resource. Format:
  `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}`.

- **<var translate="no">SIMILARITY_TOP_K</var>**: Optional: The number of top
  contexts
  to retrieve.

  ```bash
  curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATION_METHOD" \
  -d '{
    "contents": {
      "role": "user",
      "parts": {
        "text": "INPUT_PROMPT"
      }
    },
    "tools": {
      "retrieval": {
        "disable_attribution": false,
        "vertex_rag_store": {
          "rag_resources": {
              "rag_corpus": "RAG_CORPUS_RESOURCE"
            },
          "similarity_top_k": SIMILARITY_TOP_K
        }
      }
    }
  }'
  ```

### Python

To learn how to install or update the Vertex AI SDK for Python, see [Install the Vertex AI SDK for Python](https://docs.cloud.google.com/vertex-ai/docs/start/use-vertex-ai-python-sdk).

For more information, see the
[Python API reference documentation](https://docs.cloud.google.com/python/docs/reference/aiplatform/latest.md.txt).


    from google import genai
    from google.genai import types as genai_types

    # TODO(developer): Update and un-comment below lines
    # PROJECT_ID = "your-project-id"
    # corpus_name = "projects/{PROJECT_ID}/locations/us-east5/ragCorpora/{rag_corpus_id}"

    rag_retrieval_tool = genai_types.Tool(
        retrieval=genai_types.Retrieval(
            vertex_rag_store=genai_types.VertexRagStore(
                rag_resources=[
                    genai_types.VertexRagStoreRagResource(
                        rag_corpus=corpus_name
                    )
                ],
                rag_retrieval_config=genai_types.RagRetrievalConfig(
                    top_k=10,
                    filter=genai_types.RagRetrievalConfigFilter(
                        vector_distance_threshold=0.5
                    ),
                ),
            ),
        )
    )

    # Create a GenAI SDK client to make a generate_content request
    genai_client = genai.Client(vertexai=True, project=PROJECT_ID, location="global")

    response = genai_client.models.generate_content(
        model="gemini-3.8-flash",
        contents="Why is the sky blue?",
        config=genai_types.GenerateContentConfig(
            tools=[rag_retrieval_tool]
        ),
    )
    print(response.text)
    # Example response:
    #   The sky appears blue due to a phenomenon called Rayleigh scattering.
    #   Sunlight, which contains all colors of the rainbow, is scattered
    #   by the tiny particles in the Earth's atmosphere....
    #   ...

<br />

## What's next

- [Retrieval and ranking](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/rag-engine/retrieval-and-ranking.md.txt)