
内容纲要提示词模板核心概念PromptTemplate面向纯文本 LLM 的字符串模板ChatPromptTemplate面向对话模型的结构化模板MessagesPlaceholder在消息列表中动态插入内容的占位符使用SystemMessage、HumanMessage、AIMessage灵活组合模板自定义模板继承StringPromptTemplate实现特殊逻辑关键流程定义模板 → 声明变量 → 格式化format/format_messages→ 提交给 LLM涉及组件langchain_core.prompts、langchain_core.messages代码演示完整可运行的 Python 脚本涵盖所有模板类型引言在构建 AI Agent 或大语言模型应用时提示词Prompt是连接业务逻辑与模型能力的桥梁。LangChain 提供了一套丰富的提示词模板系统使开发者可以像写配置一样管理复杂的提示词结构而无需手动拼接字符串。本文将系统讲解五种最常用的提示词模板字符串模板、对话模板、消息占位符、Message 组合模板以及自定义模板并提供可直接运行的代码示例。一、字符串模板PromptTemplate字符串模板是最基础的提示词模板适用于传统的文本补全模型LLM它接收一个包含占位符的字符串通过format方法将参数注入最终生成一段完整的文本提示。核心特点输入输出均为纯文本不支持结构化消息。fromlangchain_core.promptsimportPromptTemplate# 定义模板花括号内为变量template你是一个{role}帮我起一个具有{country}特色的{gender}名字。promptPromptTemplate.from_template(template)# 传入参数格式化formattedprompt.format(role算命大师,country法国,gender女孩)print(formatted)输出你是一个算命大师帮我起一个具有法国特色的女孩名字。使用时需注意模板中声明的变量数量必须与format传入的参数完全一致否则会抛出异常。二、对话模板ChatPromptTemplate对话模板是当前应用最广泛的形式专为对话类模型Chat Model设计。它返回的是一个结构化的消息列表每条消息都带有明确的角色system、human、ai便于下游处理。fromlangchain_core.promptsimportChatPromptTemplate# 使用 from_messages 构建消息列表templateChatPromptTemplate.from_messages([(system,你是一个起名大师你的名字叫{name}。),(human,你好感觉如何),(ai,你好我状态非常好。),(human,你叫什么名字),(ai,你好我叫{name}。),(human,{user_input}),])# 注意对话模板使用 format_messages 而非 formatmessagestemplate.format_messages(name陈大师,user_input你的爸爸是谁呢)print(messages)输出将是一个包含SystemMessage、HumanMessage、AIMessage的列表每条消息都带有content字段并保留了元数据非常适合在应用中进行结构化解析和后续调用。三、消息占位符MessagesPlaceholder当需要在消息列表的特定位置动态插入一组消息例如历史聊天记录但又不确定其具体数量或类型时可以使用MessagesPlaceholder。它相当于一个“插槽”在最终调用模型前可以被替换为实际的消息列表。fromlangchain_core.promptsimportChatPromptTemplate,MessagesPlaceholderfromlangchain_core.messagesimportHumanMessage# 构造带占位符的模板promptChatPromptTemplate.from_messages([(system,你是一个厉害的人工智能助手。),MessagesPlaceholder(variable_namehistory),(human,{question})])# 在调用阶段动态传入消息列表resultprompt.invoke({history:[HumanMessage(content你好请多关照)],question:今天天气如何})print(result.messages)此外也可以直接用(placeholder, {history})这种简写方式效果等价。占位符的灵活性在于它允许在invoke阶段而不一定在format阶段再确定插入的内容这对构建复杂 Agent 的多轮对话记忆非常实用。四、使用 Message 直接组合模板除了通过ChatPromptTemplate.from_messages声明式构建还可以直接用SystemMessage、HumanMessage、AIMessage等消息对象手动拼装形成消息列表。这种方式更灵活适合将公共的系统消息或用户消息进行复用组合。fromlangchain_core.messagesimportSystemMessage,HumanMessage,AIMessagefromlangchain_core.promptsimportChatPromptTemplate# 手动构建消息system_msgSystemMessage(content你是一个起名大师,additional_kwargs{大师名字:陈瞎子})human_msgHumanMessage(content请问大师叫什么)ai_msgAIMessage(content我叫陈瞎子。)# 直接拼成列表即是一个合法的消息模板chat_list[system_msg,human_msg,ai_msg]promptChatPromptTemplate.from_messages(chat_list)print(prompt.format_messages())这种方式下你可以将某个SystemMessage作为公共提示词在多个场景中复用并自由组合后续对话流程大幅提升代码的模块化程度。五、自定义提示词模板当内置的PromptTemplate和ChatPromptTemplate无法满足需求时可以通过继承StringPromptTemplate来实现自己的模板逻辑。例如创建一个“函数大师”模板输入函数名自动获取函数源代码并生成一段要求解释代码的提示词。步骤继承StringPromptTemplate重写format方法在其中实现自定义逻辑如获取源代码、拼接提示调用时和普通模板一致importinspectfromlangchain_core.promptsimportStringPromptTemplate# 定义一个示例函数defhello_world(a,b,c):测试函数print(hello world)returna,b,c# 自定义模板类classCustomCodeExplainerTemplate(StringPromptTemplate):defformat(self,**kwargs)-str:func_namekwargs[function_name]# 获取函数源代码source_codeinspect.getsource(globals()[func_name])# 内嵌提示词prompt_template(你是一个非常有经验和天赋的程序员。现在给你如下函数名称你会按照如下格式输出这段代码的名称、源代码和中文解释。\n函数名称: {function_name}\n源代码: {source_code}\n代码解释: )returnprompt_template.format(function_namefunc_name,source_codesource_code)# 使用自定义模板custom_promptCustomCodeExplainerTemplate(input_variables[function_name])final_promptcustom_prompt.format(function_namehello_world)print(final_prompt)输出已包含函数名称和源代码。后续你可以将该提示词直接交给 LLM得到代码解释。这种模式允许你在模板内部封装任何复杂的预处理逻辑从而将提示词构建过程完全自动化。五种模板对比模板类型输入变量占位输出格式适用模型灵活性PromptTemplate字符串花括号纯文本LLM补全低ChatPromptTemplate消息列表变量结构化消息列表Chat Model中MessagesPlaceholder动态消息插槽含占位符的消息列表Chat Model高Message 对象组合无消息列表Chat Model高自定义StringPromptTemplate自定义任意均可极高模板工作流程以下 Mermaid 时序图展示了从定义模板到 LLM 调用的一般流程。大语言模型提示词模板开发者大语言模型提示词模板开发者定义模板及变量传入参数 (format / format_messages / invoke)返回格式化后的提示词或消息列表将格式化结果作为输入发送返回模型响应完整可运行代码以下代码整合了上述五种模板的示例可直接复制执行。执行前请安装依赖pipinstalllangchain langchain-coreimportinspectfromlangchain_core.promptsimport(PromptTemplate,ChatPromptTemplate,MessagesPlaceholder,StringPromptTemplate)fromlangchain_core.messagesimportHumanMessage,SystemMessage,AIMessage# 1. 字符串模板 str_templatePromptTemplate.from_template(你是一个{role}帮我起一个具有{country}特色的{gender}名字。)str_resultstr_template.format(role算命大师,country法国,gender女孩)print(字符串模板结果\n,str_result,\n)# 2. 对话模板 chat_templateChatPromptTemplate.from_messages([(system,你是一个起名大师你的名字叫{name}。),(human,你好感觉如何),(ai,你好我状态非常好。),(human,你叫什么名字),(ai,你好我叫{name}。),(human,{user_input}),])chat_resultchat_template.format_messages(name陈大师,user_input你的爸爸是谁呢)print(对话模板结果\n,chat_result,\n)# 3. 消息占位符 placeholder_templateChatPromptTemplate.from_messages([(system,你是一个厉害的人工智能助手。),MessagesPlaceholder(variable_namehistory),(human,{question})])ph_resultplaceholder_template.invoke({history:[HumanMessage(content你好请多关照)],question:今天天气如何})print(消息占位符结果\n,ph_result.messages,\n)# 4. Message 组合模板 sys_msgSystemMessage(content你是一个起名大师,additional_kwargs{大师名字:陈瞎子})human_msgHumanMessage(content请问大师叫什么)ai_msgAIMessage(content我叫陈瞎子。)composed_list[sys_msg,human_msg,ai_msg]composed_templateChatPromptTemplate.from_messages(composed_list)comp_resultcomposed_template.format_messages()print(Message 组合模板结果\n,comp_result,\n)# 5. 自定义模板 defhello_world(a,b,c):测试函数print(hello world)returna,b,cclassCustomCodeExplainerTemplate(StringPromptTemplate):defformat(self,**kwargs)-str:func_namekwargs[function_name]source_codeinspect.getsource(globals()[func_name])prompt_template(你是一个非常有经验和天赋的程序员。现在给你如下函数名称你会按照如下格式输出这段代码的名称、源代码和中文解释。\n函数名称: {function_name}\n源代码: {source_code}\n代码解释: )returnprompt_template.format(function_namefunc_name,source_codesource_code)custom_promptCustomCodeExplainerTemplate(input_variables[function_name])custom_resultcustom_prompt.format(function_namehello_world)print(自定义模板结果\n,custom_result,\n)总结本文详细介绍了 LangChain 中五种提示词模板的用法及适用场景从最简单的字符串模板到高度灵活的自定义模板覆盖了绝大多数 LLM 应用的提示词构建需求。通过对比和完整代码示例开发者可以快速选择适合自己项目的模板类型并基于此构建稳健、可维护的 AI Agent 系统。