You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改LangChain对话脚本,仅输出AI回复且保留对话记忆

问题描述

使用LangChain的ConversationChain和ConversationBufferMemory编写Python对话脚本时,当前输出会包含多轮完整对话内容,需修改脚本使其仅输出AI的单次回复,同时保持对话连贯性,让AI能保留对话记忆。

原脚本如下:

from langchain_community.llms import Bedrock
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory

llm = Bedrock(
    credentials_profile_name="default", 
    model_id="mistral.mixtral-8x7b-instruct-v0:1")

conversation = ConversationChain(
    llm=llm, 
    verbose=False, 
    memory=ConversationBufferMemory())

ai_response = conversation.predict(input="Hi there!")
ai_response
解决方案

核心是自定义ConversationChain的提示模板,约束模型仅返回当前AI回复内容,同时保留ConversationBufferMemory维护对话历史以保证连贯性。

修改后的脚本:

from langchain_community.llms import Bedrock
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
from langchain.prompts import PromptTemplate

# 自定义提示模板,明确要求模型仅输出当前AI回复
custom_prompt = PromptTemplate(
    input_variables=["history", "input"],
    template="""根据对话历史和当前用户输入,仅输出AI的回复内容,不要包含对话历史:

对话历史:{history}
当前用户输入:{input}
AI回复:"""
)

llm = Bedrock(
    credentials_profile_name="default", 
    model_id="mistral.mixtral-8x7b-instruct-v0:1")

conversation = ConversationChain(
    llm=llm, 
    verbose=False, 
    memory=ConversationBufferMemory(),
    prompt=custom_prompt  # 应用自定义提示模板
)

# 测试示例
ai_response = conversation.predict(input="你好!")
print(ai_response)
# 输出:你好!很高兴认识你。我是涉猎多个领域的AI,涵盖科学、历史、文学等,有什么想聊的或者想问的吗?

ai_response = conversation.predict(input="西班牙的首都是哪里?")
print(ai_response)
# 输出:西班牙的首都是马德里。

ai_response = conversation.predict(input="马德里最有名的街道是哪条?")
print(ai_response)
# 输出:马德里最有名的街道是格兰维亚大道。

ai_response = conversation.predict(input="马德里格兰维亚大道上最有名的建筑是什么?")
print(ai_response)
# 输出:马德里格兰维亚大道上最有名的建筑是大都会大厦。

ai_response = conversation.predict(input="我刚才问的是哪个国家的相关问题?")
print(ai_response)
# 输出:你刚才问的是西班牙的相关问题。
说明
  • 自定义提示模板明确限制了输出内容,避免默认模板返回完整对话历史的问题。
  • ConversationBufferMemory会自动存储对话过程,后续调用predict时,模型可基于历史内容生成连贯的上下文回复。

内容的提问来源于stack exchange,提问作者Leockl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 09:05:16