Skip to main content
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 类来存储聊天消息历史。

Learn more about the package on 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"}

🦜🔗 库安装

The integration lives in its own langchain-google-memorystore-redis package, so we need to install it.

%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云项目

设置您的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工作区,请参阅设置说明这里
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()