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
相关推荐
AI大模型1 小时前
AI智能体开发框架LangChain & LangGraph快速入门实战(包含LangSmith)
程序员·langchain·llm
本就一无所有 何惧重新开始3 小时前
Redis技术应用
java·数据库·spring boot·redis·后端·缓存
阿巴~阿巴~5 小时前
Redis重大版本演进全解析:从2.6到7.0
服务器·数据库·redis·ubuntu·缓存·centos
ajsbxi6 小时前
【Redis】缓存读/写操作流程
redis·笔记·spring·缓存·bootstrap
DevYK8 小时前
企业级Agent开发教程(四) 基于 MongoDB 实现持久化记忆缓存
langchain·agent
洲覆9 小时前
基于 clangd 搭建 Redis 6.2 源码阅读与调试环境
开发语言·数据库·redis·缓存
凯子坚持 c9 小时前
Redis 事务深度解析:从基础到实践
数据库·redis·缓存
zym大哥大1 天前
C++客服端访问redis
数据库·redis·缓存
赖small强1 天前
Linux内存管理-缓存系统中的Major和Minor详解
linux·缓存·交换缓存机制·major fault·minor fault
啊森要自信1 天前
【GUI自动化测试】YAML 配置文件应用:从语法解析到 Python 读写
android·python·缓存·pytest·pip·dash