跳到主要內容
Open In ColabOpen on GitHub

Google Firestore (原生模式)

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

本筆記本介紹如何使用 Google Cloud Firestore,透過 FirestoreChatMessageHistory 類別來儲存聊天訊息歷史記錄。

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

Open In Colab

開始之前

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

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

🦜🔗 函式庫安裝

此整合存在於其自身的 langchain-google-firestore 套件中,因此我們需要安裝它。

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

僅限 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,請查看此處的設定說明 here
from google.colab import auth

auth.authenticate_user()

基本用法

FirestoreChatMessageHistory

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

  1. session_id - 一個唯一的識別字串,用於指定會期的 ID。
  2. collection:Firestore 集合的單一 / 分隔路徑。
from langchain_google_firestore import FirestoreChatMessageHistory

chat_history = FirestoreChatMessageHistory(
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

清理

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

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

chat_history.clear()

自訂用戶端

用戶端預設是使用可用的環境變數建立的。可以將自訂用戶端傳遞至建構函式。

from google.auth import compute_engine
from google.cloud import firestore

client = firestore.Client(
project="project-custom",
database="non-default-database",
credentials=compute_engine.Credentials(),
)

history = FirestoreChatMessageHistory(
session_id="session-id", collection="History", client=client
)

history.add_user_message("New message")

history.messages

history.clear()

此頁面是否對您有幫助?