1
---
2
name: agent-platform-rag-engine-management
3
metadata:
4
version: "1.0.4"
5
category: AiAndMachineLearning
6
description: >-
7
Manage and query Agent Platform RAG Engine Corpora and retrieve grounded
8
contexts using the Google GenAI SDK. Use when listing RAG corpora or files,
9
inspecting a corpus, retrieving contexts, or generating content grounded in a
10
RAG corpus. Do not use for standard database queries (use SQL/Spanner skills),
11
Google Workspace RAG, or other RAG products like gRAG.
12
---
13
14
# Agent Platform RAG Engine Management
15
16
This skill provides instructions on how to interact with Agent Platform RAG
17
Engine using the Agent Platform Python SDK. You MUST use the `vertexai` Python
18
SDK to perform RAG Engine operations, rather than raw REST calls or MCP tools,
19
because this code is intended to be run by external clients.
20
21
## Attribution
22
23
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you MUST
24
read [Usage Attribution](references/attribution.md). For commands executed
25
directly in the terminal (never in generated scripts, Terraform, or user code),
26
prefix `gcloud` with `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` and append the
27
attribution suffix to `User-Agent` headers:
28
29
```text
30
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:agent-platform-rag-engine-management)"
31
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:agent-platform-rag-engine-management)
32
```
33
34
## Safety & Confirmation Tiers (CRITICAL)
35
36
Before executing any commands or scripts on behalf of the user, you must adhere
37
to the following safety tiers based on the action requested:
38
39
1. **Tier R: Read-only (`list_corpora`, `list_files`, `get_corpus`,
40
`retrieval_query`)**
41
* No confirmation needed. Execute immediately to gather information or
42
retrieve grounded contexts.
43
2. **Tier RC: Read-only but consumes Compute Resources
44
(`client.models.generate_content`)**
45
46
* Requires **interactive confirmation** with 'Yes'/'No' options before
47
executing grounded content generation. The confirmation prompt MUST
48
clearly explain the proposed generation execution and its key parameters
49
(e.g., target corpus ID, query text, target model). Natural-language
50
paraphrases without specifying exact parameters are insufficient, as
51
explicit parameter listing is required to ensure unambiguous user
52
approval of the specific resource and configuration.
53
* **Same-turn restriction**: Do not execute the generation code in the
54
same turn as presenting the confirmation prompt. Stop and wait for the
55
user's reply; only execute after explicit 'Yes' / approval.
56
* **Gold Standard Example**:
57
58
> I will perform grounded content generation with the following
59
> parameters. Please confirm this information before I proceed:
60
>
61
> * **Target Corpus ID**: `projects/123/locations/us/ragCorpora/abc`
62
> * **Target Model**: `gemini-3.8-flash`
63
> * **Query Text**: "What are the company policies on remote work?"
64
>
65
> Do you confirm? [Yes/No]
66
67
## Phase 0: Environment Setup
68
69
**CRITICAL**: Before running any of the Python snippets below, you must ensure
70
the environment is correctly initialized by following these steps:
71
72
1. **Google Cloud Authentication**: Authenticate with your Google Cloud
73
credentials and configure active Application Default Credentials (ADC) for
74
Agent Platform access:
75
76
```bash
77
gcloud auth login
78
gcloud auth application-default login
79
```
80
81
2. **Python Dependencies**: This skill needs `google-cloud-aiplatform` and
82
`google-genai`, which the sandbox already provides. Do **not** create a
83
virtual environment — it starts empty and hides packages the environment
84
already provides, forcing a redundant install. Do not spend a separate
85
command checking for them: run the snippet directly, and only if it fails
86
with `ModuleNotFoundError`, install in the same command as the retry:
87
88
```bash
89
pip install -q google-cloud-aiplatform google-genai && python3 - <<'PY'
90
...
91
PY
92
```
93
94
3. **Execution**: Run each snippet as a quoted heredoc, `python3 - <<'PY'` ...
95
`PY`, rather than `python3 -c '...'`, whose nested quotes break easily.
96
There is no environment to activate first. When one step needs several of
97
the snippets below (for example, list the corpora and then the files in
98
each), combine them into one script and one command. The
99
`vertexai.preview.rag` deprecation warning printed on stderr is expected;
100
keep using these snippets rather than switching clients because of it.
101
102
## Workflow Decision Tree
103
104
1. **Information Gathering**: Has the user provided the Project ID, Region, and
105
Corpus ID?
106
107
* **No** -> Proceed to [1. Listing Corpora and Files] to discover the
108
necessary Resource Names and IDs. Only ask the user if discovery fails.
109
* **Yes** -> Proceed.
110
111
2. **Task Type**: What does the user want to do?
112
113
* **List Corpora and Files** -> Proceed to [1. Listing Corpora and Files].
114
* **Inspect a Corpus** -> Proceed to [2. Getting / Inspecting a RAG Engine
115
Corpus].
116
* **Search for Contexts** -> Proceed to [3. Retrieving Contexts].
117
* **Answer questions using RAG Engine** -> Proceed to [4. Answering the
118
User with Retrieved Context].
119
120
> [!TIP]
121
>
122
> **Placeholder Parameter Replacement:** The Python scripts below use bracketed
123
> string placeholders (like `"{project_id}"`, `"{region}"`, and
124
> `"{corpus_id}"`). You **MUST** dynamically replace these placeholders with the
125
> actual Project ID, Region, and Corpus ID values provided in the user's prompt
126
> (or active context) before generating, providing, or executing the scripts.
127
128
## 1. Listing Corpora and Files (Discovery)
129
130
If you do not know the Resource Name of the corpus or file, you MUST list them
131
first to discover them. The SDK handles pagination automatically when converted
132
to a list, but you can also use manual pagination for large sets.
133
134
### 1.1 Listing and Discovering Corpora
135
136
```python
137
import vertexai
138
from vertexai.preview import rag
139
140
vertexai.init(project="{project_id}", location="{region}")
141
142
# Approach A: List ALL (Automatic Pagination)
143
# The SDK's Pager iterates through all pages for you.
144
all_corpora = list(rag.list_corpora())
145
print(f"Found {len(all_corpora)} corpora in total.")
146
for c in all_corpora:
147
print(f"Corpus Name: {c.name} | Display Name: {c.display_name}")
148
149
# Approach B: Manual Pagination (for very large projects)
150
pager = rag.list_corpora(page_size=10)
151
# Process first page
152
for c in pager:
153
print(f"Corpus: {c.display_name}")
154
155
# Get next page if needed
156
if pager.next_page_token:
157
second_page = rag.list_corpora(
158
page_size=10, page_token=pager.next_page_token
159
)
160
```
161
162
### 1.2 Listing and Discovering Files
163
164
To understand what files (and types) are in a corpus, list them and inspect the
165
`display_name` (usually includes the extension).
166
167
```python
168
import vertexai
169
from vertexai.preview import rag
170
171
vertexai.init(project="{project_id}", location="{region}")
172
corpus_name = (
173
"projects/{project_id}/locations/{region}/ragCorpora/{corpus_id}"
174
)
175
176
# List files with automatic pagination
177
files = list(rag.list_files(corpus_name=corpus_name))
178
print(f"Found {len(files)} files.")
179
180
for f in files:
181
# High-level SDK RagFile objects usually have name, display_name,
182
# description
183
print(f"File: {f.display_name} | Resource: {f.name}")
184
# Tip: Check extension to understand file type (PDF, TXT, etc.)
185
if f.display_name.lower().endswith(".pdf"):
186
print(" Type: PDF")
187
elif f.display_name.lower().endswith(".txt"):
188
print(" Type: Plain Text")
189
```
190
191
## 2. Getting / Inspecting an Agent Platform RAG Engine Corpus
192
193
To retrieve details about an existing Agent Platform RAG Engine corpus:
194
195
```python
196
import vertexai
197
from vertexai.preview import rag
198
199
vertexai.init(project="{project_id}", location="{region}")
200
201
# To get details of a specific corpus
202
corpus_name = (
203
"projects/{project_id}/locations/{region}/ragCorpora/{corpus_id}"
204
)
205
corpus = rag.get_corpus(name=corpus_name)
206
print(f"Corpus Name: {corpus.name}")
207
print(f"Display Name: {corpus.display_name}")
208
```
209
210
## 3. Retrieving Contexts
211
212
To retrieve relevant contexts from a RAG Engine corpus based on a query. If no
213
contexts come back, that is a valid answer: report it with the corpus and query
214
you used. If a broader search is reasonable, try it in the same script (for
215
example a larger `similarity_top_k`) rather than as a separate command.
216
217
```python
218
import vertexai
219
from vertexai.preview import rag
220
221
vertexai.init(project="{project_id}", location="{region}")
222
223
corpus_name = (
224
"projects/{project_id}/locations/{region}/ragCorpora/{corpus_id}"
225
)
226
query = "What is the speed of light?"
227
228
# Retrieve contexts
229
response = rag.retrieval_query(
230
rag_corpora=[corpus_name],
231
text=query,
232
similarity_top_k=3
233
)
234
235
for context in response.contexts.contexts:
236
print(f"Context text: {context.text}")
237
print(f"Source: {context.source_uri}")
238
```
239
240
## 4. Answering the User with Retrieved Context
241
242
To use the retrieved context alongside an Agent Platform model to generate a
243
grounded response:
244
245
```python
246
from google import genai
247
from google.genai import types
248
249
client = genai.Client(vertexai=True, project="{project_id}", location="{region}")
250
corpus_name = (
251
"projects/{project_id}/locations/{region}/ragCorpora/{corpus_id}"
252
)
253
254
# Define the Agent Platform RAG Engine tool pointing to the corpus
255
rag_tool = types.Tool(
256
retrieval=types.Retrieval(
257
vertex_rag_store=types.VertexRagStore(
258
rag_resources=[types.VertexRagStoreRagResource(rag_corpus=corpus_name)],
259
rag_retrieval_config=types.RagRetrievalConfig(
260
top_k=3,
261
filter=types.RagRetrievalConfigFilter(
262
vector_similarity_threshold=0.5,
263
),
264
),
265
)
266
)
267
)
268
269
# Generate content using the RAG Engine tool
270
response = client.models.generate_content(
271
model="gemini-3.8-flash",
272
contents="What is the speed of light?",
273
config=types.GenerateContentConfig(
274
tools=[rag_tool]
275
)
276
)
277
print(response.text)
278
```
279