Google Bigtable
Google Cloud Bigtable 是一種鍵值和寬欄儲存服務,非常適合快速存取結構化、半結構化或非結構化資料。擴展您的資料庫應用程式,以建構利用 Bigtable 的 Langchain 整合的 AI 驅動體驗。
本筆記本說明如何使用 Google Cloud Bigtable 和 BigtableChatMessageHistory 類別來儲存聊天訊息歷史記錄。
在 GitHub 上了解更多關於此套件的資訊。
開始之前
要執行此筆記本,您需要執行以下操作
🦜🔗 程式庫安裝
此整合存在於其自己的 langchain-google-bigtable
套件中,因此我們需要安裝它。
%pip install -upgrade --quiet langchain-google-bigtable
僅限 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()
基本用法
初始化 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 件事
instance_id
- 用於聊天訊息歷史記錄的 Bigtable 實例。table_id
:用於儲存聊天訊息歷史記錄的 Bigtable 表格。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,
)