隆重推出我们的新合作伙伴包 langchain-redis,它将 Redis 的能力与 LangChain 生态系统集成。这项合作使开发者拥有构建快速 AI 应用所需的工具,特别是那些由检索增强生成 (RAG) 提供支持的应用。
LangChain 是一个开源框架,被超过 100 万开发者用于构建他们的生成式 AI 应用。 凭借其社区驱动的集成能力,LangChain 允许用户灵活选择他们的聊天模型提供商、向量存储、嵌入模型、检索器和其他工具。LangChain v0.2 引入了合作伙伴包,这些是与技术合作伙伴共同维护的集成。最新的一个,langchain-redis,为 LangChain 用户带来了 Redis 特性。
Redis 是 AI 应用的首选,特别是在实时 RAG 方面。原因如下:
我们的新软件包利用了 Redis 的优势,提供了三个核心特性:
RedisVectorStore 类利用 Redis 的向量相似性能力,实现:
为了使您的大语言模型交互更快速、更具成本效益,我们推出了两种缓存机制:
RedisChatMessageHistory 类提供了一种由 Redis 支持的方式来处理聊天历史:
LLM 记忆跨对话和会话跟踪上下文,从而实现:
以下是一些展示 langchain-redis 功能的实际示例:
首先,安装必要的软件包
pip install langchain-redis langchain-openai redis
设置您的 Redis 连接
import os
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379")
print(f"Connecting to Redis at: {REDIS_URL}")
让我们创建一个向量存储并填充一些示例数据
from langchain_redis import RedisVectorStore
from langchain_openai import OpenAIEmbeddings
from langchain.docstore.document import Document
# Initialize RedisVectorStore
embeddings = OpenAIEmbeddings()
vector_store = RedisVectorStore(embeddings, redis_url=REDIS_URL, index_name="my_docs")
# Add documents
docs = [
Document(page_content="Redis is a powerful in-memory data structure store", metadata={"source": "redis_intro"}),
Document(page_content="LangChain is a framework for developing applications powered by language models", metadata={"source": "langchain_intro"}),
]
vector_store.add_documents(docs)
# Perform a similarity search
query = "What is Redis?"
results = vector_store.similarity_search(query)
print(f"Search results for '{query}':")
for doc in results:
print(f"- {doc.page_content} (Source: {doc.metadata['source']})")
缓存是使 RAG 系统更快速、更便宜、更响应的关键。LangChain Redis 合作伙伴包提供了两种强大的缓存机制:RedisCache 和 RedisSemanticCache。
1. RedisCache: 一种基于键的传统缓存系统,用于 LLM 响应,存储查询与其对应的 LLM 输出之间的精确匹配。
优点:
2. RedisSemanticCache:智能的基于相似性的缓存,使用查询的语义含义来查找类似的先前请求,即使措辞不同。
优点:
让我们看看为您的 LLM 交互添加传统缓存有多么容易
from langchain_redis import RedisCache
from langchain_openai import OpenAI
from langchain.globals import set_llm_cache
import time
# Initialize RedisCache
redis_cache = RedisCache(redis_url=REDIS_URL)
set_llm_cache(redis_cache)
# Initialize the language model
llm = OpenAI(temperature=0)
# Function to measure execution time
def timed_completion(prompt):
start_time = time.time()
result = llm.invoke(prompt)
end_time = time.time()
return result, end_time - start_time
# First call (not cached)
prompt = "Explain the concept of caching in three sentences."
result1, time1 = timed_completion(prompt)
print(f"First call (not cached):\nResult: {result1}\nTime: {time1:.2f} seconds\n")
# Second call (should be cached)
result2, time2 = timed_completion(prompt)
print(f"Second call (cached):\nResult: {result2}\nTime: {time2:.2f} seconds\n")
print(f"Speed improvement: {time1 / time2:.2f}x faster")
以下是 RedisSemanticCache 如何智能地将 LLM 响应用于语义相似的查询:
from langchain_redis import RedisSemanticCache
from langchain_openai import OpenAIEmbeddings
# Initialize RedisSemanticCache
embeddings = OpenAIEmbeddings()
semantic_cache = RedisSemanticCache(redis_url=REDIS_URL, embeddings=embeddings, distance_threshold=0.2)
set_llm_cache(semantic_cache)
# Test semantic caching
original_prompt = "What is the capital of France?"
result1, time1 = timed_completion(original_prompt)
print(f"Original query:\nPrompt: {original_prompt}\nResult: {result1}\nTime: {time1:.2f} seconds\n")
similar_prompt = "Can you tell me the capital city of France?"
result2, time2 = timed_completion(similar_prompt)
print(f"Similar query:\nPrompt: {similar_prompt}\nResult: {result2}\nTime: {time2:.2f} seconds\n")
print(f"Speed improvement: {time1 / time2:.2f}x faster")
聊天历史对于维持上下文和使 AI 对话自然流畅至关重要,尤其是在 RAG 系统中。通过存储和引用过去的交互,RAG 系统可以提供感觉更连贯、更相关的响应。在此历史记录中搜索又增加了一层复杂性。
例如,如果用户提及先前讨论过的内容,系统可以快速检索对话的相关部分,并将其与新信息结合起来,给出更智能的答案。这使得对话流程更自然、更连续,并允许 RAG 系统在先前的交互基础上进行构建,就像人类一样。
让我们看看 RedisChatMessageHistory 如何发挥作用:
from langchain_redis import RedisChatMessageHistory
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
# Initialize RedisChatMessageHistory
message_history = RedisChatMessageHistory("user_123", redis_url=REDIS_URL)
# Create a conversational chain
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful AI assistant."),
MessagesPlaceholder(variable_name="history"),
("human", "{input}")
])
chain = prompt | llm
# Function to get or create a RedisChatMessageHistory instance
def get_redis_history(session_id: str):
return RedisChatMessageHistory(session_id, redis_url=REDIS_URL)
# Create a runnable with message history
chain_with_history = RunnableWithMessageHistory(
chain,
get_redis_history,
input_messages_key="input",
history_messages_key="history"
)
# Use the chain in a conversation
response1 = chain_with_history.invoke(
{"input": "Hi, my name is Alice."},
config={"configurable": {"session_id": "alice_123"}}
)
print("AI Response 1:", response1.content)
response2 = chain_with_history.invoke(
{"input": "What's my name?"},
config={"configurable": {"session_id": "alice_123"}}
)
print("AI Response 2:", response2.content)
langchain-redis 合作伙伴包是 Redis 使命中的一大飞跃,旨在为开发者提供构建强大 AI 应用所需的工具。凭借 Redis 的速度、灵活性和可扩展性,我们正在简化创建能够轻松处理复杂、实时交互的 AI 应用的过程。
使用 langchain-redis,您可以获得:
我们刚刚开始这项集成,迫不及待地想看到它的未来发展。 从更智能的缓存到先进的向量搜索算法,LangChain 和 Redis 的结合已准备好突破 AI 的界限。
探索这个新软件包,实验其功能,并向我们发送您的反馈。您的见解和用例将塑造这项集成的未来,确保它满足 AI 开发社区不断变化的需求。
请访问 https://github.com/langchain-ai/langchain-redis 上的 langchain-redis 软件包仓库,以及 https://pypi.ac.cn/project/langchain-redis/ 上的 PyPi 预打包库。
敬请关注,持续编码。让我们利用 Redis 和 LangChain 更快速地构建快速 AI 应用。