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 循环即可批量生成不同参数的请求!
相关推荐
GreenTea3 小时前
GrokBot 核心成员 Lauren Tan:每月交付 2000 个 PR 的人,是怎么用 AI 的
前端·后端·架构
码事漫谈3 小时前
FDE:一个缩写,两种命运
后端
名字还没想好☜5 小时前
Go context.AfterFunc 实战(Go 1.21):context 一取消就自动跑清理,告别手写 goroutine 监听 Done
后端·golang·go
明月_清风5 小时前
为什么最近开始关注 JEV?几个实战案例告诉你答案
人工智能·后端
GetcharZp6 小时前
5 分钟拥有自己的 S3:RustFS 上手(MinIO 的 Rust 替代,Apache 2.0 可商用)
后端
行百里er7 小时前
Redis 版本演进、新特性与协议那些事儿
redis·后端
Joy T7 小时前
Spring AI 2.0 Agent 进阶:Memory、State 与 Context Engineering 常见技术全景
java·人工智能·后端·spring·agent入门·agent state
打工仔折腾 AI8 小时前
FastAPI 从本机到生产服务器:Nginx+Gunicorn+Uvicorn 完整部署实录
人工智能·后端·python·nginx·fastapi·gunicorn
IT_陈寒8 小时前
Java空指针这次真把我坑惨了
前端·人工智能·后端