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
相关推荐
clz131452112 分钟前
RAG 文档切分实战:从语义分层到长度优化
langchain
l1t2 小时前
DeepSeek总结的PostgreSQL 中的 SQL 与 PL/pgSQL:计划缓存
sql·缓存·postgresql
寻道码路2 小时前
AI Agent 工程化开发实战(四):工具调用循环——解构 create_agent 背后的机制
人工智能·langchain·ai agent·工具调用·langgraph
染指11104 小时前
160.Agent-LangGraph-自定义主管架构智能体
人工智能·windows·microsoft·langchain·1024程序员节·agents
hongyangcao4 小时前
Cloudflare GLM-5.3 串号事故复盘:KV 缓存页记账错了一个字段,155 条回复答进了别人的会话
人工智能·缓存·ai
lambo mercy18 小时前
核心组件8——检索器(Retrievers)
langchain
MetaLite21 小时前
Spring 同一个类里调用 @CacheEvict,为什么缓存没清掉?
java·spring·缓存
hweiyu0021 小时前
Redis命令:SMOVE
redis·缓存
可乐ea21 小时前
Agent 隔离为什么失效:CPU 缓存成了跨机器信道
缓存·ai智能体·红队测试·沙箱安全·agent隔离·侧信道
小易老师AI实战1 天前
LangChain create_agent 与 LangGraph 底层原理及实战对比
langchain·agent·大模型应用开发·langgraph