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

基于LangChain构建对话机器人:传递初始上下文与SystemMessage处理

在LangChain中用SystemMessage传递初始上下文实现对话机器人

LangChain完全支持通过SystemMessage传递初始上下文与指导,这也是针对支持聊天消息格式的大模型(如GPT系列)的推荐做法,相比纯文本Prompt模板,更贴合模型的原生对话设计逻辑。下面是具体的实现方案:

基础实现(带初始系统上下文)

直接通过ChatPromptTemplate组合系统消息、对话历史与用户输入,示例代码如下:

from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain

# 初始化大模型
llm = ChatOpenAI(temperature=0)

# 定义系统消息模板(初始上下文/指导)
system_template = """你是一个友好的AI助手,善于结合给定的上下文提供详细的回答。如果不知道问题的答案,请如实说明。"""
system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)

# 构建聊天提示模板,包含系统消息、对话历史、用户输入
chat_prompt = ChatPromptTemplate.from_messages([
    system_message_prompt,
    MessagesPlaceholder(variable_name="history"),  # 对话历史占位符
    HumanMessagePromptTemplate.from_template("{input}")  # 用户输入模板
])

# 初始化对话链,搭配记忆组件
conversation = ConversationChain(
    prompt=chat_prompt,
    llm=llm,
    verbose=True,
    memory=ConversationBufferMemory(return_messages=True)  # 需设置return_messages=True适配聊天消息格式
)

# 发起对话
response = conversation.predict(input="你好,介绍下你自己")
print(response)

对应原示例代码的改造版本

如果你要替换原示例中的纯文本PromptTemplate,只需把原模板里的系统提示部分提取为SystemMessage,其余对话历史和用户输入逻辑保留:

from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, MessagesPlaceholder, HumanMessagePromptTemplate
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain

llm = ChatOpenAI(temperature=0)

# 原示例中的系统提示转为SystemMessage
system_template = """The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know."""
system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)

chat_prompt = ChatPromptTemplate.from_messages([
    system_message_prompt,
    MessagesPlaceholder(variable_name="history"),
    HumanMessagePromptTemplate.from_template("{input}"),
])

# 记忆组件需设置ai_prefix并开启return_messages=True
conversation = ConversationChain(
    prompt=chat_prompt,
    llm=llm,
    verbose=True,
    memory=ConversationBufferMemory(ai_prefix="AI Assistant", return_messages=True)
)

# 测试对话
response = conversation.predict(input="Hi, how are you?")
print(response)

关键注意点

  • 使用聊天消息格式时,记忆组件必须设置return_messages=True,这样记忆会以消息对象形式存储,适配ChatPromptTemplate的要求。
  • SystemMessage优先级通常高于后续的用户/助手消息,能稳定为AI提供核心行为指导,适合定义机器人角色、回答规则等初始上下文。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 04:22:09