Skip to main content
Open In ColabOpen on GitHub

Google Firestore (原生模式)

Google Cloud Firestore 是一款无服务器的文档型数据库,可根据任何需求进行扩展。通过利用 Firestore 的 Langchain 集成,来扩展您的数据库应用,构建由人工智能驱动的体验。

本笔记本将介绍如何使用 FirestoreChatMessageHistory 类来使用 Google Cloud Firestore 存储聊天消息历史记录。

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

在 Colab 中打开

开始之前

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

在笔记本的运行时环境确认对数据库的访问权限后,请填充以下值并运行单元格,然后再运行示例脚本。

🦜🔗 库安装

集成位于独立的 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 个内容:

  1. session_id - 一个唯一的标识符字符串,用于指定会话的 ID。
  2. 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()