使用Google Cloud SQL存储聊天历史:从设置到集成的全面指南
引言
在现代应用程序中,存储和处理聊天历史是一项重要功能。通过使用Google Cloud SQL与Langchain的集成,我们可以轻松实现这一功能,而无需担心底层数据库的复杂性。本文将指导您如何使用Google Cloud SQL来存储聊天消息历史,并涵盖从环境设置、API启用到实际编程的各个方面。
主要内容
准备工作
在开始之前,您需要:
- 创建一个Google Cloud项目。
- 启用Cloud SQL Admin API。
- 创建一个Cloud SQL for MySQL实例。
- 创建一个数据库。
- 可选:添加IAM数据库用户。
📦 安装库
首先安装需要的包:
%pip install --upgrade --quiet langchain-google-cloud-sql-mysql langchain-google-vertexai
注:如果使用Colab,请重新启动内核以确保环境更改生效。
🔐 认证
认证对Google Cloud的访问以便使用其服务:
from google.colab import auth
auth.authenticate_user()
☁ 设置Google Cloud项目
将项目ID配置为当前使用的项目:
PROJECT_ID = "my-project-id" # @请填入您的Google Cloud项目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-mysql-instance"
DATABASE = "my-database"
TABLE_NAME = "message_store"
创建一个MySQLEngine对象来配置连接池:
from langchain_google_cloud_sql_mysql import MySQLEngine
engine = MySQLEngine.from_instance(
project_id=PROJECT_ID, region=REGION, instance=INSTANCE, database=DATABASE
)
初始化表格
使用MySQLEngine的init_chat_history_table方法创建相应的表:
engine.init_chat_history_table(table_name=TABLE_NAME)
MySQLChatMessageHistory类
初始化并添加聊天消息:
from langchain_google_cloud_sql_mysql import MySQLChatMessageHistory
history = MySQLChatMessageHistory(
engine, session_id="test_session", table_name=TABLE_NAME
)
history.add_user_message("hi!") # 用户消息
history.add_ai_message("whats up?") # AI回复
print(history.messages)
清理
当某个会话的历史不再需要时,可以清除数据:
history.clear()
🔗 消息历史链与Vertex AI
启用Vertex AI API:
!gcloud services enable aiplatform.googleapis.com
结合LCEL模块进行高级操作:
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: MySQLChatMessageHistory(
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)
常见问题和解决方案
- 连接问题:如果连接到Cloud SQL实例时遇到困难,确保已启用必要的API,并使用IAM或内置认证正确配置连接。
- 数据丢失:若数据在清理操作后丢失,确认是否在生产中误操作清除历史。
总结和进一步学习资源
通过本文的步骤,您可以将Google Cloud SQL与Langchain集成,轻松实现聊天历史的存储和管理。推荐进一步阅读Google Cloud官方文档及Langchain文档,以掌握更多高级功能。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---