适用于 Redis 的 Google Memorystore
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()
基本用法
MemorystoreChatMessage历史记录
要初始化MemorystoreMessageHistoryclass 中,你只需要提供 2 件事:
redis_client- 一个 Memorystore Redis 的实例。session_id- 每个聊天消息历史记录对象必须具有唯一的会话 ID。如果会话 ID 中已经存储了消息,则可以检索这些消息。
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()