Menggunakan database Weaviate dengan Vertex AI RAG Engine

Halaman ini menunjukkan cara menghubungkan korpus RAG Engine ke database Weaviate.

Anda juga dapat mengikutinya menggunakan notebook RAG Engine dengan Weaviate ini.

Anda dapat menggunakan instance database Weaviate, yang merupakan database open source, dengan RAG Engine untuk mengindeks dan melakukan penelusuran kemiripan berbasis vektor. Penelusuran kemiripan adalah cara untuk menemukan potongan teks yang mirip dengan teks yang Anda cari, yang memerlukan penggunaan model penyematan. Model penyematan menghasilkan data vektor untuk setiap bagian teks yang dibandingkan. Penelusuran kemiripan digunakan untuk mengambil konteks semantik untuk penjelasan guna menampilkan konten yang paling akurat dari LLM Anda.

Dengan RAG Engine, Anda dapat terus menggunakan instance database vektor terkelola sepenuhnya, yang Anda tanggung jawab untuk menyediakannya. RAG Engine menggunakan database vektor untuk penyimpanan, pengelolaan indeks, dan penelusuran.

Pertimbangan

Pertimbangkan langkah-langkah berikut sebelum menggunakan database Weaviate:

  1. Anda harus membuat, mengonfigurasi, dan men-deploy instance dan koleksi database Weaviate. Ikuti petunjuk di Membuat koleksi Weaviate untuk menyiapkan koleksi berdasarkan skema Anda.
  2. Anda harus memberikan kunci Weaviate API, yang memungkinkan RAG Engine berinteraksi dengan database Weaviate. RAG Engine mendukung AuthN dan AuthZ berbasis kunci API, yang terhubung ke database Weaviate Anda dan mendukung koneksi HTTPS.
  3. RAG Engine tidak menyimpan dan mengelola kunci API Weaviate Anda. Sebagai gantinya, Anda harus melakukan hal berikut:
    1. Simpan kunci Anda di Google Cloud Secret Manager.
    2. Berikan izin akun layanan project Anda untuk mengakses secret.
    3. Berikan akses RAG Engine ke nama resource secret Anda.
    4. Saat Anda berinteraksi dengan database Weaviate, RAG Engine akan mengakses resource rahasia menggunakan akun layanan Anda.
  4. Korpus RAG Engine dan koleksi Weaviate memiliki pemetaan satu-satu. File RAG disimpan dalam koleksi database Weaviate. Saat panggilan dilakukan ke CreateRagCorpus API atau UpdateRagCorpus API, korpus RAG akan dikaitkan dengan koleksi database.
  5. Selain penelusuran semantik berbasis penyematan yang padat, penelusuran campuran juga didukung dengan RAG Engine melalui database Weaviate. Anda juga dapat menyesuaikan bobot antara kesamaan vektor rapat dan jarang dalam penelusuran campuran.

Menyediakan database Weaviate

Sebelum menggunakan database Weaviate dengan RAG Engine, Anda harus melakukan hal berikut:

  1. Konfigurasikan dan deploy instance database Weaviate Anda.
  2. Siapkan endpoint HTTPS.
  3. Buat koleksi Weaviate Anda.
  4. Gunakan kunci API Anda untuk menyediakan Weaviate menggunakan AuthN dan AuthZ.
  5. Sediakan akun layanan RAG Engine Anda.

Mengonfigurasi dan men-deploy instance database Weaviate

Anda harus mengikuti panduan memulai cepat Weaviate resmi. Namun, Anda dapat menggunakan Google Cloud Panduan marketplace, yang bersifat opsional.

Anda dapat menyiapkan instance Weaviate di mana saja selama endpoint Weaviate dapat diakses untuk dikonfigurasi dan di-deploy di project Anda. Kemudian, Anda dapat mengelola sepenuhnya instance database Weaviate.

Karena RAG Engine tidak terlibat dalam tahap apa pun dalam siklus proses instance database Weaviate, Anda bertanggung jawab untuk memberikan izin ke RAG Engine agar dapat menyimpan dan menelusuri data di database Weaviate. Anda juga bertanggung jawab untuk memastikan bahwa data dalam database Anda dapat digunakan oleh RAG Engine. Misalnya, jika Anda mengubah data, RAG Engine tidak bertanggung jawab atas perilaku yang tidak terduga karena perubahan tersebut.

Menyiapkan endpoint HTTPS

Selama penyediaan Weaviate, pastikan Anda membuat endpoint HTTPS. Meskipun koneksi HTTP didukung, sebaiknya traffic database RAG Engine dan Weaviate menggunakan koneksi HTTPS.

Membuat koleksi Weaviate

Karena korpus RAG Engine dan koleksi Weaviate memiliki pemetaan satu-satu, Anda harus membuat koleksi di database Weaviate sebelum mengaitkan koleksi dengan korpus RAG Engine. Atribusi satu kali ini dibuat saat Anda memanggil CreateRagCorpus API atau UpdateRagCorpus API.

Saat membuat koleksi di Weaviate, Anda harus menggunakan skema berikut:

Nama properti Jenis data
fileId text
corpusId text
chunkId text
chunkDataType text
chunkData text
fileOriginalUri text

Menggunakan kunci API untuk menyediakan Weaviate menggunakan AuthN dan AuthZ

Menyediakan kunci API Weaviate melibatkan langkah-langkah berikut:

  1. Buat kunci API Weaviate.
  2. Konfigurasikan Weaviate menggunakan kunci API Weaviate Anda.
  3. Simpan kunci API Weaviate Anda di Secret Manager.

Membuat kunci API

RAG Engine hanya dapat terhubung ke instance database Weaviate menggunakan kunci API Anda untuk autentikasi dan otorisasi. Anda harus mengikuti panduan resmi Weaviate untuk autentikasi guna mengonfigurasi autentikasi berbasis kunci API di instance database Weaviate Anda.

Jika pembuatan kunci API Weaviate memerlukan informasi identitas untuk dikaitkan dengan yang berasal dari RAG Engine, Anda harus membuat korpus pertama, dan menggunakan akun layanan RAG Engine sebagai identitas.

Menyimpan kunci API di Secret Manager

Kunci API menyimpan Informasi Identitas Pribadi yang Sensitif (SPII), yang tunduk pada persyaratan hukum. Jika data SPII disusupi atau disalahgunakan, seseorang mungkin akan mengalami risiko atau bahaya yang signifikan. Untuk meminimalkan risiko bagi individu saat menggunakan RAG Engine, jangan menyimpan dan mengelola kunci API Anda, dan hindari membagikan kunci API yang tidak dienkripsi.

Untuk melindungi SPII, lakukan hal berikut:

  1. Simpan kunci API Anda di Secret Manager.
  2. Berikan izin ke akun layanan RAG Engine untuk secret Anda, dan kelola kontrol akses di tingkat resource secret.
    1. Buka izin project Anda.
    2. Aktifkan opsi Sertakan pemberian peran yang disediakan Google.
    3. Temukan akun layanan, yang memiliki format

      service-{project number}@gcp-sa-vertex-rag.iam.gserviceaccount.com

    4. Edit akun utama akun layanan.
    5. Tambahkan peran Secret Manager Secret Accessor ke akun layanan.
  3. Selama pembuatan atau pembaruan korpus RAG, teruskan nama resource secret ke RAG Engine, dan simpan nama resource secret.

Saat Anda membuat permintaan API ke instance database Weaviate, RAG Engine menggunakan setiap akun layanan untuk membaca kunci API yang sesuai dengan resource rahasia Anda di Secret Manager dari project Anda.

Menyediakan akun layanan RAG Engine

Saat Anda membuat resource pertama dalam project, RAG Engine akan membuat akun layanan khusus. Anda dapat menemukan akun layanan dari halaman IAM project. Akun layanan mengikuti format berikut:

service-{project number}@gcp-sa-vertex-rag.iam.gserviceaccount.com

Misalnya, service-123456789@gcp-sa-vertex-rag.iam.gserviceaccount.com.

Saat berintegrasi dengan database Weaviate, akun layanan Anda akan digunakan dalam skenario berikut:

  • Anda dapat menggunakan akun layanan untuk membuat kunci Weaviate API untuk autentikasi. Dalam beberapa kasus, pembuatan kunci API tidak memerlukan informasi pengguna, yang berarti akun layanan tidak diperlukan saat membuat kunci API.
  • Anda dapat mengikat akun layanan dengan kunci API di database Weaviate untuk mengonfigurasi autentikasi (AuthN) dan otorisasi (AuthZ). Namun, akun layanan Anda tidak diperlukan.
  • Anda dapat menyimpan Secret Manager kunci API di project, dan Anda dapat memberikan izin akun layanan ke resource secret ini.
  • RAG Engine menggunakan akun layanan untuk mengakses kunci API dari Secret Manager di project Anda.

Menyiapkan lingkungan konsol Google Cloud

Klik untuk mempelajari cara menyiapkan lingkungan Anda

Pelajari cara menyiapkan lingkungan Anda dengan memilih salah satu tab berikut:

Python

  1. 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.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Enable the Vertex AI API.

    Enable the API

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  5. Enable the Vertex AI API.

    Enable the API

  6. In the Google Cloud console, activate Cloud Shell.

    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.

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

  8. Instal atau update Vertex AI SDK untuk Python dengan menjalankan perintah berikut:

    pip3 install --upgrade "google-cloud-aiplatform>=1.38"
        

Node.js

  1. 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.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Enable the Vertex AI API.

    Enable the API

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  5. Enable the Vertex AI API.

    Enable the API

  6. In the Google Cloud console, activate Cloud Shell.

    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.

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

  8. Instal atau perbarui Vertex AI SDK untuk Node.js dengan menjalankan perintah berikut:

    npm install @google-cloud/vertexai
        

Java

  1. 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.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Enable the Vertex AI API.

    Enable the API

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  5. Enable the Vertex AI API.

    Enable the API

  6. In the Google Cloud console, activate Cloud Shell.

    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.

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

  8. Untuk menambahkan google-cloud-vertexai sebagai dependensi, tambahkan kode yang sesuai untuk lingkungan Anda:

    Maven dengan BOM

    Tambahkan HTML berikut ke pom.xml Anda:

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

    Maven tanpa BOM

    Tambahkan HTML berikut ke pom.xml Anda:

    <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

  1. 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.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Enable the Vertex AI API.

    Enable the API

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  5. Enable the Vertex AI API.

    Enable the API

  6. In the Google Cloud console, activate Cloud Shell.

    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.

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

  8. Tinjau paket Vertex AI API Go yang tersedia untuk menentukan paket mana yang paling sesuai dengan kebutuhan project Anda:

    • Paket cloud.google.com/go/vertexai (direkomendasikan)

      vertexai adalah paket yang dibuat manusia yang memberikan akses ke kemampuan dan fitur umum.

      Paket ini direkomendasikan sebagai titik awal bagi sebagian besar developer yang mem-build dengan Vertex AI API. Untuk mengakses kemampuan dan fitur yang belum tercakup dalam paket ini, gunakan aiplatform yang dibuat otomatis.

    • Paket cloud.google.com/go/aiplatform

      aiplatform adalah paket yang dibuat otomatis.

      Paket ini ditujukan untuk project yang memerlukan akses ke kemampuan dan fitur Vertex AI API yang belum disediakan oleh paket vertexai yang ditulis manusia.

  9. Instal paket Go yang diinginkan berdasarkan kebutuhan project Anda dengan menjalankan salah satu perintah berikut:

    # 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#

  1. 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.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Enable the Vertex AI API.

    Enable the API

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  5. Enable the Vertex AI API.

    Enable the API

  6. In the Google Cloud console, activate Cloud Shell.

    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.

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

  1. 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.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Enable the Vertex AI API.

    Enable the API

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  5. Enable the Vertex AI API.

    Enable the API

  6. In the Google Cloud console, activate Cloud Shell.

    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.

  7. Konfigurasikan variabel lingkungan dengan memasukkan kode berikut. Ganti PROJECT_ID dengan ID project Google Cloud Anda.
    MODEL_ID="gemini-1.5-flash-002"
    PROJECT_ID="PROJECT_ID"
        
  8. Sediakan endpoint:
    gcloud beta services identity create --service=aiplatform.googleapis.com --project=${PROJECT_ID}
        
  9. Opsional: Jika Anda menggunakan Cloud Shell dan diminta untuk memberikan otorisasi pada Cloud Shell, klik Authorize.

Menyiapkan korpus RAG

Untuk mengakses data dari database Weaviate, RAG Engine harus memiliki akses ke korpus RAG. Bagian ini memberikan langkah-langkah untuk membuat satu korpus RAG dan korpus RAG tambahan.

Menggunakan CreateRagCorpus API dan UpdateRagCorpus API

Anda harus menentukan kolom berikut saat memanggil API CreateRagCorpus dan UpdateRagCorpus:

  • rag_vector_db_config.weaviate: Setelah Anda memanggil CreateRagCorpus API, konfigurasi database vektor akan dipilih. Konfigurasi database vektor berisi semua kolom konfigurasi. Jika kolom rag_vector_db_config.weaviate tidak ditetapkan, rag_vector_db_config.rag_managed_db akan ditetapkan secara default.
  • weaviate.http_endpoint: Endpoint Weaviate HTTPS atau HTTP dibuat selama penyediaan instance database Weaviate.
  • weaviate.collection_name: Nama koleksi yang dibuat selama penyediaan instance Weaviate. Nama harus diawali dengan huruf kapital.
  • api_auth.api_key_config: Konfigurasi menentukan untuk menggunakan kunci API guna memberikan otorisasi akses Anda ke database vektor.
  • api_key_config.api_key_secret_version: Nama resource secret yang disimpan di Secret Manager, yang berisi kunci Weaviate API Anda.

Anda dapat membuat dan mengaitkan korpus RAG ke koleksi Weaviate di instance database. Namun, Anda mungkin memerlukan akun layanan untuk membuat kunci API dan mengonfigurasi instance database Weaviate. Saat Anda membuat korpus RAG pertama, akun layanan akan dibuat. Setelah Anda membuat korpus RAG pertama, pengaitan antara database Weaviate dan kunci API mungkin belum siap digunakan dalam pembuatan korpus RAG lainnya.

Jika database dan kunci Anda belum siap dikaitkan dengan korpus RAG, lakukan hal berikut pada korpus RAG:

  1. Tetapkan kolom weaviate di rag_vector_db_config.

    • Anda tidak dapat mengubah database vektor terkait.
    • Biarkan kolom http_endpoint dan collection_name kosong. Kedua kolom tersebut dapat diperbarui di lain waktu.
  2. Jika tidak memiliki kunci API yang disimpan di Secret Manager, Anda dapat meninggalkan kolom api_auth kosong. Saat memanggil API UpdateRagCorpus, Anda dapat memperbarui kolom api_auth. Weaviate mengharuskan hal berikut dilakukan:

    1. Tetapkan api_key_config di kolom api_auth.
    2. Tetapkan api_key_secret_version kunci API Weaviate Anda di Secret Manager. Kolom api_key_secret_version menggunakan format berikut:

      projects/{project}/secrets/{secret}/versions/{version}

  3. Jika menentukan kolom yang hanya dapat ditetapkan satu kali, seperti http_endpoint atau collection_name, Anda tidak dapat mengubahnya kecuali jika menghapus korpus RAG, dan membuat korpus RAG lagi. Kolom lain seperti kolom kunci API, api_key_secret_version, dapat diperbarui.

  4. Saat memanggil UpdateRagCorpus, Anda dapat menetapkan kolom vector_db. vector_db harus ditetapkan ke weaviate oleh panggilan API CreateRagCorpus Anda. Jika tidak, sistem akan memilih opsi Database Terkelola RAG, yang merupakan default. Opsi ini tidak dapat diubah saat Anda memanggil API UpdateRagCorpus. Saat memanggil UpdateRagCorpus dan kolom vector_db ditetapkan sebagian, Anda dapat memperbarui kolom yang ditandai sebagai Dapat Diubah (juga disebut sebagai dapat diubah).

Tabel ini mencantumkan kolom WeaviateConfig yang dapat diubah dan tidak dapat diubah yang digunakan dalam kode Anda.

Nama kolom Dapat Diubah atau Tidak Dapat Diubah
http_endpoint Tidak dapat diubah setelah ditetapkan
collection_name Tidak dapat diubah setelah ditetapkan
api_key_authentication Dapat diubah

Membuat korpus RAG pertama

Jika akun layanan RAG Engine tidak ada, lakukan tindakan berikut:

  1. Buat korpus RAG di RAG Engine dengan konfigurasi Weaviate kosong, yang memulai penyediaan RAG Engine untuk membuat akun layanan.
  2. Pilih nama untuk akun layanan RAG Engine Anda yang mengikuti format ini:

    service-{project number}@gcp-sa-vertex-rag.iam.gserviceaccount.com

    Misalnya, service-123456789@gcp-sa-vertex-rag.iam.gserviceaccount.com.

  3. Dengan menggunakan akun layanan, akses secret yang disimpan di Secret Manager project Anda, yang berisi kunci Weaviate API Anda.
  4. Dapatkan informasi berikut setelah penyediaan Weaviate selesai:
    • Endpoint HTTPS atau HTTP Weaviate Anda.
    • Nama koleksi Weaviate Anda.
  5. Panggil CreateRagCorpus API untuk membuat korpus RAG dengan konfigurasi Weaviate kosong, dan panggil UpdateRagCorpus API untuk memperbarui korpus RAG dengan informasi berikut:
    • Endpoint HTTPS atau HTTP Weaviate Anda.
    • Nama koleksi Weaviate Anda.
    • Nama resource kunci API.

Membuat korpus RAG lain

Jika akun layanan RAG Engine sudah ada, lakukan tindakan berikut:

  1. Dapatkan akun layanan RAG Engine dari izin project Anda.
  2. Aktifkan opsi "Sertakan pemberian peran yang disediakan Google"
  3. Pilih nama untuk akun layanan RAG Engine Anda yang mengikuti format ini:

    service-{project number}@gcp-sa-vertex-rag.iam.gserviceaccount.com

  4. Dengan menggunakan akun layanan, akses secret yang disimpan di Secret Manager project Anda, yang berisi kunci Weaviate API Anda.
  5. Selama penyediaan Weaviate, dapatkan informasi berikut:
    • Endpoint HTTPS atau HTTP Weaviate.
    • Nama koleksi Weaviate Anda.
  6. Buat korpus RAG di RAG Engine, dan hubungkan dengan koleksi Weaviate Anda dengan melakukan salah satu hal berikut:
    1. Lakukan panggilan API CreateRagCorpus untuk membuat korpus RAG dengan konfigurasi Weaviate yang terisi, yang merupakan opsi yang lebih disukai.
    2. Lakukan panggilan API CreateRagCorpus untuk membuat korpus RAG dengan konfigurasi Weaviate kosong, dan lakukan panggilan API UpdateRagCorpus untuk memperbarui korpus RAG dengan informasi berikut:
      • Endpoint HTTP database Weaviate
      • Nama Koleksi Weaviate
      • Kunci API

Contoh

Bagian ini menyajikan contoh kode yang menunjukkan cara menyiapkan database Weaviate, Secret Manager, korpus RAG, dan file RAG. Kode contoh juga disediakan untuk menunjukkan cara mengimpor file, mengambil konteks, membuat konten, dan menghapus korpus RAG dan file RAG.

Untuk menggunakan notebook Model Garden RAG API, lihat Menggunakan Weaviate dengan Llama 3.

Menyiapkan database Weaviate

Contoh kode ini menunjukkan cara menyiapkan data Weaviate dan Pengelola Rahasia.

REST

# 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

Menyiapkan Secret Manager

Untuk menyiapkan Secret Manager, Anda harus mengaktifkan Secret Manager, dan menetapkan izin.

Membuat Rahasia

Untuk mengaktifkan Secret Manager, lakukan hal berikut:

Konsol

  1. Buka halaman Secret Manager.

    Buka Secret Manager

  2. Klik + Create Secret.

  3. Masukkan Nama secret Anda. Nama rahasia hanya boleh berisi huruf Latin (A-Z), angka (0-9), tanda hubung (-), dan garis bawah (_).

  4. Penentuan kolom berikut bersifat opsional:

    1. Untuk mengupload file dengan secret Anda, klik Browse.
    2. Baca Kebijakan replikasi.
    3. Jika Anda ingin mengelola lokasi untuk secret secara manual, centang Kelola lokasi secara manual untuk secret ini. Minimal satu region harus dipilih.
    4. Pilih opsi enkripsi Anda.
    5. Jika Anda ingin menetapkan periode rotasi secara manual, centang Tetapkan periode rotasi.
    6. Jika Anda ingin menentukan topik Publikasikan atau berlangganan untuk menerima notifikasi peristiwa, klik Tambahkan topik.
    7. Secara default, masa berlaku secret tidak pernah berakhir. Jika Anda ingin menetapkan tanggal habis masa berlaku, centang Tetapkan tanggal habis masa berlaku.
    8. Secara default, versi secret dihancurkan berdasarkan permintaan. Untuk menunda penghancuran versi secret, centang Set duration for delayed destruction.
    9. Jika Anda ingin menggunakan label untuk mengatur dan mengategorikan secret, klik + Tambahkan label.
    10. Jika Anda ingin menggunakan anotasi untuk melampirkan metadata non-identitas ke secret, klik + Tambahkan anotasi.
  5. Klik Buat secret.

REST

# 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\": {}}}"

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Python Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

def create_secret(
    project_id: str, secret_id: str, ttl: Optional[str] = None
) -> secretmanager.Secret:
    """
    Create a new secret with the given name. A secret is a logical wrapper
    around a collection of secret versions. Secret versions hold the actual
    secret material.

     Args:
        project_id (str): The project ID where the secret is to be created.
        secret_id (str): The ID to assign to the new secret. This ID must be unique within the project.
        ttl (Optional[str]): An optional string that specifies the secret's time-to-live in seconds with
                             format (e.g., "900s" for 15 minutes). If specified, the secret
                             versions will be automatically deleted upon reaching the end of the TTL period.

    Returns:
        secretmanager.Secret: An object representing the newly created secret, containing details like the
                              secret's name, replication settings, and optionally its TTL.

    Example:
        # Create a secret with automatic replication and no TTL
        new_secret = create_secret("my-project", "my-new-secret")

        # Create a secret with a TTL of 30 days
        new_secret_with_ttl = create_secret("my-project", "my-timed-secret", "7776000s")
    """

    # Import the Secret Manager client library.
    from google.cloud import secretmanager

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the parent project.
    parent = f"projects/{project_id}"

    # Create the secret.
    response = client.create_secret(
        request={
            "parent": parent,
            "secret_id": secret_id,
            "secret": {"replication": {"automatic": {}}, "ttl": ttl},
        }
    )

    # Print the new secret name.
    print(f"Created secret: {response.name}")

Menetapkan izin

Anda harus memberikan izin Secret Manager ke akun layanan Anda.

Konsol

  1. Di bagian IAM & Admin di konsol Google Cloud, temukan akun layanan, lalu klik ikon pensil untuk mengedit.

  2. Di kolom Role, pilih Secret Manager Secret Accessor.

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Python Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

def iam_grant_access(
    project_id: str, secret_id: str, member: str
) -> iam_policy_pb2.SetIamPolicyRequest:
    """
    Grant the given member access to a secret.
    """

    # Import the Secret Manager client library.
    from google.cloud import secretmanager

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the secret.
    name = client.secret_path(project_id, secret_id)

    # Get the current IAM policy.
    policy = client.get_iam_policy(request={"resource": name})

    # Add the given member with access permissions.
    policy.bindings.add(role="roles/secretmanager.secretAccessor", members=[member])

    # Update the IAM Policy.
    new_policy = client.set_iam_policy(request={"resource": name, "policy": policy})

    # Print data about the secret.
    print(f"Updated IAM policy on {secret_id}")

Menambahkan Versi Secret

REST

# TODO(developer): Update the variables.
# Select a resource name for your Secret, which contains your API Key.
SECRET_NAME="MyWeaviateApiKeySecret"

# 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}\"}}"

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Python Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

from google.cloud import secretmanager
import google_crc32c  # type: ignore


def add_secret_version(
    project_id: str, secret_id: str, payload: str
) -> secretmanager.SecretVersion:
    """
    Add a new secret version to the given secret with the provided payload.
    """

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the parent secret.
    parent = client.secret_path(project_id, secret_id)

    # Convert the string payload into a bytes. This step can be omitted if you
    # pass in bytes instead of a str for the payload argument.
    payload_bytes = payload.encode("UTF-8")

    # Calculate payload checksum. Passing a checksum in add-version request
    # is optional.
    crc32c = google_crc32c.Checksum()
    crc32c.update(payload_bytes)

    # Add the secret version.
    response = client.add_secret_version(
        request={
            "parent": parent,
            "payload": {
                "data": payload_bytes,
                "data_crc32c": int(crc32c.hexdigest(), 16),
            },
        }
    )

    # Print the new secret version name.
    print(f"Added secret version: {response.name}")

Menggunakan Weaviate dengan Llama 3

Notebook Model Garden RAG API menunjukkan cara menggunakan Vertex AI SDK untuk Python dengan korpus Weaviate dan model Llama 3. Untuk menggunakan notebook, Anda harus melakukan hal berikut:

  1. Siapkan database Weaviate.

  2. Siapkan Secret Manager.

  3. Gunakan notebook Model Garden RAG API.

Untuk contoh lainnya, lihat Contoh.

Membuat korpus RAG

Contoh kode ini menunjukkan cara membuat korpus RAG, dan menetapkan instance Weaviate sebagai database vektornya.

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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Python Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# weaviate_http_endpoint = "weaviate-http-endpoint"
# weaviate_collection_name = "weaviate-collection-name"
# weaviate_api_key_secret_manager_version = "projects/{PROJECT_ID}/secrets/{SECRET_NAME}/versions/latest"
# display_name = "test_corpus"
# description = "Corpus Description"

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

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

# Configure Vector DB
vector_db = rag.Weaviate(
    weaviate_http_endpoint=weaviate_http_endpoint,
    collection_name=weaviate_collection_name,
    api_key=weaviate_api_key_secret_manager_version,
)

corpus = rag.create_corpus(
    display_name=display_name,
    description=description,
    embedding_model_config=embedding_model_config,
    vector_db=vector_db,
)
print(corpus)
# Example response:
# RagCorpus(name='projects/1234567890/locations/us-central1/ragCorpora/1234567890',
# display_name='test_corpus', description='Corpus Description', embedding_model_config=...
# ...

Menggunakan file RAG

RAG API menangani upload, impor, listingan, dan penghapusan file.

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: Project ID Anda.
  • LOCATION: Region untuk memproses permintaan.
  • RAG_CORPUS_ID: ID resource RagCorpus.
  • INPUT_FILE: Jalur file lokal.
  • FILE_DISPLAY_NAME: Nama tampilan RagFile.
  • RAG_FILE_DESCRIPTION: Deskripsi RagFile.

Metode HTTP dan URL:

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

Isi JSON permintaan:

{
 "rag_file": {
  "display_name": "FILE_DISPLAY_NAME",
  "description": "RAG_FILE_DESCRIPTION"
 }
}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Simpan isi permintaan dalam file bernama INPUT_FILE, lalu jalankan perintah berikut:

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

Simpan isi permintaan dalam file bernama INPUT_FILE, dan jalankan perintah berikut:

$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
Respons yang berhasil akan menampilkan resource RagFile. Komponen terakhir kolom RagFile.name adalah rag_file_id yang dibuat server.

Python

Untuk mempelajari cara menginstal atau mengupdate Vertex AI SDK untuk Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi Python API.


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# corpus_name = "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}"
# path = "path/to/local/file.txt"
# display_name = "file_display_name"
# description = "file description"

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

rag_file = rag.upload_file(
    corpus_name=corpus_name,
    path=path,
    display_name=display_name,
    description=description,
)
print(rag_file)
# RagFile(name='projects/[PROJECT_ID]/locations/us-central1/ragCorpora/1234567890/ragFiles/09876543',
#  display_name='file_display_name', description='file description')

Mengimpor file RAG

File dan folder dapat diimpor dari Drive atau Cloud Storage.

REST

Gunakan response.metadata untuk melihat kegagalan sebagian, waktu permintaan, dan waktu respons di objek response SDK.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: Project ID Anda.
  • LOCATION: Region untuk memproses permintaan.
  • RAG_CORPUS_ID: ID resource RagCorpus.
  • GCS_URIS: Daftar lokasi Cloud Storage. Contoh: gs://my-bucket1, gs://my-bucket2.
  • DRIVE_RESOURCE_ID: ID resource Drive. Contoh:
    • https://drive.google.com/file/d/ABCDE
    • https://drive.google.com/corp/drive/u/0/folders/ABCDEFG
  • DRIVE_RESOURCE_TYPE: Jenis resource Drive. Opsi:
    • RESOURCE_TYPE_FILE - File
    • RESOURCE_TYPE_FOLDER - Folder
  • CHUNK_SIZE: Opsional: Jumlah token yang harus dimiliki setiap bagian.
  • CHUNK_OVERLAP: Opsional: Jumlah token yang tumpang-tindih di antara bagian.

Metode HTTP dan URL:

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

Isi JSON permintaan:

{
  "import_rag_files_config": {
    "gcs_source": {
      "uris": GCS_URIS
    },
    "google_drive_source": {
      "resource_ids": {
        "resource_id": DRIVE_RESOURCE_ID,
        "resource_type": DRIVE_RESOURCE_TYPE
      },
    }
  }
}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Simpan isi permintaan dalam file bernama request.json, lalu jalankan perintah berikut:

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

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

$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
Respons yang berhasil akan menampilkan resource ImportRagFilesOperationMetadata.

Contoh berikut menunjukkan cara mengimpor file dari Cloud Storage. Gunakan kolom kontrol max_embedding_requests_per_min untuk membatasi kecepatan RAG Engine memanggil model penyematan selama proses pengindeksan ImportRagFiles. Kolom ini memiliki nilai default 1000 panggilan per menit.

// 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}

Contoh berikut menunjukkan cara mengimpor file dari Drive. Gunakan kolom kontrol max_embedding_requests_per_min untuk membatasi kecepatan RAG Engine memanggil model penyematan selama proses pengindeksan ImportRagFiles. Kolom ini memiliki nilai default 1000 panggilan per menit.

// 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

Untuk mempelajari cara menginstal atau mengupdate Vertex AI SDK untuk Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi Python API.


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# corpus_name = "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}"
# paths = ["https://drive.google.com/file/123", "gs://my_bucket/my_files_dir"]  # Supports Google Cloud Storage and Google Drive Links

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

response = rag.import_files(
    corpus_name=corpus_name,
    paths=paths,
    chunk_size=512,  # Optional
    chunk_overlap=100,  # Optional
    max_embedding_requests_per_min=900,  # Optional
)
print(f"Imported {response.imported_rag_files_count} files.")
# Example response:
# Imported 2 files.

Mendapatkan file RAG

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: Project ID Anda.
  • LOCATION: Region untuk memproses permintaan.
  • RAG_CORPUS_ID: ID resource RagCorpus.
  • RAG_FILE_ID: ID resource RagFile.

Metode HTTP dan URL:

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

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Jalankan perintah berikut:

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

PowerShell

Jalankan perintah berikut:

$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
Respons yang berhasil akan menampilkan resource RagFile.

Python

Untuk mempelajari cara menginstal atau mengupdate Vertex AI SDK untuk Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi Python API.


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# file_name = "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}/ragFiles/{rag_file_id}"

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

rag_file = rag.get_file(name=file_name)
print(rag_file)
# Example response:
# RagFile(name='projects/1234567890/locations/us-central1/ragCorpora/11111111111/ragFiles/22222222222',
# display_name='file_display_name', description='file description')

Mencantumkan file RAG

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: Project ID Anda.
  • LOCATION: Region untuk memproses permintaan.
  • RAG_CORPUS_ID: ID resource RagCorpus.
  • PAGE_SIZE: Ukuran halaman daftar standar. Anda dapat menyesuaikan jumlah RagFiles yang akan ditampilkan per halaman dengan memperbarui parameter page_size.
  • PAGE_TOKEN: Token halaman daftar standar. Biasanya diperoleh menggunakan ListRagFilesResponse.next_page_token dari panggilan VertexRagDataService.ListRagFiles sebelumnya.

Metode HTTP dan 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

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Jalankan perintah berikut:

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

Jalankan perintah berikut:

$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
Anda akan menerima kode status yang berhasil (2xx) beserta daftar RagFiles di bagian RAG_CORPUS_ID yang diberikan.

Python

Untuk mempelajari cara menginstal atau mengupdate Vertex AI SDK untuk Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi Python API.


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# corpus_name = "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}"

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

files = rag.list_files(corpus_name=corpus_name)
for file in files:
    print(file.display_name)
    print(file.name)
# Example response:
# g-drive_file.txt
# projects/1234567890/locations/us-central1/ragCorpora/111111111111/ragFiles/222222222222
# g_cloud_file.txt
# projects/1234567890/locations/us-central1/ragCorpora/111111111111/ragFiles/333333333333

Menghapus file RAG

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: Project ID Anda.
  • LOCATION: Region untuk memproses permintaan.
  • RAG_CORPUS_ID: ID resource RagCorpus.
  • RAG_FILE_ID: ID resource RagFile. Format: projects/{project}/locations/{location}/ragCorpora/{rag_corpus}/ragFiles/{rag_file_id}.

Metode HTTP dan URL:

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

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Jalankan perintah berikut:

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

PowerShell

Jalankan perintah berikut:

$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
Respons yang berhasil akan menampilkan resource DeleteOperationMetadata.

Python

Untuk mempelajari cara menginstal atau mengupdate Vertex AI SDK untuk Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi Python API.


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# file_name = "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}/ragFiles/{rag_file_id}"

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

rag.delete_file(name=file_name)
print(f"File {file_name} deleted.")
# Example response:
# Successfully deleted the RagFile.
# File projects/1234567890/locations/us-central1/ragCorpora/1111111111/ragFiles/2222222222 deleted.

Mengambil konteks

Saat pengguna mengajukan pertanyaan atau memberikan perintah, komponen pengambilan di RAG akan menelusuri pusat informasinya untuk menemukan informasi yang relevan dengan kueri.

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • LOCATION: Region untuk memproses permintaan.
  • PROJECT_ID: Project ID Anda.
  • RAG_CORPUS_RESOURCE: Nama resource RagCorpus. Format: projects/{project}/locations/{location}/ragCorpora/{rag_corpus}.
  • VECTOR_DISTANCE_THRESHOLD: Hanya konteks dengan jarak vektor yang lebih kecil dari nilai minimum yang ditampilkan.
  • TEXT: Teks kueri untuk mendapatkan konteks yang relevan.
  • SIMILARITY_TOP_K: Jumlah konteks teratas yang akan diambil.

Metode HTTP dan URL:

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

Isi JSON permintaan:

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

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Simpan isi permintaan dalam file bernama request.json, lalu jalankan perintah berikut:

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

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

$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
Anda akan menerima kode status yang berhasil (2xx) dan daftar RagFiles terkait.

Python

Untuk mempelajari cara menginstal atau mengupdate Vertex AI SDK untuk Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi Python API.


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# corpus_name = "projects/[PROJECT_ID]/locations/us-central1/ragCorpora/[rag_corpus_id]"

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

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

Membuat konten

Prediksi mengontrol metode LLM yang menghasilkan konten.

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: Project ID Anda.
  • LOCATION: Region untuk memproses permintaan.
  • MODEL_ID: Model LLM untuk pembuatan konten. Contoh: gemini-1.5-pro-002
  • GENERATION_METHOD: Metode LLM untuk pembuatan konten. Opsi: generateContent, streamGenerateContent
  • INPUT_PROMPT: Teks yang dikirim ke LLM untuk pembuatan konten. Coba gunakan perintah yang relevan dengan File rag yang diupload.
  • RAG_CORPUS_RESOURCE: Nama resource RagCorpus. Format: projects/{project}/locations/{location}/ragCorpora/{rag_corpus}.
  • SIMILARITY_TOP_K: Opsional: Jumlah konteks teratas yang akan diambil.
  • VECTOR_DISTANCE_THRESHOLD: Opsional: Konteks dengan jarak vektor yang lebih kecil dari nilai minimum akan ditampilkan.

Metode HTTP dan URL:

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

Isi JSON permintaan:

{
 "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
   }
  }
 }
}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Simpan isi permintaan dalam file bernama request.json, lalu jalankan perintah berikut:

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

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

$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
Respons yang berhasil akan menampilkan konten yang dihasilkan dengan kutipan.

Python

Untuk mempelajari cara menginstal atau mengupdate Vertex AI SDK untuk Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi Python API.


from vertexai.preview import rag
from vertexai.preview.generative_models import GenerativeModel, Tool
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# corpus_name = "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}"

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

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

rag_model = GenerativeModel(
    model_name="gemini-1.5-flash-001", tools=[rag_retrieval_tool]
)
response = rag_model.generate_content("Why is the sky blue?")
print(response.text)
# Example response:
#   The sky appears blue due to a phenomenon called Rayleigh scattering.
#   Sunlight, which contains all colors of the rainbow, is scattered
#   by the tiny particles in the Earth's atmosphere....
#   ...

Penelusuran campuran didukung dengan database Weaviate, yang menggabungkan penelusuran semantik dan kata kunci untuk meningkatkan relevansi hasil penelusuran. Selama pengambilan hasil penelusuran, kombinasi skor kemiripan dari semantik (vektor padat) dan pencocokan kata kunci (vektor jarang) menghasilkan hasil terakhir yang diberi peringkat.

Penelusuran campuran menggunakan API pengambilan RAG Engine

Ini adalah contoh cara mengaktifkan penelusuran campuran menggunakan API pengambilan Mesin RAG.

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

Untuk mempelajari cara menginstal atau mengupdate Vertex AI SDK untuk Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi Python API.


from vertexai.preview import rag
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# corpus_name = "projects/[PROJECT_ID]/locations/us-central1/ragCorpora/[rag_corpus_id]"

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

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

Menggunakan penelusuran campuran dan Mesin RAG untuk pembuatan yang di-grounding

Ini adalah contoh cara menggunakan penelusuran campuran dan RAG Engine untuk pembuatan yang beralasan.

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

Untuk mempelajari cara menginstal atau mengupdate Vertex AI SDK untuk Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi Python API.


from vertexai.preview import rag
from vertexai.preview.generative_models import GenerativeModel, Tool
import vertexai

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# corpus_name = "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}"

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

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

rag_model = GenerativeModel(
    model_name="gemini-1.5-flash-001", tools=[rag_retrieval_tool]
)
response = rag_model.generate_content("Why is the sky blue?")
print(response.text)
# Example response:
#   The sky appears blue due to a phenomenon called Rayleigh scattering.
#   Sunlight, which contains all colors of the rainbow, is scattered
#   by the tiny particles in the Earth's atmosphere....
#   ...

Langkah selanjutnya