跳到主要內容
Open In ColabOpen on GitHub

Google Memorystore for Redis

Google Cloud Memorystore for Redis 是一項全受管服務,由 Redis 記憶體內資料儲存區提供支援,可建構應用程式快取,以提供次毫秒級的資料存取。擴展您的資料庫應用程式,以建構由 AI 驅動的體驗,並利用 Memorystore for Redis 的 Langchain 整合功能。

本筆記本說明如何使用 Google Cloud Memorystore for Redis,透過 MemorystoreChatMessageHistory 類別儲存聊天訊息歷史記錄。

GitHub 上深入瞭解套件。

Open In Colab

開始之前

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

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

# @markdown Please specify an endpoint associated with the instance or demo purpose.
ENDPOINT = "redis://127.0.0.1:6379" # @param {type:"string"}

🦜🔗 程式庫安裝

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

%pip install -upgrade --quiet langchain-google-memorystore-redis

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

基本用法

MemorystoreChatMessageHistory

若要初始化 MemorystoreMessageHistory 類別,您只需要提供 2 件事

  1. redis_client - Memorystore Redis 的執行個體。
  2. session_id - 每個聊天訊息歷史記錄物件都必須具有唯一的會話 ID。如果會話 ID 已在 Redis 中儲存訊息,則可以擷取這些訊息。
import redis
from langchain_google_memorystore_redis import MemorystoreChatMessageHistory

# Connect to a Memorystore for Redis instance
redis_client = redis.from_url("redis://127.0.0.1:6379")

message_history = MemorystoreChatMessageHistory(redis_client, session_id="session1")
message_history.messages

清除

當特定會話的歷史記錄過時且可以刪除時,可以透過以下方式完成。

注意: 刪除後,資料將不再儲存在 Memorystore for Redis 中,且會永久消失。

message_history.clear()

此頁面是否實用?