Google Spanner
Google Cloud Spanner 是一個高度可擴展的資料庫,它將無限的可擴展性與關聯式語意(例如二級索引、強一致性、結構描述和 SQL)結合在一個簡單的解決方案中,提供 99.999% 的可用性。
本筆記本將介紹如何使用 Spanner
和 SpannerChatMessageHistory
類別來儲存聊天訊息記錄。在 GitHub 上了解更多關於此套件的資訊。
開始之前
要執行此筆記本,您需要執行以下操作
🦜🔗 程式庫安裝
此整合位於其自身的 langchain-google-spanner
套件中,因此我們需要安裝它。
%pip install --upgrade --quiet langchain-google-spanner
僅限 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)
🔐 驗證
以登入此筆記本的 IAM 使用者身分驗證 Google Cloud,以便存取您的 Google Cloud 專案。
- 如果您使用 Colab 執行此筆記本,請使用以下儲存格並繼續。
- 如果您使用 Vertex AI Workbench,請查看 這裡 的設定說明。
from google.colab import auth
auth.authenticate_user()
☁ 設定您的 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}
💡 API 啟用
langchain-google-spanner
套件要求您在您的 Google Cloud 專案中啟用 Spanner API。
# enable Spanner API
!gcloud services enable spanner.googleapis.com
基本用法
設定 Spanner 資料庫值
在 Spanner 執行個體頁面中找到您的資料庫值。
# @title Set Your Values Here { display-mode: "form" }
INSTANCE = "my-instance" # @param {type: "string"}
DATABASE = "my-database" # @param {type: "string"}
TABLE_NAME = "message_store" # @param {type: "string"}
初始化表格
SpannerChatMessageHistory
類別需要具有特定結構描述的資料庫表格,才能儲存聊天訊息記錄。
輔助方法 init_chat_history_table()
可用於建立具有正確結構描述的表格。
from langchain_google_spanner import (
SpannerChatMessageHistory,
)
SpannerChatMessageHistory.init_chat_history_table(table_name=TABLE_NAME)
SpannerChatMessageHistory
要初始化 SpannerChatMessageHistory
類別,您只需要提供 3 件事
instance_id
- Spanner 執行個體的名稱database_id
- Spanner 資料庫的名稱session_id
- 一個唯一識別字串,用於指定會話的 ID。table_name
- 資料庫中用於儲存聊天訊息記錄的表格名稱。
message_history = SpannerChatMessageHistory(
instance_id=INSTANCE,
database_id=DATABASE,
table_name=TABLE_NAME,
session_id="user-session-id",
)
message_history.add_user_message("hi!")
message_history.add_ai_message("whats up?")
message_history.messages
自訂用戶端
預設建立的用戶端是預設用戶端。若要使用非預設用戶端,可以將自訂用戶端傳遞至建構函式。
from google.cloud import spanner
custom_client_message_history = SpannerChatMessageHistory(
instance_id="my-instance",
database_id="my-database",
client=spanner.Client(...),
)
清除
當特定會話的歷史記錄過時且可以刪除時,可以透過以下方式完成。注意:一旦刪除,資料將不再儲存在 Cloud Spanner 中,並且將永遠消失。
message_history = SpannerChatMessageHistory(
instance_id=INSTANCE,
database_id=DATABASE,
table_name=TABLE_NAME,
session_id="user-session-id",
)
message_history.clear()