Skip to main content
Open In Colab在 GitHub 上打开

适用于 PostgreSQL 的 Google AlloyDB

Google Cloud AlloyDB for PostgreSQL 是一个完全托管的PostgreSQL适用于要求最苛刻的企业工作负载的兼容数据库服务。AlloyDB结合了最好的Google CloudPostgreSQL,以实现卓越的性能、规模和可用性。扩展您的数据库应用程序以利用构建 AI 驱动的体验AlloyDBLangchain 集成。

此笔记本介绍了如何使用Google Cloud AlloyDB for PostgreSQL要使用AlloyDBChatMessageHistory类。

GitHub 上了解有关该软件包的更多信息。

Open In Colab

准备工作

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

🦜🔗 库安装

集成存在于自己的langchain-google-alloydb-pg包中,因此我们需要安装它。

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

💡 API 支持

langchain-google-alloydb-pg软件包要求您在 Google Cloud 项目中启用 AlloyDB Admin API

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

AlloyDBEngine 连接池

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

要创建AlloyDBEngineAlloyDBEngine.from_instance()您只需提供 5 项内容:

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

默认情况下,将使用 IAM 数据库身份验证作为数据库身份验证的方法。此库使用属于源自环境的应用程序默认凭证 (ADC) 的 IAM 委托人。

或者,也可以使用使用用户名和密码访问 AlloyDB 数据库的内置数据库身份验证。只需提供可选的userpasswordarguments 设置为AlloyDBEngine.from_instance():

  • 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,
)

初始化表

AlloyDBChatMessageHistoryclass 需要一个具有特定架构的 Database Table 来存储聊天消息历史记录。

AlloyDBEngineengine 具有 helper 方法init_chat_history_table(),可用于创建具有适合您的架构的表。

engine.init_chat_history_table(table_name=TABLE_NAME)

AlloyDBChatMessage历史

要初始化AlloyDBChatMessageHistoryclass 你只需要提供 3 件事:

  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)