PromptTemplate 与 ChatPromptTemplate 完整教程 一、为什么需要提示词模板Prompt 就是传递给大模型的指令指令质量直接决定输出效果。 很多新手直接使用 f-string 拼接提示词python运行prompt f为商品{product_name}写广告语卖点{selling_points}写法简单但项目规模扩大后缺陷明显长提示词混杂在业务代码中可读性差多处复用相同提示词重复代码难以统一维护字符串拼接容易出现空格、换行、转义 bug不方便统一调试、迭代优化 Prompt 规则。LangChain 提供两套模板方案把固定指令和动态变量彻底解耦实现提示词统一管理。二、PromptTemplate纯文本提示模板适用场景单轮简单文本任务没有区分 system/human 角色。 只生成一段完整字符串无结构化消息概念。基础示例python运行from langchain_core.prompts import PromptTemplate prompt_template PromptTemplate.from_template( 请为商品 {product_name} 写一句广告语突出卖点{selling_points} ) prompt prompt_template.invoke({ product_name: 罗技鼠标, selling_points: 静音、高灵敏、低延迟 }) print(prompt.text)模板中{变量名}会自动被传入数据填充。三、ChatPromptTemplate【推荐优先使用】现代对话大模型DeepSeek、GPT、Claude、通义千问原生支持角色消息系统指令、用户提问、AI 历史回复。ChatPromptTemplate可以构建结构化消息列表SystemMessage定义 AI 身份、全局规则、约束条件HumanMessage用户输入内容AIMessage模型历史回答基础示例python运行from langchain_core.prompts import ChatPromptTemplate chat_template ChatPromptTemplate.from_messages([ (system, 你是电商运营专家文案简洁有吸引力。), (human, 请为商品 {product_name} 撰写文案卖点{selling_points}) ]) prompt chat_template.invoke({ product_name: 罗技鼠标, selling_points: 静音、高灵敏、低延迟 }) # 直接把prompt对象传给model.invoke不要只传字符串两者核心区分表格模板输出形式适用场景PromptTemplate纯文本字符串简单文本生成、不需要角色区分ChatPromptTemplate结构化消息列表对话模型、Agent、多轮交互、绝大多数业务开发开发建议新项目统一使用ChatPromptTemplate兼容性更强。四、高质量 Prompt 通用编写规范一套标准业务 Prompt 包含四大要素照着搭建能大幅降低模型输出跑偏概率角色定位明确 AI 身份电商运营、学习规划师、客服核心任务清晰说明需要完成什么工作输入字段罗列外部传入的变量信息约束规则字数限制、语气、禁止行为、输出要求五、三大业务实战案例DeepSeek统一封装模型工具避免重复初始化代码。 新建utils/model_factory.pypython运行import os from dotenv import load_dotenv from langchain.chat_models import init_chat_model def get_deepSeek_model(temperature: float 0.7): load_dotenv() model init_chat_model( modeldeepseek-v4-flash, model_provideropenai, base_urlos.getenv(DEEPSEEK_BASE_URL), api_keyos.getenv(DEEPSEEK_API_KEY), temperaturetemperature ) return model案例 1商品详情文案生成python运行from langchain_core.prompts import ChatPromptTemplate from utils.model_factory import get_deepSeek_model model get_deepSeek_model(temperature0.5) prompt_str 商品名称{product_name} 商品卖点{selling_points} 目标用户{target_user} 要求 1. 文案不超过150字 2. 站在用户视角突出使用收益 3. 杜绝夸大、虚假宣传 chat_template ChatPromptTemplate.from_messages([ (system, 资深电商运营擅长撰写自然、接地气的商品详情文案。), (human, prompt_str) ]) prompt chat_template.invoke({ product_name: 无线静音鼠标, selling_points: 静音按键、蓝牙连接、续航30天、轻便便携, target_user: 办公室、图书馆办公人群 }) response model.invoke(prompt) print(response.content)案例 2定制化学习计划生成python运行from langchain_core.prompts import ChatPromptTemplate from utils.model_factory import get_deepSeek_model model get_deepSeek_model(0.5) prompt_str 学习主题{topic} 总时长{days}天 每日可用学习时间{hours_per_day}小时 学习者基础{level} 输出要求 1. 按天数划分学习内容 2. 每日配套实操练习任务 3. 难度匹配学习者现有基础 chat_template ChatPromptTemplate.from_messages([ (system, 专业编程讲师擅长制定可落地、循序渐进的学习方案。), (human, prompt_str) ]) prompt chat_template.invoke({ topic: LangChain开发, days: 3, hours_per_day: 1, level: 掌握基础Python语法 }) response model.invoke(prompt) print(response.content)案例 3智能电商客服回复贴近真实业务外部传入用户提问、订单状态、物流数据动态生成回复。python运行from langchain_core.prompts import ChatPromptTemplate from utils.model_factory import get_deepSeek_model model get_deepSeek_model(0.7) prompt_str 用户问题{user_question} 订单状态{order_status} 物流信息{shipping_info} 回复规范 1. 先安抚用户情绪 2. 客观说明当前现状 3. 给出清晰可行方案 4. 全文不超过120字 chat_template ChatPromptTemplate.from_messages([ (system, 电商在线客服语气礼貌稳重不推诿、不使用模糊话术。), (human, prompt_str) ]) prompt chat_template.invoke({ user_question: 快递三天物流没有更新包裹是不是丢失了, order_status: 已发货, shipping_info: 包裹抵达上海转运中心暂未更新下一站流转信息 }) response model.invoke(prompt) print(response.content)六、MessagesPlaceholder实现多轮对话记忆业务场景中我们经常需要传入历史对话让 AI 拥有上下文。 普通{变量}只能填充一段文本MessagesPlaceholder 支持插入一整条消息列表是多轮对话的核心组件。核心参数说明variable_name占位符名称调用时传入同名变量optional是否允许不传历史消息空对话场景开启n_messages限制最多加载最近 N 条消息防止上下文溢出完整示例python运行from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from utils.model_factory import get_deepSeek_model model get_deepSeek_model(temperature0.7) chat_prompt ChatPromptTemplate.from_messages([ (system, 专业问答助手简洁作答。), MessagesPlaceholder(variable_namehistory, optionalTrue, n_messages4), (human, {question}) ]) prompt chat_prompt.invoke({ history: [ (human, 我的名字叫Alice), (ai, 很高兴认识你Alice), (human, 我正在学习Python), (ai, Python是非常实用的编程语言), (human, 我还在用LangChain开发应用), (ai, LangChain能够快速搭建大模型应用), ], question: 我叫什么名字 }) resp model.invoke(prompt) print(resp.content)⚠️ 注意history 必须是消息列表不能直接传入字符串否则会抛出类型异常。简写形式(placeholder, {history})等价于开启optionalTrue的 MessagesPlaceholder。七、学习重点总结Prompt 是发给大模型的指令指令结构直接影响输出质量PromptTemplate面向纯文本ChatPromptTemplate面向对话模型优先选择后者模板通过{变量}实现提示词复用便于后期统一维护迭代标准 Prompt 结构角色 任务 输入信息 约束条件MessagesPlaceholder用于注入历史对话消息实现多轮上下文记忆。八、常见开发疑问1. Prompt 越长效果越好吗并不是。只保留必要规则多余要求会造成模型注意力分散更容易遗漏约束。2. 模型经常不遵守指令怎么办大模型不具备程序的确定性。如果对输出格式要求严格后续可以结合PydanticOutputParser结构化输出增加一层代码校验。3. 什么时候选两种模板简单一次性文本任务可用PromptTemplate只要调用对话模型、做多轮对话、Agent 开发一律使用ChatPromptTemplate。

本月热点