跳到主要内容
Open In ColabOpen on GitHub

Google Memorystore for Redis

Google Cloud Memorystore for Redis 是一项完全托管的服务,由 Redis 内存数据存储提供支持,用于构建应用程序缓存,从而提供亚毫秒级的数据访问。扩展您的数据库应用程序,利用 Memorystore for Redis 的 Langchain 集成构建 AI 驱动的体验。

本笔记本介绍了如何使用 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()

此页对您有帮助吗?