006.LangChain Prompt Template

该教程旨在带大家从 0 起步,掌握用 Python 开发大模型应用的技能。若当前内容让你感到晦涩,可回溯本合集的前期文章,降低学习难度。


1. 为什么要用 Prompt Template?

手动拼字符串 Prompt Template
每次都要自己写一大段提示 模板 + 变量,一次写多次用
容易拼错、漏掉空格 结构清晰,可读可维护
难以批量跑不同参数 一个 for 循环就能批量生成

2. 安装与准备

复制代码
pip install langchain langchain-deepseek

3. 单条角色消息模板(System / Human / AI)

LangChain 为三种角色各提供独立模板类:

角色 模板类 format 后返回对象
system SystemMessagePromptTemplate SystemMessage
human HumanMessagePromptTemplate HumanMessage
ai AIMessagePromptTemplate AIMessage

3.1. 创建模板

python 复制代码
from langchain_core.prompts import SystemMessagePromptTemplate, HumanMessagePromptTemplate

# 系统消息模板
sys_tmpl = SystemMessagePromptTemplate.from_template(
    "你是一名专业的翻译人员。"
    "请将内容从 {input_lang} 翻译为 {output_lang}"
)

# 用户消息模板
human_tmpl = HumanMessagePromptTemplate.from_template("{text}")

3.2. 查看变量

python 复制代码
print(sys_tmpl.input_variables)
print(human_tmpl.input_variables)

3.3. 填充变量

python 复制代码
sys_msg = sys_tmpl.format(input_lang="Chinese", output_lang="French")
user_msg = human_tmpl.format(text="你好,世界!")

print(sys_msg)
print(user_msg)

3.4. 发给 DeepSeek 模型

python 复制代码
from langchain_deepseek import ChatDeepSeek

model = ChatDeepSeek(model="deepseek-chat", temperature=0)

response = model.invoke([sys_msg, user_msg])
print(response.content)

4. 批量翻译示例

python 复制代码
tasks = [
    {"input_lang": "Chinese", "output_lang": "French", "text": "你好,世界!"},
    {"input_lang": "Japanese", "output_lang": "German", "text": "こんにちは、地球"},
    {"input_lang": "English", "output_lang": "Spanish", "text": "Hello, Universe!"},
]

for t in tasks:
    msgs = [
        sys_tmpl.format(**t),
        human_tmpl.format(text=t["text"])
    ]
    print(model.invoke(msgs).content)

5. 一体化:ChatPromptTemplate

如果想一次性定义多条消息,可用 ChatPromptTemplate.from_messages

python 复制代码
from langchain_core.prompts import ChatPromptTemplate

chat_tmpl = ChatPromptTemplate.from_messages([
    ("system", "你是一名专业的翻译人员。 请将内容从 {input_lang} 翻译为 {output_lang}"),
    ("human", "{text}"),
])

prompt_value = chat_tmpl.invoke({
    "input_lang": "Chinese",
    "output_lang": "French",
    "text": "你好,LangChain!"
})

# prompt_value 已包含所有变量被填充后的消息
response = llm.invoke(prompt_value.to_messages())
print(response.content)

6. 完整代码

python 复制代码
from langchain_core.prompts import SystemMessagePromptTemplate, HumanMessagePromptTemplate
from langchain_core.prompts import ChatPromptTemplate
from langchain_deepseek import ChatDeepSeek

# 系统消息模板
sys_tmpl = SystemMessagePromptTemplate.from_template(
    "你是一名专业的翻译人员。"
    "请将内容从 {input_lang} 翻译为 {output_lang}"
)

# 用户消息模板
human_tmpl = HumanMessagePromptTemplate.from_template("{text}")

# 查看变量
print(sys_tmpl.input_variables)
print(human_tmpl.input_variables)

# 填充变量
sys_msg = sys_tmpl.format(input_lang="Chinese", output_lang="French")
user_msg = human_tmpl.format(text="你好,世界!")

# 打印消息
print(sys_msg)
print(user_msg)

# 发送给Deepseek,默认会读取环境变量DEEPSEEK_API_KEY
model = ChatDeepSeek(model="deepseek-chat", temperature=0)

response = model.invoke([sys_msg, user_msg])
print(response.content)

# 批量翻译
tasks = [
    {"input_lang": "Chinese", "output_lang": "French", "text": "你好,世界!"},
    {"input_lang": "Japanese", "output_lang": "German", "text": "こんにちは、地球"},
    {"input_lang": "English", "output_lang": "Spanish", "text": "Hello, Universe!"},
]

for t in tasks:
    msgs = [
        sys_tmpl.format(**t),
        human_tmpl.format(text=t["text"])
    ]
    print(model.invoke(msgs).content)

# 一体化:ChatPromptTemplate
chat_tmpl = ChatPromptTemplate.from_messages([
    ("system", "你是一名专业的翻译人员。 请将内容从 {input_lang} 翻译为 {output_lang}"),
    ("human", "{text}"),
])

# prompt_value 已包含所有变量被填充后的消息
prompt_value = chat_tmpl.invoke({
    "input_lang": "Chinese",
    "output_lang": "French",
    "text": "你好,LangChain!"
})

response = model.invoke(prompt_value.to_messages())
print(response.content)

7. 小结

  1. 模板类 = 角色 + 字符串 + 变量占位符 {}
  2. from_template → 创建单角色模板
  3. from_messages → 创建多角色模板
  4. format / invoke → 填变量,得消息列表
  5. 用 for 循环即可批量生成不同参数的请求!
相关推荐
唐青枫36 分钟前
看懂内存地址之后,才算真正入门 Zig:指针、切片与实战
后端
朋克洛德的码农37 分钟前
Go并发-sync包四剑客:Mutex、RWMutex、WaitGroup、Once-从入门到原理
开发语言·后端·golang
fulton38 分钟前
为什么不用现成的开源工具?NovelOps与6大AI写作工具横向对比
后端
fulton42 分钟前
3个月踩坑实录:从想法到270章规划,AI写长篇到底要花多少成本?
后端
fulton43 分钟前
为什么AI写到20章就开始"复制粘贴"自己?创意扰动机制详解
后端
艺艺生辉44 分钟前
从if-else到策略模式
后端·设计模式
fulton44 分钟前
AI写小说失败的第一原因是什么
后端
fulton44 分钟前
这段文字有AI味"到底怎么判断
后端
fulton1 小时前
为什么AI写的小说节奏总是崩
后端
fulton1 小时前
为什么AI写到30章角色就崩人设
后端