LangChain Prompt 工程实战:从基础模板到高级消息占位符

发布时间:2026/7/23 5:29:27

LangChain Prompt 工程实战:从基础模板到高级消息占位符 1. 本章目标通过本章学习你将能够理解 Prompt 在大模型应用中的核心作用使用普通字符串编写简单的 Prompt使用PromptTemplate管理单段提示词使用ChatPromptTemplate管理聊天消息给 Prompt 注入变量实现动态内容编写适合业务场景的提示词完成商品文案、学习计划、客服回复三个实战案例2. 什么是 PromptPrompt提示词就是给大模型的指令告诉它要做什么。简单示例请用一句话介绍 LangChain。实际项目中的复杂 Prompt你是一名电商运营专家。 请根据商品名称、商品卖点、目标用户生成一段适合详情页展示的商品文案。 要求 1. 语气自然 2. 不超过 150 字 3. 突出用户利益Prompt 的质量直接决定了模型输出的质量好的 Prompt 能让模型更好地理解你的意图。3. 为什么需要 Prompt 模板如果每次都手写完整的 Prompt会遇到这些问题代码冗长字符串太长代码难以阅读重复劳动多个地方需要写类似的提示词容易出错变量拼接时容易出错维护困难后期修改需要到处找传统写法不推荐promptf请为商品{product_name}写一段文案卖点是{selling_points}这种写法虽然能用但当提示词变长后就很难维护。解决方案Prompt 模板LangChain 提供了 Prompt 模板可以把固定内容和变量分开让代码更清晰、更易维护。4. PromptTemplate 基本使用PromptTemplate适合处理普通文本提示词它会生成一段完整的字符串。示例代码fromlangchain_core.promptsimportPromptTemplate# 1. 创建模板prompt_templatePromptTemplate.from_template(请为商品 {product_name} 写一句广告语突出卖点{selling_points})# 2. 填充变量promptprompt_template.invoke({product_name:无线鼠标,selling_points:静音、续航长、轻便,})# 3. 使用提示词print(prompt.text)模板变量{product_name} {selling_points}这些变量会被实际数据替换实现动态内容生成。5. ChatPromptTemplate 基本使用如果要使用 system / human / ai 消息结构推荐使用ChatPromptTemplate。示例代码fromlangchain_core.promptsimportChatPromptTemplate# 1. 创建聊天模板prompt_templateChatPromptTemplate.from_messages([(system,你是一名电商运营专家回答要简洁、有吸引力。),(human,请为商品 {product_name} 写一段文案卖点是{selling_points}),])# 2. 填充变量promptprompt_template.invoke({product_name:无线鼠标,selling_points:静音、续航长、轻便,})# 3. 查看生成的消息列表print(prompt)核心特点生成结构化消息列表[SystemMessage, HumanMessage, AIMessage]适合现代对话大模型GPT、Claude、通义千问等本课程后续会经常使用它随堂练习fromlangchain_core.promptsimportPromptTemplate prompt_templatePromptTemplate.from_template(请为商品 {product_name} 写一句广告语突出卖点{selling_points})promptprompt_template.invoke({product_name:logi鼠标,selling_points:特别安静灵敏速度快无延迟})print(prompt.text)fromlangchain_core.promptsimportChatPromptTemplate chat_templateChatPromptTemplate.from_messages([(system,你是一名电商运营专家回答要简洁、有吸引力。),(human,请为商品 {product_name} 写一段文案卖点是{selling_points})])promptchat_template.invoke({product_name:logi鼠标,selling_points:特别安静灵敏速度快无延迟})print(prompt)# 注意使用时需要将整个对象传递给大模型而不是字符串print(prompt.messages[1].content)6. Prompt 编写建议第一阶段先掌握几个最实用的原则。6.1 明确角色例如你是一名电商运营专家。角色可以帮助模型确定回答风格。6.2 明确任务例如请根据商品名称和卖点生成一段详情页文案。任务越明确模型越容易输出想要的结果。6.3 明确约束例如要求 1. 不超过 150 字 2. 不要使用夸张宣传 3. 适合年轻上班族约束可以减少输出跑偏。6.4 给出输入字段例如商品名称{product_name} 商品卖点{selling_points} 目标用户{target_user}让模型清楚知道每个变量的含义。7. 案例一商品文案生成器本案例根据商品信息生成一段电商文案。创建01_product_copywriter.pyimportosfromdotenvimportload_dotenvfromlangchain.chat_modelsimportinit_chat_modelfromlangchain_core.promptsimportChatPromptTemplate load_dotenv()modelinit_chat_model(modeldeepseek-v4-flash,model_provideropenai,base_urlos.getenv(DEEPSEEK_BASE_URL),api_keyos.getenv(DEEPSEEK_API_KEY),temperature0.5)prompt_str 请根据下面信息生成一段商品详情页文案。 商品名称{product_name} 商品卖点{selling_points} 目标用户{target_user} 要求 1. 不超过 150 字 2. 突出用户能获得的好处 3. 不要使用虚假夸张表达 chat_promt_templateChatPromptTemplate.from_messages([(system,你是一名电商运营专家擅长写自然、有吸引力但不过度夸张的商品文案),(human,prompt_str)])promptchat_promt_template.invoke({product_name:无线静音鼠标,selling_points:静音按键、蓝牙连接、续航 30 天、轻便便携,target_user:经常在办公室和图书馆使用电脑的人,})responsemodel.invoke(prompt)print(response.content)运行python 01_product_copywriter.py这个案例体现了 Prompt 的基本结构角色输入要求输出任务8. 减少重复代码封装模型初始化前面几个案例都重复写了模型初始化代码。将其放入到一个 utils 工具包下可以创建model_factory.pyimportosfromdotenvimportload_dotenvfromlangchain.chat_modelsimportinit_chat_modeldefget_deepSeek_model(temperature:float0.7):load_dotenv()modelinit_chat_model(modeldeepseek-v4-flash,model_provideropenai,base_urlos.getenv(DEEPSEEK_BASE_URL),api_keyos.getenv(DEEPSEEK_API_KEY),temperaturetemperature)returnmodel然后案例中可以改成frommodel_factoryimportget_deepseek_model modelget_deepseek_model(temperature0.5)这不是复杂封装只是减少重复代码。9. 案例二学习计划生成器本案例根据学习目标生成学习计划。创建02_study_plan.pyfromlangchain_core.promptsimportChatPromptTemplatefromutils.model_factoryimportget_deepSeek_model modelget_deepSeek_model(0.5)prompt_str 请为我制定一个学习计划。 学习主题{topic} 学习时长{days} 天 每天可学习时间{hours_per_day} 小时 当前基础{level} 要求 1. 按天列出学习内容 2. 每天给出练习任务 3. 内容要适合当前基础 chat_promt_templateChatPromptTemplate.from_messages([(system,你是一名编程课程规划老师擅长为初学者制定可执行的学习计划。),(human,prompt_str)])promptchat_promt_template.invoke({topic:langchain,days:3,hours_per_day:1,level:会python基础})responsemodel.invoke(prompt)print(response.content)运行python 02_study_plan.py这个案例可以看到Prompt 可以接收多个变量变量可以是字符串也可以是数字模型输出可以被规则引导10. 案例三客服回复生成器本案例根据用户问题和订单状态生成客服回复。创建03_customer_reply.pyfromlangchain_core.promptsimportChatPromptTemplatefromutils.model_factoryimportget_deepSeek_model modelget_deepSeek_model(0.7)prompt_str 请根据用户问题和订单状态生成一段客服回复。 用户问题{user_question} 订单状态{order_status} 物流信息{shipping_info} 要求 1. 先安抚用户 2. 再说明当前情况 3. 最后给出下一步建议 4. 不超过 120 字 chat_promt_templateChatPromptTemplate.from_messages([(system,你是一名电商客服回复要礼貌、明确不推卸责任。),(human,prompt_str)])promptchat_promt_template.invoke({user_question:我的快递三天没更新了是不是丢了,order_status:已发货,shipping_info:物流显示包裹已到达上海转运中心暂未更新下一站信息})responsemodel.invoke(prompt)print(response.content)运行python 03_customer_reply.py这个案例接近真实业务用户问题来自前端订单状态来自数据库物流信息来自第三方接口Prompt 负责组织这些信息并生成回复11.MessagesPlaceholder作用MessagesPlaceholder用来在ChatPromptTemplate中插入一组消息列表。它通常用于插入聊天历史插入 Agent 中间步骤插入已经构造好的多条 message普通变量{question}只能填充一段文本而MessagesPlaceholder(history)可以一次插入多条(历史)消息。基本导入from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder基本语法MessagesPlaceholder(variable_name)常用写法MessagesPlaceholder(history)完整参数MessagesPlaceholder(variable_namehistory,optionalTrue,n_messages6,)参数说明参数类型说明variable_namestr占位符对应的输入变量名optionalbool是否允许不传该变量n_messagesint | None最多保留最近多少条消息在 ChatPromptTemplate 中使用prompt ChatPromptTemplate.from_messages([ (system, You are a helpful assistant. ), MessagesPlaceholder(history), (human, {question}), ]):::color2这里面有一个照应关系当MessagesPlaceholder(“history”)时默认optionalFalse也就是说 prompt.invoke 时必须传入history 这个标签当然这个标签的名字两个地方保持一致即可那如果optionalTrue, 那么prompt.invoke 时可以不传递 history另外这个history必须是一个列表才行:::调用时传入prompt_value prompt.invoke({ history: [ (human, My name is Alice.), (ai, Nice to meet you, Alice.), ], question: What is my name?, })最终消息顺序相当于[ SystemMessage(contentYou are a helpful assistant.), HumanMessage(contentMy name is Alice.), AIMessage(contentNice to meet you, Alice.), HumanMessage(contentWhat is my name?), ]输入格式MessagesPlaceholder对应的变量必须是**消息列表**。可以使用 tuple 格式history [ (human, 你好), (ai, 你好有什么可以帮你), ]也可以使用 LangChain 消息对象fromlangchain_core.messagesimportHumanMessage,AIMessage history[HumanMessage(content你好),AIMessage(content你好有什么可以帮你),]错误写法prompt.invoke({ history: 你好, question: 刚才我说了什么, })font stylecolor:#DF2A3F;history/font不能是普通字符串必须是 list。optionalTrue默认情况下如果没有传入history会报错。promptChatPromptTemplate.from_messages([(system,You are a helpful assistant.),MessagesPlaceholder(history),(human,{question}),])prompt.invoke({question:Hello!,})如果聊天历史可能为空建议设置prompt ChatPromptTemplate.from_messages([ (system, You are a helpful assistant.), MessagesPlaceholder(history, optionalTrue), (human, {question}), ])这样就可以不传historyprompt_value prompt.invoke({ question: Hello!, })n_messagesn_messages用来限制插入最近多少条消息。prompt ChatPromptTemplate.from_messages([ (system, You are a concise assistant.), MessagesPlaceholder(history, optionalTrue, n_messages4), (human, {question}), ])示例输入prompt_value prompt.invoke({ history: [ (human, My name is Alice.), (ai, Nice to meet you, Alice.), (human, I like Python.), (ai, Great choice.), (human, I also use LangChain.), (ai, LangChain is useful for LLM apps.), ], question: What do you know about me?, })这里history只会插入最近 4 条消息[ HumanMessage(contentI like Python.), AIMessage(contentGreat choice.), HumanMessage(contentI also use LangChain.), AIMessage(contentLangChain is useful for LLM apps.), ]然后再追加当前问题HumanMessage(contentWhat do you know about me?)placeholder 简写MessagesPlaceholder也可以使用 tuple 简写prompt ChatPromptTemplate.from_messages([ (system, You are a helpful assistant.), (placeholder, {history}), (human, {question}), ])通常等价于promptChatPromptTemplate.from_messages([(system,You are a helpful assistant.),MessagesPlaceholder(history,optionalTrue),(human,{question}),])如果需要设置n_messages建议使用显式写法MessagesPlaceholder(history, optionalTrue, n_messages4)fromlangchain_core.promptsimportChatPromptTemplate,MessagesPlaceholderfromutils.model_factoryimportget_deepSeek_model modelget_deepSeek_model(temperature0.7)chat_promptChatPromptTemplate.from_messages([(system,你是一个很棒的问答助手),MessagesPlaceholder(variable_namehistory,optionalTrue,n_messages4),(human,{question})])promptchat_prompt.invoke({history:[(human,My name is Alice.),(ai,Nice to meet you, Alice.),(human,I like Python.),(ai,Great choice.),(human,I also use LangChain.),(ai,LangChain is useful for LLM apps.),],question:我叫什么名字})respmodel.invoke(prompt)print(resp.content)12. 本章重点本章最重要的是掌握Prompt 是给模型的任务说明Prompt 应该包含角色、任务、输入、约束PromptTemplate适合普通文本提示词ChatPromptTemplate适合聊天模型Prompt 模板可以通过变量复用业务场景中要把输入信息清晰地交给模型

相关新闻