Skip to main content
Open on GitHub

Redis

Redis (Remote Dictionary Server) 是一个开源的内存存储系统, 用作分布式、基于内存的键值数据库、缓存和消息代理,可选地提供持久性。 由于它将所有数据保存在内存中,并且因为其设计原因,Redis 提供了低延迟的读写操作, 使其特别适用于需要缓存的应用场景。Redis 是最受欢迎的 NoSQL 数据库之一,也是最流行的整体数据库之一。

此页面介绍了如何在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"。 这是一项非官方扩展,只要没有为哨兵提供的连接URL,就属于对正式IANA注册协议方案的扩展。

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

The format is redis+sentinel://[[username]:[password]]@[host-or-ip]:[port]/[service-name]/[db-number] with the default values of "service-name = mymaster" and "db-number = 0" if not set explicit. The service-name is the redis server monitoring group name as configured within the Sentinel.

The current url format limits the connection string to one sentinel host only (no list can be given) and both Redis server and sentinel must have the same password set (if used).

Redis Cluster连接URL

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

缓存在

Cache wrapper 允许使用 Redis 作为远程、低延迟的内存缓存,用于存储LLM提示和响应。

标准缓存

The standard cache is the Redis 茶余饭后之谈,在全球的 开源 和 企业 用户中,都是生产环境中用例的标准配置。

from langchain.cache import RedisCache
API 参考:RedisCache

要使用此缓存与您的 LLM:

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

要使用此缓存与您的 LLM:

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

向量存储

矢量存储包装器将Redis转换为用于语义搜索或LLM内容检索的低延迟向量数据库。

from langchain_community.vectorstores import Redis
API 参考:Redis

要详细了解Redis向量存储封装的详细走查,请参见这个笔记本

检索器

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

内存

Redis 可以用于持久化大语言模型(LLM)对话。

Vector Store Retriever Memory

对于VectorStoreRetrieverMemory包装器的更详细 walkthrough,请参见此笔记本

聊天消息历史记录记忆

对于缓存对话消息历史的详细示例,请参见此笔记本