谷歌 Memorystore for Redis
Google Cloud Memorystore for Redis 是一项完全托管的服务,由 Redis 内存数据存储提供支持,用于构建提供亚毫秒级数据访问的应用程序缓存。利用 Memorystore for Redis 的 Langchain 集成,扩展您的数据库应用程序以构建 AI 驱动的体验。
本笔记本详细介绍了如何使用 Google Cloud Memorystore for Redis 通过 MemorystoreChatMessageHistory
类存储聊天消息历史记录。
在 GitHub 上了解有关该包的更多信息。
开始之前
要运行此笔记本,您需要执行以下操作:
在确认此笔记本的运行时环境可以访问数据库后,填写以下值并运行单元格,然后再运行示例脚本。
# @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
类,您只需提供两项内容:
redis_client
- 一个 Memorystore Redis 实例。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()