LangChain(3)对话缓存方式 Conversational Memory

LLM 默认是无状态的,即询问当前的问题与上下文无关,当我们需要将多轮对话信息给到LLM 时,就需要使用缓存Memory。缓存方式有多种。

python 复制代码
from langchain import OpenAI
from langchain.chains import ConversationChain

# first initialize the large language model
llm = OpenAI(
		temperature=0,
		openai_api_key="OPENAI_API_KEY",
		model_name="text-davinci-003" # 也可用gpt-3.5-turbo
		)

# now initialize the conversation chain 默认无缓存
conversation = ConversationChain(llm=llm)

# 方式1 ConversationBufferMemory: 会将之前所有对话都作为输入送到LLM中,受模型接受token数量的限制
from langchain.chains.conversation.memory import ConversationBufferMemory
conversation_buf = ConversationChain(
		llm=llm,
		memory=ConversationBufferMemory()
		)

# 方式2 ConversationSummaryMemory:将之前对话总结Summary后,加上新的询问query输入到LLM中
from langchain.chains.conversation.memory import ConversationSummaryMemory
conversation = ConversationChain(
		llm=llm,
		memory=ConversationSummaryMemory(llm=llm)
		)

# 方式3 ConversationBufferWindowMemory:将最近k轮对话,加上新的询问query输入到LLM中
from langchain.chains.conversation.memory import ConversationBufferWindowMemory
conversation = ConversationChain(
llm=llm,
memory=ConversationBufferWindowMemory(k=1)
)

# 方式4 ConversationSummaryBufferMemory:将很久之前的对话Summary,最近的对话保存全部送入LLM中
conversation_sum_bufw = ConversationChain(
llm=llm, memory=ConversationSummaryBufferMemory(
llm=llm,
max_token_limit=650
)

# 其它 Memory 类型
# ConversationKnowledgeGraphMemory
# ConversationEntityMemory
相关推荐
MAGICIAN...11 小时前
【Redis】--持久化机制
数据库·redis·缓存
我真的是大笨蛋11 小时前
JVM调优总结
java·jvm·数据库·redis·缓存·性能优化·系统架构
拾忆,想起17 小时前
Redis复制延迟全解析:从毫秒到秒级的优化实战指南
java·开发语言·数据库·redis·后端·缓存·性能优化
破烂儿21 小时前
基于机器学习的缓存准入策略研究
人工智能·机器学习·缓存
参.商.21 小时前
【Day21】146.LRU缓存 (Least Recently Used)
leetcode·缓存·golang
Dorcas_FE21 小时前
axios请求缓存与重复拦截:“相同请求未完成时,不发起新请求”
前端·spring·缓存
知其然亦知其所以然1 天前
三分钟接入!SpringAI 玩转 Perplexity 聊天模型实战
后端·spring·langchain
用户9125188677671 天前
LangChain集成Qwen大模型多种方式分享与最佳实践
langchain
玲小珑1 天前
LangChain.js 完全开发手册(六)Vector 向量化技术与语义搜索
前端·langchain·ai编程
码熔burning1 天前
Redis 的三种高效缓存读写策略!
redis·缓存·mybatis