使用Google AlloyDB for PostgreSQL存储聊天消息历史

Google Cloud AlloyDB for PostgreSQL 是一种完全托管的 PostgreSQL 兼容数据库服务,专为满足企业级工作负载而设计。结合了 Google Cloud 的优势与 PostgreSQL 的强大功能,AlloyDB 提供卓越的性能、扩展性和可用性。借助 AlloyDB 和 Langchain 的集成,您可以将数据库应用扩展为构建 AI 驱动的体验。在本文中,我们将介绍如何使用 Google Cloud AlloyDB for PostgreSQL 存储聊天消息历史。

核心原理解析

为了实现这一目标,我们将使用 AlloyDBChatMessageHistory 类,它允许我们将消息历史存储在 AlloyDB 中。这个过程包括创建合适的数据库实例、启用 API、配置连接等步骤。

代码实现演示

准备工作

首先,确保你已经在 Google Cloud 上创建了项目,并启用了 AlloyDB API。

安装库

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

鉴权

使用 Colab 时,可以通过以下代码进行 Google Cloud 鉴权:

from google.colab import auth
auth.authenticate_user()

设置 Google Cloud 项目

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

启用 AlloyDB API

!gcloud services enable alloydb.googleapis.com

设置数据库参数

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

配置 AlloyDBEngine 连接池

from langchain_google_alloydb_pg import AlloyDBEngine

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

初始化消息存储表

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("what's up?")

print(history.messages)

清理数据

当某个会话的历史记录不再需要时,可以使用以下方法删除:

history.clear()

应用场景分析

通过这种方式,我们可以在数据库中高效而有组织地存储和检索聊天历史,使其能够适用于多个 AI 驱动的应用场景,如客户支持机器人、个人助手等。

实践建议

  1. 确保所有 API 和服务都已正确启用。
  2. 定期清理不再需要的会话数据以节省存储和成本。
  3. 使用 IAM 角色进行细粒度的权限管理,确保数据安全。

如果遇到问题欢迎在评论区交流。

—END—

你可能感兴趣的:(postgresql,数据库)