Skip to main content
Open In ColabOpen on GitHub

Google Memorystore for Redis

Google Cloud Memorystore for Redis is a fully-managed service that is powered by the Redis in-memory data store to build application caches that provide sub-millisecond data access. Extend your database application to build AI-powered experiences leveraging Memorystore for Redis's Langchain integrations.

本笔记本介绍了如何使用 Google Cloud Memorystore for RedisMemorystoreChatMessageHistory 类一起存储聊天消息历史记录。

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 类,您只需提供以下两项内容:

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