Skip to main content
Open on GitHub

Redis

Redis (Remote Dictionary Server) is an open-source in-memory storage, used as a distributed, in-memory key–value database, cache and message broker, with optional durability. Because it holds all data in memory and because of its design, Redis offers low-latency reads and writes, making it particularly suitable for use cases that require a cache. Redis is the most popular NoSQL database, and one of the most popular databases overall.

本页面介绍了如何在LangChain中使用Redis生态系统。 内容分为两部分:安装与设置,以及对特定Redis封装器的引用。

安装与设置

安装 Python SDK:

pip install redis

要在本地运行 Redis,可以使用 Docker:

docker run --name langchain-redis -d -p 6379:6379 redis redis-server --save 60 1 --loglevel warning

停止容器:

docker stop langchain-redis

并重新启动它:

docker start langchain-redis

连接

我们需要一个 Redis URL 连接字符串,以连接到数据库,支持独立的 Redis 服务器或者带有复制和 Redis 哨兵的高可用性设置。

Redis 独立连接 URL

对于独立的 Redis 服务器,可以使用官方的 Redis 连接 URL 格式,如 Python Redis 模块中 “from_url()” 方法所描述的那样:Redis.from_url

示例: redis_url = "redis://:secret-pass@localhost:6379/0"

Redis Sentinel 连接 url

对于 Redis 哨兵设置,连接方案为“redis+sentinel”。 这是对官方 IANA 注册协议方案的非官方扩展,只要没有可用的哨兵连接 URL。

示例: redis_url = "redis+sentinel://:secret-pass@sentinel-host:26379/mymaster/0"

格式为 redis+sentinel://[[username]:[password]]@[host-or-ip]:[port]/[service-name]/[db-number] 如果未明确设置,则默认值为“service-name = mymaster”和“db-number = 0”。 service-name 是 Sentinel 中配置的 Redis 服务器监控组名称。

当前的 URL 格式限制了连接字符串只能指定一个哨兵主机(无法提供列表),并且 Redis 服务器和哨兵必须设置相同的密码(如果使用的话)。

Redis 集群连接 url

目前,所有需要“redis_url”参数的方法都不支持Redis集群。 使用Redis集群的唯一方法是通过接受预配置Redis客户端的LangChain类,例如 RedisCache (示例如下)。

缓存

缓存包装器允许使用 Redis 作为远程、低延迟的内存缓存,用于存储大型语言模型的提示和响应。

标准缓存

标准缓存是Redis在生产环境中的经典用例,适用于全球范围内的开源用户和企业用户。

from langchain.cache import RedisCache
API 参考:RedisCache

要将此缓存与您的大语言模型一起使用:

from langchain.globals import set_llm_cache
import redis

redis_client = redis.Redis.from_url(...)
set_llm_cache(RedisCache(redis_client))
API 参考:set_llm_cache

语义缓存

语义缓存允许用户根据用户输入与之前缓存结果之间的语义相似性来检索缓存的提示。在底层,它将 Redis 同时用作缓存和向量存储。

from langchain.cache import RedisSemanticCache
API 参考:RedisSemanticCache

要将此缓存与您的大语言模型一起使用:

from langchain.globals import set_llm_cache
import redis

# use any embedding provider...
from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings

redis_url = "redis://localhost:6379"

set_llm_cache(RedisSemanticCache(
embedding=FakeEmbeddings(),
redis_url=redis_url
))
API 参考:set_llm_cache

VectorStore

向量存储包装器将 Redis 转变为低延迟的向量数据库,用于语义搜索或大型语言模型内容检索。

from langchain_community.vectorstores import Redis
API 参考:Redis

有关Redis向量存储包装器的更详细演练,请参见此笔记本

检索器

Redis 向量存储检索器包装器对向量存储类进行了泛化,以实现低延迟的文档检索。要创建检索器,只需在基础向量存储类上调用 .as_retriever()

存储

Redis可以用来持久化LLM对话。

向量存储检索器内存

有关 VectorStoreRetrieverMemory 包装器的更详细演练,请参阅 此笔记本

聊天消息历史记录存储

有关使用Redis缓存对话消息历史的详细示例,请参见此笔记本