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
相关推荐
xhuiting7 分钟前
Redis专题(二)
redis·缓存
小驴程序源24 分钟前
【OpenClaw 完整安装实施教程(Windows + Ollama 本地模型)】
gpt·langchain·aigc·embedding·ai编程·llama·gpu算力
Trouvaille ~27 分钟前
零基础入门 LangChain 与 LangGraph(三):环境搭建、包安装与第一个 LangChain 程序
python·ai·chatgpt·langchain·大模型·openai·langgraph
西西弗Sisyphus1 小时前
大模型运行的 enforce_eager 参数
langchain·prompt·transformer·vllm·enforce_eager
花千树-0102 小时前
Java 实现 ReAct Agent:工具调用与推理循环
java·spring boot·ai·chatgpt·langchain·aigc·ai编程
zlp19923 小时前
软考(系统架构师)-案例分析之Redis与缓存
redis·缓存·软考高级·软考·系统架构师
m0_747124533 小时前
LangChain 索引增强对话链详解
python·ai·langchain
小雨青年4 小时前
当缓存成为生产力:GitHub Actions 缓存机制的深度优化指南
缓存·github
山檐雾4 小时前
C#泛型缓存
缓存·c#
星夜泊客6 小时前
《Lua 模块化核心:require 的地址传递与缓存机制》
缓存·lua