【langchain——对话链+记忆模块】通过代码构造可多轮会话,自动调整记忆长度的基于知识库检索的购物推荐智能体搭建
2026/7/22 4:12:46 网站建设 项目流程

1、前言

  • 解决langchain搭建的智能体多轮会话中的记忆连接不连贯的问题

2、记忆模块的种类(常见3种)

调用的包名:from langchain_classic.memory import xxx

名称优缺点使用函数
ConversationBufferMemory保留完整的对话上下文,实现简单适合短对话,随着对话增长会占用大量tokenConversationBufferMemory()
ConversationBufferWindowMemory只保留最近K次的会话,控制内存使用,会丢失早期的对话历史ConversationBufferWindowMemory(k=2)
ConversationSummaryBufferMemory保留最近详细对话+早期摘要,实现相对复杂ConversationSummaryBufferMemory(llm=llm,max_token_limit=1000)

3、对话链的两种包

from langchain_classic.chains.conversation.baseimportxxx
名称优缺点调用方法
ConversationChain适用于通用对话场景ConversationChain(llm=llm, prompt=PromptTemplate.from_template(“xxxx”),verbose=True, memory=window_memory)
RetrievalQAWithSourcesChain适用于基于知识库问答,调包:from langchain_classic.chains import RetrievalQAWithSourcesChainRetrievalQAWithSourcesChain.from_chain_type(llm=llm,chain_type=“stuff”, retriever=retriever,memory=memory, return_source_documents=True)
补充:

RetrievalQAWithSourcesChain下的chain_type有四种类型,如下表格:

chain_type类型具体作用
stuff将所有文档内容放入上下文
map_reduce先单独处理每个文档,再汇总
refine迭代式优化答案
map_rerank对每个文档打分再选择

为上一节的电商推荐模块转变为对话链的方式

fromlangchain_classic.chainsimportLLMChainfromlangchain_classic.chains.conversation.baseimportConversationChain window_memory=ConversationBufferWindowMemory(k=5)extract_product_name=ConversationChain(llm=llm,prompt=PromptTemplate.from_template("你是一个专业提取用户需求的助手,能够提取用户input中的最新需求并结合历史聊天记录chat_history里面想要的商品名称。例如:我想买花露水 -> 花露水,如果用户指定品牌或者价格,请注明品牌名称(老白健康也是牌子)。例如:(历史说想买牛奶)我想买蒙牛的。-> 牛奶(蒙牛)。直接输出最终商品名称即可,严禁多于废话。input为{input}, 历史为{history}"),verbose=True,memory=window_memory)introduct_products=ConversationChain(llm=llm,prompt=PromptTemplate.from_template("请结合用户需求,和在知识库中检索出来的商品列表,挑选最符合的商品推荐给用户,输出格式为:"\"为您推荐xx个商品,第一款为xxx,该商品xxxx,第二款为xxx,该商品xxxx。卖点根据商品名称自己联网进行补充推荐给用户。注意:当用户说换一批需要避开历史中推荐过的商品,需要推荐满足历史中用户想买的商品且不同品牌的进行推荐,例如:历史用户说牛奶,那必须现在推荐牛奶相关的商品。商品列表为{input}, 历史:{history}"),verbose=True,memory=window_memory)whileTrue:user_input=input("\n💬 请输入你的需求:").strip()print("***********************************************************")print("memory:",window_memory)print("***********************************************************")ifuser_input.lower()in["退出","exit","quit","q","退下吧"]:print("👋 再见!")breakextract_result=extract_product_name.predict(input=user_input)print("extract_result:",extract_result)products_list=Weight_hunhe_search(extract_result,vector_weight=0.7,bm25_weight=0.3,k=10)answer=introduct_products.predict(input=f'{products_list}')#.invoke({"input":f'{user_input}',"product_list":f'{products_list}', "history":f"{window_memory}"})['text']print("answer:",answer)

结果展示

第一次推荐的三种米”换一批“以后推荐另外三种大米

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询