Google Memorystore for Redis
Google Cloud Memorystore for Redis 是一个全托管服务,基于 Redis 内存数据存储,用于构建提供亚毫秒级数据访问的应用缓存。利用 Memorystore for Redis 的 Langchain 集成,扩展您的数据库应用以构建由 AI 驱动的体验。
本笔记本将介绍如何使用 MemorystoreChatMessageHistory 类,通过 Google Cloud Memorystore for Redis 来存储聊天消息历史记录。
在 GitHub 上了解有关该软件包的更多信息。
开始之前
要运行此 Notebook,您需要完成以下操作:
在确认此 Notebook 的运行时环境已访问数据库后,请在运行示例脚本之前填写以下值并运行单元格。
# @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,请查看此处的设置说明 here。
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()