以编程方式使用文档

> Cloud SQL 是一个完全托管的关系型数据库服务,提供高性能、无缝集成和出色的可扩展性。它提供 PostgreSQL、PostgreSQL 和 SQL Server 数据库引擎。通过 Cloud SQL 的 LangChain 集成扩展您的数据库应用程序,以构建 AI 驱动的体验。

本笔记本介绍如何使用 Cloud SQL for PostgreSQL 使用 PostgresVectorStore class.

了解更多关于该包的信息,请访问 GitHub.

![在 Colab 中打开](https://colab.research.google.com/github/googleapis/langchain-google-cloud-sql-pg-python/blob/main/docs/vector_store.ipynb)

准备工作

要运行本笔记本,您需要完成以下操作:

🦜🔗 库安装

安装集成库, langchain-google-cloud-sql-pg,以及嵌入服务的库, langchain-google-vertexai.

pip install -qU  langchain-google-cloud-sql-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,请查看 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}

基本用法

设置 Cloud SQL 数据库值

Cloud SQL 实例页面.

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

PostgresEngine 连接池

将 Cloud SQL 作为向量存储建立连接的要求和参数之一是 PostgresEngine 对象。该 PostgresEngine 会为您的 Cloud SQL 数据库配置一个连接池,使应用程序能够成功连接并遵循行业最佳实践。

要创建一个 PostgresEngine 使用 PostgresEngine.from_instance() 您只需提供 4 个内容:

  1. project_id :Cloud SQL 实例所在 Google Cloud 项目的项目 ID。
  2. region :Cloud SQL 实例所在的区域。
  3. instance :Cloud SQL 实例的名称。
  4. database :Cloud SQL 实例上要连接的数据库名称。

默认情况下, IAM 数据库身份验证 将用作数据库身份验证方法。此库使用来自 应用默认凭据(ADC) 环境中获取的 IAM 主体。

有关 IAM 数据库身份验证的更多信息,请参阅:

可选地, 内置数据库身份验证 也可以使用用户名和密码访问 Cloud SQL 数据库。只需提供可选的 userpassword 参数即可。 PostgresEngine.from_instance():

  • * user :用于内置数据库身份验证和登录的数据库用户
  • * password :用于内置数据库身份验证和登录的数据库密码。

"**注意**:本教程演示了异步接口。所有异步方法都有对应的同步方法。"

from langchain_google_cloud_sql_pg import PostgresEngine

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

初始化表

PostgresVectorStore 类需要一个数据库表。该 PostgresEngine 引擎有一个辅助方法 init_vectorstore_table() 可用于为您创建具有正确架构的表。

from langchain_google_cloud_sql_pg import PostgresEngine

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
)

初始化默认 PostgresVectorStore

from langchain_google_cloud_sql_pg import PostgresVectorStore

store = await PostgresVectorStore.create(  # Use .create() to initialize an async vector store
    engine=engine,
    table_name=TABLE_NAME,
    embedding_service=embedding,
)

添加文本

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_cloud_sql_pg.indexes import IVFFlatIndex

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

Re-index

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

移除索引

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

创建自定义向量存储

向量存储可以利用关系数据来过滤相似性搜索。

创建带有自定义元数据列的表。

from langchain_google_cloud_sql_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 PostgresVectorStore
custom_store = await PostgresVectorStore.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",
)

使用元数据过滤器搜索文档

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