
本文详解 langchain 中 chatprompttemplate 的消息类型分工,指出因混淆 system 与 human 消息导致翻译指令失效的问题,并提供结构清晰、可直接运行的 prompt 链优化方案。
本文详解 langchain 中 chatprompttemplate 的消息类型分工,指出因混淆 system 与 human 消息导致翻译指令失效的问题,并提供结构清晰、可直接运行的 prompt 链优化方案。
在使用 LangChain 构建 prompt chain 实现「文本重写 + 多语言翻译」时,一个常见却隐蔽的错误是:将任务指令(如“请重写并翻译成某语言”)错误地放在 system 消息中,而非 human 消息里。这会导致大语言模型无法将其识别为当前请求的具体操作目标——因为 system 消息仅用于设定角色与通用行为准则,而实际的输入内容和明确指令必须通过 human 消息传递。
✅ 正确的消息角色划分
| 消息类型 | 作用 | 示例 |
|---|---|---|
| system | 定义模型角色、能力边界与基础原则(不随每次调用变化) | "你是一位擅长文本重写与多语言翻译的专业助手。" |
| human | 传递本次请求的原始输入、具体任务要求及动态参数(如目标语言) | "请先重写以下文本,再将其翻译为捷克语:{input}" |
| ai | (本场景中无需显式定义)模型历史响应,用于对话上下文 |
原代码中,("system", "The rephrased car audit report should be in the following language: {language}.") 这类指令被置于 system 角色下,模型通常会忽略其作为本次执行指令的优先级,从而只完成重写,跳过翻译。
✅ 优化后的完整链构建示例
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
# ✅ 正确:system 消息仅定义角色
system_message = "You are a helpful assistant specializing in rephrasing and translating technical documents accurately."
# ✅ 正确:human 模板包含完整、明确的两步指令 + 占位符
human_template = """Your task has two mandatory steps:
1. Rephrase the following text to improve clarity, grammar, and professional tone, while preserving all factual content and technical meaning:
{input}
2. Translate the rephrased version into {language}. Output only the final translated text — no explanations, no markup, no extra formatting."""
chat_prompt = ChatPromptTemplate.from_messages([
("system", system_message),
("human", human_template)
])
# 绑定 LLM 与输出解析器
chain = chat_prompt | llm | StrOutputParser()
# 调用示例(与 Streamlit 集成逻辑一致)
answer = chain.invoke({
"input": "The car failed the brake test due to worn pads and insufficient fluid level.",
"language": "Czech (CZ)"
})
⚠️ 关键注意事项
- 避免在 system 中嵌入动态指令:{language} 等变量应仅出现在 human 消息模板中,否则 LangChain 可能无法正确渲染,或模型无法感知其为本次任务约束。
- 指令需具象、分步、无歧义:使用编号步骤(如“1. … 2. …”)显著提升模型遵循率;强调“仅输出结果”可减少冗余响应。
- 验证 prompt 渲染结果:调试时可通过 chat_prompt.invoke({"input": "...", "language": "..."}) 打印最终组装的 prompt,确认指令是否按预期呈现。
- **语言标识建议统一用 ISO 639-1 代码(如 "cs")或标准名称(如 "Czech"),避免括号附加信息(如 "Czech (CZ)")干扰模型理解——可在前端展示时映射,但传给模型时应精简。
通过明确区分消息语义、将任务逻辑置于 human 层,并辅以结构化指令表述,即可稳定实现「重写+翻译」双目标 prompt chain,大幅提升 LangChain 应用的可靠性与可控性。











