国庆节10月1日
--


PromptTemplate 与 ChatPromptTemplate 的用法与取舍,以及从"字符串提示词"到"消息列表"的机制演进

构造提示词有两种方式:Python 字符串拼接(f-string、format()、+)和 LangChain 的 PromptTemplate / ChatPromptTemplate。
1# 方式一:字符串拼接2topic = "Python"3difficulty = "初学者"4prompt_str = f"你是一个{difficulty}级别的编程导师。请用简单易懂的语言解释{topic}。"5response = model.invoke(prompt_str)| 字符串拼接 | 提示词模板 | |
|---|---|---|
| 上手成本 | 简单直接,零学习成本 | 有一点学习成本,初期写法略复杂 |
| 可读性 | 变量一多就混乱 | 结构清晰(变量占位) |
| 可维护性 | 修改容易出错 | 易维护、可复用 |
| 变量校验 | ❌ 无(容易漏/拼错) | ✅ 自动校验(更安全) |
| 复杂场景 | ❌ 多轮对话 / RAG / Few-shot 难做 | ✅ 支持对话 / RAG / Agent |
| 生态集成 | — | 与 LangChain 生态无缝集成,便于调试与日志追踪 |
开发建议:小项目 / 临时 demo 用字符串拼接;正式开发做 AI 应用,提示词模板是必选。
1from langchain_core.prompts import PromptTemplate # ← 1.x 里必须从 langchain_core 导入2
3topic = "Python"4difficulty = "初学者"5
6template = PromptTemplate.from_template(7 "你是一个{difficulty}级别的编程导师。请用简单易懂的语言解释{topic}。"8)9
10# 用 format() 填变量,得到最终提示词字符串11prompt = template.format(difficulty=difficulty, topic=topic)12response = model.invoke(prompt)导入路径踩坑:课程讲义里写的是 from langchain.prompts import ...,但在 LangChain 1.x 上会直接报
ModuleNotFoundError: No module named 'langchain.prompts'(本机 langchain 1.2.12 实测)。
正确写法一律从 langchain_core 导入:from langchain_core.prompts import PromptTemplate, ChatPromptTemplate。
1from langchain_core.prompts import ChatPromptTemplate2
3prompt_template = ChatPromptTemplate([4 ("system", "你是一个AI开发工程师. 你的名字是 {name}."),5 ("human", "{user_input}"),6])7
8# invoke() 返回的是【消息列表】(可直接传给模型)9prompt = prompt_template.invoke({"name": "小谷AI", "user_input": "你能帮我做什么?"})10print(prompt)实例化有两种方式:from_messages()(推荐) 和 初始化方法传 messages 参数;传入的都是”元组构成的列表”,每个元组是 (role, content)。
| 角色字符串 | 含义 | 用途 |
|---|---|---|
"system" | 系统消息 | 设定 AI 的行为、角色、规则 |
"user" / "human" | 用户消息 | 用户的输入/问题 |
"assistant" / "ai" | AI 消息 | AI 的回复(用于对话历史) |
PromptTemplate 用 format() 返回字符串;ChatPromptTemplate 用 invoke() 返回消息列表——这个差别决定了它能直接喂给聊天模型,也因此成为 1.x 的主力工具。
同一个模板,三个方法三副面孔,先记住返回类型,就知道该在什么场合用哪个:
| 方式 | 返回类型 | 用途 |
|---|---|---|
invoke({...}) | ChatPromptValue | 最常用,里面装着 messages,可直接传给模型 |
format(...) | str | 想看”拼出来长什么样”,或要落库/打日志 |
format_messages(...) | list | 要一个真正的 List[BaseMessage](自己再拼装) |
1from langchain_core.prompts import ChatPromptTemplate2
3prompt_template = ChatPromptTemplate([4 ("system", "你是一个AI开发工程师. 你的名字是 {name}."),5 ("human", "你能开发哪些AI应用?"),6 ("ai", "我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等."),7 ("human", "{user_input}"),8])9
10# 方式1:invoke() → ChatPromptValue11prompt = prompt_template.invoke({"name": "小谷AI", "user_input": "你能帮我做什么?"})12print(type(prompt)) # <class 'langchain_core.prompt_values.ChatPromptValue'>13print(len(prompt.messages)) # 414
15# 方式2:format() → 字符串16prompt_str = prompt_template.format(name="小谷AI", user_input="你能帮我做什么?")17print(type(prompt_str)) # <class 'str'>format() 打印出来长这样——角色名 + 内容一行行拼好,就是个”给人看”的预览:
1System: 你是一个AI开发工程师. 你的名字是 小谷AI.2Human: 你能开发哪些AI应用?3AI: 我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等.4Human: 你能帮我做什么?1# 方式3:format_messages() → 消息列表2messages = prompt_template.format_messages(name="小谷AI", user_input="你能帮我做什么?")3print(type(messages)) # <class 'list'>三种方式参数写法不一样:invoke() 收一个字典(invoke({...})),format() / format_messages() 收关键字参数(format(name=..., user_input=...))。另外还有个 format_prompt(),返回的也是 ChatPromptValue——和 invoke() 等价,只是名字更”老派”。
实测(本机 langchain-core 1.2.18):invoke → ChatPromptValue、format → str、format_messages → list、format_prompt → ChatPromptValue,与课程完全一致。
模板 + 模型连起来的完整流程——“提供大模型 → 提供提示词 → 结合调用”三步:
1from dotenv import load_dotenv2from langchain_core.prompts import ChatPromptTemplate3import os4from langchain.chat_models import init_chat_model5
6###### 1、提供大模型 #########7load_dotenv(override=True)8
9model = init_chat_model(10 model="gpt-5.4-mini",11 model_provider="openai",12 api_key=os.getenv("CLOSEAI_API_KEY"),13 base_url=os.getenv("CLOSEAI_BASE_URL"),14)15
16###### 2、提供提示词 #########17chat_prompt = ChatPromptTemplate.from_messages([18 ("system", "你是一个数学家,你可以计算任何算式"),19 ("human", "{text}"),20])21
22# 输入提示23prompt_value = chat_prompt.invoke({24 "text": "我今年18岁,我的舅舅今年38岁,我的爷爷今年72岁,我和舅舅一共多少岁了?"25})26
27###### 3、结合提示词,调用大模型 #########28# 得到模型的输出29output = model.invoke(prompt_value)30# 打印输出内容31print(output.content)输出:
1你今年 18 岁,舅舅今年 38 岁。2一共是:3
418 + 38 = **56 岁**5
6所以,你和舅舅一共 **56 岁**。chat_prompt.invoke({...}) 的结果可以直接塞给 model.invoke(...)——因为前者给的就是一个消息列表。这就是”模板 ↔ 模型”之间最顺的接口:模板负责填变量,模型负责生成,中间不需要你做任何转换。
前面一直用”元组构成的列表”,其实那只是六种合法元素里的第一种。看源码签名:
1def __init__(2 self,3 messages: Sequence[4 BaseMessagePromptTemplate | BaseMessage | BaseChatPromptTemplate5 | tuple[str | type, str | list[dict] | list[object]] | str | dict[str, Any]6 ],7 *,8 template_format: Literal["f-string", "mustache", "jinja2"] = "f-string",9 **kwargs: Any,10) -> None: ...from_messages() 的签名一模一样(from_messages() 的底层也是调用类的 __init__() 方法)。结论:参数是列表类型,列表的元素可以是字符串、字典、元组、Message 对象、MessagePromptTemplate、ChatPromptTemplate。
类型1:str 列表(不推荐)——因为默认角色全是 human:
1chat_template = ChatPromptTemplate.from_messages([2 "Hello, {name}!" # 等价于 ("human", "Hello, {name}!")3])4print(chat_template.invoke({"name": "小谷AI"}))5# messages=[HumanMessage(content='Hello, 小谷AI!', ...)]类型2:tuple 列表——最常用((role, content)):
1prompt = ChatPromptTemplate.from_messages([2 ("system", "你的名字是{role}."),3 ("human", "很高兴认识你"),4])5print(prompt.invoke({"role": "小智"}))类型3:dict 列表——和 JSON 消息格式一致,适合从配置/文件里读模板:
1prompt = ChatPromptTemplate.from_messages([2 {"role": "system", "content": "你的名字是{role}."},3 {"role": "human", "content": "很高兴认识你"},4])5print(prompt.invoke({"role": "小智"}))类型4:Message 列表——已经实例化好的 SystemMessage / HumanMessage 直接放进去(等于”写死的消息”):
1from langchain_core.messages import SystemMessage, HumanMessage2
3chat_prompt_template = ChatPromptTemplate.from_messages([4 SystemMessage(content="我是一个贴心的智能助手"),5 HumanMessage(content="我的问题是:人工智能英文怎么说?"),6])7messages = chat_prompt_template.invoke({})8print(messages)在 XxxMessage 里不能有占位符!写 HumanMessage(content="我的问题是:{word}英文怎么说?") 再 invoke({"word": "人工智能"}),结果是原样透传:
1messages=[..., HumanMessage(content='我的问题是:{word}英文怎么说?', ...)]{word} 不会被替换、也不会报错——就这么静静地错下去了。要填变量就用元组 / PromptTemplate / 下面的 MessagePromptTemplate。
类型5:MessagePromptTemplate 列表——SystemMessagePromptTemplate、HumanMessagePromptTemplate、AIMessagePromptTemplate 分别用来”生成”对应的消息:
HumanMessagePromptTemplate → HumanMessage,content + role="human")1from langchain_core.prompts import (2 ChatPromptTemplate,3 HumanMessagePromptTemplate,4 SystemMessagePromptTemplate,5)6
7system_message_prompt = SystemMessagePromptTemplate.from_template("你是一个{role}")8human_message_prompt = HumanMessagePromptTemplate.from_template("给我解释{concept},用浅显易懂的语言")9
10chat_prompt = ChatPromptTemplate.from_messages([11 system_message_prompt,12 human_message_prompt,13])14
15formatted_messages = chat_prompt.invoke({"role": "物理学家", "concept": "相对论"})16print(formatted_messages)17# messages=[SystemMessage(content='你是一个物理学家', ...), HumanMessage(content='给我解释相对论,用浅显易懂的语言', ...)]类型6:嵌套的 ChatPromptTemplate——可以理解为”ChatPromptTemplate 里嵌套了 ChatPromptTemplate”:
1nested_prompt_template1 = ChatPromptTemplate.from_messages([2 ("system", "我是一个人工智能助手,我的名字叫{name}")3])4nested_prompt_template2 = ChatPromptTemplate.from_messages([5 ("human", "很高兴认识你,我的问题是{question}")6])7
8prompt_template = ChatPromptTemplate.from_messages([9 nested_prompt_template1, nested_prompt_template2,10])11prompt_template.invoke({"name": "小智", "question": "你为什么这么帅?"})两种实例模板的变量会被合并到同一次 invoke 里(上面 name 和 question 就是分别填进两个嵌套模板的)。
综合使用——六种元素可以混着放:
1from langchain_core.prompts import (2 ChatPromptTemplate,3 SystemMessagePromptTemplate,4 HumanMessagePromptTemplate,5)6from langchain_core.messages import SystemMessage, HumanMessage7
8# 示例 1: 使用 BaseMessage(已实例化的消息)9system_msg = SystemMessage(content="你是一个AI工程师。")10human_msg = HumanMessage(content="你好!")11
12# 示例 2: 使用 BaseMessagePromptTemplate13system_prompt = SystemMessagePromptTemplate.from_template("你是一个{role}.")14human_prompt = HumanMessagePromptTemplate.from_template("{user_input}")15
16# 示例 3: 使用 BaseChatPromptTemplate(嵌套的 ChatPromptTemplate)17nested_prompt = ChatPromptTemplate.from_messages([("system", "嵌套提示词")])18
19prompt = ChatPromptTemplate.from_messages([20 system_msg, # MessageLike (BaseMessage)21 human_msg, # MessageLike (BaseMessage)22 system_prompt, # MessageLike (BaseMessagePromptTemplate)23 human_prompt, # MessageLike (BaseMessagePromptTemplate)24 nested_prompt, # MessageLike (BaseChatPromptTemplate)25])26
27prompt.invoke({"role": "人工智能专家", "user_input": "介绍一下大模型的应用场景"})template_format 还有三种取值:"f-string"(默认)、"mustache"、"jinja2"。默认的 f-string 用 {变量};换 mustache 或 jinja2 时同样写 {{ name }} 也能正确渲染——处理”用户提供的模板”时,jinja2/mustache 语法更不容易和别的占位符冲突:
1ChatPromptTemplate.from_messages([("human", "Hello {{ name }}!")], template_format="mustache")2# messages=[HumanMessage(content='Hello 小谷!', ...)]LangChain 1.0 的核心演进之一:一个结构化、富含元数据的消息列表,取代了单一字符串,成为与模型交互的标准数据格式。
| 旧时代:LLM + PromptTemplate | 新时代:ChatModel + ChatPromptTemplate | |
|---|---|---|
| 模型接口 | LLM(文本进文本出) | ChatModel(主流接口) |
| 输入/输出 | 都是纯文本字符串 | 都是消息列表 |
| 角色支持 | ❌ 无 | ✅ system / user / assistant |
| 对话历史 | ❌ 不支持 | ✅ 支持 |
| 适用场景 | 简单提示 | 聊天、对话、多轮交互 |
旧时代的痛苦:要用字符串模拟多轮聊天,开发者必须手动拼接、伪造对话角色:
1"Human:你好\nAI:你好!有什么我能帮忙的吗?\nHuman:..."这样不仅结构混乱、难以维护,还极易让模型混淆对话的边界与上下文,影响生成质量。现代聊天模型 API 已原生支持角色概念,不再接受单一字符串,而是要求结构化的消息列表——这也为构建复杂、可靠的多轮对话智能体系统打下了基础。
模板会用了,接下来四个特性解决的是”真实项目里反复出现的四种麻烦”:变量老是重复填、历史消息要动态插、模板散落各处、提示词要拼装。
痛点:某些变量在所有调用里都相同(比如”你是客服专员”),每次 invoke 都要重复写一遍。
做法:用 partial() 预填充固定变量,创建模板的变体。适合”部分变量固定 + 需要为不同用户/场景定制模板”。
1from langchain_core.prompts import ChatPromptTemplate2
3# 原始模板4template = ChatPromptTemplate.from_messages([5 ("system", "你是{role},目标用户是{audience}"),6 ("user", "{task}"),7])8
9# 部分填充:把 role 和 audience 固定下来10customer_support_template = template.partial(11 role="客服专员",12 audience="普通用户",13)14
15# 现在只需要提供 task16messages = customer_support_template.invoke({"task": "解释退款政策"})17print(messages)18# messages=[SystemMessage(content='你是客服专员,目标用户是普通用户', ...),19# HumanMessage(content='解释退款政策', ...)]典型场景:一套基础模板,派生出多个部门的变体——这就是”提示词的多态”:
1base_template = ChatPromptTemplate.from_messages([2 ("system", "你是{department}的{role}"),3 ("user", "{task}"),4])5
6# IT 部门7it_template = base_template.partial(department="IT 部门", role="技术支持")8
9# 销售部门10sales_template = base_template.partial(department="销售部门", role="销售顾问")11
12sales_template.invoke({"task": "为什么每年年底汽车会促销"})13# ChatPromptValue(messages=[SystemMessage(content='你是销售部门的销售顾问', ...),14# HumanMessage(content='为什么每年年底汽车会促销', ...)])partial() 返回的是新模板,原模板不受影响——所以 base_template 还能继续派生出第三、第四个变体。被预填充的变量从”必填”变成”已填”,invoke 时再传也不会报错(以预填值为准)。
痛点:多轮对话的历史、Agent 的中间步骤,都是”一段条数不定的消息”——它们的角色也不知道(human 还是 ai 混着来),没法用 ("human", "{x}") 这种写法。
做法:用消息占位符,在特定位置插入整个消息列表。多轮对话系统存历史、Agent 处理中间步骤时非常有用。
方式1:JSON 形式(("placeholder", "{变量}"))
1from langchain_core.prompts import ChatPromptTemplate2
3template = ChatPromptTemplate.from_messages([4 ("system", "你是一个有用的AI助手"),5 ("placeholder", "{conversation}"),6])7
8prompt_value = template.invoke({9 "conversation": [10 ("human", "你好!"),11 ("ai", "今天我能帮你做什么?"),12 ("human", "你能给我做一个冰激凌吗?"),13 ("ai", "抱歉,我没有这样的能力"),14 ]15})16print(prompt_value)填充进去的元组被逐个翻译成真正的消息对象(("human", ...) → HumanMessage,("ai", ...) → AIMessage):
1messages=[SystemMessage(content='你是一个有用的AI助手', ...),2 HumanMessage(content='你好!', ...),3 AIMessage(content='今天我能帮你做什么?', ...),4 HumanMessage(content='你能给我做一个冰激凌吗?', ...),5 AIMessage(content='抱歉,我没有这样的能力', ...)]方式2:MessagesPlaceholder 实例
1from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder2from langchain_core.messages import HumanMessage3
4prompt_template = ChatPromptTemplate.from_messages([5 ("system", "You are a helpful assistant"),6 MessagesPlaceholder("msgs"),7])8prompt_template.invoke({"msgs": [HumanMessage(content="hi!")]})9
10# 也可以用 format_messages:11# prompt_template.format_messages(msgs=[HumanMessage(content="hi!")])生成的是”系统消息 + 你传进来的那些消息”:传 1 条就是 2 条,传 5 条就是 6 条——这正是”把一串消息插到指定位置”的价值。
MessagesPlaceholder("msgs") 的位置参数就是变量名(等价于 MessagesPlaceholder(variable_name="msgs")),两种写法都可以。
实战:存对话历史——system 固定、history 动态、question 每次不同:
1prompt_template = ChatPromptTemplate.from_messages([2 ("system", "你是一个非常友好的AI助手"),3 MessagesPlaceholder(variable_name="history"),4 ("human", "{question}"),5])6
7prompt_template.invoke({8 "history": [9 ("human", "5 + 2 = ?"),10 ("ai", "5 + 2 = 7"),11 ],12 "question": "结果再乘以4呢?",13})14# ChatPromptValue(messages=[SystemMessage('你是一个非常友好的AI助手'),15# HumanMessage('5 + 2 = ?'), AIMessage('5 + 2 = 7'),16# HumanMessage('结果再乘以4呢?')])这就是”手动维护对话历史”的正规写法:以前要在列表里手工拼接 {"role": ..., "content": ...},现在模板本身就留好了历史的坑位——每次只需把 history 换成最新的消息列表。第 7 篇最后那台聊天机器人,改用这个模板会清爽很多。
痛点:模板一多就散落在各个文件里。实际项目中建议创建模板库,统一收集、集中管理。
举例1:templates.py 用一个类当”模板仓库”
1from langchain_core.prompts import ChatPromptTemplate2
3class PromptLibrary:4 """可复用的提示词模板库"""5
6 TRANSLATOR = ChatPromptTemplate.from_messages([7 ("system", "你是专业翻译,精通{source_lang}和{target_lang}"),8 ("user", "翻译以下文本:\n{text}"),9 ])10
11 CODE_REVIEWER = ChatPromptTemplate.from_messages([12 ("system", "你是{language}代码审查专家,重点关注{focus}"),13 ("user", "审查代码:\n```{language}\n{code}\n```"),14 ])15
16 SUMMARIZER = ChatPromptTemplate.from_messages([17 ("system", "你是内容摘要专家"),18 ("user", "将以下内容总结为{num}个要点:\n{content}"),19 ])20
21 TUTOR = ChatPromptTemplate.from_messages([22 ("system", "你是{subject}导师,学生水平:{level}"),23 ("user", "{question}"),24 ])其它文件里直接取用,一行调用、变量照填:
1from templates import PromptLibrary2
3messages = PromptLibrary.TRANSLATOR.format_messages(4 source_lang="英语",5 target_lang="中文",6 text="Hello World",7)举例2:按功能拆成包——模板多了以后,比”一个大类”更好维护:
1# ├── __init__.py2# ├── common.py # 通用模板3# ├── translation.py # 翻译相关4# └── coding.py # 编程相关1from langchain_core.prompts import ChatPromptTemplate2
3FRIENDLY_ASSISTANT = ChatPromptTemplate.from_messages([4 ("system", "你是一个友好的助手"),5 ("user", "{input}"),6])痛点:一个 system 提示词往往由”角色 + 风格 + 限制”几段拼成,想复用其中某一段。
方法1:字符串组合——在 Python 层面把片段先拼好,再交给模板:
1# 定义可复用的部分2role_part = "你是一个{domain}专家。"3style_part = "回答风格:{style}。"4constraint_part = "限制:{constraint}。"5
6# 组合7full_system = role_part + style_part + constraint_part8
9template = ChatPromptTemplate.from_messages([10 ("system", full_system),11 ("user", "{question}"),12])方法2:用 + 运算符——模板对象直接相加(LangChain 1.0 支持),合并后的模板包含两边所有消息:
1template1 = ChatPromptTemplate.from_messages([("system", "你是助手")])2template2 = ChatPromptTemplate.from_messages([("user", "{input}")])3
4# 组合(LangChain 1.0 支持)5combined = template1 + template2两种方法的差别:字符串组合拼的是同一条消息的内容;+ 拼的是消息与消息(template1 的 system + template2 的 user)。
实测(本机 langchain-core 1.2.18):template1 + template2 返回的还是 ChatPromptTemplate,combined.invoke({"input": "hi"}) 得到 [SystemMessage('你是助手'), HumanMessage('hi')]——两边的变量会自动合并,一次 invoke 全填上。
from_template 建模板,再用 format() 填变量,返回的是字符串;聊天模板用 invoke() 填变量,返回的是消息列表,可以直接传给聊天模型from_messages()(推荐)与初始化方法传 messages 参数;两种方式传入的都是”元组构成的列表”,每个元组是 (角色, 内容)format_prompt(),返回的也是 ChatPromptValue(与 invoke 等价);三者的参数写法也不同——invoke 收一个字典,另外两个收关键字参数partial():它返回的是新模板(原模板不受影响),被预填的变量从”必填”变成”已填”;消息占位符也有两种写法——JSON 形式的 ("placeholder", "{变量}") 与 MessagesPlaceholder 实例,后者的位置参数就是变量名+ 运算符拼的是消息与消息(合并后两边的变量会自动合并,一次 invoke 全填上)2-1 一个提示词,三种”取结果”方式 ① 用字符串拼接写一句”你是一个 {难度} 级别的编程导师,请解释 {主题}“,直接调用模型; ② 用字符串模板重写同一句,用它的填充方法拿到最终提示词再调用模型; ③ 用聊天模板把同一句拆成”系统消息 + 用户消息”两条,然后分别用三种调用方式把变量填进去,打印每次返回值的类型,并把其中”能直接交给模型”的那一份传给模型、打印回复。
一级 · 思路:字符串模板只能出字符串,聊天模板出的是消息列表——这正是它能直接喂给模型的原因
二级 · 方法:PromptTemplate.from_template(...).format(...);ChatPromptTemplate.from_messages([...]) 的 .invoke({...}) / .format(...) / .format_messages(...)
三级 · 骨架:打印类型会分别得到 ChatPromptValue / str / list;注意前两个接收参数的方式不一样(一个收字典、两个收关键字参数)
2-2 六类元素混着放(并验证一个坑)
构造一个模板,列表里同时放:① 一条写死的系统消息对象、② 一条写死的用户消息对象、③ 一个能生成系统消息的模板(带占位符)、④ 一个能生成用户消息的模板(带占位符)、⑤ 嵌套进来的另一个模板。一次性填变量,打印生成的消息列表(按顺序打印每条的角色和内容),确认嵌套模板的变量也被填上了。
再做一个实验:往写死的消息对象里塞一个 {变量},看填变量时它到底会不会被替换。
一级 · 思路:模板列表的元素可以是”对象""元组""模板”等多种形态,变量会被合并到同一次调用里一起填
二级 · 方法:SystemMessagePromptTemplate.from_template(...) / HumanMessagePromptTemplate.from_template(...) / 嵌套的 ChatPromptTemplate.from_messages([...])
三级 · 骨架:prompt.invoke({"role": ..., "user_input": ...}) 后遍历 filled.messages;实验项的结果是”原样透传”,既不替换也不报错——要变量就得用元组、字符串模板或消息模板
2-3 预填充:一套模板派生多个变体 写一个基础模板:系统消息里有两个变量(部门 + 角色),用户消息是任务。用预填充把”部门 + 角色”固定下来,派生两个不同部门(如 IT 部门 / 销售部门)的变体;每个变体只填”任务”就能拿到消息列表,打印出来对比;最后再验证原模板没被改动——用它派生第三个部门。 被预填的变量在调用时再传一次会怎样?也试一试。
一级 · 思路:把”所有调用里都相同”的变量提前填死,剩下的每次现填;要理解它返回的是新模板而不是改原模板
二级 · 方法:base_template.partial(department="IT 部门", role="技术支持")
三级 · 骨架:变体只要 invoke({"task": "..."});被预填的变量再传也以预填值为准
2-4 用消息占位符管理对话历史 写一个模板:“系统消息(固定)+ 一串对话历史(条数与角色都不定)+ 本次问题(每次不同)“,用两种写法把历史插进去(JSON 形式 / 占位符实例)。 然后准备一段 4 条的假历史,分别传 0 条、2 条、4 条,打印每次生成的消息总条数,验证”传 N 条历史就多 N 条消息”。
一级 · 思路:历史消息的角色是混着的,没法用 ("human", "{x}") 这种写法表达,所以要一个”占位符”
二级 · 方法:("placeholder", "{history}") 或 MessagesPlaceholder(variable_name="history")(也支持位置参数)
三级 · 骨架:template.invoke({"history": [("human", "..."), ("ai", "...")], "question": "..."});元组会被逐个翻译成真正的消息对象
1import os2from dotenv import load_dotenv3from langchain.chat_models import init_chat_model4from langchain_core.prompts import (5 PromptTemplate,6 ChatPromptTemplate,7 MessagesPlaceholder,8 SystemMessagePromptTemplate,9 HumanMessagePromptTemplate,10)11from langchain_core.messages import SystemMessage, HumanMessage12
13load_dotenv(override=True)14
15model = init_chat_model(16 model="deepseek-v4-flash",17 model_provider="openai",18 base_url=os.getenv("DEEPSEEK_BASE_URL"),19 api_key=os.getenv("DEEPSEEK_API_KEY"),20)21
22# ========== 2-1 一个提示词,三种"取结果"方式 ==========23topic, difficulty = "装饰器", "初学者"24
25r0 = model.invoke(f"你是一个{difficulty}级别的编程导师。请用简单易懂的语言解释{topic}。")26print("[字符串拼接]", r0.content)27
28template = PromptTemplate.from_template(29 "你是一个{difficulty}级别的编程导师。请用简单易懂的语言解释{topic}。"30)31r1 = model.invoke(template.format(difficulty=difficulty, topic=topic))32print("[字符串模板]", r1.content)33
34chat_template = ChatPromptTemplate.from_messages([35 ("system", "你是一个{difficulty}级别的编程导师。"),36 ("human", "请用简单易懂的语言解释{topic}。"),37])38value_invoke = chat_template.invoke({"difficulty": difficulty, "topic": topic})39value_format = chat_template.format(difficulty=difficulty, topic=topic)40value_msgs = chat_template.format_messages(difficulty=difficulty, topic=topic)41
42print("invoke ->", type(value_invoke)) # ChatPromptValue43print("format ->", type(value_format)) # str44print("format_messages ->", type(value_msgs)) # list45print("format() 打印出来长这样:")46print(value_format) # System: ... / Human: ...47print("[模型回复]", model.invoke(value_invoke).content)48
49# ========== 2-2 六类元素混着放 ==========50system_msg = SystemMessage("你是一个AI工程师。")51human_msg = HumanMessage("你好!")52system_prompt = SystemMessagePromptTemplate.from_template("你是一个{role}。")53human_prompt = HumanMessagePromptTemplate.from_template("{user_input}")54nested_prompt = ChatPromptTemplate.from_messages([("system", "嵌套提示词")])55
56prompt = ChatPromptTemplate.from_messages([57 system_msg, # 写死的系统消息58 human_msg, # 写死的用户消息59 system_prompt, # 能生成系统消息的模板60 human_prompt, # 能生成用户消息的模板61 nested_prompt, # 嵌套的另一个模板62])63filled = prompt.invoke({"role": "人工智能专家", "user_input": "介绍一下大模型的应用场景"})64for m in filled.messages:65 print(type(m).__name__, "->", m.content)66
67# 坑:写死的消息对象里放占位符,不会被替换68bad = ChatPromptTemplate.from_messages([69 HumanMessage(content="我的问题是:{word}英文怎么说?")70])71print("占位符实验结果:", bad.invoke({"word": "人工智能"}).messages[0].content)72# 输出:我的问题是:{word}英文怎么说? —— 原样透传,不替换也不报错73
74# ========== 2-3 预填充:一套模板派生多个变体 ==========75base_template = ChatPromptTemplate.from_messages([76 ("system", "你是{department}的{role}"),77 ("user", "{task}"),78])79it_template = base_template.partial(department="IT 部门", role="技术支持")80sales_template = base_template.partial(department="销售部门", role="销售顾问")81
82print("IT 变体:", it_template.invoke({"task": "解释退款政策"}).messages[0].content)83print("销售变体:", sales_template.invoke({"task": "为什么每年年底汽车会促销"}).messages[0].content)84
85# 原模板不受影响,还能继续派生86hr_template = base_template.partial(department="人力资源部", role="招聘专员")87print("第三个变体:", hr_template.invoke({"task": "怎么写好一份 JD"}).messages[0].content)88
89# ========== 2-4 用消息占位符管理对话历史 ==========90# 写法1:JSON 形式91template_json = ChatPromptTemplate.from_messages([92 ("system", "你是一个有用的AI助手"),93 ("placeholder", "{conversation}"),94])95pv = template_json.invoke({96 "conversation": [("human", "你好!"), ("ai", "今天我能帮你做什么?")],97})98print("写法1:", [type(m).__name__ for m in pv.messages])99
100# 写法2:占位符实例101template = ChatPromptTemplate.from_messages([102 ("system", "你是一个非常友好的AI助手"),103 MessagesPlaceholder(variable_name="history"),104 ("human", "{question}"),105])106history_pool = [107 ("human", "5 + 2 = ?"), ("ai", "5 + 2 = 7"),108 ("human", "结果再乘以 3 呢?"), ("ai", "等于 21"),109]110for n in (0, 2, 4):111 filled = template.invoke({"history": history_pool[:n], "question": "结果再乘以4呢?"})112 print(f"历史 {n} 条 -> 总共 {len(filled.messages)} 条消息") # 2 / 4 / 63-1 小型提示词工厂 把模板库、模板组合、预填充串起来:
一级 · 思路:模板库管收集、+ 管拼装、预填充管固定值,最后一次性 invoke 交给模型
二级 · 方法:PromptLibrary.CODE_REVIEWER + ask_more,再 .partial(language="Python", focus="边界条件")
三级 · 骨架:msgs = fixed.invoke({"code": "...", "num": "3"}),然后 model.invoke(msgs);两边的变量会合并,一次全填
1# ========== 3-1 小型提示词工厂 ==========2class PromptLibrary:3 """可复用的提示词模板库"""4
5 TRANSLATOR = ChatPromptTemplate.from_messages([6 ("system", "你是专业翻译,精通{source_lang}和{target_lang}"),7 ("user", "翻译以下文本:\n{text}"),8 ])9
10 CODE_REVIEWER = ChatPromptTemplate.from_messages([11 ("system", "你是{language}代码审查专家,重点关注{focus}"),12 ("user", "审查代码:\n{code}"),13 ])14
15
16ask_more = ChatPromptTemplate.from_messages([17 ("user", "另外,请用{num}条要点总结你的建议"),18])19
20combined = PromptLibrary.CODE_REVIEWER + ask_more # 模板组合21fixed = combined.partial(language="Python", focus="边界条件") # 预填充固定变量22
23msgs = fixed.invoke({"code": "def div(a, b): return a / b", "num": "3"})24print("组合后的消息:", [type(m).__name__ for m in msgs.messages])25print("第一条:", msgs.messages[0].content) # 你是Python代码审查专家,重点关注边界条件26print("模型回复:", model.invoke(msgs).content)如果你喜欢,那么欢迎来到我的世界!
了解更多暂未播放



"生活不是等待暴风雨过去,而是学会在雨中跳舞。"—— 塞维涅夫人


