Skip to main content

Redis(Redis)

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

安装和设置(Installation and Setup)

  • 使用pip install redis安装Redis Python SDK。

包装器(Wrappers)

所有需要Redis URL连接字符串来连接数据库的包装器都支持独立的Redis服务器或具有复制和Redis Sentinel的高可用性设置。

Redis独立连接URL(Redis Standalone connection url)

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

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

Redis Sentinel连接URL(Redis Sentinel connection url)

对于Redis Sentinel设置,连接方案是“redis+sentinel”。这是官方IANA注册的协议方案的非官方扩展,只要没有可用的Sentinels连接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格式限制了连接字符串只能有一个Sentinel主机(不能给出列表),并且Redis服务器和Sentinel必须设置相同的密码(如果使用)。

Redis集群连接URL(Redis Cluster connection url)

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

缓存(Cache)

缓存包装器允许将Redis用作远程、低延迟的内存缓存,用于LLM提示和响应。

标准缓存(Standard Cache)

标准缓存是Redis在生产环境中用例的基础,适用于全球的开源企业用户。

导入此缓存:

from langchain.cache import RedisCache

使用此缓存与您的LLMs:

import langchain
import redis

redis_client = redis.Redis.from_url(...)
langchain.llm_cache = RedisCache(redis_client)

语义缓存(Semantic Cache)

语义缓存允许用户根据用户输入和先前缓存结果之间的语义相似性检索缓存的提示。在底层,它将Redis作为缓存和向量存储器混合使用。

导入此缓存:

from langchain.cache import RedisSemanticCache

使用此缓存与您的LLMs:

import langchain
import redis

# 使用任何嵌入提供程序...
from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings

redis_url = "redis://localhost:6379"

langchain.llm_cache = RedisSemanticCache(
embedding=FakeEmbeddings(),
redis_url=redis_url
)

向量存储器(VectorStore)

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

导入此向量存储器:

from langchain.vectorstores import Redis

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

检索器(Retriever)

Redis向量存储器检索器包装器将向量存储器类泛化为执行低延迟文档检索的类。只需在基本向量存储器类上调用.as_retriever()即可创建检索器。

内存(Memory)

Redis可用于持久化LLM对话。

向量存储器内存(Vector Store Retriever Memory)

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

聊天消息历史内存(Chat Message History Memory)

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