利用 Google AlloyDB 和 LangChain 构建智能聊天记录系统

86 阅读3分钟

引言

在当今的云计算环境中,数据库的性能、扩展性和可用性越来越受到关注。Google Cloud AlloyDB for PostgreSQL 提供了一种完全托管的 PostgreSQL 兼容数据库服务,适合企业级工作负载。通过将 AlloyDB 与 LangChain 集成,我们可以创建一个高效的、支持 AI 的聊天记录系统。本篇文章将详细介绍如何使用 Google Cloud AlloyDB for PostgreSQL 存储聊天消息历史记录,并展示实际的代码示例。

主要内容

准备工作

在开始之前,请确保您已经完成以下步骤:

  1. 创建一个 Google Cloud 项目
  2. 启用 AlloyDB API
  3. 创建一个 AlloyDB 实例
  4. 创建一个 AlloyDB 数据库
  5. (可选)为数据库添加 IAM 用户

安装依赖库

为了使用 LangChain 与 AlloyDB 的集成,我们需要安装 langchain-google-alloydb-pg 包。

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

如果您在 Colab 中运行此笔记本,可以重新启动内核以使新安装的包生效。

# 在 Colab 中运行时,解除以下代码的注释以重新启动内核
# import IPython
# app = IPython.Application.instance()
# app.kernel.do_shutdown(True)

认证

在 Colab 中运行此笔记本时,需要进行 Google Cloud 认证。

from google.colab import auth
auth.authenticate_user()

设置项目

设置您的 Google Cloud 项目以便在笔记本中使用 Google Cloud 资源。

PROJECT_ID = "my-project-id"  # 替换为您的项目 ID
!gcloud config set project {PROJECT_ID}

启用 API

启用 AlloyDB 管理 API 以使用 langchain-google-alloydb-pg 包。

!gcloud services enable alloydb.googleapis.com

设置 AlloyDB 数据库参数

获取您的数据库参数,这些可以在 AlloyDB 集群页面找到。

REGION = "us-central1"
CLUSTER = "my-alloydb-cluster"
INSTANCE = "my-alloydb-instance"
DATABASE = "my-database"
TABLE_NAME = "message_store"

建立 AlloyDB Engine 连接池

创建 AlloyDBEngine 对象来配置连接池。这一步将使应用程序能够成功连接到 AlloyDB 数据库。

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)

创建聊天消息历史对象

初始化 AlloyDBChatMessageHistory 类来记录聊天消息。

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?")

print(history.messages)

清理

当不再需要特定会话的历史记录时,可以将其删除。请注意,一旦删除,数据将无法恢复。

history.clear()

聊天消息链

我们可以将聊天消息历史类与 LangChain 的 LCEL Runnables 结合使用。需要启用 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",
)

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)

常见问题和解决方案

问题:无法认证到 Google Cloud

解决方案:确保您已正确配置 Google Cloud 项目并启用了必要的 API。在 Colab 中,确保已经正确执行认证步骤。

问题:连接到 AlloyDB 数据库失败

解决方案:检查您的项目 ID、区域、群集、实例和数据库名称是否正确配置。

问题:无法启用 Vertex AI API

解决方案:确保您在项目中启用了 Vertex AI API,并具有相应的权限。

总结和进一步学习资源

本文介绍了如何使用 Google Cloud AlloyDB for PostgreSQL 存储聊天消息历史记录,并与 LangChain 集成。通过这种方式,您可以创建支持 AI 的高效聊天系统。欲了解更多信息,请参考以下资源:

参考资料

  1. Google Cloud AlloyDB 文档
  2. LangChain GitHub 仓库
  3. Vertex AI 文档

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---