提示词模板

模板类型

类型 说明 定位
PromptTemplate 面向纯文本模板,填值后通常得到一条字符串 重点掌握
ChatPromptTemplate 面向聊天模型的多角色模板,填值后得到多条消息 重点掌握
FewShotPromptTemplate 把若干“示例输入-输出”嵌入提示词 了解
PipelinePrompt 把多个子提示按顺序组合 了解

 

PromptTemplate

  

适合的场景是:

  • 摘要、改写、翻译、分类等单轮文本任务
  • 还不需要明确区分 system / user 角色
  • 需要频繁替换少量变量

常用参数

参数 说明
template 模板字符串,内部可包含 {变量名} 占位符
input_variables 调用时需要传入的变量名列表
partial_variables 在模板创建阶段就预先固定的一部分变量

常用方法

方法  返回值 适合场景
format(...) str 最常用,拿到字符串后直接给模型或自己继续拼接
invoke({...}) PromptValue 需要接入 LangChain 链时更自然
partial(...) 新的 PromptTemplate 先固定部分变量,再多次复用

format() 方法

from langchain_core.prompts import PromptTemplate

# ---------- 1. 创建模板(from_template 自动推断 {role}、{question})----------
template = PromptTemplate.from_template(
    "你是一个专业的{role}工程师,请回答我的问题给出回答,我的问题是:{question}"
)
# ---------- 2. format 填入变量,得到「最终一条提示词字符串」----------

prompt = template.format(role="python开发",question="二分查找算法怎么写?")
print(prompt)

invoke()方法

# ---------- 2. 用 invoke 传入变量(字典),得到 PromptValue 对象 ----------
prompt = template.invoke({"role": "python开发", "question": "冒泡排序怎么写?"})
print(prompt)
#text='你是一个专业的python开发工程师,请回答我的问题给出回答,我的问题是:冒泡排序怎么写?'

# ---------- 3. 从 PromptValue 取内容:to_string() 得到整段字符串 ----------
print(prompt.to_string())
# 你是一个专业的python开发工程师,请回答我的问题给出回答,我的问题是:冒泡排序怎么写?

# ---------- 4. to_messages():转成「消息列表」,可接入需要多角色消息的链 ----------
print(prompt.to_messages())
# [HumanMessage(content='你是一个专业的python开发工程师,请回答我的问题给出回答,我的问题是:冒泡排序怎么写?', additional_kwargs={}, response_metadata={})]

partial()方法

# ---------- 2. partial(role="python开发"):固定 role,得到「新模板」----------
# 新模板只剩 {question} 需要填,适合多轮只换问题、不换角色的场景
partial = template.partial(role="python开发")
print(partial)

# ---------- 3. 对新模板 format,只传 question 即可 ----------
prompt = partial.format(question="冒泡排序怎么写?")
print(prompt)

创建方式

PromptTemplate

  • 构造函数:手动指定 template 和 input_variables
  • from_template(...):由 LangChain 自动推断变量名
from langchain_core.prompts import PromptTemplate

# 方式一:构造函数
template = PromptTemplate(
    template="你是一个专业的{role}工程师,请回答:{question}",
    input_variables=["role", "question"]
)
prompt = template.format(role="python开发", question="快速排序怎么写?")

# 方式二:from_template
template = PromptTemplate.from_template("请给我一个关于{topic}的{type}解释。")
prompt = template.format(topic="量子力学", type="详细")
from langchain_core.prompts import PromptTemplate

template = PromptTemplate.from_template(
    "你是一个专业的{role}工程师,请回答我的问题给出回答,我的问题是:{question}"
)

# ---------- 2. format 填入变量,得到最终一条字符串 ----------
prompt = template.format(role="python开发",question="快速排序怎么写")
print(prompt)

组合多个模板

from langchain_core.prompts import PromptTemplate

template = (
    PrompTemplate.from_tempplate("请用一句话介绍{topic},要求通俗易懂\n")
    + "内容不超过{length}个字"
)
prompt = template.format(topic="LangChain", length=)
print(prompt)

partial_variables 与 partial()

from langchain_core.prompts import PromptTemplate
from datetime import datetime

import time

# ---------- 1. 创建时用 partial_variables 固定「时间」----------
# 写法一:构造函数。input_variables 只写「后续 format 还要传」的变量
#(这里只剩 question;time 已用 partial_variables 固定)
template1 = PromptTemplate(
    template="现在时间是:{time},请对我的问题给出答案,我的问题是{question}",
    input_variables= ["question"],
    partial_varibale= {"time": datetime.now().strftime("%y-%m-%d %H:%M:S")},
)

# 写法二(等价):from_template(..., partial_variables={...})
template2 = PromptTemplate.from_template(
    "现在时间是:{time},请对我的问题给出答案,我的问题是:{question}",
    partial_variables={"time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
)

prompt1 = template1.format(question="今天是几号?")
print(prompt1)

# ---------- 2. 用 partial() 方法:先有模板,再「固定一部分」得到新模板 ----------
template2 = PromptTemplate.from_template(
    "现在时间是:{time},请对我的问题给出答案,我的问题是:{question}"
)
partial = template2.partial(time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
prompt2 = partial.format(question="今天是几号?")
print(prompt2)

# ---------- 3. 构造函数里也可用 partial_variables ----------
# 若 format 时仍传入 foo,会覆盖 partial_variables 里的值;不传则用预设的 "hello"
template3 = PromptTemplate(
    template="{foo} {bar}",
    input_variables=["foo", "bar"],
    partial_variables={"foo": "hello"},
)
print(template3.format(foo="li4", bar="world"))  # li4 world
print(template3.format(bar="world"))  # hello world

ChatPromptTemplate

PromptTemplate 更适合“单条文本输入”,那么 ChatPromptTemplate 就是为“聊天模型场景”准备的模板类.简单理解成:“面向多角色消息的模板系统”

常用参数

类型 说明 选择
元组 ("system", "你是{name}") 最简洁,教学和业务代码里都很常见
字典 {"role": "system", "content": "你是{name}"} 更贴近 OpenAI 风格 JSON,方便和网关数据结构对齐
Message 类 SystemMessage(content="你是{name}") 最显式,角色最清楚,适合教学和复杂场景
MessagesPlaceholder 在模板中预留一段“消息列表占位”  
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.messages import SystemMessage, HumanMessage

#    元组定义
chatPromptTemplate = ChatPromptTemplate(
    [
        ("system","你是一个AI开发工程师,你的名字是{name}。"),
         ("human", "你能帮我做什么?"),
        ("ai", "我能开发很多{thing}。"),
        ("human", "{user_input}"),
    ]
)
prompt = chatPromptTemplate.format_messages(
     name="小谷AI", thing="AI", user_input="7 + 5等于多少"
)
print(prompt)

# 字典定义
# ---------- 方式一:from_messages ----------
chat_prompt = ChatPromptTemplate.from_message(
    [
        {"role": "system", "content": "你是AI助手,你的名字叫{name}。"},
        {"role": "user", "content": "请问:{question}"}
    ]
)

message = chat_prompt.format_messages(name="小问", question="什么是LangChain")
print("from_messages:", message)

# ---------- 方式二:构造函数(传入同样字典列表,效果一致)----------
chat_prompt2 = ChatPromptTemplate(
    [
        {"role": "system", "content": "你是AI助手,你的名字叫{name}。"},
        {"role": "user", "content": "请问:{question}"},
    ]
)
message2 = chat_prompt2.format_messages(name="小问", question="什么是LangChain")
print("构造函数:", message2)

#  ----------         方式三:Message 类    ----------------------
# 用 Message 类列表定义模板:系统消息 + 用户消息,内容里仍可带占位符 {name}、{question}
chat_prompt = ChatPromptTemplate(
    [
        SystemMessage(content="你是AI助手,你的名字叫{name}。"),
        HumanMessage(content="请问:{question}"),
    ]
)
message = chat_prompt.format_messages(name="亮仔", question="什么是LangChain")
print(message)



        

常用方法

方法 返回值 理解
format_messages(...) List[BaseMessage] 我要的是“消息列表
invoke({...}) ChatPromptValue 我要的是“PromptValue 对象"
format(...) str 我要的是“纯字符串"
from langchain_core.prompts import ChatPromptTemplate

chat_prompt = ChatPromtTemplate.from_messages([
    {"system", "你是一个{role},请回答我的问题"},
    {"human","请回答:{question}"}
])
# 方式一:得到消息列表
messages = chat_prompt.format_messages(
    role="python开发工程师",
    question="堆排序怎么写"
)
result = model.invoke(messages)

# 方式二:得到 ChatPromptValue
prompt_value = chat_prompt.invoke({
    "role": "python开发工程师",
    "question": "快速排序怎么写"
})
result = model.invoke(prompt_value)

# 方式三:得到纯字符串
prompt_str = chat_prompt.format(
    role="python开发工程师",
    question="快速排序怎么写"
)
print(prompt_str)

对实际项目来说,建议优先采用前两种:

  • format_messages(...) -> model.invoke(messages)
  • invoke({...}) -> model.invoke(prompt_value)

`from_messages([...])` 是创建 `ChatPromptTemplate` 的主流写法,最适合教学和实际项目阅读。

创建方式

  • ChatPromptTemplate.from_messages([...])
  • ChatPromptTemplate([...])
from langchain_core.prompts import ChatPromptTemplate
messages = [
    ("system","你是一个{role},请回答我提出的问题"),
    ("human","请回答:{question}")
]

chat_prompt1 = ChatPromptTemplate.from_message(messages)
chat_prompt2 = ChatPromptTemplate(messages)
# 经验上更推荐优先使用 from_messages(...),因为可读性更好,也更符合官方文档和社区示例的主流写法。

print(chat_prompt1.format_messages(role="python开发工程师", question="堆排序怎么写"))
print(chat_prompt2.format_messages(role="python开发工程师", question="堆排序怎么写"))

使用构造函数创建 ChatPromptTemplate

from langchain_core.prompts import ChatPromptTemplate
import os
from langchain.chat_models import init_chat_model
from dotenv import load_dotenv

load_dotenv()

chatpromptTemplate = ChatPromptTemplate(
    [
        ("system","你是一个AI开发工程师,你的名字是{name}"),
        ("human", "你能帮我做什么?"),
        ("ai", "我能开发很多{thing}。"),
        ("human", "{user_input}")
    ]
)

prompt = chatPromptTemplate.format_messages(
    name="小谷AI",thing="AI", user_input="7 + 5等于多少"
)
print(prompt)


llm = init_chat_model(
    model="qwen-plus",
    model_provider="openai",
    api_key=os.getenv("aliQwen-api"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)
print()


result = llm.invoke(prompt)
print(result.content)




    
    
    
    
    

MessagesPlaceholder

作用:  就是在模板里先留出一段“消息列表的位置”,等真正调用时再把历史对话整块塞进去

写法: 

  • 显式写法MessagesPlaceholder("memory")
  • 隐式写法("placeholder", "{memory}")
from langchian_core.messages import HumanMessage,AIMessages
from langchai_core.prompts import ChatPromptTemplate,MessagesPlaceholder

#    显式写法
prompt1 = ChatPromptTemplate.from_messages([
    ("system","你是一个资深的Python应用开发工程师,请认真回答我提出的Python相关的问题"),
    MessagesPlaceholder("memory"),
    ("human","{question}")
]
    
# 隐式写法
prompt2 = ChatPromptTemplate.fromMesssages(
    [
        ("system","你是一个资深的Python应用开发工程师,请认真回答我提出的Python相关的问题"),
        ("placeholder","{memory}"),
        ("human", "{question}"),
    ]
)
#              prompt2.invoke({    
prompt_value = prompt.invoke({
    "memory":[
        HUmanMessage(content="我的名字叫亮仔,是一名程序员"),
        AIMessage(content="好的,亮仔你好")
    ],
    "question": "请问我的名字叫什么?"
})
print(prompt_value.to_string())    
    

    

从文件加载提示词 

 1.从json中加载

json:

{
  "_type": "prompt",
  "input_variables": ["name", "what"],
  "template": "请{name}讲一个{what}的故事"
}

加载:

from langchain_core.prompts import load_prompt

template = load_prompt("prompt.json", encoding="utf-8")
print(template.format(name="张三", what="搞笑"))

2. 从yaml加载

# 从 YAML 加载提示词模板,API 与 load_prompt("prompt.json") 一致
from langchain_core.prompts import load_prompt

template = load_prompt("prompt.yaml", encoding="utf-8")
print(template.format(name="年轻人", what="滑稽"))
#

 

posted @ 2026-04-30 11:12  幻影之舞  阅读(5)  评论(0)    收藏  举报