RAG Engine API

Vertex AI RAG 엔진은 검색 증강 생성 (RAG)을 지원하는 Vertex AI 플랫폼의 구성요소입니다. RAG 엔진을 사용하면 대규모 언어 모델 (LLM)이 문서 및 데이터베이스와 같은 외부 지식 소스의 데이터에 액세스하고 이를 통합할 수 있습니다. LLM은 RAG를 사용하여 더 정확하고 유익한 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

벡터 DB의 구성입니다.

RagVectorDbConfig
매개변수

rag_managed_db

oneof vector_db: RagVectorDbConfig.RagManagedDb

벡터 데이터베이스가 지정되지 않은 경우 rag_managed_db가 기본 벡터 데이터베이스입니다.

pinecone

oneof vector_db: RagVectorDbConfig.Pinecone

Pinecone 인스턴스를 지정합니다.

pinecone.index_name

string

RAG 코퍼스와 함께 사용되는 Pinecone 색인을 만드는 데 사용되는 이름입니다.

이 값은 설정된 후에는 변경할 수 없습니다. CreateRagCorpus API 호출에서는 비워 두고 후속 UpdateRagCorpus API 호출에서 비어 있지 않은 값으로 설정할 수 있습니다.

vertex_vector_search

oneof vector_db: RagVectorDbConfig.VertexVectorSearch

Vertex 벡터 검색 인스턴스를 지정합니다.

vertex_vector_search.index

string

RAG 코퍼스와 함께 사용되는 벡터 검색 색인의 리소스 이름입니다.

형식: projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}

이 값은 설정된 후에는 변경할 수 없습니다. CreateRagCorpus API 호출에서는 비워 두고 후속 UpdateRagCorpus API 호출에서 비어 있지 않은 값으로 설정할 수 있습니다.

vertex_vector_search.index_endpoint

string

RAG 코퍼스와 함께 사용되는 벡터 검색 색인 엔드포인트의 리소스 이름입니다.

형식: projects/{project}/locations/{location}/indexes/{index}

이 값은 설정된 후에는 변경할 수 없습니다. CreateRagCorpus API 호출에서는 비워 두고 후속 UpdateRagCorpus API 호출에서 비어 있지 않은 값으로 설정할 수 있습니다.

api_auth.api_key_config.api_key_secret_version

string

Pinecone API 키가 포함된 Secret Manager에 저장된 보안 비밀의 전체 리소스 이름입니다.

형식: 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.pinecone.index_name

string

RAG 코퍼스와 함께 사용되는 Pinecone 색인을 만드는 데 사용되는 이름입니다.

RagCorpusPinecone 구성으로 생성되었고 이 필드가 이전에 설정된 적이 없는 경우 Pinecone 인스턴스의 색인 이름을 업데이트할 수 있습니다.

rag_vector_db.vertex_vector_search.index

string

RAG 코퍼스와 함께 사용되는 벡터 검색 색인의 리소스 이름입니다.

형식: projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}

RagCorpusVector Search 구성으로 생성되었으며 이 필드가 이전에 설정된 적이 없는 경우 업데이트할 수 있습니다.

rag_vector_db.vertex_vector_search.index_endpoint

string

RAG 코퍼스와 함께 사용되는 벡터 검색 색인 엔드포인트의 리소스 이름입니다.

형식: projects/{project}/locations/{location}/indexes/{index}

RagCorpusVector Search 구성으로 생성되었으며 이 필드가 이전에 설정된 적이 없는 경우 업데이트할 수 있습니다.

rag_vector_db.api_auth.api_key_config.api_key_secret_version

string

Pinecone API 키가 포함된 Secret Manager에 저장된 보안 비밀의 전체 리소스 이름입니다.

형식: 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

RagCorpus에 업로드할 RagFile의 구성입니다.

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_source: GcsSource

Cloud Storage 위치

개별 파일뿐만 아니라 전체 Cloud Storage 디렉터리의 가져오기를 지원합니다.

gcs_source.uris

list/string

업로드 파일이 포함된 Cloud Storage URI입니다.

google_drive_source

oneof import_source: GoogleDriveSource

Google Drive 위치

개별 파일과 Google Drive 폴더 가져오기를 지원합니다.

slack_source

oneof import_source: SlackSource

파일이 업로드된 Slack 채널입니다.

jira_source

oneof import_source: JiraSource

파일이 업로드된 Jira 쿼리입니다.

share_point_sources

oneof import_source: SharePointSources

파일이 업로드된 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

청크 간의 중복입니다.

max_embedding_requests_per_min

선택사항: int32

이 작업이 자료에 지정된 임베딩 모델에 허용되는 분당 최대 쿼리 수입니다. 이 값은 이 작업에만 해당하며 다른 가져오기 작업과 공유되지 않습니다. 프로젝트의 할당량 페이지에서 적절한 값을 설정합니다.

지정하지 않으면 기본값인 1,000QPM이 사용됩니다.

GoogleDriveSource

resource_ids.resource_id

필수: string

Google Drive 리소스의 ID입니다.

resource_ids.resource_type

필수: string

Google Drive 리소스의 유형입니다.

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_sourceoneof: string

다운로드할 SharePoint 폴더의 경로입니다.

share_point_sources.sharepoint_folder_id

folder_sourceoneof: string

다운로드할 SharePoint 폴더의 ID입니다.

share_point_sources.drive_name

drive_sourceoneof: string

다운로드할 드라이브의 이름입니다.

share_point_sources.drive_id

drive_sourceoneof: string

다운로드할 드라이브의 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일 수 있습니다.

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_threshold: double

벡터 거리가 기준점보다 작은 컨텍스트만 반환합니다.

filter.vector_similarity_threshold

oneof vector_db_threshold: double

벡터 유사성이 기준점보다 큰 컨텍스트만 반환합니다.

예측 매개변수

이 표에는 예측 매개변수가 나열됩니다.

GenerateContentRequest

tools.retrieval.vertex_rag_store

VertexRagStore

Vertex AI RAG 스토어를 기반으로 하는 데이터 소스를 사용하도록 설정합니다.

자세한 내용은 VertexRagStore를 참고하세요.

코퍼스 관리 예시

이 섹션에서는 API를 사용하여 RAG 코퍼스를 관리하는 방법의 예를 제공합니다.

RAG 코퍼스 예시 만들기

다음 코드 샘플은 RAG 코퍼스를 만드는 방법을 보여줍니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: 프로젝트 ID입니다.
  • LOCATION: 요청을 처리하는 리전입니다.
  • CORPUS_DISPLAY_NAME: RAG 자료의 표시 이름입니다.
  • CORPUS_DESCRIPTION: RAG 코퍼스에 대한 설명입니다.

HTTP 메서드 및 URL:

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 참조 문서를 참고하세요.

  • PROJECT_ID: 프로젝트 ID입니다.
  • LOCATION: 요청을 처리하는 리전입니다.
  • CORPUS_DISPLAY_NAME: RAG 자료의 표시 이름입니다.
  • CORPUS_DESCRIPTION: RAG 코퍼스에 대한 설명입니다.
from vertexai import rag
import vertexai

PROJECT_ID = "PROJECT_ID"
display_name = "CORPUS_DISPLAY_NAME"
description = "CORPUS_DESCRIPTION"

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

# Configure embedding model
embedding_model_config = rag.EmbeddingModelConfig(
    publisher_model="publishers/google/models/text-embedding-004"
)

corpus = rag.create_corpus(
    display_name=display_name,
    description=description,
    embedding_model_config=embedding_model_config,
)
print(corpus)
# 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_NAME: RAG 자료의 표시 이름입니다.
  • CORPUS_DESCRIPTION: RAG 코퍼스에 대한 설명입니다.
  • INDEX_NAME: 벡터 검색 색인의 리소스 이름입니다. 형식은 projects/{project}/locations/{location}/indexes/{index}입니다.
  • INDEX_ENDPOINT_NAME: 벡터 검색 색인 엔드포인트의 리소스 이름입니다. 형식은 projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}입니다.

HTTP 메서드 및 URL:

PATCH https://LOCATION-aiplatform.googleapis.com/v1/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/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: 표준 목록 페이지 크기입니다. page_size 매개변수를 업데이트하여 페이지당 반환할 RAG 자료 수를 조정할 수 있습니다.
  • PAGE_TOKEN: 표준 목록 페이지 토큰입니다. 일반적으로 이전 VertexRagDataService.ListRagCorpora 호출의 ListRagCorporaResponse.next_page_token을 사용하여 가져옵니다.

HTTP 메서드 및 URL:

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

주어진 PROJECT_ID 아래의 성공적인 상태 코드 (2xx)와 RAG 코퍼스 목록을 받아야 합니다.

Python

Python용 Vertex AI SDK를 설치하거나 업데이트하는 방법은 Python용 Vertex AI SDK 설치를 참조하세요. 자세한 내용은 Python API 참조 문서를 참고하세요.

from vertexai import rag
import vertexai

PROJECT_ID = "PROJECT_ID"
LOCATION = "us-central1"

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

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 메서드 및 URL:

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 명령어는 선택한 임베딩 모델을 가리키는 vector_db_config 내에서 RagCorpusrag_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 참조 문서를 참고하세요.

  • PROJECT_ID: 프로젝트 ID입니다.
  • LOCATION: 요청을 처리하는 리전입니다.
  • RAG_CORPUS_ID: RAG 자료 리소스의 ID입니다.
from vertexai import rag
import vertexai

PROJECT_ID = "PROJECT_ID"
LOCATION = "LOCATION"
corpus_name = "projects/{PROJECT_ID}/locations/{LOCATION}/ragCorpora/{rag_corpus_id}"

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

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_ID: RagCorpus 리소스의 ID입니다.

HTTP 메서드 및 URL:

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

PROJECT_ID = "PROJECT_ID"
corpus_name = "projects/{PROJECT_ID}/locations/LOCATION/ragCorpora/RAG_CORPUS_ID"

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

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. import rag

파일 관리 예시

이 섹션에서는 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 참조 문서를 참고하세요.

  • PROJECT_ID: 프로젝트 ID입니다.
  • LOCATION: 요청을 처리하는 리전입니다.
  • RAG_CORPUS_ID: RAG 자료의 자료 ID입니다.
  • LOCAL_FILE_PATH: 업로드할 파일의 로컬 경로입니다.
  • DISPLAY_NAME: RAG 파일의 표시 이름입니다.
  • DESCRIPTION: RAG 파일에 대한 설명입니다.
from vertexai import rag
import vertexai

PROJECT_ID = "PROJECT_ID"
corpus_name = "projects/{PROJECT_ID}/locations/LOCATION/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="LOCATION")

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 파일 가져오기 예

Drive 또는 Cloud Storage에서 파일과 폴더를 가져올 수 있습니다. response.metadata를 사용하여 SDK의 response 객체에서 부분 실패, 요청 시간, 응답 시간을 확인할 수 있습니다.

response.skipped_rag_files_count는 가져오기 중에 건너뛴 파일 수를 나타냅니다. 다음 조건이 충족되면 파일이 건너뜁니다.

  1. 파일이 이미 가져와졌습니다.
  2. 파일이 변경되지 않았습니다.
  3. 파일의 청크 구성이 변경되지 않았습니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: 프로젝트 ID입니다.
  • LOCATION: 요청을 처리하는 리전입니다.
  • RAG_CORPUS_ID: RAG 자료의 자료 ID입니다.
  • FOLDER_RESOURCE_ID: Drive 폴더의 리소스 ID입니다.
  • GCS_URIS: Cloud Storage 위치 목록입니다. 예를 들면 gs://my-bucket1입니다.
  • CHUNK_SIZE: 각 청크에 있어야 하는 토큰 수입니다.
  • CHUNK_OVERLAP: 청크 간에 겹치는 토큰 수입니다.
  • EMBEDDING_MODEL_QPM_RATE: RAG의 임베딩 모델 액세스를 제한하는 QPM 비율입니다. 예: 1,000

HTTP 메서드 및 URL:

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에서 파일을 가져오는 방법을 보여줍니다. max_embedding_requests_per_min 제어 필드를 사용하여 RAG 엔진이 ImportRagFiles 색인 생성 프로세스 중에 임베딩 모델을 호출하는 속도를 제한합니다. 이 필드의 기본값은 분당 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
  }
}'

다음 샘플은 Drive에서 파일을 가져오는 방법을 보여줍니다. max_embedding_requests_per_min 제어 필드를 사용하여 RAG 엔진이 ImportRagFiles 색인 생성 프로세스 중에 임베딩 모델을 호출하는 속도를 제한합니다. 이 필드의 기본값은 분당 1000 호출입니다.

  • PROJECT_ID: 프로젝트 ID입니다.
  • LOCATION: 요청을 처리하는 리전입니다.
  • RAG_CORPUS_ID: RAG 자료의 자료 ID입니다.
  • FOLDER_RESOURCE_ID: Drive 폴더의 리소스 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
  }
}'

Python

Python용 Vertex AI SDK를 설치하거나 업데이트하는 방법은 Python용 Vertex AI SDK 설치를 참조하세요. 자세한 내용은 Python API 참조 문서를 참고하세요.

  • PROJECT_ID: 프로젝트 ID입니다.
  • LOCATION: 요청을 처리하는 리전입니다.
  • RAG_CORPUS_ID: RAG 자료의 자료 ID입니다.
  • FOLDER_RESOURCE_ID: Drive 폴더의 리소스 ID입니다.
  • CHUNK_SIZE: 각 청크에 있어야 하는 토큰 수입니다.
  • CHUNK_OVERLAP: 청크 간에 겹치는 토큰 수입니다.
  • EMBEDDING_MODEL_QPM_RATE: RAG의 임베딩 모델 액세스를 제한하는 QPM 비율입니다. 예: 1,000
from vertexai import rag
import vertexai

PROJECT_ID = "PROJECT_ID"
corpus_name = "projects/{PROJECT_ID}/locations/LOCATION/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="LOCATION")

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_ID: RagCorpus 리소스의 ID입니다.
  • PAGE_SIZE: 표준 목록 페이지 크기입니다. page_size 매개변수를 업데이트하여 페이지당 반환할 RagFiles 수를 조정할 수 있습니다.
  • PAGE_TOKEN: 표준 목록 페이지 토큰입니다. 이전 VertexRagDataService.ListRagFiles 호출의 ListRagFilesResponse.next_page_token을 사용하여 가져옵니다.

HTTP 메서드 및 URL:

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

주어진 RAG_CORPUS_ID 아래의 RagFiles 목록과 함께 성공적인 상태 코드 (2xx)를 받아야 합니다.

Python

Python용 Vertex AI SDK를 설치하거나 업데이트하는 방법은 Python용 Vertex AI SDK 설치를 참조하세요. 자세한 내용은 Python API 참조 문서를 참고하세요.

코드 샘플에서 사용되는 다음 변수를 바꿉니다.

  • PROJECT_ID: 프로젝트 ID입니다.
  • LOCATION: 요청을 처리하는 리전입니다.
  • RAG_CORPUS_ID: RagCorpus 리소스의 ID입니다.
  • PAGE_SIZE: 표준 목록 페이지 크기입니다. page_size 매개변수를 업데이트하여 페이지당 반환할 RagFiles 수를 조정할 수 있습니다.
  • PAGE_TOKEN: 표준 목록 페이지 토큰입니다. 이전 VertexRagDataService.ListRagFiles 호출의 ListRagFilesResponse.next_page_token을 사용하여 가져옵니다.
from vertexai import rag
import vertexai

PROJECT_ID = "PROJECT_ID"
corpus_name = "projects/{PROJECT_ID}/locations/LOCATION/ragCorpora/RAG_CORPUS_ID"

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

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_ID: RagCorpus 리소스의 ID입니다.
  • RAG_FILE_ID: RagFile 리소스의 ID입니다.

HTTP 메서드 및 URL:

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 참조 문서를 참고하세요.

  • PROJECT_ID: 프로젝트 ID입니다.
  • LOCATION: 요청을 처리하는 리전입니다.
  • RAG_CORPUS_ID: RagCorpus 리소스의 ID입니다.
  • RAG_FILE_ID: RagFile 리소스의 ID입니다.
from vertexai import rag
import vertexai

PROJECT_ID = "PROJECT_ID"
file_name = "projects/{PROJECT_ID}/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID"

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

rag_file = rag.get_file(name=file_name)
print(rag_file)
# Example response:
# RagFile(name='projects/1234567890/locations/LOCATION/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 메서드 및 URL:

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

Python

Python용 Vertex AI SDK를 설치하거나 업데이트하는 방법은 Python용 Vertex AI SDK 설치를 참조하세요. 자세한 내용은 Python API 참조 문서를 참고하세요.

  • 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}입니다.
from vertexai import rag
import vertexai

PROJECT_ID = "PROJECT_ID"
file_name = "projects/{PROJECT_ID}/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID"

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

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

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: 프로젝트 ID입니다.
  • LOCATION: 요청을 처리하는 리전입니다.
  • RAG_CORPUS_RESOURCE: RagCorpus 리소스의 이름입니다. 형식은 projects/{project}/locations/{location}/ragCorpora/{rag_corpus}입니다.
  • VECTOR_DISTANCE_THRESHOLD: 벡터 거리가 기준점보다 작은 컨텍스트만 반환됩니다.
  • TEXT: 관련 컨텍스트를 가져올 쿼리 텍스트입니다.
  • SIMILARITY_TOP_K: 검색할 인기 컨텍스트 수입니다.

HTTP 메서드 및 URL:

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) 및 관련 RagFiles 목록을 받아야 합니다.

Python

Python용 Vertex AI SDK를 설치하거나 업데이트하는 방법은 Python용 Vertex AI SDK 설치를 참조하세요. 자세한 내용은 Python API 참조 문서를 참고하세요.

  • PROJECT_ID: 프로젝트 ID입니다.
  • LOCATION: 요청을 처리하는 리전입니다.
  • RAG_CORPUS_RESOURCE: RagCorpus 리소스의 이름입니다. 형식은 projects/{project}/locations/{location}/ragCorpora/{rag_corpus}입니다.
  • VECTOR_DISTANCE_THRESHOLD: 벡터 거리가 기준점보다 작은 컨텍스트만 반환됩니다.
  • TEXT: 관련 컨텍스트를 가져올 쿼리 텍스트입니다.
  • SIMILARITY_TOP_K: 검색할 인기 컨텍스트 수입니다.
from vertexai import rag
import vertexai

PROJECT_ID = "PROJECT_ID"
corpus_name = "projects/[PROJECT_ID]/locations/LOCATION/ragCorpora/RAG_CORPUS_ID"

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

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="TEXT",
    similarity_top_k=SIMILARITY_TOP_K,  # Optional
    vector_distance_threshold=VECTOR_DISTANCE_THRESHOLD,  # Optional
)
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 방법입니다. 옵션: generateContent, streamGenerateContent
  • INPUT_PROMPT: 콘텐츠 생성을 위해 LLM에 전송된 텍스트입니다. 업로드된 래그 파일과 관련된 프롬프트를 사용해 보세요.
  • RAG_CORPUS_RESOURCE: RagCorpus 리소스의 이름입니다. 형식은 projects/{project}/locations/{location}/ragCorpora/{rag_corpus}입니다.
  • SIMILARITY_TOP_K: 선택사항: 검색할 인기 컨텍스트 수입니다.
  • VECTOR_DISTANCE_THRESHOLD: 선택사항: 벡터 거리가 기준점보다 작은 컨텍스트가 반환됩니다.
  • USER: 사용자 이름입니다.

HTTP 메서드 및 URL:

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 참조 문서를 참고하세요.

  • PROJECT_ID: 프로젝트 ID입니다.
  • LOCATION: 요청을 처리하는 리전입니다.
  • MODEL_ID: 콘텐츠 생성을 위한 LLM 모델입니다. 예를 들면 gemini-1.5-pro-002입니다.
  • GENERATION_METHOD: 콘텐츠 생성을 위한 LLM 방법입니다. 옵션: generateContent, streamGenerateContent
  • INPUT_PROMPT: 콘텐츠 생성을 위해 LLM에 전송된 텍스트입니다. 업로드된 래그 파일과 관련된 프롬프트를 사용해 보세요.
  • RAG_CORPUS_RESOURCE: RagCorpus 리소스의 이름입니다. 형식은 projects/{project}/locations/{location}/ragCorpora/{rag_corpus}입니다.
  • SIMILARITY_TOP_K: 선택사항: 검색할 인기 컨텍스트 수입니다.
  • VECTOR_DISTANCE_THRESHOLD: 선택사항: 벡터 거리가 기준점보다 작은 컨텍스트가 반환됩니다.
from vertexai import rag
from vertexai.generative_models import GenerativeModel, Tool
import vertexai

PROJECT_ID = "PROJECT_ID"
corpus_name = "projects/{PROJECT_ID}/locations/LOCATION/ragCorpora/RAG_CORPUS_ID"

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

rag_retrieval_tool = Tool.from_retrieval(
    retrieval=rag.Retrieval(
        source=rag.VertexRagStore(
            rag_resources=[
                rag.RagResource(
                    rag_corpus="RAG_CORPUS_RESOURCE",
                    # Optional: supply IDs from `rag.list_files()`.
                    # rag_file_ids=["rag-file-1", "rag-file-2", ...],
                )
            ],
            similarity_top_k=SIMILARITY_TOP_K,  # Optional
            vector_distance_threshold=VECTOR_DISTANCE_THRESHOLD,  # Optional
        ),
    )
)

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

다음 단계