このページでは、RAG Engine コーパスを Weaviate データベースに接続する方法について説明します。
オープンソース データベースである Weaviate データベース インスタンスと RAG Engine を使用して、インデックスを作成し、ベクトルベースの類似性検索を実行できます。類似性検索は、検索しているテキストに類似するテキストを見つける方法です。この場合、エンベディング モデルを使用する必要があります。エンベディング モデルは、比較対象のテキストごとにベクトルデータを生成します。類似性検索は、グラウンディングのためのセマンティック コンテキストを取得し、LLM から最も正確なコンテンツを返すために使用されます。
RAG Engine を使用すると、フルマネージド ベクトル データベース インスタンスを引き続き使用できます(プロビジョニングはお客様の責任で行っていただく必要があります)。RAG Engine は、ストレージ、インデックス管理、検索にベクトル データベースを使用します。
考慮事項
Weaviate データベースを使用する前に、次の点を考慮してください。
- Weaviate データベース インスタンスとコレクションを作成、構成、デプロイする必要があります。Weaviate コレクションを作成するの手順に沿って、スキーマに基づいてコレクションを設定します。
- Weaviate API キーを指定する必要があります。これにより、RAG Engine が Weaviate データベースとやり取りできるようになります。RAG Engine は、API キーベースの
AuthN
とAuthZ
をサポートしています。これにより、Weaviate データベースに接続し、HTTPS 接続をサポートします。 - RAG Engine は、Weaviate API キーの保存と管理を行いません。代わりに、次のことを行う必要があります。
- キーを Google Cloud Secret Manager に保存します。
- プロジェクトのサービス アカウントにシークレットへのアクセス権を付与します。
- RAG Engine に、シークレットのリソース名へのアクセス権を付与します。
- Weaviate データベースを操作すると、RAG Engine はサービス アカウントを使用してシークレット リソースにアクセスします。
- RAG Engine コーパスと Weaviate コレクションには 1 対 1 のマッピングがあります。RAG ファイルは Weaviate データベース コレクションに保存されます。
CreateRagCorpus
API またはUpdateRagCorpus
API が呼び出されると、RAG コーパスがデータベース コレクションに関連付けられます。 - 密エンベディング ベースのセマンティック検索に加えて、Weaviate データベースを介して RAG Engine でハイブリッド検索を行うこともできます。ハイブリッド検索では、密ベクトルとスパース ベクトルの類似性間の重みを調整することもできます。
Weaviate データベースをプロビジョニングする
RAG Engine で Weaviate データベースを使用する前に、次のことを行う必要があります。
- Weaviate データベース インスタンスを構成してデプロイします。
- HTTPS エンドポイントを準備します。
- Weaviate コレクションを作成します。
- API キー、
AuthN
、AuthZ
を使用して、Weaviate をプロビジョニングします。 - RAG Engine サービス アカウントをプロビジョニングします。
Weaviate データベース インスタンスを構成してデプロイする
Weaviate 公式ガイドのクイックスタートに沿って操作する必要があります。ただし、Google Cloud Marketplace ガイドを使用することもできます。
Weaviate エンドポイントがアクセス可能で、プロジェクトで構成してデプロイできる限り、Weaviate インスタンスはどこにでも設定できます。これで、Weaviate データベース インスタンスを完全に管理できるようになります。
RAG Engine は Weaviate データベース インスタンスのライフサイクルのどのステージにも関与しないため、Weaviate データベースにデータを保存して検索できるように、RAG Engine に権限を付与するのはお客様の責任となります。また、データベース内のデータが RAG Engine で使用できるようにする責任もお客様にあります。たとえば、データを変更した場合、その変更が原因で予期しない動作が発生しても、RAG Engine 側に責任はありません。
HTTPS エンドポイントを準備する
Weaviate のプロビジョニング中に、HTTPS エンドポイントを作成してください。HTTP 接続はサポートされていますが、RAG Engine と Weaviate データベースのトラフィックに HTTPS 接続を使用することをおすすめします。
Weaviate コレクションを作成する
RAG Engine コーパスと Weaviate コレクションには 1 対 1 のマッピングがあるため、コレクションを RAG Engine コーパスに関連付ける前に、Weaviate データベースにコレクションを作成する必要があります。この 1 回限りの関連付けは、CreateRagCorpus
API または UpdateRagCorpus
API を呼び出すときに行われます。
Weaviate でコレクションを作成する場合は、次のスキーマを使用する必要があります。
プロパティ名 | データ型 |
---|---|
fileId |
text |
corpusId |
text |
chunkId |
text |
chunkDataType |
text |
chunkData |
text |
fileOriginalUri |
text |
API キーを使用し、AuthN
と AuthZ
を使用して Weaviate をプロビジョニングする。
Weaviate API キーのプロビジョニングは、次の手順で行います。
- Weaviate API キーを作成します。
- Weaviate API キーを使用して Weaviate を構成します。
- Weaviate API キーを Secret Manager に保存します。
API キーを作成する
RAG Engine は、認証と認可に API キーを使用して Weaviate データベース インスタンスに接続します。Weaviate データベース インスタンスで API キーベースの認証を構成するには、Weaviate の認証に関する公式ガイドに沿って操作する必要があります。
Weaviate API キーの作成で、RAG Engine から取得した ID 情報に関連付ける ID 情報が必要になる場合は、最初のコーパスを作成し、RAG Engine サービス アカウントを ID として使用する必要があります。
API キーを Secret Manager に保存する
API キーには、個人を特定できる機密情報(SPII)が保持されます。この情報には法的要件が適用されます。SPII データが漏洩または不正使用された場合、個人に重大なリスクや損害が及ぶ可能性があります。RAG Engine を使用する際の個人に対するリスクを最小限に抑えるため、API キーを保存して管理しないでください。また、暗号化されていない API キーを共有しないようにします。
SPII を保護するには、次の操作を行います。
- API キーを Secret Manager に保存します。
- RAG Engine サービス アカウントにシークレットへの権限を付与し、シークレット リソースレベルでアクセス制御を管理します。
- プロジェクトの権限に移動します。
- [Google 提供のロール付与を含める] オプションを有効にします。
- サービス アカウントを見つけます。形式は次のとおりです。
service-{project number}@gcp-sa-vertex-rag.iam.gserviceaccount.com
- サービス アカウントのプリンシパルを編集します。
- サービス アカウントに Secret Manager のシークレット アクセサー ロールを追加します。
- RAG コーパスの作成または更新時に、シークレット リソース名を RAG Engine に渡し、シークレット リソース名を保存します。
Weaviate データベース インスタンスに API リクエストを送信すると、RAG Engine は各サービス アカウントを使用して、プロジェクトの Secret Manager のシークレット リソースに対応する API キーを読み取ります。
RAG Engine サービス アカウントをプロビジョニングする
プロジェクトで最初のリソースを作成すると、RAG Engine は専用のサービス アカウントを作成します。サービス アカウントは、プロジェクトの [IAM] ページで確認できます。サービス アカウントの形式は次のとおりです。
service-{project number}@gcp-sa-vertex-rag.iam.gserviceaccount.com
例: service-123456789@gcp-sa-vertex-rag.iam.gserviceaccount.com
Weaviate データベースと統合する際に、サービス アカウントは次のシナリオで使用されます。
- サービス アカウントを使用して、認証用の Weaviate API キーを生成できます。API キーの生成にユーザー情報が必要ない場合もあります。その場合、API キーの生成時にサービス アカウントは必要ありません。
- サービス アカウントを Weaviate データベースの API キーにバインドして、認証(
AuthN
)と認可(AuthZ
)を構成できますが、サービス アカウントは必須ではありません。 - API キーの Secret Manager をプロジェクトに保存し、これらのシークレット リソースに対する権限をサービス アカウントに付与できます。
- RAG Engine は、サービス アカウントを使用して、プロジェクトの Secret Manager から API キーにアクセスします。
Google Cloud コンソール環境を設定する
環境の設定方法については、こちらをクリックしてください
環境の設定方法については、次のいずれかのタブを選択してください。
Python
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
次のコマンドを実行して、Vertex AI SDK for Python をインストールまたは更新します。
pip3 install --upgrade "google-cloud-aiplatform>=1.38"
Node.js
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
次のコマンドを実行して、Vertex AI SDK for Node.js をインストールまたは更新します。
npm install @google-cloud/vertexai
Java
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
-
google-cloud-vertexai
を依存関係として追加するには、環境に適したコードを追加します。BOM ありの Maven
pom.xml
に次の HTML を追加します。<dependencyManagement> <dependencies> <dependency> <groupId>com.google.cloud</groupId> <artifactId>libraries-bom</artifactId> <version>26.32.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-vertexai</artifactId> </dependency> </dependencies>
BOM なしの Maven
pom.xml
に次の HTML を追加します。<dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-vertexai</artifactId> <version>0.4.0</version> </dependency>
Gradle without BOM
Add the following to your
build.gradle
implementation 'com.google.cloud:google-cloud-vertexai:0.4.0'
Go
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
利用可能な Vertex AI API Go パッケージを確認して、プロジェクトのニーズに最適なパッケージを判断します。
パッケージ cloud.google.com/go/vertexai(推奨)
vertexai
は人の手で作成されたパッケージで、一般的な機能へのアクセスを提供します。Vertex AI API を使用して構築するほとんどのデベロッパーにとって、これは出発点としておすすめのパッケージです。このパッケージに含まれていない機能にアクセスするには、自動生成された
aiplatform
を使用してください。パッケージ cloud.google.com/go/aiplatform
aiplatform
は自動生成されたパッケージです。このパッケージは、人が作成した
vertexai
パッケージではまだ提供されていない Vertex AI API 機能にアクセスする必要があるプロジェクトを対象としています。
次のいずれかのコマンドを実行して、プロジェクトのニーズに基づいて必要な Go パッケージをインストールします。
# Human authored package. Recommended for most developers. go get cloud.google.com/go/vertexai
# Auto-generated package. go get cloud.google.com/go/aiplatform
C#
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
REST
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.
- 次のように入力して、環境変数を構成します。
PROJECT_ID
は、Google Cloud プロジェクトの ID に置き換えます。MODEL_ID="gemini-1.5-flash-002" PROJECT_ID="PROJECT_ID"
- エンドポイントをプロビジョニングします。
gcloud beta services identity create --service=aiplatform.googleapis.com --project=${PROJECT_ID}
-
省略可: Cloud Shell を使用しているときに Cloud Shell の承認を求められた場合は、[承認] をクリックします。
RAG コーパスを準備する
Weaviate データベースのデータにアクセスするには、RAG Engine が RAG コーパスにアクセスできる必要があります。このセクションでは、単一の RAG コーパスと追加の RAG コーパスを作成する手順について説明します。
CreateRagCorpus
API と UpdateRagCorpus
API を使用する
CreateRagCorpus
API と UpdateRagCorpus
API を呼び出す場合は、次のフィールドを指定する必要があります。
rag_vector_db_config.weaviate
:CreateRagCorpus
API を呼び出した後、ベクトル データベースの構成が選択されます。ベクトル データベースの構成には、すべての構成フィールドが含まれています。rag_vector_db_config.weaviate
フィールドが設定されていない場合、デフォルトでrag_vector_db_config.rag_managed_db
が設定されます。weaviate.http_endpoint
: HTTPS または HTTP Weaviate エンドポイントは、Weaviate データベース インスタンスのプロビジョニング中に作成されます。weaviate.collection_name
: Weaviate インスタンスのプロビジョニング中に作成されるコレクションの名前。名前の先頭は大文字にする必要があります。api_auth.api_key_config
: ベクトル データベースへのアクセスを承認するために API キーを使用するように構成します。api_key_config.api_key_secret_version
: Secret Manager に保存されているシークレットのリソース名。ここには Weaviate API キーが含まれています。
RAG コーパスを作成して、データベース インスタンス内の Weaviate コレクションに関連付けることができます。ただし、API キーの生成や Weaviate データベース インスタンスの構成には、サービス アカウントが必要になる場合があります。最初の RAG コーパスを作成すると、サービス アカウントが生成されます。最初の RAG コーパスを作成した後、Weaviate データベースと API キーの関連付けが、別の RAG コーパスの作成で使用可能な状態になっていない場合があります。
データベースとキーを RAG コーパスに関連付ける準備ができていない場合は、RAG コーパスに対して次の操作を行います。
rag_vector_db_config
のweaviate
フィールドを設定します。- 関連付けられたベクトル データベースは変更できません。
http_endpoint
フィールドとcollection_name
フィールドの両方を空のままにします。どちらのフィールドも後で更新できます。
API キーを Secret Manager に保存していない場合は、
api_auth
フィールドを空白のままにします。UpdateRagCorpus
API を呼び出すときに、api_auth
フィールドを更新できます。Weaviate を使用するには、次のことを行う必要があります。api_auth
フィールドにapi_key_config
を設定します。Secret Manager で Weaviate API キーの
api_key_secret_version
を設定します。api_key_secret_version
フィールドの形式は次のとおりです。projects/{project}/secrets/{secret}/versions/{version}
http_endpoint
やcollection_name
など、1 回しか設定できないフィールドを指定した場合、RAG コーパスを削除して RAG コーパスを再度作成しない限り、そのフィールドを変更することはできません。API キーフィールドapi_key_secret_version
などの他のフィールドは更新できます。UpdateRagCorpus
を呼び出すときに、vector_db
フィールドを設定できます。vector_db
は、CreateRagCorpus
API 呼び出しによってweaviate
に設定する必要があります。指定しない場合、デフォルトの [RAG Managed Database] オプションが選択されます。このオプションは、UpdateRagCorpus
API を呼び出すときに変更できません。UpdateRagCorpus
を呼び出してvector_db
フィールドが部分的に設定されている場合、「変更可能」(可変)とマークされているフィールドを更新できます。
次の表に、コードで使用される WeaviateConfig
の可変フィールドと不変フィールドを示します。
フィールド名 | 変更可能または変更不可 |
---|---|
http_endpoint |
設定後は変更不可 |
collection_name |
設定後は変更不可 |
api_key_authentication |
変更可 |
最初の RAG コーパスを作成する
RAG Engine サービス アカウントが存在しない場合は、次の操作を行います。
- 空の Weaviate 構成を使用して、RAG Engine に RAG コーパスを作成します。これにより、RAG Engine のプロビジョニングが開始され、サービス アカウントが作成されます。
- 次の形式の RAG Engine サービス アカウントの名前を選択します。
service-{project number}@gcp-sa-vertex-rag.iam.gserviceaccount.com
例:
service-123456789@gcp-sa-vertex-rag.iam.gserviceaccount.com
- サービス アカウントを使用して、プロジェクトの Secret Manager に保存されているシークレット(Weaviate API キーを含む)にアクセスします。
- Weaviate のプロビジョニングが完了したら、次の情報を取得します。
- Weaviate の HTTPS または HTTP エンドポイント。
- Weaviate コレクションの名前。
CreateRagCorpus
API を呼び出して空の Weaviate 構成で RAG コーパスを作成し、UpdateRagCorpus
API を呼び出して次の情報で RAG コーパスに更新します。- Weaviate の HTTPS または HTTP エンドポイント。
- Weaviate コレクションの名前。
- API キーのリソース名。
別の RAG コーパスを作成する
RAG Engine サービス アカウントが存在する場合は、次の操作を行います。
- プロジェクトの権限から RAG Engine サービス アカウントを取得します。
- [Google 提供のロール付与を含む] オプションを有効にします。
- 次の形式の RAG Engine サービス アカウントの名前を選択します。
service-{project number}@gcp-sa-vertex-rag.iam.gserviceaccount.com
- サービス アカウントを使用して、プロジェクトの Secret Manager に保存されているシークレット(Weaviate API キーを含む)にアクセスします。
- Weaviate のプロビジョニング中に、次の情報を取得します。
- Weaviate の HTTPS または HTTP エンドポイント。
- Weaviate コレクションの名前。
- RAG Engine で RAG コーパスを作成し、次のいずれかの方法で Weaviate コレクションに接続します。
CreateRagCorpus
API 呼び出しを行い、Weaviate 構成が入力された RAG コーパスを作成します。これは推奨の方法です。CreateRagCorpus
API 呼び出しを実行して空の Weaviate 構成で RAG コーパスを作成し、UpdateRagCorpus
API 呼び出しを実行して次の情報で RAG コーパスに更新します。- Weaviate データベースの HTTP エンドポイント
- Weaviate コレクション名
- API キー
例
このセクションでは、Weaviate データベース、Secret Manager、RAG コーパス、RAG ファイルを設定する方法を説明するサンプルコードを示します。また、ファイルのインポート方法、コンテキストの取得方法、コンテンツの生成方法、RAG コーパスと RAG ファイルの削除方法を示すサンプルコードも用意されています。
Model Garden RAG API ノートブックを使用するには、Llama 3 で Weaviate を使用するをご覧ください。
Weaviate データベースを設定する
このコードサンプルは、Weaviate データと Secret Manager を設定する方法を示しています。
# TODO(developer): Update the variables.
# The HTTPS/HTTP Weaviate endpoint you created during provisioning.
HTTP_ENDPOINT_NAME="https://your.weaviate.endpoint.com"
# Your Weaviate API Key.
WEAVIATE_API_KEY="example-api-key"
# Select your Weaviate collection name, which roughly corresponds to a Vertex AI Knowledge Engine Corpus.
# For example, "MyCollectionName"
# Note that the first letter needs to be capitalized.
# Otherwise, Weavaite will capitalize it for you.
WEAVIATE_COLLECTION_NAME="MyCollectionName"
# Create a collection in Weaviate which includes the required schema fields shown below.
echo '{
"class": "'${WEAVIATE_COLLECTION_NAME}'",
"properties": [
{ "name": "fileId", "dataType": [ "string" ] },
{ "name": "corpusId", "dataType": [ "string" ] },
{ "name": "chunkId", "dataType": [ "string" ] },
{ "name": "chunkDataType", "dataType": [ "string" ] },
{ "name": "chunkData", "dataType": [ "string" ] },
{ "name": "fileOriginalUri", "dataType": [ "string" ] }
]
}' | curl \
-X POST \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer "${WEAVIATE_API_KEY} \
-d @- \
${HTTP_ENDPOINT_NAME}/v1/schema
Secret Manager を設定する
Secret Manager を設定するには、Secret Manager を有効にして権限を設定する必要があります。
Secret Manager を有効にする
Secret Manager を有効にするには、次の操作を行います。
- [Secret Manager] ページに移動します。
- [+ シークレットの作成] をクリックします。
- シークレットの名前を入力します。シークレット名には、英字(A~Z)、数字(0~9)、ダッシュ(-)、アンダースコア(_)のみを使用できます。
- 次のフィールドの指定は任意です。
- シークレットを含むファイルをアップロードするには、[参照] をクリックします。
- レプリケーション ポリシーを確認します。
- シークレットのロケーションを手動で管理する場合は、[このシークレットのロケーションを手動で管理する] チェックボックスをオンにします。少なくとも 1 つのリージョンを選択する必要があります。
- 暗号化オプションを選択します。
- ローテーション期間を手動で設定する場合は、[ローテーション期間を設定する] をオンにします。
- イベント通知を受け取るために公開トピックまたはサブスクリプション トピックを指定する場合は、[Add topics] をクリックします。
- デフォルトでは、シークレットは期限切れにはなりません。有効期限を設定する場合は、[有効期限を設定する] をオンにします。
- デフォルトで、シークレット バージョンはリクエストされると破棄されます。シークレット バージョンの破棄を遅らせるには、[破棄の遅延期間を設定する] をオンにします。
- ラベルを使用してシークレットを整理および分類する場合は、[+ ラベルを追加] をクリックします。
- アノテーションを使用して非識別的なメタデータをシークレットに関連付ける場合は、[+ アノテーションを追加] をクリックします。
- [シークレットの作成] をクリックします。
権限を設定する
サービス アカウントに Secret Manager の権限を付与する必要があります。
Google Cloud コンソールの [IAM と管理] セクションで、サービス アカウントを見つけて、鉛筆アイコンをクリックして編集します。
[ロール] フィールドで、[Secret Manager のシークレット アクセサー] を選択します。
このコードサンプルは、Secret Manager を設定する方法を示しています。
# TODO(developer): Update the variables.
# Select a resource name for your Secret, which contains your API Key.
SECRET_NAME="MyWeaviateApiKeySecret"
# Create a secret in SecretManager.
curl "https://secretmanager.googleapis.com/v1/projects/${PROJECT_ID}/secrets?secretId=${SECRET_NAME}" \
--request "POST" \
--header "authorization: Bearer $(gcloud auth print-access-token)" \
--header "content-type: application/json" \
--data "{\"replication\": {\"automatic\": {}}}"
# Your Weaviate API Key.
WEAVIATE_API_KEY="example-api-key"
# Encode your WEAVIATE_API_KEY using base 64.
SECRET_DATA=$(echo ${WEAVIATE_API_KEY} | base64)
# Create a new version of your secret which uses SECRET_DATA as payload
curl.
"https://secretmanager.googleapis.com/v1/projects/${PROJECT_ID}/secrets/${SECRET_NAME}:addVersion" \
--request "POST" \
--header "authorization: Bearer $(gcloud auth print-access-token)" \
--header "content-type: application/json" \
--data "{\"payload\": {\"data\": \"${SECRET_DATA}\"}}"
Llama 3 で Weaviate を使用する
Model Garden RAG API ノートブックでは、Vertex AI SDK for Python で Weaviate コーパスと Llama 3 モデルを使用する方法を示しています。ノートブックを使用するには、次の操作を行う必要があります。
その他の例については、例をご覧ください。
RAG コーパスを作成する
このコードサンプルは、RAG コーパスを作成し、Weaviate インスタンスをベクトル データベースとして設定する方法を示しています。
REST
# TODO(developer): Update the variables.
PROJECT_ID = "YOUR_PROJECT_ID"
# The HTTPS/HTTP Weaviate endpoint you created during provisioning.
HTTP_ENDPOINT_NAME="https://your.weaviate.endpoint.com"
# Your Weaviate collection name, which roughly corresponds to a Vertex AI Knowledge Engine Corpus.
# For example, "MyCollectionName"
# Note that the first letter needs to be capitalized.
# Otherwise, Weaviate will capitalize it for you.
WEAVIATE_COLLECTION_NAME="MyCollectionName"
# The resource name of your Weaviate API Key your Secret.
SECRET_NAME="MyWeaviateApiKeySecret"
# The Secret Manager resource name containing the API Key for your Weaviate endpoint.
# For example, projects/{project}/secrets/{secret}/versions/latest
APIKEY_SECRET_VERSION="projects/${PROJECT_ID}/secrets/${SECRET_NAME}/versions/latest"
# Select a Corpus display name.
CORPUS_DISPLAY_NAME="SpecialCorpus"
# Call CreateRagCorpus API and set all Vector DB Config parameters for Weaviate to create a new corpus associated to your selected Weaviate collection.
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/ragCorpora \
-d '{
"display_name" : '\""${CORPUS_DISPLAY_NAME}"\"',
"rag_vector_db_config" : {
"weaviate": {
"http_endpoint": '\""${HTTP_ENDPOINT_NAME}"\"',
"collection_name": '\""${WEAVIATE_COLLECTION_NAME}"\"'
},
"api_auth" : {
"api_key_config": {
"api_key_secret_version": '\""${APIKEY_SECRET_VERSION}"\"'
}
}
}
}'
# TODO(developer): Update the variables.
# Get operation_id returned in CreateRagCorpus.
OPERATION_ID="your-operation-id"
# Poll Operation status until done = true in the response.
curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/operations/${OPERATION_ID}
# Call ListRagCorpora API to verify the RAG corpus is created successfully.
curl -sS -X GET \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/ragCorpora"
Python
import vertexai
from vertexai.preview import rag
from vertexai.preview.generative_models import GenerativeModel, Tool
# Set Project
PROJECT_ID = "YOUR_PROJECT_ID" # @param {type:"string"}
vertexai.init(project=PROJECT_ID, location="us-central1")
# Configure a Google first-party embedding model
embedding_model_config = rag.EmbeddingModelConfig(
publisher_model="publishers/google/models/text-embedding-004"
)
# Configure a third-party model or a Google fine-tuned first-party model as a Vertex Endpoint resource
# See https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/model_garden/model_garden_e5.ipynb for
# deploying 3P embedding models to endpoints
ENDPOINT_ID = "your-model-endpoint-id" # @param {type:"string"}
MODEL_ENDPOINT = "projects/{PROJECT_ID}/locations/us-central1/endpoints/{ENDPOINT_ID}"
embedding_model_config = rag.EmbeddingModelConfig(
endpoint=MODEL_ENDPOINT,
)
# Configure a Weaviate Vector Database Instance for the corpus
WEAVIATE_HTTP_ENDPOINT = "weaviate-http-endpoint" # @param {type:"string"}
COLLECTION_NAME = "weaviate-collection-name" # @param {type:"string"}
API_KEY = "your-secret-manager-resource-name" # @param {type:"string"}
vector_db = rag.Weaviate(
weaviate_http_endpoint=WEAVIATE_HTTP_ENDPOINT,
collection_name=COLLECTION_NAME,
api_key=API_KEY,
)
# Name your corpus
DISPLAY_NAME = "your-corpus-name" # @param {type:"string"}
rag_corpus = rag.create_corpus(
display_name=DISPLAY_NAME, embedding_model_config=embedding_model_config, vector_db=vector_db
)
# Check the corpus just created
rag.list_corpora()
RAG ファイルを使用する
RAG API は、ファイルのアップロード、インポート、一覧取得、削除を処理します。
REST
リクエストのデータを使用する前に、次のように置き換えます。
- PROJECT_ID: 実際のプロジェクト ID。
- LOCATION: リクエストを処理するリージョン。
- RAG_CORPUS_ID:
RagCorpus
リソースの ID。 - INPUT_FILE: ローカル ファイルのパス。
- FILE_DISPLAY_NAME:
RagFile
の表示名。 - RAG_FILE_DESCRIPTION:
RagFile
の説明。
HTTP メソッドと URL:
POST https://LOCATION-aiplatform.googleapis.com/upload/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles:upload
リクエストの本文(JSON):
{ "rag_file": { "display_name": "FILE_DISPLAY_NAME", "description": "RAG_FILE_DESCRIPTION" } }
リクエストを送信するには、次のいずれかのオプションを選択します。
curl
リクエスト本文を INPUT_FILE
という名前のファイルに保存して、次のコマンドを実行します。
curl -X POST \
-H "Content-Type: application/json; charset=utf-8" \
-d @INPUT_FILE \
"https://LOCATION-aiplatform.googleapis.com/upload/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles:upload"
PowerShell
リクエスト本文を INPUT_FILE
という名前のファイルに保存して、次のコマンドを実行します。
$headers = @{ }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile INPUT_FILE `
-Uri "https://LOCATION-aiplatform.googleapis.com/upload/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles:upload" | Select-Object -Expand Content
RagFile
リソースが返されます。RagFile.name
フィールドの最後のコンポーネントは、サーバー生成の rag_file_id
です。Python
Vertex AI SDK for Python のインストールまたは更新の方法については、Vertex AI SDK for Python をインストールするをご覧ください。 詳細については、Python API リファレンス ドキュメントをご覧ください。
RAG ファイルをインポートする
ファイルとフォルダは、ドライブまたは Cloud Storage からインポートできます。
REST
response.metadata
を使用して、SDK の response
オブジェクトで部分的な失敗、リクエスト時間、レスポンス時間を確認します。
リクエストのデータを使用する前に、次のように置き換えます。
- PROJECT_ID: 実際のプロジェクト ID。
- LOCATION: リクエストを処理するリージョン。
- RAG_CORPUS_ID:
RagCorpus
リソースの ID。 - GCS_URIS: Cloud Storage ロケーションのリスト。例:
gs://my-bucket1, gs://my-bucket2
- DRIVE_RESOURCE_ID: ドライブ リソースの ID。例:
https://drive.google.com/file/d/ABCDE
https://drive.google.com/corp/drive/u/0/folders/ABCDEFG
- DRIVE_RESOURCE_TYPE: ドライブ リソースのタイプ。オプション:
RESOURCE_TYPE_FILE
- ファイルRESOURCE_TYPE_FOLDER
- フォルダ- CHUNK_SIZE: 省略可。各チャンクに必要なトークンの数。
- CHUNK_OVERLAP: 省略可: チャンク間で重複するトークンの数。
HTTP メソッドと URL:
POST https://LOCATION-aiplatform.googleapis.com/upload/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles:import
リクエストの本文(JSON):
{ "import_rag_files_config": { "gcs_source": { "uris": GCS_URIS }, "google_drive_source": { "resource_ids": { "resource_id": DRIVE_RESOURCE_ID, "resource_type": DRIVE_RESOURCE_TYPE }, } } }
リクエストを送信するには、次のいずれかのオプションを選択します。
curl
リクエスト本文を request.json
という名前のファイルに保存して、次のコマンドを実行します。
curl -X POST \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/upload/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles:import"
PowerShell
リクエスト本文を request.json
という名前のファイルに保存して、次のコマンドを実行します。
$headers = @{ }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/upload/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 Engine が ImportRagFiles
インデックス登録プロセス中にエンベディング モデルを呼び出すレートを制限します。このフィールドのデフォルト値は、1 分あたり 1000
回の呼び出しです。
// Cloud Storage bucket/file location.
// Such as "gs://rag-e2e-test/"
GCS_URIS=YOUR_GCS_LOCATION
// Enter the QPM rate to limit RAG's access to your embedding model
// Example: 1000
EMBEDDING_MODEL_QPM_RATE=MAX_EMBEDDING_REQUESTS_PER_MIN_LIMIT
// ImportRagFiles
// Import a single Cloud Storage file or all files in a Cloud Storage bucket.
// Input: ENDPOINT, 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://${ENDPOINT}/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": 512
},
"max_embedding_requests_per_min": '"${EMBEDDING_MODEL_QPM_RATE}"'
}
}'
// Poll the operation status.
// The response contains the number of files imported.
OPERATION_ID=OPERATION_ID
poll_op_wait ${OPERATION_ID}
次のサンプルは、ドライブからファイルをインポートする方法を示しています。max_embedding_requests_per_min
制御フィールドを使用して、RAG Engine が ImportRagFiles
インデックス登録プロセス中にエンベディング モデルを呼び出すレートを制限します。このフィールドのデフォルト値は、1 分あたり 1000
回の呼び出しです。
// Google Drive folder location.
FOLDER_RESOURCE_ID=YOUR_GOOGLE_DRIVE_FOLDER_RESOURCE_ID
// Enter the QPM rate to limit RAG's access to your embedding model
// Example: 1000
EMBEDDING_MODEL_QPM_RATE=MAX_EMBEDDING_REQUESTS_PER_MIN_LIMIT
// ImportRagFiles
// Import all files in a Google Drive folder.
// Input: ENDPOINT, 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://${ENDPOINT}/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=OPERATION_ID
poll_op_wait ${OPERATION_ID}
Python
Vertex AI SDK for Python のインストールまたは更新の方法については、Vertex AI SDK for Python をインストールするをご覧ください。 詳細については、Python API リファレンス ドキュメントをご覧ください。
RAG ファイルを取得する
REST
リクエストのデータを使用する前に、次のように置き換えます。
- PROJECT_ID: 実際のプロジェクト ID。
- LOCATION: リクエストを処理するリージョン。
- RAG_CORPUS_ID:
RagCorpus
リソースの ID。 - RAG_FILE_ID:
RagFile
リソースの ID。
HTTP メソッドと URL:
GET https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID
リクエストを送信するには、次のいずれかのオプションを選択します。
curl
次のコマンドを実行します。
curl -X GET \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID"
PowerShell
次のコマンドを実行します。
$headers = @{ }
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 for Python のインストールまたは更新の方法については、Vertex AI SDK for Python をインストールするをご覧ください。 詳細については、Python API リファレンス ドキュメントをご覧ください。
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/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles?page_size=PAGE_SIZE&page_token=PAGE_TOKEN
リクエストを送信するには、次のいずれかのオプションを選択します。
curl
次のコマンドを実行します。
curl -X 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"
PowerShell
次のコマンドを実行します。
$headers = @{ }
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
RAG_CORPUS_ID
の下で、成功ステータス コード(2xx)と RagFiles
のリストが返されます。Python
Vertex AI SDK for Python のインストールまたは更新の方法については、Vertex AI SDK for Python をインストールするをご覧ください。 詳細については、Python API リファレンス ドキュメントをご覧ください。
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/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID
リクエストを送信するには、次のいずれかのオプションを選択します。
curl
次のコマンドを実行します。
curl -X DELETE \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/ragCorpora/RAG_CORPUS_ID/ragFiles/RAG_FILE_ID"
PowerShell
次のコマンドを実行します。
$headers = @{ }
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 for Python のインストールまたは更新の方法については、Vertex AI SDK for Python をインストールするをご覧ください。 詳細については、Python API リファレンス ドキュメントをご覧ください。
コンテキストを取得する
ユーザーが質問をするか、プロンプトを指定すると、RAG の検索コンポーネントがナレッジベースを検索し、クエリに関連する情報を探します。
REST
リクエストのデータを使用する前に、次のように置き換えます。
- LOCATION: リクエストを処理するリージョン。
- PROJECT_ID: 実際のプロジェクト ID。
- 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/v1beta1/projects/PROJECT_ID/locations/LOCATION:retrieveContexts
リクエストの本文(JSON):
{ "vertex_rag_store": { "rag_resources": { "rag_corpus": "RAG_CORPUS_RESOURCE", }, "vector_distance_threshold": 0.8 }, "query": { "text": "TEXT", "similarity_top_k": SIMILARITY_TOP_K } }
リクエストを送信するには、次のいずれかのオプションを選択します。
curl
リクエスト本文を request.json
という名前のファイルに保存して、次のコマンドを実行します。
curl -X POST \
-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
という名前のファイルに保存して、次のコマンドを実行します。
$headers = @{ }
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
RagFiles
のリストが返されます。Python
Vertex AI SDK for Python のインストールまたは更新の方法については、Vertex AI SDK for Python をインストールするをご覧ください。 詳細については、Python API リファレンス ドキュメントをご覧ください。
コンテンツを生成する
予測は、コンテンツを生成する LLM メソッドを制御します。
REST
リクエストのデータを使用する前に、次のように置き換えます。
- PROJECT_ID: 実際のプロジェクト ID。
- LOCATION: リクエストを処理するリージョン。
- MODEL_ID: コンテンツ生成用の LLM モデル。例:
gemini-1.5-pro-002
- GENERATION_METHOD: コンテンツ生成の LLM メソッド。オプション:
generateContent
、streamGenerateContent
- INPUT_PROMPT: コンテンツ生成のために LLM に送信されるテキスト。アップロードされた Rag ファイルに関連するプロンプトを使用するようにしてください。
- RAG_CORPUS_RESOURCE:
RagCorpus
リソースの名前。形式:projects/{project}/locations/{location}/ragCorpora/{rag_corpus}
。 - SIMILARITY_TOP_K: 省略可。取得する上位コンテキストの数。
- VECTOR_DISTANCE_THRESHOLD: 省略可。ベクトル距離がしきい値より小さいコンテキストが返されます。
HTTP メソッドと URL:
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 "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
という名前のファイルに保存して、次のコマンドを実行します。
$headers = @{ }
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 for Python のインストールまたは更新の方法については、Vertex AI SDK for Python をインストールするをご覧ください。 詳細については、Python API リファレンス ドキュメントをご覧ください。
ハイブリッド検索
ハイブリッド検索は Weaviate データベースでサポートされています。Weaviate データベースは、セマンティック検索とキーワード検索の両方を組み合わせて、検索結果の関連性を高めます。検索結果の取得時に、セマンティック(密ベクトル)とキーワード マッチング(スパース ベクトル)の類似性スコアを組み合わせて、最終的なランキング結果が生成されます。
RAG Engine 検索 API を使用したハイブリッド検索
これは、RAG Engine 検索 API を使用してハイブリッド検索を有効にする方法の例です。
REST
このコードサンプルでは、次の変数を使用します。
- PROJECT_ID: Google Cloud プロジェクト ID。
- RAG_CORPUS_RESOURCE: RAG コーパスの完全なリソース名(
projects/*/locations/us-central1/ragCorpora/*
形式)。 - DISTANCE_THRESHOLD: ベクトル検索距離に設定されるしきい値(
[0, 1.0]
の範囲内)。デフォルト値は0.3
に設定されています。 - ALPHA: アルファ値は、セマンティック検索結果とキーワード検索結果の重みを制御します。範囲は
[0, 1]
です。ここで、0
はスパース ベクトル検索、1
は密ベクトル検索です。デフォルト値は0.5
で、スパース ベクトル検索と密ベクトル検索のバランスを取っています。 - RETRIEVAL_QUERY: 取得クエリ。
- TOP_K: 取得する上位
k
個の結果の数。
この例は、URL で HTTP メソッドを呼び出す方法を示しています。
POST https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1:retrieveContexts
このコードサンプルは、リクエスト JSON 本文を使用する方法を示しています。
{
"vertex_rag_store": {
"rag_resources": {
"rag_corpus": '\""${RAG_CORPUS_RESOURCE}"\"',
},
"vector_distance_threshold": ${DISTANCE_THRESHOLD}
},
"query": {
"text": '\""${RETRIEVAL_QUERY}"\"',
"similarity_top_k": ${TOP_K},
"ranking": { "alpha" : ${ALPHA}}
}
}
Python
from vertexai.preview import rag
import vertexai
# TODO(developer): Update the variables.
# PROJECT_ID = "your-project-id"
# rag_corpus_id = "your-rag-corpus-id"
# Only one corpus is supported at this time
# Initialize Vertex AI API once per session
vertexai.init(project=PROJECT_ID, location="us-central1")
response = rag.retrieval_query(
rag_resources=[
rag.RagResource(
rag_corpus=rag_corpus_id,
# Optional: supply IDs from `rag.list_files()`.
# rag_file_ids=["rag-file-1", "rag-file-2", ...],
)
],
text="What is RAG and why it is helpful?",
similarity_top_k=10, # Optional
vector_distance_threshold=0.5, # Optional
ranking=rag.RagQuery.Ranking(
alpha=0.5
), # Optional
)
print(response)
ハイブリッド検索と RAG Engine を使用してグラウンディングされた結果を生成する
これは、ハイブリッド検索と RAG Engine を使用して、グラウンディングされた結果を生成する方法の例です。
REST
このコードサンプルでは、次の変数を使用します。
- PROJECT_ID: Google Cloud プロジェクト ID。
- RAG_CORPUS_RESOURCE: RAG コーパスの完全なリソース名(
projects/*/locations/us-central1/ragCorpora/*
形式)。 - DISTANCE_THRESHOLD: ベクトル検索距離に設定されるしきい値(
[0, 1.0]
の範囲内)。デフォルト値は0.3
に設定されています。 - ALPHA: アルファ値は、セマンティック検索結果とキーワード検索結果の重みを制御します。範囲は
[0, 1]
です。ここで、0
はスパース ベクトル検索、1
は密ベクトル検索です。デフォルト値は0.5
で、スパース ベクトル検索と密ベクトル検索のバランスを取っています。 - INPUT_PROMPT: 入力プロンプト。
- TOP_K: 取得する上位
k
個の結果の数。
この例は、URL で HTTP メソッドを呼び出す方法を示しています。
POST https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/publishers/google/models/gemini-pro:generateContent
このコードサンプルは、リクエスト JSON 本文を使用する方法を示しています。
{
"contents": {
"role": "user",
"parts": {
"text": '\""${INPUT_PROMPT}"\"'
}
},
"tools": {
"retrieval": {
"vertex_rag_store": {
"rag_resources": {
"rag_corpus": '\""${RAG_CORPUS_RESOURCE}"\"',
},
"similarity_top_k": ${TOP_K},
"vector_distance_threshold": ${DISTANCE_THRESHOLD},
"ranking": { "alpha" : ${ALPHA}}
}
}
}
}
Python
from vertexai.preview import rag
from vertexai.preview.generative_models import GenerativeModel, Tool
import vertexai
# TODO(developer): Update the variables.
# PROJECT_ID = "your-project-id"
# rag_corpus_id = "your-rag-corpus-id" # Only one corpus is supported at this time
# Initialize Vertex AI API once per session
vertexai.init(project=PROJECT_ID, location="us-central1")
rag_retrieval_tool = Tool.from_retrieval(
retrieval=rag.Retrieval(
source=rag.VertexRagStore(
rag_resources=[
rag.RagResource(
rag_corpus=rag_corpus_id, # Currently only 1 corpus is allowed.
# 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
ranking=rag.RagQuery.Ranking(
alpha=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)
次のステップ
- グラウンディングの詳細を確認する。グラウンディングの概要をご覧ください。
- RAG Engine の詳細については、RAG Engine を使用するをご覧ください。
- グラウンディングと RAG の詳細を確認する。RAG を使用したレスポンスのグラウンディングをご覧ください。