谷歌 Firestore(原生模式)
Google Cloud Firestore 是一个可扩展以满足任何需求的无服务器文档型数据库。通过利用
Firestore's
的 Langchain 集成,扩展您的数据库应用程序以构建 AI 驱动的体验。
本手册介绍了如何使用 Google Cloud Firestore 通过 FirestoreChatMessageHistory
类存储聊天消息历史。
在 GitHub 上了解有关该包的更多信息。
开始之前
要运行此笔记本,您需要执行以下操作:
在确认此笔记本的运行时环境可以访问数据库后,填写以下值并运行单元格,然后再运行示例脚本。
🦜🔗 库安装
该集成位于其独立的 langchain-google-firestore
包中,因此我们需要安装它。
%pip install --upgrade --quiet langchain-google-firestore
仅限 Colab:取消注释以下单元格以重新启动内核,或使用按钮重新启动内核。对于 Vertex AI Workbench,您可以使用顶部的按钮重新启动终端。
# # Automatically restart kernel after installs so that your environment can access the new packages
# import IPython
# app = IPython.Application.instance()
# app.kernel.do_shutdown(True)
☁ 设置您的 Google Cloud 项目
设置您的 Google Cloud 项目,以便您可以在此笔记本中利用 Google Cloud 资源。
如果您不知道您的项目 ID,请尝试以下操作:
- 运行
gcloud config list
。 - 运行
gcloud projects list
。 - 请参阅支持页面:查找项目 ID。
# @markdown Please fill in the value below with your Google Cloud project ID and then run the cell.
PROJECT_ID = "my-project-id" # @param {type:"string"}
# Set the project id
!gcloud config set project {PROJECT_ID}
🔐 认证
以登录此笔记本的 IAM 用户身份向 Google Cloud 进行认证,以便访问您的 Google Cloud 项目。
- 如果您正在使用 Colab 运行此笔记本,请使用下面的单元格并继续。
- 如果您正在使用 Vertex AI Workbench,请查看此处的设置说明。
from google.colab import auth
auth.authenticate_user()
基本用法
FirestoreChatMessageHistory
要初始化 FirestoreChatMessageHistory
类,您只需提供 3 项信息
session_id
- 用于指定会话 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
清理
当特定会话的历史记录已过时并可以从数据库和内存中删除时,可以通过以下方式完成。
注意:一旦删除,数据将不再存储在 Firestore 中,并且永远丢失。
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()