forked from GoogleCloudPlatform/python-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrag.py
More file actions
422 lines (329 loc) · 13 KB
/
rag.py
File metadata and controls
422 lines (329 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# flake8: noqa ANN001, ANN201
from typing import List, Optional
def create_corpus(
project_id: str,
display_name: Optional[str] = None,
description: Optional[str] = None,
):
# [START generativeaionvertexai_rag_create_corpus]
from vertexai.preview import rag
import vertexai
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# display_name = "test_corpus"
# description = "Corpus Description"
# Initialize Vertex AI API once per session
vertexai.init(project=project_id, location="us-central1")
# Configure embedding model
embedding_model_config = rag.EmbeddingModelConfig(
publisher_model="publishers/google/models/text-embedding-004"
)
corpus = rag.create_corpus(
display_name=display_name,
description=description,
embedding_model_config=embedding_model_config,
)
print(corpus)
# [END generativeaionvertexai_rag_create_corpus]
return corpus
def get_corpus(project_id: str, corpus_name: str):
# [START generativeaionvertexai_rag_get_corpus]
from vertexai.preview import rag
import vertexai
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# corpus_name = "projects/{project_id}/locations/us-central1/ragCorpora/{rag_corpus_id}"
# Initialize Vertex AI API once per session
vertexai.init(project=project_id, location="us-central1")
corpus = rag.get_corpus(name=corpus_name)
print(corpus)
# [END generativeaionvertexai_rag_get_corpus]
return corpus
def list_corpora(project_id: str):
# [START generativeaionvertexai_rag_list_corpora]
from vertexai.preview import rag
import vertexai
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# Initialize Vertex AI API once per session
vertexai.init(project=project_id, location="us-central1")
corpora = rag.list_corpora()
print(corpora)
# [END generativeaionvertexai_rag_list_corpora]
return corpora
def upload_file(
project_id: str,
corpus_name: str,
path: str,
display_name: Optional[str] = None,
description: Optional[str] = None,
):
# [START generativeaionvertexai_rag_upload_file]
from vertexai.preview import rag
import vertexai
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# corpus_name = "projects/{project_id}/locations/us-central1/ragCorpora/{rag_corpus_id}"
# path = "path/to/local/file.txt"
# display_name = "file_display_name"
# description = "file description"
# Initialize Vertex AI API once per session
vertexai.init(project=project_id, location="us-central1")
rag_file = rag.upload_file(
corpus_name=corpus_name,
path=path,
display_name=display_name,
description=description,
)
print(rag_file)
# [END generativeaionvertexai_rag_upload_file]
return rag_file
def import_files(
project_id: str,
corpus_name: str,
paths: List[str],
):
# [START generativeaionvertexai_rag_import_files]
from vertexai.preview import rag
import vertexai
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# corpus_name = "projects/{project_id}/locations/us-central1/ragCorpora/{rag_corpus_id}"
# paths = ["https://drive.google.com/file/123", "gs://my_bucket/my_files_dir"] # Supports Google Cloud Storage and Google Drive Links
# Initialize Vertex AI API once per session
vertexai.init(project=project_id, location="us-central1")
response = rag.import_files(
corpus_name=corpus_name,
paths=paths,
chunk_size=512, # Optional
chunk_overlap=100, # Optional
max_embedding_requests_per_min=900, # Optional
)
print(f"Imported {response.imported_rag_files_count} files.")
# [END generativeaionvertexai_rag_import_files]
return response
async def import_files_async(
project_id: str,
corpus_name: str,
paths: List[str],
):
# [START generativeaionvertexai_rag_import_files_async]
from vertexai.preview import rag
import vertexai
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# corpus_name = "projects/{project_id}/locations/us-central1/ragCorpora/{rag_corpus_id}"
# Supports Google Cloud Storage and Google Drive Links
# paths = ["https://drive.google.com/file/d/123", "gs://my_bucket/my_files_dir"]
# Initialize Vertex AI API once per session
vertexai.init(project=project_id, location="us-central1")
response = await rag.import_files_async(
corpus_name=corpus_name,
paths=paths,
chunk_size=512, # Optional
chunk_overlap=100, # Optional
max_embedding_requests_per_min=900, # Optional
)
result = await response.result()
print(f"Imported {result.imported_rag_files_count} files.")
# [END generativeaionvertexai_rag_import_files_async]
return result
def get_file(project_id: str, file_name: str):
# [START generativeaionvertexai_rag_get_file]
from vertexai.preview import rag
import vertexai
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# file_name = "projects/{project_id}/locations/us-central1/ragCorpora/{rag_corpus_id}/ragFiles/{rag_file_id}"
# Initialize Vertex AI API once per session
vertexai.init(project=project_id, location="us-central1")
rag_file = rag.get_file(name=file_name)
print(rag_file)
# [END generativeaionvertexai_rag_get_file]
return rag_file
def list_files(project_id: str, corpus_name: str):
# [START generativeaionvertexai_rag_list_files]
from vertexai.preview import rag
import vertexai
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# corpus_name = "projects/{project_id}/locations/us-central1/ragCorpora/{rag_corpus_id}"
# Initialize Vertex AI API once per session
vertexai.init(project=project_id, location="us-central1")
files = rag.list_files(corpus_name=corpus_name)
for file in files:
print(file)
# [END generativeaionvertexai_rag_list_files]
return files
def delete_file(project_id: str, file_name: str) -> None:
# [START generativeaionvertexai_rag_delete_file]
from vertexai.preview import rag
import vertexai
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# file_name = "projects/{project_id}/locations/us-central1/ragCorpora/{rag_corpus_id}/ragFiles/{rag_file_id}"
# Initialize Vertex AI API once per session
vertexai.init(project=project_id, location="us-central1")
rag.delete_file(name=file_name)
print(f"File {file_name} deleted.")
# [END generativeaionvertexai_rag_delete_file]
def delete_corpus(project_id: str, corpus_name: str) -> None:
# [START generativeaionvertexai_rag_delete_corpus]
from vertexai.preview import rag
import vertexai
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# corpus_name = "projects/{project_id}/locations/us-central1/ragCorpora/{rag_corpus_id}"
# Initialize Vertex AI API once per session
vertexai.init(project=project_id, location="us-central1")
rag.delete_corpus(name=corpus_name)
print(f"Corpus {corpus_name} deleted.")
# [END generativeaionvertexai_rag_delete_corpus]
def retrieval_query(
project_id: str,
rag_corpus_id: str,
):
# [START generativeaionvertexai_rag_retrieval_query]
from vertexai.preview import rag
import vertexai
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# rag_corpus_id = "9183965540115283968" # Only one corpus is supported at this time
# Initialize Vertex AI API once per session
vertexai.init(project=project_id, location="us-central1")
response = rag.retrieval_query(
rag_resources=[
rag.RagResource(
rag_corpus=rag_corpus_id,
# Supply IDs from `rag.list_files()`.
# rag_file_ids=["rag-file-1", "rag-file-2", ...],
)
],
text="What is RAG and why it is helpful?",
similarity_top_k=10, # Optional
vector_distance_threshold=0.5, # Optional
)
print(response)
# [END generativeaionvertexai_rag_retrieval_query]
return response
def generate_content_with_rag(
project_id: str,
rag_corpus_id: str,
):
# [START generativeaionvertexai_rag_generate_content]
from vertexai.preview import rag
from vertexai.preview.generative_models import GenerativeModel, Tool
import vertexai
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# rag_corpus_id = "9183965540115283968" # Only one corpus is supported at this time
# Initialize Vertex AI API once per session
vertexai.init(project=project_id, location="us-central1")
rag_retrieval_tool = Tool.from_retrieval(
retrieval=rag.Retrieval(
source=rag.VertexRagStore(
rag_resources=[
rag.RagResource(
rag_corpus=rag_corpus_id, # Currently only 1 corpus is allowed.
# Supply IDs from `rag.list_files()`.
# rag_file_ids=["rag-file-1", "rag-file-2", ...],
)
],
similarity_top_k=3, # Optional
vector_distance_threshold=0.5, # Optional
),
)
)
rag_model = GenerativeModel(
model_name="gemini-1.5-flash-001", tools=[rag_retrieval_tool]
)
response = rag_model.generate_content("Why is the sky blue?")
print(response.text)
# [END generativeaionvertexai_rag_generate_content]
return response
def quickstart(
project_id: str,
display_name: str,
paths: List[str],
):
# [START generativeaionvertexai_rag_quickstart]
from vertexai.preview import rag
from vertexai.preview.generative_models import GenerativeModel, Tool
import vertexai
# Create a RAG Corpus, Import Files, and Generate a response
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# display_name = "test_corpus"
# paths = ["https://drive.google.com/file/d/123", "gs://my_bucket/my_files_dir"] # Supports Google Cloud Storage and Google Drive Links
# Initialize Vertex AI API once per session
vertexai.init(project=project_id, location="us-central1")
# Create RagCorpus
# Configure embedding model, for example "text-embedding-004".
embedding_model_config = rag.EmbeddingModelConfig(
publisher_model="publishers/google/models/text-embedding-004"
)
rag_corpus = rag.create_corpus(
display_name=display_name,
embedding_model_config=embedding_model_config,
)
# Import Files to the RagCorpus
response = rag.import_files(
rag_corpus.name,
paths,
chunk_size=512, # Optional
chunk_overlap=100, # Optional
max_embedding_requests_per_min=900, # Optional
)
# Direct context retrieval
response = rag.retrieval_query(
rag_resources=[
rag.RagResource(
rag_corpus=rag_corpus.name,
# Supply IDs from `rag.list_files()`.
# rag_file_ids=["rag-file-1", "rag-file-2", ...],
)
],
text="What is RAG and why it is helpful?",
similarity_top_k=10, # Optional
vector_distance_threshold=0.5, # Optional
)
print(response)
# Enhance generation
# Create a RAG retrieval tool
rag_retrieval_tool = Tool.from_retrieval(
retrieval=rag.Retrieval(
source=rag.VertexRagStore(
rag_resources=[
rag.RagResource(
rag_corpus=rag_corpus.name, # Currently only 1 corpus is allowed.
# Supply IDs from `rag.list_files()`.
# rag_file_ids=["rag-file-1", "rag-file-2", ...],
)
],
similarity_top_k=3, # Optional
vector_distance_threshold=0.5, # Optional
),
)
)
# Create a gemini-pro model instance
rag_model = GenerativeModel(
model_name="gemini-1.5-flash-001", tools=[rag_retrieval_tool]
)
# Generate response
response = rag_model.generate_content("What is RAG and why it is helpful?")
print(response.text)
# [END generativeaionvertexai_rag_quickstart]
return rag_corpus, response