LangChain 的 Redis 缓存
本 Notebook 演示了如何使用 langchain-redis 包中的 RedisCache 和 RedisSemanticCache 类来为 LLM 响应实现缓存。
设置
首先,让我们安装所需的依赖项,并确保我们有一个正在运行的 Redis 实例。
%pip install -U langchain-core langchain-redis langchain-openai redis
请确保你已运行 Redis 服务器。你可以使用 Docker 启动一个:
docker run -d -p 6379:6379 redis:latest
或者根据你的操作系统说明安装并本地运行 Redis。
import os
# Use the environment variable if set, otherwise default to localhost
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379")
print(f"Connecting to Redis at: {REDIS_URL}")
Connecting to Redis at: redis://redis:6379
导入所需库
import time
from langchain.globals import set_llm_cache
from langchain.schema import Generation
from langchain_openai import OpenAI, OpenAIEmbeddings
from langchain_redis import RedisCache, RedisSemanticCache
API Reference:set_llm_cache | Generation | OpenAI | OpenAIEmbeddings | RedisCache | RedisSemanticCache
import langchain_core
import langchain_openai
import openai
import redis