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
相关推荐
Maiko Star6 小时前
* LangChain 自定义中间件详解:Hook、装饰器、类与执行顺序
中间件·langchain
夏天拐跑了西瓜12 小时前
一文入门LangChain:从框架认知到构建你的第一个AI Agent
python·langchain·conda·agent
hweiyu0014 小时前
Redis命令:HMGET
redis·缓存
BD_Marathon20 小时前
LangSmith的介绍与基本使用
langchain
Alson_Code20 小时前
从0到1打造个人专属编程智能体
人工智能·langchain·ai编程
陕西企来客1 天前
豆包检索层 9 月迭代后信源陈旧的核心 —— 缓存策略的可用性优先转向
缓存
柒和远方1 天前
LangSmith RAG 量化评估:从"感觉还行"到"数据说话"
langchain·llm·测试
染指11101 天前
131.Agent-Agent设计模式-MAS多智能体系统(Multi-Agent-System)
人工智能·设计模式·langchain·agent·agents
三掌柜6661 天前
ArkWeb 手记 07|缓存和离线页怎么做
缓存·harmonyos
流浪0011 天前
大模型技术全景(十三):记忆管理 Memory
llm·memory·记忆