Google Cloud Firestore(数据存储模式)
Google Cloud Firestore in Datastore 是一种无服务器、面向文档的数据库,可随需求扩展。通过利用
Datastore'sLangchain 集成,扩展您的数据库应用程序以构建由人工智能驱动的体验。
本笔记本介绍了如何使用Google Cloud Firestore in Datastore与DatastoreChatMessageHistory类一起存储聊天消息历史。
Learn more about the package on GitHub.
开始之前
要运行此笔记本,您需要执行以下操作:
在确认此笔记本的运行环境可以访问数据库后,请填写以下值并运行该单元格,然后再运行示例脚本。
🦜🔗 库安装
The integration lives in its own langchain-google-datastore package, so we need to install it.
%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云项目
设置您的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工作区,请参阅设置说明这里。
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 类时,您只需提供以下三点:
session_id- 一个唯一的标识符字符串,用于指定会话的ID。kind- 要写入的Datastore种类的名称。这是一个可选值,默认情况下将使用ChatHistory作为种类。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
清理
当特定会话的历史记录已过时,可以从数据库和内存中删除时,可以通过以下方式进行。
注意: 数据一旦删除,将不再存储在数据存储中,并且永远无法恢复。
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()