RAG Engine API

Vertex AI RAG 引擎是 Vertex AI Platform 的组成部分,有助于检索增强生成 (RAG)。RAG 引擎可让大语言模型 (LLM) 访问和整合外部知识源(例如文档和数据库)中的数据。通过使用 RAG,LLM 可以生成更准确、信息更丰富的 LLM 回答。

示例语法

本部分介绍了用于创建 RAG 语料库的语法。

curl

PROJECT_ID: Your project ID.
LOCATION: The region to process the request.
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" : "...",
  "description": "..."
}'

Python

corpus = rag.create_corpus(display_name=..., description=...)
print(corpus)

参数列表

本部分列出了以下内容

参数 示例
请参阅语料库管理参数 请参阅语料库管理示例
请参阅文件管理参数 请参阅文件管理示例

语料库管理参数

如需了解 RAG 语料库,请参阅语料库管理

创建 RAG 语料库

下表列出了用于创建 RAG 语料库的参数。

正文请求
参数

display_name

必需:string

RAG 语料库的显示名称。

description

可选:string

RAG 语料库的说明。

vector_db_config

可选:不可变:RagVectorDbConfig

向量数据库的配置。

vertex_ai_search_config.serving_config

可选:string

Vertex AI Search 的配置。

格式:projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config}projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/servingConfigs/{serving_config}

RagVectorDbConfig
参数

rag_managed_db

oneof vector_dbRagVectorDbConfig.RagManagedDb

如果未指定向量数据库,则 rag_managed_db 是默认的向量数据库。

weaviate

oneof vector_dbRagVectorDbConfig.Weaviate

指定您的 Weaviate 实例。

weaviate.http_endpoint

string

Weaviate 实例的 HTTP 端点。

此值一经设置便无法更改。您可以在 CreateRagCorpus API 调用中将其留空,并在后续的 UpdateRagCorpus API 调用中将其设置为非空值。

weaviate.collection_name

string

RAG 语料库映射到的 Weaviate 集合。

此值一经设置便无法更改。您可以在 CreateRagCorpus API 调用中将其留空,并在后续的 UpdateRagCorpus API 调用中将其设置为非空值。

pinecone

oneof vector_dbRagVectorDbConfig.Pinecone

指定您的 Pinecone 实例。

pinecone.index_name

string

这是用于创建与 RAG 语料库搭配使用的 Pinecone 索引的名称。

此值一经设置便无法更改。您可以在 CreateRagCorpus API 调用中将其留空,并在后续的 UpdateRagCorpus API 调用中将其设置为非空值。

vertex_feature_store

oneof vector_dbRagVectorDbConfig.VertexFeatureStore

指定您的 Vertex AI Feature Store 实例。

vertex_feature_store.feature_view_resource_name

string

RAG 语料库映射到的 Vertex AI Feature Store FeatureView

格式:projects/{project}/locations/{location}/featureOnlineStores/{feature_online_store}/featureViews/{feature_view}

此值一经设置便无法更改。您可以在 CreateRagCorpus API 调用中将其留空,并在后续的 UpdateRagCorpus API 调用中将其设置为非空值。

vertex_vector_search

oneof vector_dbRagVectorDbConfig.VertexVectorSearch

指定您的 Vertex Vector Search 实例。

vertex_vector_search.index

string

这是与 RAG 语料库搭配使用的 Vector Search 索引的资源名称。

格式:projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}

此值一经设置便无法更改。您可以在 CreateRagCorpus API 调用中将其留空,并在后续的 UpdateRagCorpus API 调用中将其设置为非空值。

vertex_vector_search.index_endpoint

string

这是与 RAG 语料库搭配使用的 Vector Search 索引端点的资源名称。

格式:projects/{project}/locations/{location}/indexes/{index}

此值一经设置便无法更改。您可以在 CreateRagCorpus API 调用中将其留空,并在后续的 UpdateRagCorpus API 调用中将其设置为非空值。

api_auth.api_key_config.api_key_secret_version

string

这是存储在 Secret Manager 中的密文的完整资源名称,该密文包含 Weaviate 或 Pinecone API 密钥,具体取决于您选择的向量数据库。

格式:projects/{PROJECT_NUMBER}/secrets/{SECRET_ID}/versions/{VERSION_ID}

您可以在 CreateRagCorpus API 调用中将其留空,并在后续的 UpdateRagCorpus API 调用中将其设置为非空值。

rag_embedding_model_config.vertex_prediction_endpoint.endpoint

可选:不可变:string

要用于 RAG 语料库的嵌入模型。此值一经设置便无法更改。如果您将其留空,我们会使用 text-embedding-004 作为嵌入模型。

更新 RAG 语料库

下表列出了用于更新 RAG 语料库的参数。

正文请求
参数

display_name

可选:string

RAG 语料库的显示名称。

description

可选:string

RAG 语料库的说明。

rag_vector_db.weaviate.http_endpoint

string

Weaviate 实例的 HTTP 端点。

如果您的 RagCorpus 是使用 Weaviate 配置创建的,并且之前从未设置过此字段,那么您可以更新 Weaviate 实例的 HTTP 端点。

rag_vector_db.weaviate.collection_name

string

RAG 语料库映射到的 Weaviate 集合。

如果您的 RagCorpus 是使用 Weaviate 配置创建的,并且之前从未设置过此字段,那么您可以更新 Weaviate 实例的集合名称。

rag_vector_db.pinecone.index_name

string

这是用于创建与 RAG 语料库搭配使用的 Pinecone 索引的名称。

如果您的 RagCorpus 是使用 Pinecone 配置创建的,并且之前从未设置过此字段,那么您可以更新 Pinecone 实例的索引名称。

rag_vector_db.vertex_feature_store.feature_view_resource_name

string

RAG 语料库映射到的 Vertex AI Feature Store FeatureView

格式:projects/{project}/locations/{location}/featureOnlineStores/{feature_online_store}/featureViews/{feature_view}

如果您的 RagCorpus 是使用 Vertex AI Feature Store 配置创建的,并且之前从未设置过此字段,则您可以更新它。

rag_vector_db.vertex_vector_search.index

string

这是与 RAG 语料库搭配使用的 Vector Search 索引的资源名称。

格式:projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}

如果您的 RagCorpus 是使用 Vector Search 配置创建的,并且之前从未设置过此字段,则您可以更新它。

rag_vector_db.vertex_vector_search.index_endpoint

string

这是与 RAG 语料库搭配使用的 Vector Search 索引端点的资源名称。

格式:projects/{project}/locations/{location}/indexes/{index}

如果您的 RagCorpus 是使用 Vector Search 配置创建的,并且之前从未设置过此字段,则您可以更新它。

rag_vector_db.api_auth.api_key_config.api_key_secret_version

string

存储在 Secret Manager 中的密文的完整资源名称,该密文包含 Weaviate 或 Pinecone API 密钥,具体取决于您选择的向量数据库。

格式:projects/{PROJECT_NUMBER}/secrets/{SECRET_ID}/versions/{VERSION_ID}

列出 RAG 语料库

下表列出了用于列出 RAG 语料库的参数。

参数

page_size

可选:int

标准列表页面大小。

page_token

可选:string

标准列表页面令牌。 通常从上一个 [VertexRagDataService.ListRagCorpora][] 调用的 [ListRagCorporaResponse.next_page_token][] 中获取。

获取 RAG 语料库

下表列出了用于获取 RAG 语料库的参数。

参数

name

string

RagCorpus 资源的名称。格式:projects/{project}/locations/{location}/ragCorpora/{rag_corpus_id}

删除 RAG 语料库

下表列出了用于删除 RAG 语料库的参数。

参数

name

string

RagCorpus 资源的名称。格式:projects/{project}/locations/{location}/ragCorpora/{rag_corpus_id}

文件管理参数

如需了解 RAG 文件,请参阅文件管理

上传 RAG 文件

下表列出了用于上传 RAG 文件的参数。

正文请求
参数

parent

string

RagCorpus 资源的名称。格式:projects/{project}/locations/{location}/ragCorpora/{rag_corpus_id}

rag_file

必需:RagFile

要上传的文件。

upload_rag_file_config

必需:UploadRagFileConfig

要上传到 RagCorpusRagFile 的配置。

RagFile

display_name

必需:string

RAG 文件的显示名称。

description

可选:string

RAG 文件的说明。

UploadRagFileConfig

rag_file_transformation_config.rag_file_chunking_config.fixed_length_chunking.chunk_size

int32

每个分块具有的词元数。

rag_file_transformation_config.rag_file_chunking_config.fixed_length_chunking.chunk_overlap

int32

分块之间的重叠部分。

导入 RAG 文件

下表列出了用于导入 RAG 文件的参数。

参数

parent

必需:string

RagCorpus 资源的名称。

格式:projects/{project}/locations/{location}/ragCorpora/{rag_corpus_id}

gcs_source

oneof import_sourceGcsSource

Cloud Storage 位置。

支持导入单个文件以及整个 Cloud Storage 目录。

gcs_source.uris

list/string

包含上传文件的 Cloud Storage URI。

google_drive_source

oneof import_sourceGoogleDriveSource

Google 云端硬盘位置。

支持导入单个文件以及 Google 云端硬盘文件夹。

slack_source

oneof import_sourceSlackSource

上传文件的 Slack 频道。

jira_source

oneof import_sourceJiraSource

上传文件的 Jira 查询。

share_point_sources

oneof import_sourceSharePointSources

上传文件的 SharePoint 来源。

rag_file_transformation_config.rag_file_chunking_config.fixed_length_chunking.chunk_size

int32

每个分块具有的词元数。

rag_file_transformation_config.rag_file_chunking_config.fixed_length_chunking.chunk_overlap

int32

分块之间的重叠部分。

rag_file_parsing_config

可选:RagFileParsingConfig

指定 RagFiles 的解析配置。

如果未设置此字段,RAG 会使用默认解析器。

max_embedding_requests_per_min

可选:int32

此作业可以对语料库中指定的嵌入模型进行的每分钟查询次数上限。此值仅适用于此作业,不会与其他导入作业共用。请参阅项目的“配额”页面,设置适当的值。

如果未指定,则使用默认值 1,000 QPM。

GoogleDriveSource

resource_ids.resource_id

必需:string

Google 云端硬盘资源的 ID。

resource_ids.resource_type

必需:string

Google 云端硬盘资源的类型。

SlackSource

channels.channels

重复:SlackSource.SlackChannels.SlackChannel

Slack 频道信息,包括要导入的 ID 和时间范围。

channels.channels.channel_id

必需:string

Slack 频道 ID。

channels.channels.start_time

可选:google.protobuf.Timestamp

要导入的消息的起始时间戳。

channels.channels.end_time

可选:google.protobuf.Timestamp

要导入的消息的结束时间戳。

channels.api_key_config.api_key_secret_version

必需:string

存储在 Secret Manager 中的密文的完整资源名称,该密文包含可用于访问 Slack 频道 ID 的 Slack 频道访问令牌。
请参阅:https://api.slack.com/tutorials/tracks/getting-a-token。

格式:projects/{PROJECT_NUMBER}/secrets/{SECRET_ID}/versions/{VERSION_ID}

JiraSource

jira_queries.projects

重复:string

要完整导入的 Jira 项目的列表。

jira_queries.custom_queries

重复:string

要导入的自定义 Jira 查询的列表。如需了解 JQL (Jira 查询语言),请参阅
Jira 支持

jira_queries.email

必需:string

Jira 电子邮件地址。

jira_queries.server_uri

必需:string

Jira 服务器 URI。

jira_queries.api_key_config.api_key_secret_version

必需:string

存储在 Secret Manager 中的密文的完整资源名称,该密文包含可用于访问 Slack 频道 ID 的 Jira API 密钥。
请参阅:https://support.atlassian.com/atlassian-account/docs/manage-api-tokens-for-your-atlassian-account/

格式:projects/{PROJECT_NUMBER}/secrets/{SECRET_ID}/versions/{VERSION_ID}

SharePointSources

share_point_sources.sharepoint_folder_path

folder_source 中的 oneofstring

要作为下载来源的 SharePoint 文件夹的路径。

share_point_sources.sharepoint_folder_id

folder_source 中的 oneofstring

要作为下载来源的 SharePoint 文件夹的 ID。

share_point_sources.drive_name

drive_source 中的 oneofstring

要作为下载来源的云端硬盘的名称。

share_point_sources.drive_id

drive_source 中的 oneofstring

要作为下载来源的云端硬盘的 ID。

share_point_sources.client_id

string

在 Microsoft Azure 门户中注册的应用的应用 ID。
应用还必须配置 MS Graph 权限“Files.ReadAll”“Sites.ReadAll”和“BrowserSiteLists.Read.All”。

share_point_sources.client_secret.api_key_secret_version

必需:string

存储在 Secret Manager 中的密文的完整资源名称,该密文包含在 Azure 中注册的应用的应用密文。

格式:projects/{PROJECT_NUMBER}/secrets/{SECRET_ID}/versions/{VERSION_ID}

share_point_sources.tenant_id

string

Azure Active Directory 实例的唯一标识符。

share_point_sources.sharepoint_site_name

string

要作为下载来源的 SharePoint 网站的名称。这可以是网站名称,也可以是网站 ID。

RagFileParsingConfig

layout_parser

oneof parserRagFileParsingConfig.LayoutParser

要用于 RagFile 的布局解析器。

layout_parser.processor_name

string

Document AI 处理器或处理器版本的完整资源名称。

格式:
projects/{project_id}/locations/{location}/processors/{processor_id}
projects/{project_id}/locations/{location}/processors/{processor_id}/processorVersions/{processor_version_id}

layout_parser.max_parsing_requests_per_min

string

作业每分钟可向 Document AI 处理器发出的请求数上限。

请访问 https://cloud.google.com/document-ai/quotas 和项目的“配额”页面,在此处设置适当的值。如果未指定,则使用默认值 120 QPM。

获取 RAG 文件

下表列出了用于获取 RAG 文件的参数。

参数

name

string

RagFile 资源的名称。格式:projects/{project}/locations/{location}/ragCorpora/{rag_file_id}

删除 RAG 文件

下表列出了用于删除 RAG 文件的参数。

参数

name

string

RagFile 资源的名称。格式:projects/{project}/locations/{location}/ragCorpora/{rag_file_id}

检索和预测

本部分列出了检索和预测参数。

检索参数

下表列出了 retrieveContexts API 的参数。

参数

parent

必需:string

要检索 RagContexts 的位置的资源名称。
用户必须有权在项目中进行调用。

格式:projects/{project}/locations/{location}

vertex_rag_store

VertexRagStore

Vertex RagStore 的数据源。

query

必需:RagQuery

单个 RAG 检索查询。

VertexRagStore
VertexRagStore

rag_resources

列表:RagResource

RAG 来源的表示法。它可用于仅指定语料库或 RagFile。仅支持一个语料库或一个语料库中的多个文件。

rag_resources.rag_corpus

可选:string

RagCorpora 资源名称。

格式:projects/{project}/locations/{location}/ragCorpora/{rag_corpus}

rag_resources.rag_file_ids

列表:string

RagFile 资源的列表。

格式:projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file}

RagQuery

text

string

要获取相关上下文的文本格式的查询。

rag_retrieval_config

可选:RagRetrievalConfig

用于查询的检索配置。

RagRetrievalConfig

top_k

可选:int32

要检索的上下文数量。

hybrid_search.alpha

可选:float

alpha 值用于控制密集和稀疏向量搜索结果之间的权重。范围为 [0, 1],其中 0 表示仅进行稀疏向量搜索,1 表示仅进行密集向量搜索。默认值为 0.5,可平等均衡稀疏向量搜索和密集向量搜索。

混合搜索仅适用于 Weaviate。

filter.vector_distance_threshold

oneof vector_db_thresholddouble

仅返回向量距离小于阈值的上下文。

filter.vector_similarity_threshold

oneof vector_db_thresholddouble

仅返回向量相似度大于阈值的上下文。

ranking.rank_service.model_name

可选:string

排名服务的模型名称。

示例:semantic-ranker-512@latest

ranking.llm_ranker.model_name

可选:string

用于排名的模型名称。

示例:gemini-1.5-pro

预测参数

下表列出了预测参数。

GenerateContentRequest

tools.retrieval.vertex_rag_store

VertexRagStore

设置为使用由 Vertex AI RAG 存储空间提供支持的数据源。

如需了解详情,请参阅 VertexRagStore

语料库管理示例

本部分举例说明了如何使用 API 管理 RAG 语料库。

创建 RAG 语料库示例

此代码示例演示了如何创建 RAG 语料库。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的项目 ID
  • LOCATION:处理请求的区域。
  • CORPUS_DISPLAY_NAMERagCorpus 的显示名称。
  • CORPUS_DESCRIPTIONRagCorpus 的说明。

HTTP 方法和网址:

POST https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora

请求 JSON 正文:

{
  "display_name" : "CORPUS_DISPLAY_NAME",
  "description": "CORPUS_DESCRIPTION",
}

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora"

PowerShell

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora" | Select-Object -Expand Content
您应该会收到一个成功状态代码 (2xx)。

以下示例演示了如何使用 REST API 创建 RAG 语料库。

  PROJECT_ID: Your project ID.
  LOCATION: The region to process the request.
  CORPUS_DISPLAY_NAME: The display name of the <code>RagCorpus</code>.
    // CreateRagCorpus
    // Input: LOCATION, PROJECT_ID, CORPUS_DISPLAY_NAME
    // Output: CreateRagCorpusOperationMetadata
    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora \
    -d '{
          "display_name" : "CORPUS_DISPLAY_NAME"
      }'

Vertex AI SDK for Python

如需了解如何安装或更新 Vertex AI SDK for Python,请参阅安装 Vertex AI SDK for Python。 如需了解详情,请参阅 Python 版 Vertex AI SDK API 参考文档


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-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 (Optional)
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)
# Example response:
# RagCorpus(name='projects/1234567890/locations/us-central1/ragCorpora/1234567890',
# display_name='test_corpus', description='Corpus Description', embedding_model_config=...
# ...

更新 RAG 语料库示例

您可以使用新的显示名称、说明和向量数据库配置更新 RAG 语料库。不过,您无法更改 RAG 语料库中的以下参数

  • 向量数据库类型。例如,您无法将向量数据库从 Weaviate 更改为 Vertex AI Feature Store。
  • 如果您使用的是托管式数据库选项,则无法更新向量数据库配置。

以下示例演示了如何更新 RAG 语料库。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的项目 ID
  • LOCATION:处理请求的区域。
  • CORPUS_ID:RAG 语料库的语料库 ID。
  • CORPUS_DISPLAY_NAMERagCorpus 的显示名称。
  • CORPUS_DESCRIPTIONRagCorpus 的说明。
  • INDEX_NAMEVector Search Index 的资源名称。格式:projects/{project}/locations/{location}/indexes/{index}
  • INDEX_ENDPOINT_NAMEVector Search Index Endpoint 的资源名称。格式:projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}

HTTP 方法和网址:

PATCH https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/CORPUS_ID

请求 JSON 正文:

{
  "display_name" : "CORPUS_DISPLAY_NAME",
  "description": "CORPUS_DESCRIPTION",
  "rag_vector_db_config": {
     "vertex_vector_search": {
         "index": "INDEX_NAME",
         "index_endpoint": "INDEX_ENDPOINT_NAME",
     }
  }
}

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/CORPUS_ID"

PowerShell

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method PATCH `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/CORPUS_ID" | Select-Object -Expand Content
您应该会收到一个成功状态代码 (2xx)。

列出 RAG 语料库示例

此代码示例演示了如何列出所有 RAG 语料库。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的项目 ID
  • LOCATION:处理请求的区域。
  • PAGE_SIZE:标准列表页面大小。您可以通过更新 page_size 参数来调整每页返回的 RagCorpora 数量。
  • PAGE_TOKEN:标准列表页面词元。通常使用前一个 VertexRagDataService.ListRagCorpora 调用的 ListRagCorporaResponse.next_page_token 获取。

HTTP 方法和网址:

GET https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora?page_size=PAGE_SIZE&page_token=PAGE_TOKEN

如需发送请求,请选择以下方式之一:

curl

执行以下命令:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora?page_size=PAGE_SIZE&page_token=PAGE_TOKEN"

PowerShell

执行以下命令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora?page_size=PAGE_SIZE&page_token=PAGE_TOKEN" | Select-Object -Expand Content
您应该会收到一个成功状态代码 (`2xx`) 和一个给定 PROJECT_ID 下的 RagCorpora 列表。

Vertex AI SDK for Python

如需了解如何安装或更新 Vertex AI SDK for Python,请参阅安装 Vertex AI SDK for Python。 如需了解详情,请参阅 Python 版 Vertex AI SDK API 参考文档


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"

# Initialize Vertex AI API once per session
vertexai.init(project=PROJECT_ID, location="us-central1")

corpora = rag.list_corpora()
print(corpora)
# Example response:
# ListRagCorporaPager<rag_corpora {
#   name: "projects/[PROJECT_ID]/locations/us-central1/ragCorpora/2305843009213693952"
#   display_name: "test_corpus"
#   create_time {
# ...

获取 RAG 语料库示例

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的项目 ID
  • LOCATION:处理请求的区域。
  • RAG_CORPUS_IDRagCorpus 资源的 ID。

HTTP 方法和网址:

GET https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID

如需发送请求,请选择以下方式之一:

curl

执行以下命令:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID"

PowerShell

执行以下命令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID" | Select-Object -Expand Content
成功的响应会返回 RagCorpus 资源。

示例使用 getlist 命令来演示 RagCorpus 如何在 vector_db_config 中使用 rag_embedding_model_config 字段指向您选择的嵌入模型。

  PROJECT_ID: Your project ID.
  LOCATION: The region to process the request.
  RAG_CORPUS_ID: The corpus ID of your RAG corpus.
// GetRagCorpus
// Input: LOCATION, PROJECT_ID, RAG_CORPUS_ID
// Output: RagCorpus
curl -X GET \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID

// ListRagCorpora
curl -sS -X GET \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/

Vertex AI SDK for Python

如需了解如何安装或更新 Vertex AI SDK for Python,请参阅安装 Vertex AI SDK for Python。 如需了解详情,请参阅 Python 版 Vertex AI SDK API 参考文档


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-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)
# Example response:
# RagCorpus(name='projects/[PROJECT_ID]/locations/us-central1/ragCorpora/1234567890',
# display_name='test_corpus', description='Corpus Description',
# ...

删除 RAG 语料库示例

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的项目 ID
  • LOCATION:处理请求的区域。
  • RAG_CORPUS_IDRagCorpus 资源的 ID。

HTTP 方法和网址:

DELETE https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID

如需发送请求,请选择以下方式之一:

curl

执行以下命令:

curl -X DELETE \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID"

PowerShell

执行以下命令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method DELETE `
-Headers $headers `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID" | Select-Object -Expand Content
成功的响应会返回 DeleteOperationMetadata

Vertex AI SDK for Python

如需了解如何安装或更新 Vertex AI SDK for Python,请参阅安装 Vertex AI SDK for Python。 如需了解详情,请参阅 Python 版 Vertex AI SDK API 参考文档


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-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.")
# Example response:
# Successfully deleted the RagCorpus.
# Corpus projects/[PROJECT_ID]/locations/us-central1/ragCorpora/123456789012345 deleted.

文件管理示例

本部分举例说明了如何使用 API 管理 RAG 文件。

上传 RAG 文件示例

REST

在使用任何请求数据之前,请先进行以下替换:

  PROJECT_ID: Your project ID.
  LOCATION: The region to process the request.
  RAG_CORPUS_ID: The corpus ID of your RAG corpus.
  LOCAL_FILE_PATH: The local path to the file to be uploaded.
  DISPLAY_NAME: The display name of the RAG file.
  DESCRIPTION: The description of the RAG file.

如需发送请求,请使用以下命令:

  curl -X POST \
    -H "X-Goog-Upload-Protocol: multipart" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -F metadata="{'rag_file': {'display_name':' DISPLAY_NAME', 'description':'DESCRIPTION'}}" \
    -F file=@LOCAL_FILE_PATH \
    "https://LOCATION-aiplatform.googleapis.com/upload/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles:upload"

Vertex AI SDK for Python

如需了解如何安装或更新 Vertex AI SDK for Python,请参阅安装 Vertex AI SDK for Python。 如需了解详情,请参阅 Python 版 Vertex AI SDK API 参考文档


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-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)
# RagFile(name='projects/[PROJECT_ID]/locations/us-central1/ragCorpora/1234567890/ragFiles/09876543',
#  display_name='file_display_name', description='file description')

导入 RAG 文件示例

您可以从云端硬盘或 Cloud Storage 导入文件和文件夹。

response.skipped_rag_files_count 是指导入期间跳过的文件数量。如果满足以下条件,系统会跳过某个文件:

  1. 该文件已导入。
  2. 该文件未更改。
  3. 该文件的分块配置未更改。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的项目 ID
  • LOCATION:处理请求的区域。
  • RAG_CORPUS_IDRagCorpus 资源的 ID。
  • GCS_URIS:Cloud Storage 位置列表。示例:gs://my-bucket1, gs://my-bucket2
  • CHUNK_SIZE(可选):每个分块应具有的词元数。
  • CHUNK_OVERLAP(可选):分块之间的词元重叠数。

HTTP 方法和网址:

POST https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles:import

请求 JSON 正文:

{
  "import_rag_files_config": {
    "gcs_source": {
      "uris": "GCS_URIS"
    },
    "rag_file_chunking_config": {
      "chunk_size": CHUNK_SIZE,
      "chunk_overlap": CHUNK_OVERLAP
    }
  }
}

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles:import"

PowerShell

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles:import" | Select-Object -Expand Content
成功的响应会返回 ImportRagFilesOperationMetadata 资源。

以下示例演示了如何从 Cloud Storage 导入文件。使用 max_embedding_requests_per_min 控制字段限制 RAG 引擎在 ImportRagFiles 索引编制过程中调用嵌入模型的速率。该字段的默认值为每分钟 1000 次调用。

  PROJECT_ID: Your project ID.
  LOCATION: The region to process the request.
  RAG_CORPUS_ID: The corpus ID of your RAG corpus.
  GCS_URIS: A list of Cloud Storage locations. Example: gs://my-bucket1.
  CHUNK_SIZE: Number of tokens each chunk should have.
  CHUNK_OVERLAP: Number of tokens overlap between chunks.
  EMBEDDING_MODEL_QPM_RATE: The QPM rate to limit RAGs access to your embedding model. Example: 1000.
// ImportRagFiles
// Import a single Cloud Storage file or all files in a Cloud Storage bucket.
// Input: LOCATION, PROJECT_ID, RAG_CORPUS_ID, GCS_URIS
// Output: ImportRagFilesOperationMetadataNumber
// Use ListRagFiles to find the server-generated rag_file_id.
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles:import \
-d '{
  "import_rag_files_config": {
    "gcs_source": {
      "uris": "GCS_URIS"
    },
    "rag_file_chunking_config": {
      "chunk_size": CHUNK_SIZE,
      "chunk_overlap": CHUNK_OVERLAP
    },
    "max_embedding_requests_per_min": EMBEDDING_MODEL_QPM_RATE
  }
}'

// Poll the operation status.
// The response contains the number of files imported.
OPERATION_ID: The operation ID you get from the response of the previous command.
poll_op_wait OPERATION_ID

以下示例演示了如何从云端硬盘导入文件。使用 max_embedding_requests_per_min 控制字段限制 RAG 引擎在 ImportRagFiles 索引编制过程中调用嵌入模型的速率。该字段的默认值为每分钟 1000 次调用。

  PROJECT_ID: Your project ID.
  LOCATION: The region to process the request.
  RAG_CORPUS_ID: The corpus ID of your RAG corpus.
  FOLDER_RESOURCE_ID: The resource ID of your Google Drive folder.
  CHUNK_SIZE: Number of tokens each chunk should have.
  CHUNK_OVERLAP: Number of tokens overlap between chunks.
  EMBEDDING_MODEL_QPM_RATE: The QPM rate to limit RAGs access to your embedding model. Example: 1000.
// ImportRagFiles
// Import all files in a Google Drive folder.
// Input: LOCATION, PROJECT_ID, RAG_CORPUS_ID, FOLDER_RESOURCE_ID
// Output: ImportRagFilesOperationMetadataNumber
// Use ListRagFiles to find the server-generated rag_file_id.
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles:import \
-d '{
  "import_rag_files_config": {
    "google_drive_source": {
      "resource_ids": {
        "resource_id": "FOLDER_RESOURCE_ID",
        "resource_type": "RESOURCE_TYPE_FOLDER"
      }
    },
    "max_embedding_requests_per_min": EMBEDDING_MODEL_QPM_RATE
  }
}'

// Poll the operation status.
// The response contains the number of files imported.
OPERATION_ID: The operation ID you get from the response of the previous command.
poll_op_wait OPERATION_ID

Python 版 Vertex AI SDK

如需了解如何安装或更新 Vertex AI SDK for Python,请参阅安装 Vertex AI SDK for Python。 如需了解详情,请参阅 Python 版 Vertex AI SDK API 参考文档


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-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.")
# Example response:
# Imported 2 files.

列出 RAG 文件示例

此代码示例演示了如何列出 RAG 文件。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的项目 ID
  • LOCATION:处理请求的区域。
  • RAG_CORPUS_IDRagCorpus 资源的 ID。
  • PAGE_SIZE:标准列表页面大小。您可以通过更新 page_size 参数来调整每页返回的 RagFiles 数量。
  • PAGE_TOKEN:标准列表页面词元。通常使用前一个 VertexRagDataService.ListRagFiles 调用的 ListRagFilesResponse.next_page_token 获取。

HTTP 方法和网址:

GET https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles?page_size=PAGE_SIZE&page_token=PAGE_TOKEN

如需发送请求,请选择以下方式之一:

curl

执行以下命令:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles?page_size=PAGE_SIZE&page_token=PAGE_TOKEN"

PowerShell

执行以下命令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles?page_size=PAGE_SIZE&page_token=PAGE_TOKEN" | Select-Object -Expand Content
您应该会收到一个成功状态代码 (2xx) 以及给定 RAG_CORPUS_ID 下的 RagFiles 列表。

Python 版 Vertex AI SDK

如需了解如何安装或更新 Vertex AI SDK for Python,请参阅安装 Vertex AI SDK for Python。 如需了解详情,请参阅 Python 版 Vertex AI SDK API 参考文档


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-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.display_name)
    print(file.name)
# Example response:
# g-drive_file.txt
# projects/1234567890/locations/us-central1/ragCorpora/111111111111/ragFiles/222222222222
# g_cloud_file.txt
# projects/1234567890/locations/us-central1/ragCorpora/111111111111/ragFiles/333333333333

获取 RAG 文件示例

此代码示例演示了如何获取 RAG 文件。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的项目 ID
  • LOCATION:处理请求的区域。
  • RAG_CORPUS_IDRagCorpus 资源的 ID。
  • RAG_FILE_IDRagFile 资源的 ID。

HTTP 方法和网址:

GET https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID

如需发送请求,请选择以下方式之一:

curl

执行以下命令:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID"

PowerShell

执行以下命令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID" | Select-Object -Expand Content
成功的响应会返回 RagFile 资源。

Python 版 Vertex AI SDK

如需了解如何安装或更新 Vertex AI SDK for Python,请参阅安装 Vertex AI SDK for Python。 如需了解详情,请参阅 Python 版 Vertex AI SDK API 参考文档


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-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)
# Example response:
# RagFile(name='projects/1234567890/locations/us-central1/ragCorpora/11111111111/ragFiles/22222222222',
# display_name='file_display_name', description='file description')

删除 RAG 文件示例

此代码示例演示了如何删除 RAG 文件。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的项目 ID
  • LOCATION:处理请求的区域。
  • RAG_CORPUS_IDRagCorpus 资源的 ID。
  • RAG_FILE_IDRagFile 资源的 ID。格式:projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file_id}

HTTP 方法和网址:

DELETE https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID

如需发送请求,请选择以下方式之一:

curl

执行以下命令:

curl -X DELETE \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID"

PowerShell

执行以下命令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method DELETE `
-Headers $headers `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID" | Select-Object -Expand Content
成功的响应会返回 DeleteOperationMetadata 资源。

Python 版 Vertex AI SDK

如需了解如何安装或更新 Vertex AI SDK for Python,请参阅安装 Vertex AI SDK for Python。 如需了解详情,请参阅 Python 版 Vertex AI SDK API 参考文档


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-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.")
# Example response:
# Successfully deleted the RagFile.
# File projects/1234567890/locations/us-central1/ragCorpora/1111111111/ragFiles/2222222222 deleted.

检索查询

当用户提问或提供问题时,RAG 中的检索组件会搜索其知识库,以查找与查询相关的信息。

REST

在使用任何请求数据之前,请先进行以下替换:

  • LOCATION:处理请求的区域。
  • PROJECT_ID:您的项目 ID
  • RAG_CORPUS_RESOURCERagCorpus 资源的名称。格式:projects/{project}/locations/{location}/ragCorpora/{rag_corpus}
  • VECTOR_DISTANCE_THRESHOLD:仅返回向量距离小于阈值的上下文。
  • TEXT:要获取相关上下文的查询文本。
  • SIMILARITY_TOP_K:要检索的热门上下文数量。

HTTP 方法和网址:

POST https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION:retrieveContexts

请求 JSON 正文:

{
 "vertex_rag_store": {
    "rag_resources": {
      "rag_corpus": "RAG_CORPUS_RESOURCE"
    },
    "vector_distance_threshold": VECTOR_DISTANCE_THRESHOLD
  },
  "query": {
   "text": "TEXT",
   "similarity_top_k": SIMILARITY_TOP_K
  }
}

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION:retrieveContexts"

PowerShell

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION:retrieveContexts" | Select-Object -Expand Content
您应该会收到一个成功状态代码 (2xx) 以及相关RagFiles 的列表。

Python 版 Vertex AI SDK

如需了解如何安装或更新 Vertex AI SDK for Python,请参阅安装 Vertex AI SDK for Python。 如需了解详情,请参阅 Python 版 Vertex AI SDK API 参考文档


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-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")

response = rag.retrieval_query(
    rag_resources=[
        rag.RagResource(
            rag_corpus=corpus_name,
            # Optional: supply IDs from `rag.list_files()`.
            # rag_file_ids=["rag-file-1", "rag-file-2", ...],
        )
    ],
    text="Hello World!",
    similarity_top_k=10,  # Optional
    vector_distance_threshold=0.5,  # Optional
    # vector_search_alpha=0.5, # Optional - Only supported for Weaviate
)
print(response)
# Example response:
# contexts {
#   contexts {
#     source_uri: "gs://your-bucket-name/file.txt"
#     text: "....
#   ....

生成

LLM 使用检索到的上下文生成有依据的回答。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的项目 ID
  • LOCATION:处理请求的区域。
  • MODEL_ID:用于内容生成的 LLM 模型。示例:gemini-1.5-pro-002
  • GENERATION_METHOD:用于生成内容的 LLM 方法。选项:generateContentstreamGenerateContent
  • INPUT_PROMPT:发送到 LLM 用于生成内容的文本。尝试使用与上传的 rag 文件相关的问题。
  • RAG_CORPUS_RESOURCERagCorpus 资源的名称。格式:projects/{project}/locations/{location}/ragCorpora/{rag_corpus}
  • SIMILARITY_TOP_K(可选):要检索的热门上下文数量。
  • VECTOR_DISTANCE_THRESHOLD(可选):返回向量距离小于阈值的上下文。

HTTP 方法和网址:

POST https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATION_METHOD

请求 JSON 正文:

{
 "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,
    "vector_distance_threshold": VECTOR_DISTANCE_THRESHOLD
   }
  }
 }
}

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATION_METHOD"

PowerShell

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATION_METHOD" | Select-Object -Expand Content
成功的响应会返回生成的内容以及引用。

Python 版 Vertex AI SDK

如需了解如何安装或更新 Vertex AI SDK for Python,请参阅安装 Vertex AI SDK for Python。 如需了解详情,请参阅 Python 版 Vertex AI SDK API 参考文档


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 = "your-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_retrieval_tool = Tool.from_retrieval(
    retrieval=rag.Retrieval(
        source=rag.VertexRagStore(
            rag_resources=[
                rag.RagResource(
                    rag_corpus=corpus_name,
                    # Optional: 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)
# 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....
#   ...

后续步骤