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

如何阻止LangChain对话AI自动延续人机对话及无效记忆存储?

解决LangChain ConversationChain自动生成无效对话的问题

问题描述

使用LangChain结合AzureOpenAI构建对话链时,调用conv('What is 5+5?')后,AI不仅返回问题答案,还自动生成后续的人机对话内容(如Human: How many states are in the USA?等),这些无效内容会被存入对话记忆,导致后续调用对话链时,AI会基于这些无效记忆做出响应。

原因分析

  1. 模型类型不匹配:代码中使用AzureOpenAI类调用gpt-35-turbo模型,但AzureOpenAI是针对文本补全模型设计的,而gpt-35-turbo属于聊天模型,补全模式下AI容易无限制延续文本生成。
  2. 默认Prompt无约束:ConversationChain的默认Prompt没有明确限制AI的输出范围,AI会基于对话语境自动延续生成后续对话。

解决方案

1. 使用适配聊天模型的类

将AzureOpenAI替换为AzureChatOpenAI,该类专门适配gpt-35-turbo这类聊天模型,能更好地处理对话场景,减少无意义的文本补全。

2. 自定义Prompt模板约束输出

通过自定义Prompt,明确要求AI仅回答当前问题,不得生成后续对话内容。

3. 可选:设置终止词(针对补全模型)

如果仍使用文本补全模型,可设置stop参数指定终止词,当AI生成到这些词时自动停止输出。

修改后的代码示例

import openai
from langchain.chat_models import AzureChatOpenAI
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
from langchain.prompts import PromptTemplate

# 配置Azure OpenAI参数
openai.api_type = "azure"
openai.api_version = "2023-07-01-preview"
openai.api_base = "你的API地址"
openai.api_key = "你的API密钥"

# 使用AzureChatOpenAI适配gpt-35-turbo聊天模型
llm = AzureChatOpenAI(
    azure_deployment="gpt-35-turbo_nofilter",
    temperature=0  # 降低随机性,确保输出更可控
)

# 自定义Prompt模板,明确约束AI输出
custom_prompt = PromptTemplate(
    input_variables=["history", "input"],
    template="""以下是人类与AI的对话历史:

{history}

人类:{input}
AI:请仅回答人类当前提出的问题,不要生成后续的对话内容。"""
)

# 初始化对话链,应用自定义Prompt和记忆组件
conv = ConversationChain(
    llm=llm,
    memory=ConversationBufferMemory(),
    prompt=custom_prompt
)

# 测试调用
response = conv("5+5等于多少?")["response"]
print(response)

针对补全模型的备选方案(不推荐)

如果必须使用AzureOpenAI类,可添加stop参数阻止AI生成后续对话:

from langchain.llms import AzureOpenAI

llm = AzureOpenAI(
    engine="gpt-35-turbo_nofilter",
    temperature=0,
    stop=["Human:"]  # 当AI生成"Human:"时停止输出
)

conv = ConversationChain(llm=llm, memory=ConversationBufferMemory())
response = conv("What is 5+5?")["response"]
print(response.strip())  # 去除可能的多余空白

效果验证

修改后调用对话链,AI只会返回当前问题的答案,不会生成后续的人机对话内容,对话记忆中仅存入有效的交互记录,避免无效内容占用记忆空间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 19:14:50