Skip to main content
Open In Colab在 GitHub 上打开

Google Firestore(数据存储模式)

Datastore 中的 Google Cloud Firestore 是一个面向文档的无服务器数据库,可扩缩以满足任何需求。扩展您的数据库应用程序以利用构建 AI 驱动的体验Datastore'sLangchain 集成。

本笔记本介绍了如何在 Datastore 中使用 Google Cloud Firestore 来存储聊天消息历史记录,并将DatastoreChatMessageHistory类。

GitHub 上了解有关该软件包的更多信息。

Open In Colab

准备工作

要运行此笔记本,您需要执行以下作:

在此笔记本的运行时环境中确认对数据库的访问后,填写以下值并在运行示例脚本之前运行单元格。

🦜🔗 库安装

集成存在于自己的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

基本用法

DatastoreChatMessage历史记录

要初始化DatastoreChatMessageHistoryclass 你只需要提供 3 件事:

  1. session_id- 一个唯一标识符字符串,用于指定会话的 ID。
  2. kind- 要写入的 Datastore 类型的名称。这是一个可选值,默认情况下,它将使用ChatHistory作为种类。
  3. 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()

自定义客户端

默认情况下,客户端是使用可用的环境变量创建的。可以将自定义客户端传递给构造函数。

from google.auth import compute_engine
from google.cloud import datastore

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

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

history.add_user_message("New message")

history.messages

history.clear()