Skip to main content
Open In ColabOpen on GitHub

Google AlloyDB for PostgreSQL

Google Cloud AlloyDB for PostgreSQL 是一款完全托管的 PostgreSQL 兼容数据库服务,适用于要求最高的企业级工作负载。AlloyDB 结合了 Google CloudPostgreSQL 的优势,实现卓越的性能、扩展性和可用性。通过 AlloyDB Langchain 集成,扩展您的数据库应用程序,构建由 AI 驱动的体验。

该笔记本介绍了如何使用 Google Cloud AlloyDB for PostgreSQLAlloyDBChatMessageHistory 类一起存储聊天消息历史。

Learn more about the package on GitHub.

Open In Colab

开始之前

要运行此笔记本,您需要执行以下操作:

🦜🔗 库安装

The integration lives in its own langchain-google-alloydb-pg package, so we need to install it.

%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工作区,请参阅设置说明这里
from google.colab import auth

auth.authenticate_user()

☁ 设置您的Google云项目

设置您的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}

💡 API 启用

The langchain-google-alloydb-pg package requires that you enable the AlloyDB Admin API in your Google Cloud Project.

# enable AlloyDB API
!gcloud services enable alloydb.googleapis.com

基本用法

设置AlloyDB数据库值

AlloyDB 集群页面中查找您的数据库值。

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

AlloyDB引擎连接池

将 AlloyDB 建立为 ChatMessageHistory 内存存储的一个要求和参数是 AlloyDBEngine 对象。AlloyDBEngine 配置了到您的 AlloyDB 数据库的连接池,从而实现从您的应用程序成功连接,并遵循行业最佳实践。

要使用AlloyDBEngine.from_instance()创建一个AlloyDBEngine,您只需提供5个内容项:

  1. project_id : 在包含 AlloyDB 实例的 Google 云项目中的项目 ID。
  2. region : Region where the AlloyDB instance is located.
  3. cluster: The name of the AlloyDB cluster.
  4. instance : AlloyDB 实例的名称。
  5. database : 连接到AlloyDB实例时要使用的数据库名称。

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

Optionally, 内置数据库认证 可以使用用户名和密码访问AlloyDB数据库。只需向AlloyDBEngine.from_instance()提供可选的userpassword参数:

  • user : 使用内置数据库进行身份验证和登录时要使用的数据库用户
  • password : 使用内置数据库身份验证和登录时的数据库密码。
from langchain_google_alloydb_pg import AlloyDBEngine

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

初始化表格

AlloyDBChatMessageHistory 类需要一个具有特定模式的数据库表,以存储聊天消息历史。

AlloyDBEngine 引擎有一个辅助方法 init_chat_history_table(),可用于为您创建具有正确模式的表。

engine.init_chat_history_table(table_name=TABLE_NAME)

AlloyDB聊天消息历史

初始化 AlloyDBChatMessageHistory 类时,您只需提供以下三点:

  1. engine - 一个AlloyDBEngine引擎的实例。
  2. session_id - 一个唯一的标识符字符串,用于指定会话的ID。
  3. table_name : 用于存储聊天消息历史记录的 AlloyDB 数据库中的表名。
from langchain_google_alloydb_pg import AlloyDBChatMessageHistory

history = AlloyDBChatMessageHistory.create_sync(
engine, session_id="test_session", table_name=TABLE_NAME
)
history.add_user_message("hi!")
history.add_ai_message("whats up?")
history.messages

清理

当特定会话的历史记录已过时并可以删除时,可以通过以下方式进行。

注意: 数据一旦删除,将不再存储在 AlloyDB 中,并且会永久丢失。

history.clear()

🔗 链接

我们可以轻松地将此消息历史类与LCEL Runnables结合使用

为此,我们将使用Google Vertex AI 聊天模型之一,这要求你在 Google Cloud 项目中启用 Vertex AI API

# enable Vertex AI API
!gcloud services enable aiplatform.googleapis.com
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_google_vertexai import ChatVertexAI
prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a helpful assistant."),
MessagesPlaceholder(variable_name="history"),
("human", "{question}"),
]
)

chain = prompt | ChatVertexAI(project=PROJECT_ID)
chain_with_history = RunnableWithMessageHistory(
chain,
lambda session_id: AlloyDBChatMessageHistory.create_sync(
engine,
session_id=session_id,
table_name=TABLE_NAME,
),
input_messages_key="question",
history_messages_key="history",
)
# This is where we configure the session id
config = {"configurable": {"session_id": "test_session"}}
chain_with_history.invoke({"question": "Hi! I'm bob"}, config=config)
chain_with_history.invoke({"question": "Whats my name"}, config=config)