跳到主要內容
Open In ColabOpen on GitHub

Google Firestore (Datastore 模式)

Google Cloud Firestore Datastore 是一種無伺服器、面向文件的資料庫,可擴展以滿足任何需求。擴展您的資料庫應用程式,以利用 Datastore 的 Langchain 整合來建立 AI 驅動的體驗。

本筆記本說明如何使用 Google Cloud Firestore Datastore,透過 DatastoreChatMessageHistory 類別來儲存聊天訊息歷史記錄。

GitHub 上了解更多關於此套件的資訊。

Open In Colab

開始之前

若要執行此筆記本,您需要執行以下操作

在確認在此筆記本的執行階段環境中可以存取資料庫之後,填寫以下值並在執行範例腳本之前執行儲存格。

🦜🔗 程式庫安裝

此整合位於其自己的 langchain-google-datastore 套件中,因此我們需要安裝它。

%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 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()

API 啟用

langchain-google-datastore 套件要求您在您的 Google Cloud 專案中啟用 Datastore API

# enable Datastore API
!gcloud services enable datastore.googleapis.com

基本用法

DatastoreChatMessageHistory

若要初始化 DatastoreChatMessageHistory 類別,您只需要提供 3 件事

  1. session_id - 一個唯一的識別字串,用於指定工作階段的 ID。
  2. kind - 要寫入的 Datastore 類別名稱。這是一個可選值,預設情況下,它將使用 ChatHistory 作為類別。
  3. 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

清理

當特定工作階段的歷史記錄過時,並且可以從資料庫和記憶體中刪除時,可以透過以下方式完成。

注意: 一旦刪除,資料將不再儲存在 Datastore 中,並且永遠消失。

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()

此頁面是否有幫助?