File size: 27,181 Bytes
1856027 | 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 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 | # -*- coding: utf-8 -*-
# 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
#
# http://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.
#
"""RAG data management SDK."""
from typing import Optional, Sequence, Union
from google import auth
from google.api_core import operation_async
from google.auth.transport import requests as google_auth_requests
from google.cloud import aiplatform
from google.cloud.aiplatform import initializer
from google.cloud.aiplatform import utils
from google.cloud.aiplatform_v1 import (
CreateRagCorpusRequest,
DeleteRagCorpusRequest,
DeleteRagFileRequest,
GetRagCorpusRequest,
GetRagFileRequest,
ImportRagFilesResponse,
ListRagCorporaRequest,
ListRagFilesRequest,
RagCorpus as GapicRagCorpus,
UpdateRagCorpusRequest,
)
from google.cloud.aiplatform_v1.services.vertex_rag_data_service.pagers import (
ListRagCorporaPager,
ListRagFilesPager,
)
from vertexai.rag.utils import (
_gapic_utils,
)
from vertexai.rag.utils.resources import (
JiraSource,
RagCorpus,
RagFile,
RagVectorDbConfig,
SharePointSources,
SlackChannelsSource,
TransformationConfig,
)
def create_corpus(
display_name: Optional[str] = None,
description: Optional[str] = None,
backend_config: Optional[
Union[
RagVectorDbConfig,
None,
]
] = None,
) -> RagCorpus:
"""Creates a new RagCorpus resource.
Example usage:
```
import vertexai
from vertexai import rag
vertexai.init(project="my-project")
rag_corpus = rag.create_corpus(
display_name="my-corpus-1",
)
```
Args:
display_name: If not provided, SDK will create one. The display name of
the RagCorpus. The name can be up to 128 characters long and can
consist of any UTF-8 characters.
description: The description of the RagCorpus.
backend_config: The backend config of the RagCorpus, specifying a
data store and/or embedding model.
Returns:
RagCorpus.
Raises:
RuntimeError: Failed in RagCorpus creation due to exception.
RuntimeError: Failed in RagCorpus creation due to operation error.
"""
if not display_name:
display_name = "vertex-" + utils.timestamped_unique_name()
parent = initializer.global_config.common_location_path(project=None, location=None)
rag_corpus = GapicRagCorpus(display_name=display_name, description=description)
_gapic_utils.set_backend_config(
backend_config=backend_config,
rag_corpus=rag_corpus,
)
request = CreateRagCorpusRequest(
parent=parent,
rag_corpus=rag_corpus,
)
client = _gapic_utils.create_rag_data_service_client()
try:
response = client.create_rag_corpus(request=request)
except Exception as e:
raise RuntimeError("Failed in RagCorpus creation due to: ", e) from e
return _gapic_utils.convert_gapic_to_rag_corpus(response.result(timeout=600))
def update_corpus(
corpus_name: str,
display_name: Optional[str] = None,
description: Optional[str] = None,
backend_config: Optional[
Union[
RagVectorDbConfig,
None,
]
] = None,
) -> RagCorpus:
"""Updates a RagCorpus resource.
Example usage:
```
import vertexai
from vertexai import rag
vertexai.init(project="my-project")
rag_corpus = rag.update_corpus(
corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
display_name="my-corpus-1",
)
```
Args:
corpus_name: The name of the RagCorpus resource to update. Format:
``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}`` or
``{rag_corpus}``.
display_name: If not provided, the display name will not be updated. The
display name of the RagCorpus. The name can be up to 128 characters long
and can consist of any UTF-8 characters.
description: The description of the RagCorpus. If not provided, the
description will not be updated.
backend_config: The backend config of the RagCorpus, specifying a
data store and/or embedding model.
Returns:
RagCorpus.
Raises:
RuntimeError: Failed in RagCorpus update due to exception.
RuntimeError: Failed in RagCorpus update due to operation error.
"""
corpus_name = _gapic_utils.get_corpus_name(corpus_name)
if display_name and description:
rag_corpus = GapicRagCorpus(
name=corpus_name, display_name=display_name, description=description
)
elif display_name:
rag_corpus = GapicRagCorpus(name=corpus_name, display_name=display_name)
elif description:
rag_corpus = GapicRagCorpus(name=corpus_name, description=description)
else:
rag_corpus = GapicRagCorpus(name=corpus_name)
_gapic_utils.set_backend_config(
backend_config=backend_config,
rag_corpus=rag_corpus,
)
request = UpdateRagCorpusRequest(
rag_corpus=rag_corpus,
)
client = _gapic_utils.create_rag_data_service_client()
try:
response = client.update_rag_corpus(request=request)
except Exception as e:
raise RuntimeError("Failed in RagCorpus update due to: ", e) from e
return _gapic_utils.convert_gapic_to_rag_corpus_no_embedding_model_config(
response.result(timeout=600)
)
def get_corpus(name: str) -> RagCorpus:
"""
Get an existing RagCorpus.
Args:
name: An existing RagCorpus resource name. Format:
``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
or ``{rag_corpus}``.
Returns:
RagCorpus.
"""
corpus_name = _gapic_utils.get_corpus_name(name)
request = GetRagCorpusRequest(name=corpus_name)
client = _gapic_utils.create_rag_data_service_client()
try:
response = client.get_rag_corpus(request=request)
except Exception as e:
raise RuntimeError("Failed in getting the RagCorpus due to: ", e) from e
return _gapic_utils.convert_gapic_to_rag_corpus(response)
def list_corpora(
page_size: Optional[int] = None, page_token: Optional[str] = None
) -> ListRagCorporaPager:
"""
List all RagCorpora in the same project and location.
Example usage:
```
import vertexai
from vertexai import rag
vertexai.init(project="my-project")
# List all corpora.
rag_corpora = list(rag.list_corpora())
# Alternatively, return a ListRagCorporaPager.
pager_1 = rag.list_corpora(page_size=10)
# Then get the next page, use the generated next_page_token from the last pager.
pager_2 = rag.list_corpora(page_size=10, page_token=pager_1.next_page_token)
```
Args:
page_size: The standard list page size. Leaving out the page_size
causes all of the results to be returned.
page_token: The standard list page token.
Returns:
ListRagCorporaPager.
"""
parent = initializer.global_config.common_location_path(project=None, location=None)
request = ListRagCorporaRequest(
parent=parent,
page_size=page_size,
page_token=page_token,
)
client = _gapic_utils.create_rag_data_service_client()
try:
pager = client.list_rag_corpora(request=request)
except Exception as e:
raise RuntimeError("Failed in listing the RagCorpora due to: ", e) from e
return pager
def delete_corpus(name: str) -> None:
"""
Delete an existing RagCorpus.
Args:
name: An existing RagCorpus resource name. Format:
``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
or ``{rag_corpus}``.
"""
corpus_name = _gapic_utils.get_corpus_name(name)
request = DeleteRagCorpusRequest(name=corpus_name)
client = _gapic_utils.create_rag_data_service_client()
try:
client.delete_rag_corpus(request=request)
print("Successfully deleted the RagCorpus.")
except Exception as e:
raise RuntimeError("Failed in RagCorpus deletion due to: ", e) from e
return None
def upload_file(
corpus_name: str,
path: Union[str, Sequence[str]],
display_name: Optional[str] = None,
description: Optional[str] = None,
transformation_config: Optional[TransformationConfig] = None,
) -> RagFile:
"""
Synchronous file upload to an existing RagCorpus.
Example usage:
```
import vertexai
from vertexai import rag
vertexai.init(project="my-project")
// Optional.
transformation_config = TransformationConfig(
chunking_config=ChunkingConfig(
chunk_size=1024,
chunk_overlap=200,
),
)
rag_file = rag.upload_file(
corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
display_name="my_file.txt",
path="usr/home/my_file.txt",
transformation_config=transformation_config,
)
```
Args:
corpus_name: The name of the RagCorpus resource into which to upload the file.
Format: ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
or ``{rag_corpus}``.
path: A local file path. For example,
"usr/home/my_file.txt".
display_name: The display name of the data file.
description: The description of the RagFile.
transformation_config: The config for transforming the RagFile, like chunking.
Returns:
RagFile.
Raises:
RuntimeError: Failed in RagFile upload.
ValueError: RagCorpus is not found.
RuntimeError: Failed in indexing the RagFile.
"""
corpus_name = _gapic_utils.get_corpus_name(corpus_name)
location = initializer.global_config.location
# GAPIC doesn't expose a path (scotty). Use requests API instead
if display_name is None:
display_name = "vertex-" + utils.timestamped_unique_name()
headers = {"X-Goog-Upload-Protocol": "multipart"}
if not initializer.global_config.api_endpoint:
request_endpoint = "{}-{}".format(
location, aiplatform.constants.base.API_BASE_PATH
)
else:
request_endpoint = initializer.global_config.api_endpoint
upload_request_uri = "https://{}/upload/v1/{}/ragFiles:upload".format(
request_endpoint,
corpus_name,
)
js_rag_file = {"rag_file": {"display_name": display_name}}
if description:
js_rag_file["rag_file"]["description"] = description
if transformation_config and transformation_config.chunking_config:
chunk_size = transformation_config.chunking_config.chunk_size
chunk_overlap = transformation_config.chunking_config.chunk_overlap
js_rag_file["upload_rag_file_config"] = {
"rag_file_transformation_config": {
"rag_file_chunking_config": {
"fixed_length_chunking": {
"chunk_size": chunk_size,
"chunk_overlap": chunk_overlap,
}
}
}
}
files = {
"metadata": (None, str(js_rag_file)),
"file": open(path, "rb"),
}
credentials, _ = auth.default()
authorized_session = google_auth_requests.AuthorizedSession(credentials=credentials)
try:
response = authorized_session.post(
url=upload_request_uri,
files=files,
headers=headers,
)
except Exception as e:
raise RuntimeError("Failed in uploading the RagFile due to: ", e) from e
if response.status_code == 404:
raise ValueError(
"RagCorpus '%s' is not found: %s", corpus_name, upload_request_uri
)
if response.json().get("error"):
raise RuntimeError(
"Failed in indexing the RagFile due to: ", response.json().get("error")
)
return _gapic_utils.convert_json_to_rag_file(response.json())
def import_files(
corpus_name: str,
paths: Optional[Sequence[str]] = None,
source: Optional[Union[SlackChannelsSource, JiraSource, SharePointSources]] = None,
transformation_config: Optional[TransformationConfig] = None,
timeout: int = 600,
max_embedding_requests_per_min: int = 1000,
partial_failures_sink: Optional[str] = None,
) -> ImportRagFilesResponse:
"""
Import files to an existing RagCorpus, wait until completion.
Example usage:
```
import vertexai
from vertexai import rag
from google.protobuf import timestamp_pb2
vertexai.init(project="my-project")
# Google Drive example
paths = [
"https://drive.google.com/file/d/123",
"https://drive.google.com/drive/folders/456"
]
# Google Cloud Storage example
paths = ["gs://my_bucket/my_files_dir", ...]
transformation_config = TransformationConfig(
chunking_config=ChunkingConfig(
chunk_size=1024,
chunk_overlap=200,
),
)
response = rag.import_files(
corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
paths=paths,
transformation_config=transformation_config,
)
# Slack example
start_time = timestamp_pb2.Timestamp()
start_time.FromJsonString('2020-12-31T21:33:44Z')
end_time = timestamp_pb2.Timestamp()
end_time.GetCurrentTime()
source = rag.SlackChannelsSource(
channels = [
SlackChannel("channel1", "api_key1"),
SlackChannel("channel2", "api_key2", start_time, end_time)
],
)
# Jira Example
jira_query = rag.JiraQuery(
email="xxx@yyy.com",
jira_projects=["project1", "project2"],
custom_queries=["query1", "query2"],
api_key="api_key",
server_uri="server.atlassian.net"
)
source = rag.JiraSource(
queries=[jira_query],
)
response = rag.import_files(
corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
source=source,
transformation_config=transformation_config,
)
# SharePoint Example.
sharepoint_query = rag.SharePointSource(
sharepoint_folder_path="https://my-sharepoint-site.com/my-folder",
sharepoint_site_name="my-sharepoint-site.com",
client_id="my-client-id",
client_secret="my-client-secret",
tenant_id="my-tenant-id",
drive_id="my-drive-id",
)
source = rag.SharePointSources(
share_point_sources=[sharepoint_query],
)
# Return the number of imported RagFiles after completion.
print(response.imported_rag_files_count)
```
Args:
corpus_name: The name of the RagCorpus resource into which to import files.
Format: ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
or ``{rag_corpus}``.
paths: A list of uris. Eligible uris will be Google Cloud Storage
directory ("gs://my-bucket/my_dir") or a Google Drive url for file
(https://drive.google.com/file/... or folder
"https://drive.google.com/corp/drive/folders/...").
source: The source of the Slack or Jira import.
Must be either a SlackChannelsSource or JiraSource.
transformation_config: The config for transforming the imported
RagFiles.
max_embedding_requests_per_min:
Optional. The max number of queries per
minute that this job is allowed to make to the
embedding model specified on the corpus. This
value is specific to this job and not shared
across other import jobs. Consult the Quotas
page on the project to set an appropriate value
here. If unspecified, a default value of 1,000
QPM would be used.
timeout: Default is 600 seconds.
partial_failures_sink: Either a GCS path to store partial failures or a
BigQuery table to store partial failures. The format is
"gs://my-bucket/my/object.ndjson" for GCS or
"bq://my-project.my-dataset.my-table" for BigQuery. An existing GCS
object cannot be used. However, the BigQuery table may or may not
exist - if it does not exist, it will be created. If it does exist,
the schema will be checked and the partial failures will be appended
to the table.
Returns:
ImportRagFilesResponse.
"""
if source is not None and paths is not None:
raise ValueError("Only one of source or paths must be passed in at a time")
if source is None and paths is None:
raise ValueError("One of source or paths must be passed in")
corpus_name = _gapic_utils.get_corpus_name(corpus_name)
request = _gapic_utils.prepare_import_files_request(
corpus_name=corpus_name,
paths=paths,
source=source,
transformation_config=transformation_config,
max_embedding_requests_per_min=max_embedding_requests_per_min,
partial_failures_sink=partial_failures_sink,
)
client = _gapic_utils.create_rag_data_service_client()
try:
response = client.import_rag_files(request=request)
except Exception as e:
raise RuntimeError("Failed in importing the RagFiles due to: ", e) from e
return response.result(timeout=timeout)
async def import_files_async(
corpus_name: str,
paths: Optional[Sequence[str]] = None,
source: Optional[Union[SlackChannelsSource, JiraSource, SharePointSources]] = None,
transformation_config: Optional[TransformationConfig] = None,
max_embedding_requests_per_min: int = 1000,
partial_failures_sink: Optional[str] = None,
) -> operation_async.AsyncOperation:
"""
Import files to an existing RagCorpus asynchronously.
Example usage:
```
import vertexai
from vertexai import rag
from google.protobuf import timestamp_pb2
vertexai.init(project="my-project")
# Google Drive example
paths = [
"https://drive.google.com/file/d/123",
"https://drive.google.com/drive/folders/456"
]
# Google Cloud Storage example
paths = ["gs://my_bucket/my_files_dir", ...]
transformation_config = TransformationConfig(
chunking_config=ChunkingConfig(
chunk_size=1024,
chunk_overlap=200,
),
)
response = await rag.import_files_async(
corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
paths=paths,
transformation_config=transformation_config,
)
# Slack example
start_time = timestamp_pb2.Timestamp()
start_time.FromJsonString('2020-12-31T21:33:44Z')
end_time = timestamp_pb2.Timestamp()
end_time.GetCurrentTime()
source = rag.SlackChannelsSource(
channels = [
SlackChannel("channel1", "api_key1"),
SlackChannel("channel2", "api_key2", start_time, end_time)
],
)
# Jira Example
jira_query = rag.JiraQuery(
email="xxx@yyy.com",
jira_projects=["project1", "project2"],
custom_queries=["query1", "query2"],
api_key="api_key",
server_uri="server.atlassian.net"
)
source = rag.JiraSource(
queries=[jira_query],
)
response = await rag.import_files_async(
corpus_name="projects/my-project/locations/us-central1/ragCorpora/my-corpus-1",
source=source,
transformation_config=transformation_config,
)
# SharePoint Example.
sharepoint_query = rag.SharePointSource(
sharepoint_folder_path="https://my-sharepoint-site.com/my-folder",
sharepoint_site_name="my-sharepoint-site.com",
client_id="my-client-id",
client_secret="my-client-secret",
tenant_id="my-tenant-id",
drive_id="my-drive-id",
)
source = rag.SharePointSources(
share_point_sources=[sharepoint_query],
)
# Get the result.
await response.result()
```
Args:
corpus_name: The name of the RagCorpus resource into which to import files.
Format: ``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
or ``{rag_corpus}``.
paths: A list of uris. Eligible uris will be Google Cloud Storage
directory ("gs://my-bucket/my_dir") or a Google Drive url for file
(https://drive.google.com/file/... or folder
"https://drive.google.com/corp/drive/folders/...").
source: The source of the Slack or Jira import.
Must be either a SlackChannelsSource or JiraSource.
transformation_config: The config for transforming the imported
RagFiles.
max_embedding_requests_per_min:
Optional. The max number of queries per
minute that this job is allowed to make to the
embedding model specified on the corpus. This
value is specific to this job and not shared
across other import jobs. Consult the Quotas
page on the project to set an appropriate value
here. If unspecified, a default value of 1,000
QPM would be used.
partial_failures_sink: Either a GCS path to store partial failures or a
BigQuery table to store partial failures. The format is
"gs://my-bucket/my/object.ndjson" for GCS or
"bq://my-project.my-dataset.my-table" for BigQuery. An existing GCS
object cannot be used. However, the BigQuery table may or may not
exist - if it does not exist, it will be created. If it does exist,
the schema will be checked and the partial failures will be appended
to the table.
Returns:
operation_async.AsyncOperation.
"""
if source is not None and paths is not None:
raise ValueError("Only one of source or paths must be passed in at a time")
if source is None and paths is None:
raise ValueError("One of source or paths must be passed in")
corpus_name = _gapic_utils.get_corpus_name(corpus_name)
request = _gapic_utils.prepare_import_files_request(
corpus_name=corpus_name,
paths=paths,
source=source,
transformation_config=transformation_config,
max_embedding_requests_per_min=max_embedding_requests_per_min,
partial_failures_sink=partial_failures_sink,
)
async_client = _gapic_utils.create_rag_data_service_async_client()
try:
response = await async_client.import_rag_files(request=request)
except Exception as e:
raise RuntimeError("Failed in importing the RagFiles due to: ", e) from e
return response
def get_file(name: str, corpus_name: Optional[str] = None) -> RagFile:
"""
Get an existing RagFile.
Args:
name: Either a full RagFile resource name must be provided, or a RagCorpus
name and a RagFile name must be provided. Format:
``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file}``
or ``{rag_file}``.
corpus_name: If `name` is not a full resource name, an existing RagCorpus
name must be provided. Format:
``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
or ``{rag_corpus}``.
Returns:
RagFile.
"""
corpus_name = _gapic_utils.get_corpus_name(corpus_name)
name = _gapic_utils.get_file_name(name, corpus_name)
request = GetRagFileRequest(name=name)
client = _gapic_utils.create_rag_data_service_client()
try:
response = client.get_rag_file(request=request)
except Exception as e:
raise RuntimeError("Failed in getting the RagFile due to: ", e) from e
return _gapic_utils.convert_gapic_to_rag_file(response)
def list_files(
corpus_name: str, page_size: Optional[int] = None, page_token: Optional[str] = None
) -> ListRagFilesPager:
"""
List all RagFiles in an existing RagCorpus.
Example usage:
```
import vertexai
vertexai.init(project="my-project")
# List all corpora.
rag_corpora = list(rag.list_corpora())
# List all files of the first corpus.
rag_files = list(rag.list_files(corpus_name=rag_corpora[0].name))
# Alternatively, return a ListRagFilesPager.
pager_1 = rag.list_files(
corpus_name=rag_corpora[0].name,
page_size=10
)
# Then get the next page, use the generated next_page_token from the last pager.
pager_2 = rag.list_files(
corpus_name=rag_corpora[0].name,
page_size=10,
page_token=pager_1.next_page_token
)
```
Args:
corpus_name: An existing RagCorpus name. Format:
``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
or ``{rag_corpus}``.
page_size: The standard list page size. Leaving out the page_size
causes all of the results to be returned.
page_token: The standard list page token.
Returns:
ListRagFilesPager.
"""
corpus_name = _gapic_utils.get_corpus_name(corpus_name)
request = ListRagFilesRequest(
parent=corpus_name,
page_size=page_size,
page_token=page_token,
)
client = _gapic_utils.create_rag_data_service_client()
try:
pager = client.list_rag_files(request=request)
except Exception as e:
raise RuntimeError("Failed in listing the RagFiles due to: ", e) from e
return pager
def delete_file(name: str, corpus_name: Optional[str] = None) -> None:
"""
Delete RagFile from an existing RagCorpus.
Args:
name: Either a full RagFile resource name must be provided, or a RagCorpus
name and a RagFile name must be provided. Format:
``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file}``
or ``{rag_file}``.
corpus_name: If `name` is not a full resource name, an existing RagCorpus
name must be provided. Format:
``projects/{project}/locations/{location}/ragCorpora/{rag_corpus}``
or ``{rag_corpus}``.
"""
corpus_name = _gapic_utils.get_corpus_name(corpus_name)
name = _gapic_utils.get_file_name(name, corpus_name)
request = DeleteRagFileRequest(name=name)
client = _gapic_utils.create_rag_data_service_client()
try:
client.delete_rag_file(request=request)
print("Successfully deleted the RagFile.")
except Exception as e:
raise RuntimeError("Failed in RagFile deletion due to: ", e) from e
return None
|