跳到主要內容
Open In ColabOpen on GitHub

適用於 PostgreSQL 的 Google AlloyDB

AlloyDB 是一項全受管關聯式資料庫服務,可提供高效能、無縫整合和令人印象深刻的可擴充性。AlloyDB 與 PostgreSQL 100% 相容。擴展您的資料庫應用程式,以利用 AlloyDB 的 Langchain 整合功能來建構 AI 驅動的體驗。

本筆記本說明如何使用 AlloyDB for PostgreSQLAlloyDBVectorStore 類別來儲存向量嵌入。

GitHub 上瞭解有關套件的更多資訊。

Open In Colab

開始之前

若要執行本筆記本,您需要執行下列操作

🦜🔗 程式庫安裝

安裝整合程式庫 langchain-google-alloydb-pg 和嵌入服務程式庫 langchain-google-vertexai

%pip install --upgrade --quiet  langchain-google-alloydb-pg langchain-google-vertexai

僅限 Colab: 取消註解以下儲存格以重新啟動核心,或使用按鈕重新啟動核心。對於 Vertex AI Workbench,您可以使用頂端的按鈕重新啟動終端機。

# # Automatically restart kernel after installs so that your environment can access the new packages
# import IPython

# app = IPython.Application.instance()
# app.kernel.do_shutdown(True)

🔐 驗證

以登入本筆記本的 IAM 使用者身分驗證 Google Cloud,以便存取您的 Google Cloud 專案。

  • 如果您使用 Colab 執行本筆記本,請使用以下儲存格並繼續。
  • 如果您使用 Vertex AI Workbench,請查看 此處 的設定指示。
from google.colab import auth

auth.authenticate_user()

☁ 設定您的 Google Cloud 專案

設定您的 Google Cloud 專案,以便在本筆記本中利用 Google Cloud 資源。

如果您不知道您的專案 ID,請嘗試以下操作

  • 執行 gcloud config list
  • 執行 gcloud projects list
  • 請參閱支援頁面:尋找專案 ID
# @markdown Please fill in the value below with your Google Cloud project ID and then run the cell.

PROJECT_ID = "my-project-id" # @param {type:"string"}

# Set the project id
!gcloud config set project {PROJECT_ID}

基本使用方式

設定 AlloyDB 資料庫值

AlloyDB 執行個體頁面 中尋找您的資料庫值。

# @title Set Your Values Here { display-mode: "form" }
REGION = "us-central1" # @param {type: "string"}
CLUSTER = "my-cluster" # @param {type: "string"}
INSTANCE = "my-primary" # @param {type: "string"}
DATABASE = "my-database" # @param {type: "string"}
TABLE_NAME = "vector_store" # @param {type: "string"}

AlloyDBEngine 連線集區

將 AlloyDB 建立為向量儲存區的需求和引數之一是 AlloyDBEngine 物件。AlloyDBEngine 會設定與您的 AlloyDB 資料庫的連線集區,讓您的應用程式能夠成功連線,並遵循業界最佳實務。

若要使用 AlloyDBEngine.from_instance() 建立 AlloyDBEngine,您只需要提供 5 個項目

  1. project_id:AlloyDB 執行個體所在的 Google Cloud 專案的專案 ID。
  2. region:AlloyDB 執行個體所在的區域。
  3. cluster:AlloyDB 叢集的名稱。
  4. instance:AlloyDB 執行個體的名稱。
  5. database:要連線到 AlloyDB 執行個體上的資料庫名稱。

根據預設,IAM 資料庫驗證 將用作資料庫驗證方法。此程式庫使用屬於從環境來源的 應用程式預設憑證 (ADC) 的 IAM 主體。

或者,也可以使用 內建資料庫驗證,方法是使用使用者名稱和密碼來存取 AlloyDB 資料庫。只需將選用的 userpassword 引數提供給 AlloyDBEngine.from_instance() 即可

  • user:用於內建資料庫驗證和登入的資料庫使用者
  • password:用於內建資料庫驗證和登入的資料庫密碼。

注意: 本教學課程示範非同步介面。所有非同步方法都有對應的同步方法。

from langchain_google_alloydb_pg import AlloyDBEngine

engine = await AlloyDBEngine.afrom_instance(
project_id=PROJECT_ID,
region=REGION,
cluster=CLUSTER,
instance=INSTANCE,
database=DATABASE,
)

初始化表格

AlloyDBVectorStore 類別需要資料庫表格。AlloyDBEngine 引擎具有協助程式方法 init_vectorstore_table(),可用於為您建立具有正確結構描述的表格。

await engine.ainit_vectorstore_table(
table_name=TABLE_NAME,
vector_size=768, # Vector size for VertexAI model(textembedding-gecko@latest)
)

建立嵌入類別執行個體

您可以使用任何 LangChain 嵌入模型。您可能需要啟用 Vertex AI API 才能使用 VertexAIEmbeddings。我們建議為生產環境設定嵌入模型的版本,深入瞭解 文字嵌入模型

# enable Vertex AI API
!gcloud services enable aiplatform.googleapis.com
from langchain_google_vertexai import VertexAIEmbeddings

embedding = VertexAIEmbeddings(
model_name="textembedding-gecko@latest", project=PROJECT_ID
)
API 參考文件:VertexAIEmbeddings

初始化預設 AlloyDBVectorStore

from langchain_google_alloydb_pg import AlloyDBVectorStore

store = await AlloyDBVectorStore.create(
engine=engine,
table_name=TABLE_NAME,
embedding_service=embedding,
)

新增文字

import uuid

all_texts = ["Apples and oranges", "Cars and airplanes", "Pineapple", "Train", "Banana"]
metadatas = [{"len": len(t)} for t in all_texts]
ids = [str(uuid.uuid4()) for _ in all_texts]

await store.aadd_texts(all_texts, metadatas=metadatas, ids=ids)

刪除文字

await store.adelete([ids[1]])

搜尋文件

query = "I'd like a fruit."
docs = await store.asimilarity_search(query)
print(docs)

依向量搜尋文件

query_vector = embedding.embed_query(query)
docs = await store.asimilarity_search_by_vector(query_vector, k=2)
print(docs)

新增索引

套用向量索引來加速向量搜尋查詢。深入瞭解向量索引

from langchain_google_alloydb_pg.indexes import IVFFlatIndex

index = IVFFlatIndex()
await store.aapply_vector_index(index)

重新編製索引

await store.areindex()  # Re-index using default index name

移除索引

await store.adrop_vector_index()  # Delete index using default name

建立自訂向量儲存區

向量儲存區可以利用關聯式資料來篩選相似性搜尋。

建立具有自訂中繼資料欄的表格。

from langchain_google_alloydb_pg import Column

# Set table name
TABLE_NAME = "vectorstore_custom"

await engine.ainit_vectorstore_table(
table_name=TABLE_NAME,
vector_size=768, # VertexAI model: textembedding-gecko@latest
metadata_columns=[Column("len", "INTEGER")],
)


# Initialize AlloyDBVectorStore
custom_store = await AlloyDBVectorStore.create(
engine=engine,
table_name=TABLE_NAME,
embedding_service=embedding,
metadata_columns=["len"],
# Connect to a existing VectorStore by customizing the table schema:
# id_column="uuid",
# content_column="documents",
# embedding_column="vectors",
)

使用中繼資料篩選器搜尋文件

import uuid

# Add texts to the Vector Store
all_texts = ["Apples and oranges", "Cars and airplanes", "Pineapple", "Train", "Banana"]
metadatas = [{"len": len(t)} for t in all_texts]
ids = [str(uuid.uuid4()) for _ in all_texts]
await store.aadd_texts(all_texts, metadatas=metadatas, ids=ids)

# Use filter on search
docs = await custom_store.asimilarity_search_by_vector(query_vector, filter="len >= 6")

print(docs)

此頁面是否實用?