LangChain Prompt 与大语言模型提示词编写指南
针对大语言模型应用效果不佳的问题,本文梳理了编写高质量 Prompt 的核心原则。结合 LangChain 框架,详细演示了如何通过 PromptTemplate 和 ChatPromptTemplate 快速生成结构化提示词,涵盖基础变量替换、多参数控制及系统/用户角色分离等实战操作,帮助开发者高效定制 AI 交互输入。
编写优质 Prompt 的核心原则
在使用大语言模型时,输出质量往往取决于输入的 Prompt 设计。优秀的提示词能大幅激发模型潜力。设计时应遵循以下原则:
- 具体且详尽:提供明确的任务指令与充足的背景信息,确保模型精准理解需求。
- 清晰且易答:语言表达需直白准确,避免抽象模糊或带有歧义的措辞。
- 提供上下文:补充问题所处的业务场景或背景,引导模型给出更具价值的回答。
- 设定明确目标:指明任务方向与预期格式,帮助模型聚焦输出关键信息。
- 便于扩展定制:预留变量接口,方便在不同业务场景中复用和调整。
利用 Prompt Template 自动化生成提示词
当多个场景下的提示词结构高度相似,仅部分细节存在差异时,使用模板(Template)能显著提升效率。在 LangChain 中,主要依靠 PromptTemplate 类来实现这一功能。
最便捷的方式是使用 from_template 静态方法。只需在字符串中用花括号包裹占位符,调用 format 方法传入对应值即可完成拼接:
from langchain import PromptTemplate
template = """\
假如你是一个金融公司的理财经理,请你分析一下{stock}这只股票。
"""
prompt = PromptTemplate.from_template(template)
print(prompt.format(stock="腾讯控股"))
此外,也可以直接实例化对象,通过 input_variables 声明变量名列表,配合 template 字符串定义模板内容。这种方式适合需要严格控制变量元数据的场景:
# 无参数模板
no_input_prompt = PromptTemplate(input_variables=[], template="这是一个无参数模板。")
print(no_input_prompt.format())
# 单参数模板
one_input_prompt = PromptTemplate(
input_variables=["stock"],
template="假如你是一个金融公司的理财经理,请你分析一下{stock}这只股票。"
)
print(one_input_prompt.format(stock="腾讯控股"))
# 多参数模板
multiple_input_prompt = PromptTemplate(
input_variables=["personA", "thingsB"],
template="请告诉我一个关于{personA}的{thingsB}"
)
print(multiple_input_prompt.format(personA="小张", thingsB="故事"))
适配 Chat 模式的专属 Prompt 结构
Chat 类模型的消息通常包含不同的角色属性(如 system 系统指令、human 用户提问、ai 助手回复)。为了精准控制各类角色的输入,LangChain 提供了专门的组合模板工具。
首先引入角色模板组件并初始化:
from langchain.prompts import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
PromptTemplate,
)
# 定义系统角色模板
system_template = "现在你的角色是{role},请按该角色进行后续的对话."
system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)
# 定义用户输入模板
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
随后将多个角色模板组合成完整的 ChatPromptTemplate,并通过 to_messages() 转换为 Chat 模型可直接接收的消息列表:
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
messages = chat_prompt.format_prompt(role="医生", text="帮我看看我的颜值还行吗?").to_messages()
print(messages)
总结
通过掌握结构化设计与模板化封装,开发者可以稳定、高效地为大语言模型注入高质量的输入信号。以上就是 LangChain Prompt 与大语言模型提示词编写指南的详细内容,更多关于 LangChain Prompt 模板配置的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









