RAG Engine API

Vertex AI RAG Engine 是 Vertex AI 平台的一項元件,用於檢索增強生成 (RAG)。透過 RAG 引擎,大型語言模型 (LLM) 可以存取及使用外部知識來源 (例如文件和資料庫) 的資料,生成更準確實用的回覆。

本文提供 RAG Engine API 的使用資訊和範例,涵蓋下列主題:

  • 語料庫管理說明管理語料庫的 API 參數,並提供建立、更新、列出、取得及刪除 RAG 語料庫的範例。
  • 檔案管理說明管理檔案的 API 參數,並提供在 RAG 語料庫中上傳、匯入及管理檔案的範例。
  • 擷取和生成說明擷取脈絡和生成有根據的回覆的 API 參數,並提供範例。
  • 專案管理說明如何設定 RAG 引擎的專案層級設定,並提供範例。

下圖概略說明使用 RAG Engine API 的整體工作流程:

語料庫管理參數

本節說明管理 RAG 語料庫的參數。詳情請參閱「管理語料庫」。

建立 RAG 語料庫

下表說明用於建立 RAG 語料庫的參數。

向量資料庫選項

您可以為 RAG 語料庫選擇下列其中一個向量資料庫選項。

向量資料庫選項 說明 用途
rag_managed_db Vertex AI 提供的全代管無伺服器向量資料庫。這是預設選項。 如果您想要簡單的整合式解決方案,且不想管理自己的向量資料庫基礎架構,建議使用這項服務。
pinecone 與自行管理的 Pinecone 向量資料庫整合。需要提供 Pinecone 索引名稱和 API 金鑰。 如果您已設定 Pinecone,或偏好使用其特定功能,請選用這個選項。
vertex_vector_search 與 Vector Search 整合。必須提供索引和索引端點資源名稱。 如果您需要 Google Cloud 生態系統內的高效能可擴充向量搜尋解決方案,請使用這個選項。

要求主體

參數
display_name

必要條件:string

RAG 語料庫的顯示名稱。

description

自由參加:string

RAG 語料庫的說明。

encryption_spec

選用:不可變更:string

用於加密與 RAG 語料庫相關靜態資料的 CMEK 金鑰名稱。這個金鑰僅適用於向量資料庫的 RagManaged 選項。這個欄位只能在建立語料庫時設定。

格式:projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{key_name}

vector_db_config

選用:不可變更:vectorDbConfig

向量資料庫的設定。這個欄位是 oneof 物件。選擇下列其中一個選項:

  • rag_managed_db:預設的全代管向量資料庫。
  • pinecone:指定 Pinecone 執行個體。
    • index_name (string):Pinecone 索引的名稱。之後可以透過 UpdateRagCorpus 呼叫設定這項屬性。
    • api_auth.api_key_config.api_key_secret_version (string):Secret Manager 中包含 Pinecone API 金鑰的密碼完整資源名稱。格式:projects/{PROJECT_NUMBER}/secrets/{SECRET_ID}/versions/{VERSION_ID}。你稍後可以再設定。
  • vertex_vector_search:指定 Vector Search 執行個體。
    • index (string):Vector Search 索引的資源名稱。格式:projects/{project}/locations/{location}/indexes/{index}。你稍後可以再設定。
    • index_endpoint (string):Vector Search 索引端點的資源名稱。格式:projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}。你稍後可以再設定。
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}

rag_embedding_model_config.vertex_prediction_endpoint.endpoint

選用:不可變更:string

用於 RAG 語料庫的嵌入模型。設定後即無法變更值。如果留空,系統會使用 text-embedding-005 做為預設嵌入模型。

更新 RAG 語料庫

下表列出用於更新 RAG 語料庫的參數。

要求主體

參數
display_name

自由參加:string

RAG 語料庫的新顯示名稱。

description

自由參加:string

RAG 語料庫的新說明。

rag_vector_db.pinecone.index_name

string

Pinecone 索引的名稱。如果您的 RagCorpus 是以 Pinecone 設定建立,且先前未設定索引名稱,則可以設定這個欄位。

rag_vector_db.vertex_vector_search.index

string

Vector Search 索引的資源名稱。如果 RagCorpus 是以 Vector Search 設定建立,且先前未設定索引,即可設定這個欄位。

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

rag_vector_db.vertex_vector_search.index_endpoint

string

Vector Search 索引端點的資源名稱。如果您的 RagCorpus 是以 Vector Search 設定建立,且先前未設定索引端點,則可以設定這個欄位。

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

rag_vector_db.api_auth.api_key_config.api_key_secret_version

string

Secret Manager 中密鑰的完整資源名稱,內含 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

要上傳的檔案。包含下列欄位:

  • display_name (必填,string):RAG 檔案的顯示名稱。
  • description (選用,string):RAG 檔案的說明。
upload_rag_file_config

必要條件:UploadRagFileConfig

RagFile 的設定。包含下列欄位:

  • 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 個查詢的預設值。

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 執行個體的專屬 ID。

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。

llm_parser

oneof parserRagFileParsingConfig.LlmParser

用於 RagFile 的 LLM 剖析器。

llm_parser.model_name

string

LLM 模型的資源名稱。

格式:
projects/{project_id}/locations/{location}/publishers/{publisher}/models/{model}

llm_parser.max_parsing_requests_per_min

string

工作每分鐘可向 LLM 模型提出的要求數上限。

如要為專案設定適當的值,請參閱模型配額部分和專案的「配額」頁面,以便在此設定適當的值。如未指定,系統會使用預設值 5000 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

要擷取的內容數量。

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-2.5-flash

預測參數

下表列出預測參數。

GenerateContentRequest

tools.retrieval.vertex_rag_store

VertexRagStore

設定為使用由 Vertex AI RAG 商店支援的資料來源。

詳情請參閱 VertexRagStore

專案管理參數

下表列出 RAG 引擎受管理資料庫的專案層級層級設定。

級別 說明 用途
RagManagedDbConfig.scaled 生產規模層級,可為受管理向量資料庫提供高效能和自動調整資源配置功能。 建議用於查詢負載高或資料量大的實際工作環境應用程式。
RagManagedDbConfig.basic 經濟實惠的低運算資源層級,適用於受管理向量資料庫。 適用於開發、測試或流量較低的應用程式。
RagManagedDbConfig.unprovisioned 刪除代管向量資料庫及其底層資源。這會有效停用專案的受管理資料庫。 不再需要代管資料庫基礎架構時,請使用這項功能將其拆除,以利管理費用。

語料庫管理範例

本節提供範例,說明如何使用 API 管理 RAG 語料庫。

建立 RAG 語料庫範例

這些程式碼範例示範如何建立 RAG 語料庫。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的專案 ID。
  • LOCATION:處理要求的區域。
  • CORPUS_DISPLAY_NAME:RAG 語料庫的顯示名稱。
  • CORPUS_DESCRIPTION:RAG 語料庫的說明。

HTTP 方法和網址:

POST https://LOCATION-aiplatform.googleapis.com/v1/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/v1/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/v1/projects/PROJECT_ID/locations/LOCATION/ragCorpora" | Select-Object -Expand Content

您應該會收到執行成功的狀態碼 (2xx)。

以下範例說明如何使用 REST API 建立 RAG 語料庫。

  // 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/v1/projects/PROJECT_ID/locations/LOCATION/ragCorpora \
  -d '{
        "display_name" : "CORPUS_DISPLAY_NAME"
    }'

Python

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Python API 參考說明文件


from vertexai 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 backend_config
backend_config = rag.RagVectorDbConfig(
    rag_embedding_model_config=rag.RagEmbeddingModelConfig(
        vertex_prediction_endpoint=rag.VertexPredictionEndpoint(
            publisher_model="publishers/google/models/text-embedding-005"
        )
    )
)

corpus = rag.create_corpus(
    display_name=display_name,
    description=description,
    backend_config=backend_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 語料庫中變更下列不可變更的參數:

  • 向量資料庫類型。舉例來說,您無法將向量資料庫從 Pinecone 變更為 Vector Search。
  • 如果您使用受管理資料庫選項,則無法更新向量資料庫設定。

以下範例說明如何更新 RAG 語料庫。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的專案 ID。
  • LOCATION:處理要求的區域。
  • CORPUS_ID:RAG 語料庫的語料庫 ID。
  • CORPUS_DISPLAY_NAME:RAG 語料庫的顯示名稱。
  • CORPUS_DESCRIPTION:RAG 語料庫的說明。
  • INDEX_NAME:Vector Search Index 的資源名稱。格式: projects/{project}/locations/{location}/indexes/{index}
  • INDEX_ENDPOINT_NAME:Vector Search 索引端點的資源名稱。格式: projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}

HTTP 方法和網址:

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

JSON 要求內文:

{
  "display_name" : "CORPUS_DISPLAY_NAME",
  "description": "CORPUS_DESCRIPTION",
  "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/v1/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/v1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/CORPUS_ID" | Select-Object -Expand Content

成功的要求會傳回 2xx 狀態碼。

列出 RAG 語料庫範例

這些程式碼範例示範如何列出所有 RAG 語料庫。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的專案 ID。
  • LOCATION:處理要求的區域。
  • PAGE_SIZE:每個頁面要傳回的 RAG 語料庫數量上限。
  • PAGE_TOKEN:先前 ListRagCorpora 回應中的頁面權杖,用於擷取下一頁結果。

HTTP 方法和網址:

GET https://LOCATION-aiplatform.googleapis.com/v1/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/v1/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/v1/projects/PROJECT_ID/locations/LOCATION/ragCorpora?page_size=PAGE_SIZE&page_token=PAGE_TOKEN" | Select-Object -Expand Content

如果要求成功,系統會傳回 2xx 狀態碼,以及指定專案的 RAG 語料庫清單。

Python

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Python API 參考說明文件


from vertexai 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 語料庫範例

這些程式碼範例示範如何取得 RAG 語料庫。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的專案 ID。
  • LOCATION:處理要求的區域。
  • RAG_CORPUS_ID:RAG 語料庫資源的 ID。

HTTP 方法和網址:

GET https://LOCATION-aiplatform.googleapis.com/v1/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/v1/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/v1/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.
  ```

```sh
  // 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/v1/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/v1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/
  ```

Python

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Python API 參考說明文件


from vertexai 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 語料庫範例

這些程式碼範例示範如何刪除 RAG 語料庫。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的專案 ID。
  • LOCATION:處理要求的區域。
  • RAG_CORPUS_IDRagCorpus 資源的 ID。

HTTP 方法和網址:

DELETE https://LOCATION-aiplatform.googleapis.com/v1/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/v1/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/v1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID" | Select-Object -Expand Content

成功的回應會傳回 DeleteOperationMetadata

Python

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Python API 參考說明文件


from vertexai 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 檔案範例

這些程式碼範例示範如何上傳 RAG 檔案。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的專案 ID。
  • LOCATION:處理要求的區域。
  • RAG_CORPUS_ID:RAG 語料庫的語料庫 ID。
  • LOCAL_FILE_PATH:要上傳的檔案在本機的路徑。
  • DISPLAY_NAME:RAG 檔案的顯示名稱。
  • DESCRIPTION:RAG 檔案的說明。

如要傳送要求,請使用下列指令:

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/v1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles:upload"

Python

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Python API 參考說明文件


from vertexai 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.metadata,在 SDK 的 response 物件中查看部分失敗、要求時間和回應時間。

response.skipped_rag_files_count 欄位會顯示匯入作業中略過的檔案數。如果符合下列條件,服務會略過檔案:

  1. 檔案已匯入。
  2. 檔案未變更。
  3. 檔案的分塊設定未變更。

Python

from vertexai 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 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,
    transformation_config=rag.TransformationConfig(
        rag.ChunkingConfig(chunk_size=1024, chunk_overlap=256)
    ),
    import_result_sink="gs://sample-existing-folder/sample_import_result_unique.ndjson",  # Optional: This must be an existing Cloud Storage bucket folder, and the filename must be unique (non-existent).
    llm_parser=rag.LlmParserConfig(
      model_name="gemini-2.5-pro-preview-05-06",
      max_parsing_requests_per_min=100,
    ),  # Optional
    max_embedding_requests_per_min=900,  # Optional
)
print(f"Imported {response.imported_rag_files_count} files.")

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的專案 ID。
  • LOCATION:處理要求的區域。
  • RAG_CORPUS_ID:RAG 語料庫的語料庫 ID。
  • FOLDER_RESOURCE_ID:Google 雲端硬碟資料夾的資源 ID。
  • GCS_URIS:Cloud Storage 位置清單。 範例:gs://my-bucket1
  • CHUNK_SIZE:每個分塊應有的權杖數量。
  • CHUNK_OVERLAP:區塊之間重疊的權杖數量。
  • EMBEDDING_MODEL_QPM_RATE:限制 RAG 存取嵌入模型的 QPM 速率。例如:1,000。

HTTP 方法和網址:

POST https://LOCATION-aiplatform.googleapis.com/v1/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/v1/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/v1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles:import" | Select-Object -Expand Content

成功的回應會傳回 ImportRagFilesOperationMetadata 資源。

下列範例示範如何從 Cloud Storage 匯入檔案。在 ImportRagFiles 索引程序期間,使用 max_embedding_requests_per_min 控制欄位限制 RAG Engine 呼叫嵌入模型的速度。這個欄位的預設值為每分鐘 1000 次呼叫。

  • PROJECT_ID:您的專案 ID。
  • LOCATION:處理要求的區域。
  • RAG_CORPUS_ID:RAG 語料庫的語料庫 ID。
  • GCS_URIS:Cloud Storage 位置清單。 範例:gs://my-bucket1
  • CHUNK_SIZE:每個分塊應有的權杖數量。
  • CHUNK_OVERLAP:區塊之間重疊的權杖數量。
  • EMBEDDING_MODEL_QPM_RATE:限制 RAG 存取嵌入模型的 QPM 速率。例如:1,000。
// 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/v1/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
  }
}'

下列範例說明如何從雲端硬碟匯入檔案。在 ImportRagFiles 索引程序期間,使用 max_embedding_requests_per_min 控制欄位限制 RAG 引擎呼叫嵌入模型的速率。這個欄位的預設值為每分鐘 1000 次呼叫。

  • PROJECT_ID:您的專案 ID。
  • LOCATION:處理要求的區域。
  • RAG_CORPUS_ID:RAG 語料庫的語料庫 ID。
  • FOLDER_RESOURCE_ID:Google 雲端硬碟資料夾的資源 ID。
  • CHUNK_SIZE:每個分塊應有的權杖數量。
  • CHUNK_OVERLAP:區塊之間重疊的權杖數量。
  • EMBEDDING_MODEL_QPM_RATE:限制 RAG 存取嵌入模型的 QPM 速率。例如:1,000。
// 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/v1/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
  }
}'

列出 RAG 檔案範例

這些程式碼範例示範如何列出 RAG 檔案。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的專案 ID。
  • LOCATION:處理要求的區域。
  • RAG_CORPUS_IDRagCorpus 資源的 ID。
  • PAGE_SIZE:每頁傳回的 RagFiles 數量上限。
  • PAGE_TOKEN:先前 ListRagFiles 回應中的頁面權杖,用於擷取下一頁結果。

HTTP 方法和網址:

GET https://LOCATION-aiplatform.googleapis.com/v1/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/v1/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/v1/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_IDRagFiles 清單。

Python

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Python API 參考說明文件


from vertexai 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/v1/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/v1/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/v1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID" | Select-Object -Expand Content

成功的回應會傳回 RagFile 資源。

Python

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Python API 參考說明文件


from vertexai 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_ID:RagCorpus 資源的 ID。
  • RAG_FILE_ID:RagFile 資源的 ID。格式: projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file_id}

HTTP 方法和網址:

DELETE https://LOCATION-aiplatform.googleapis.com/v1/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/v1/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/v1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID" | Select-Object -Expand Content

成功的回應會傳回 DeleteOperationMetadata

Python

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Python API 參考說明文件


from vertexai 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 中的檢索元件會搜尋知識庫,找出相關資訊。

Python

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Python API 參考說明文件


from vertexai 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!",
    rag_retrieval_config=rag.RagRetrievalConfig(
        top_k=10,
        filter=rag.utils.resources.Filter(vector_distance_threshold=0.5),
    ),
)
print(response)
# Example response:
# contexts {
#   contexts {
#     source_uri: "gs://your-bucket-name/file.txt"
#     text: "....
#   ....

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的專案 ID。
  • LOCATION:處理要求的區域。
  • RAG_CORPUS_RESOURCE:資源的名稱。RagCorpus格式:projects/{project}/locations/{location}/ragCorpora/{rag_corpus}
  • VECTOR_DISTANCE_THRESHOLD:只傳回向量距離小於閾值的上下文。
  • TEXT:要取得相關情境的查詢文字。
  • SIMILARITY_TOP_K:要擷取的重要上下文數量。

HTTP 方法和網址:

POST https://LOCATION-aiplatform.googleapis.com/v1/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/v1/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/v1/projects/PROJECT_ID/locations/LOCATION:retrieveContexts" | Select-Object -Expand Content

如果要求成功,系統會傳回 2xx 狀態碼和相關情境清單。

生成範例

LLM 會根據檢索到的脈絡資訊,生成有依據的回覆。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的專案 ID。
  • LOCATION:處理要求的區域。
  • MODEL_ID:用於生成內容的大型語言模型。例如:gemini-2.5-flash
  • GENERATION_METHOD:用於生成內容的 LLM 方法。 選項:generateContentstreamGenerateContent
  • INPUT_PROMPT:傳送至大型語言模型以生成內容的文字。請嘗試使用與上傳的 RAG 檔案相關的提示。
  • RAG_CORPUS_RESOURCE:資源的名稱。RagCorpus格式:projects/{project}/locations/{location}/ragCorpora/{rag_corpus}
  • SIMILARITY_TOP_K:(選用) 要擷取的頂層情境數量。
  • VECTOR_DISTANCE_THRESHOLD:選用:傳回向量距離小於閾值的上下文。
  • USER:您的使用者名稱。

HTTP 方法和網址:

POST https://LOCATION-aiplatform.googleapis.com/v1/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/v1/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/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATION_METHOD" | Select-Object -Expand Content

成功的回應會傳回附有引文的生成內容。

Python

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Python API 參考說明文件


from vertexai import rag
from vertexai.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", ...],
                )
            ],
            rag_retrieval_config=rag.RagRetrievalConfig(
                top_k=10,
                filter=rag.utils.resources.Filter(vector_distance_threshold=0.5),
            ),
        ),
    )
)

rag_model = GenerativeModel(
    model_name="gemini-2.0-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....
#   ...

專案管理範例

層級是 RagEngineConfig 資源中的專案層級設定,會影響使用 RagManagedDb 的 RAG 語料庫。如要取得層級設定,請使用 GetRagEngineConfig。如要更新層級設定,請使用 UpdateRagEngineConfig

如要進一步瞭解如何管理層級設定,請參閱「管理層級」。

取得專案設定

下列程式碼範例說明如何讀取 RagEngineConfig

主控台

  1. 前往 Google Cloud 控制台的「RAG Engine」頁面。

    前往 RAG Engine

  2. 選取 RAG Engine 執行的區域。RAG 語料庫清單已更新。
  3. 按一下「設定 RAG Engine」。「設定 RAG Engine」窗格隨即顯示。您可以查看為 RAG 引擎選取的層級。
  4. 按一下「取消」

Python

from vertexai import rag
import vertexai

PROJECT_ID = YOUR_PROJECT_ID
LOCATION = YOUR_RAG_ENGINE_LOCATION

# Initialize Vertex AI API once per session
vertexai.init(project=PROJECT_ID, location=LOCATION)

rag_engine_config = rag.rag_data.get_rag_engine_config(
    name=f"projects/{PROJECT_ID}/locations/{LOCATION}/ragEngineConfig"
)

print(rag_engine_config)

REST

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

更新專案設定

本節提供程式碼範例,說明如何將設定變更為「已縮放」、「基本」或「未佈建」層級。

RagEngineConfig 更新為「已縮放」層級

下列程式碼範例說明如何將 RagEngineConfig 設為「已縮放」層級:

主控台

  1. 前往 Google Cloud 控制台的「RAG Engine」頁面。

    前往 RAG Engine

  2. 選取 RAG Engine 執行的區域。RAG 語料庫清單已更新。
  3. 按一下「設定 RAG Engine」。「設定 RAG Engine」窗格隨即顯示。
  4. 選取要執行 RAG Engine 的層級。
  5. 按一下 [儲存]

Python

from vertexai import rag
import vertexai

PROJECT_ID = YOUR_PROJECT_ID
LOCATION = YOUR_RAG_ENGINE_LOCATION

# Initialize Vertex AI API once per session
vertexai.init(project=PROJECT_ID, location=LOCATION)

rag_engine_config_name=f"projects/{PROJECT_ID}/locations/{LOCATION}/ragEngineConfig"

new_rag_engine_config = rag.RagEngineConfig(
name=rag_engine_config_name,
rag_managed_db_config=rag.RagManagedDbConfig(tier=rag.Scaled()),
)

updated_rag_engine_config = rag.rag_data.update_rag_engine_config(
rag_engine_config=new_rag_engine_config
)

print(updated_rag_engine_config)

REST

curl -X PATCH \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/ragEngineConfig -d "{'ragManagedDbConfig': {'scaled': {}}}"

RagEngineConfig 更新至 Basic 級別

下列程式碼範例示範如何將 RagEngineConfig 設為 Basic 層級:

主控台

  1. 前往 Google Cloud 控制台的「RAG Engine」頁面。

    前往 RAG Engine

  2. 選取 RAG Engine 執行的區域。RAG 語料庫清單已更新。
  3. 按一下「設定 RAG Engine」。「設定 RAG Engine」窗格隨即顯示。
  4. 選取要執行 RAG Engine 的層級。
  5. 按一下 [儲存]

Python

from vertexai import rag
import vertexai

PROJECT_ID = YOUR_PROJECT_ID
LOCATION = YOUR_RAG_ENGINE_LOCATION

# Initialize Vertex AI API once per session
vertexai.init(project=PROJECT_ID, location=LOCATION)

rag_engine_config_name=f"projects/{PROJECT_ID}/locations/{LOCATION}/ragEngineConfig"

new_rag_engine_config = rag.RagEngineConfig(
name=rag_engine_config_name,
rag_managed_db_config=rag.RagManagedDbConfig(tier=rag.Basic()),
)

updated_rag_engine_config = rag.rag_data.update_rag_engine_config(
rag_engine_config=new_rag_engine_config
)

print(updated_rag_engine_config)

REST

curl -X PATCH \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/ragEngineConfig -d "{'ragManagedDbConfig': {'basic': {}}}"

將「RagEngineConfig」更新為未佈建層級

下列程式碼範例說明如何將 RagEngineConfig 設為「未佈建」層級:

主控台

  1. 前往 Google Cloud 控制台的「RAG Engine」頁面。

    前往 RAG Engine

  2. 選取 RAG Engine 執行的區域。RAG 語料庫清單已更新。
  3. 按一下「設定 RAG Engine」。「設定 RAG Engine」窗格隨即顯示。
  4. 按一下「刪除 RAG Engine」。即會顯示確認對話方塊。
  5. 輸入「delete」,確認要刪除 RAG 引擎中的資料,然後按一下「Confirm」
  6. 按一下 [儲存]

Python

from vertexai import rag
import vertexai

PROJECT_ID = YOUR_PROJECT_ID
LOCATION = YOUR_RAG_ENGINE_LOCATION

# Initialize Vertex AI API once per session
vertexai.init(project=PROJECT_ID, location=LOCATION)

rag_engine_config_name=f"projects/{PROJECT_ID}/locations/{LOCATION}/ragEngineConfig"

new_rag_engine_config = rag.RagEngineConfig(
  name=rag_engine_config_name,
  rag_managed_db_config=rag.RagManagedDbConfig(tier=rag.Unprovisioned()),
)

updated_rag_engine_config = rag.rag_data.update_rag_engine_config(
  rag_engine_config=new_rag_engine_config
)

print(updated_rag_engine_config)

REST

curl -X PATCH \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/ragEngineConfig -d "{'ragManagedDbConfig': {'unprovisioned': {}}}"

後續步驟