Google Firestore (Datastore 模式)
Google Cloud Firestore (Datastore 模式) 是一种无服务器文档数据库,可根据任何需求进行扩展。利用
Datastore的 Langchain 集成来扩展您的数据库应用程序,构建由 AI 提供支持的体验。
本 Notebook 将介绍如何使用 DatastoreChatMessageHistory 类通过 Google Cloud Firestore (Datastore 模式) 来存储聊天消息记录。
在 GitHub 上了解有关该包的更多信息。
开始之前
要运行此笔记本,您需要执行以下操作:
在确认笔记本运行时环境中的数据库访问权限后,请填充以下值并运行单元格,然后再运行示例脚本。
🦜🔗 库安装
集成 reside 在我们自己的 langchain-google-datastore 包中,所以我们需要进行安装。
%pip install -upgrade --quiet langchain-google-datastore
仅限 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()
API 启用
langchain-google-datastore 包要求您在 Google Cloud 项目中启用 Datastore API。
# enable Datastore API
!gcloud services enable datastore.googleapis.com
基本用法
DatastoreChatMessageHistory
要初始化 DatastoreChatMessageHistory 类,您只需提供三项:
session_id- 一个唯一的标识符字符串,用于指定会话的 ID。kind- 要写入的 Datastore kind 的名称。这是一个可选值,默认将使用ChatHistory作为 kind。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
清理
当某个特定会话的历史记录已过时,可以从数据库和内存中删除时,可以按以下方式进行。
注意: 删除后,数据将不再存储在 Datastore 中,并且将永久丢失。
chat_history.clear()