1、前言 解决langchain搭建的智能体多轮会话中的记忆连接不连贯的问题 2、记忆模块的种类(常见3种) 调用的包名:from langchain_classic.memory import xxx
名称 优缺点 使用函数 ConversationBufferMemory 保留完整的对话上下文,实现简单适合短对话,随着对话增长会占用大量token ConversationBufferMemory() ConversationBufferWindowMemory 只保留最近K次的会话,控制内存使用,会丢失早期的对话历史 ConversationBufferWindowMemory(k=2) ConversationSummaryBufferMemory 保留最近详细对话+早期摘要,实现相对复杂 ConversationSummaryBufferMemory(llm=llm,max_token_limit=1000)
3、对话链的两种包 from langchain_classic.chains.conversation.baseimport xxx名称 优缺点 调用方法 ConversationChain 适用于通用对话场景 ConversationChain(llm=llm, prompt=PromptTemplate.from_template(“xxxx”),verbose=True, memory=window_memory) RetrievalQAWithSourcesChain 适用于基于知识库问答,调包:from langchain_classic.chains import RetrievalQAWithSourcesChain RetrievalQAWithSourcesChain.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 对每个文档打分再选择
为上一节的电商推荐模块转变为对话链的方式 from langchain_classic. chainsimport LLMChainfrom langchain_classic. chains. conversation. baseimport ConversationChain 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) while True : user_input= input ( "\n💬 请输入你的需求:" ) . strip( ) print ( "***********************************************************" ) print ( "memory:" , window_memory) print ( "***********************************************************" ) if user_input. lower( ) in [ "退出" , "exit" , "quit" , "q" , "退下吧" ] : print ( "👋 再见!" ) break extract_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) 结果展示
第一次推荐的三种米 ”换一批“以后推荐另外三种大米