本文详解如何通过合理设计 chatprompttemplate 的消息类型(system/human)来确保 llm 同时完成文本重述和目标语言翻译,避免仅重述不翻译的常见错误。
本文详解如何通过合理设计 chatprompttemplate 的消息类型(system/human)来确保 llm 同时完成文本重述和目标语言翻译,避免仅重述不翻译的常见错误。
在 LangChain 中使用 ChatPromptTemplate 构建 prompt chain 时,消息角色(role)的语义至关重要。原始代码中将所有指令(包括语言要求)都放在 "system" 消息中,而用户输入仅作为 "user" 消息传入,这导致模型未被明确告知“需执行翻译任务”——系统消息虽设定了上下文,但缺乏对具体操作步骤的显式指令;而人类消息(即 "user")又只传递了原始文本,未包含任务定义,因此模型倾向于仅完成更易识别的重述动作,忽略翻译。
✅ 正确做法是:将角色定义与任务指令分离,并将核心操作逻辑置于 "human" 消息中:
以下是优化后的完整链构建示例:
from langchain_core.prompts import ChatPromptTemplatefrom langchain_core.output_parsers import StrOutputParser# ✅ 清晰的角色分工system_message = "You are a helpful assistant specializing in rephrasing and translating technical texts accurately and professionally."human_template = ( "Your task comprises two mandatory steps:n" "1. Rephrase the following text to improve clarity, conciseness, and tone—without changing its factual meaning: {input}.n" "2. Translate the rephrased version into {language}. Output only the final translated text—no explanations, no markup, no extra commentary.")chat_prompt = ChatPromptTemplate.from_messages([ ("system", system_message), ("human", human_template),])# 链式组装(假设 llm 已初始化)chain = chat_prompt | llm | StrOutputParser()# 调用时传入 input 和 language(注意:此处 language 应为自然语言名称,如 "Czech (CZ)",与前端选中的 value 一致)answer = chain.invoke({ "input": user_input, "language": selected_language # e.g., "Czech (CZ)"})
? 关键注意事项:
通过明确划分系统角色与用户指令,并将任务逻辑结构化嵌入 human 消息,即可稳定触发 LLM 的双重能力,让 prompt chain 真正按预期工作。