跳到主要内容
Open In ColabOpen on GitHub

Google Bigtable

Google Cloud Bigtable 是一种键值和宽列存储,非常适合快速访问结构化、半结构化或非结构化数据。扩展您的数据库应用程序,利用 Bigtable 的 Langchain 集成构建 AI 驱动的体验。

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

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

Open In Colab

开始之前

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

🦜🔗 库安装

该集成位于其自己的 langchain-google-bigtable 包中,因此我们需要安装它。

%pip install -upgrade --quiet langchain-google-bigtable

Colab only: 取消注释以下单元格以重启内核,或使用按钮重启内核。对于 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()

基本用法

初始化 Bigtable 模式

BigtableChatMessageHistory 的模式要求实例和表存在,并具有一个名为 langchain 的列族。

# @markdown Please specify an instance and a table for demo purpose.
INSTANCE_ID = "my_instance" # @param {type:"string"}
TABLE_ID = "my_table" # @param {type:"string"}

如果表或列族不存在,您可以使用以下函数创建它们

from google.cloud import bigtable
from langchain_google_bigtable import create_chat_history_table

create_chat_history_table(
instance_id=INSTANCE_ID,
table_id=TABLE_ID,
)

BigtableChatMessageHistory

要初始化 BigtableChatMessageHistory 类,您只需要提供 3 件事

  1. instance_id - 用于聊天消息历史记录的 Bigtable 实例。
  2. table_id : 用于存储聊天消息历史记录的 Bigtable 表。
  3. session_id - 一个唯一的标识符字符串,用于指定会话的 ID。
from langchain_google_bigtable import BigtableChatMessageHistory

message_history = BigtableChatMessageHistory(
instance_id=INSTANCE_ID,
table_id=TABLE_ID,
session_id="user-session-id",
)

message_history.add_user_message("hi!")
message_history.add_ai_message("whats up?")
message_history.messages

清理

当特定会话的历史记录过时且可以删除时,可以按以下方式完成。

注意: 删除后,数据将不再存储在 Bigtable 中,并且永远消失。

message_history.clear()

高级用法

自定义客户端

默认创建的客户端是默认客户端,仅使用 admin=True 选项。要使用非默认客户端,可以将自定义客户端传递给构造函数。

from google.cloud import bigtable

client = (bigtable.Client(...),)

create_chat_history_table(
instance_id="my-instance",
table_id="my-table",
client=client,
)

custom_client_message_history = BigtableChatMessageHistory(
instance_id="my-instance",
table_id="my-table",
client=client,
)

此页对您有帮助吗?