【第二周】RAG与Agent实战13:通用提示词模板 (PromptTemplate)

在之前我们直接将字符串传给模型:

python 复制代码
model.invoke("帮我写一首诗")

这种写法叫做 Zero-shot(零样本)

提示。但在实际应用中,我们需要动态地替换提示词中的内容(比如用户的名字、查询的问题、文档的片段)。如果每次都手动拼接字符串("你好" + name + "..."),不仅代码难看,还容易出错(比如忘记空格、特殊字符转义等)。

LangChain 提供了 PromptTemplate 类,它就像 Python 的 f-string
format 函数的增强版,专门用于管理提示词的结构和变量。

本文将带你掌握两种使用 PromptTemplate 的方式,并重点推荐基于 Chain 链的现代写法

🛠️ 核心概念:什么是 PromptTemplate?

PromptTemplate 是一个模板引擎。它的作用是:

  1. 定义结构:预先写好提示词的固定部分(如:"你是一个翻译助手,请将以下文本翻译成英文:{text}")。
  2. 定义变量 :用 {变量名} 标记出需要动态填充的部分。
  3. 注入数据:在运行时,将具体的数据填入变量,生成最终的提示词。

💻 实战案例:给邻居宝宝起名字

我们要构建一个应用:用户输入姓氏和性别,AI 自动推荐一个符合该姓氏和性别的名字。

方式一:标准写法(手动格式化)

这是最直观的理解方式,适合初学者理解原理,但在复杂场景中不够优雅。

python 复制代码
from langchain_core.prompts import PromptTemplate
from langchain_community.llms.tongyi import Tongyi

# 1. 定义模板
# 使用 {变量名} 作为占位符
prompt_template = PromptTemplate.from_template(
    "我的邻居姓{lastname},刚生了{gender},你帮我起个名字,简单回答。"
)

# 2. 手动注入变量 (类似 python 的 .format)
# 这一步生成了一个普通的字符串
prompt_text = prompt_template.format(lastname="王", gender="儿子")

# 打印看看生成的提示词长什么样
# print(prompt_text) 
# 输出: 我的邻居姓王,刚生了儿子,你帮我起个名字,简单回答。

# 3. 创建模型对象
model = Tongyi(model="qwen-max")

# 4. 调用模型
# 注意:这里传入的是已经格式化好的字符串 input=prompt_text
res = model.invoke(input=prompt_text)

print("👶 推荐名字:", res)

缺点分析

  • 步骤繁琐 :需要先 .format() 生成字符串,再传给 model.invoke()
  • 灵活性差:如果后续要加预处理或后处理逻辑,代码会变得很乱。
  • 类型不安全.format() 只是生成字符串,LangChain 无法检查变量是否匹配。

方式二:基于 Chain 链的写法(推荐 ⭐⭐⭐⭐⭐)

这是 LangChain 现代版本(LCEL, LangChain Expression Language)推荐的写法。它将"模板"和"模型"直接连接成一个链(Chain),实现了一站式调用。

python 复制代码
from langchain_core.prompts import PromptTemplate
from langchain_community.llms.tongyi import Tongyi

# 1. 定义模板 (同上)
prompt_template = PromptTemplate.from_template(
    "我的邻居姓{lastname},刚生了{gender},你帮我起个名字,简单回答。"
)

# 2. 创建模型对象
model = Tongyi(model="qwen-max")

# 3. 构建链 (关键步骤!)
# 使用 | 符号将 template 和 model 连接起来
# 意思是:先运行 template 填充变量 -> 再把结果传给 model 处理
chain = prompt_template | model

# 4. 调用链
# 直接传入一个字典,Key 对应模板中的变量名
res = chain.invoke(input={"lastname": "王", "gender": "儿子"})

print("👶 推荐名字:", res)

优势分析

  • 简洁高效 :一行代码 chain = ... | ... 完成组装,一行代码 invoke 完成执行。
  • 语义清晰| 符号形象地表示了数据流向(数据 -> 模板 -> 模型 -> 结果)。
  • 易于扩展 :如果以后想在模板和模型之间加一个"过滤步骤",只需在中间再加一个 | 组件 即可,无需修改调用逻辑。
  • 统一接口 :无论底层是 LLM、ChatModel 还是其他组件,invoke 的用法都是一致的。

🔍 深度解析:| 操作符的魅力

在 LangChain 中,| 被称为 Runnable Sequence(可运行序列)

当你写下 chain = prompt_template | model 时,LangChain 并没有立即执行任何东西,它只是创建了一个执行计划

当你调用 chain.invoke({...}) 时:

  1. LangChain 接收字典 {"lastname": "王", "gender": "儿子"}
  2. 自动调用 prompt_template,将字典值填入 {lastname}{gender},生成字符串。
  3. 自动将生成的字符串传递给 model.invoke()
  4. 返回模型的最终结果。

这种声明式的编程风格,让构建复杂的 AI 工作流(如 RAG、Agent)变得像搭积木一样简单。


📝 常见变量命名规范

PromptTemplate 中,变量名可以随意取,但为了可读性,建议遵循以下习惯:

  • {query}{question}:用户的提问。
  • {context}:检索到的背景知识(RAG 场景常用)。
  • {history}:聊天历史。
  • {input}:通用输入。
  • {topic} , {style} , {language}:控制生成风格的参数。

例如一个 RAG 的标准模板:

python 复制代码
template = """
基于以下已知信息,简洁和专业地回答用户的问题。
如果无法从中得到答案,请说"根据已知信息无法回答该问题"。

已知信息:
{context}

问题:
{question}
"""
prompt = PromptTemplate.from_template(template)
chain = prompt | model
# 调用时:chain.invoke({"context": "...", "question": "..."})

🚀 总结

本节课我们掌握了 LangChain 中管理提示词的核心工具:

  1. PromptTemplate:用于定义带变量的提示词结构,避免手动拼接字符串。
  2. 两种调用方式
    • 标准写法.format() + model.invoke()(适合理解原理)。
    • 链式写法template | model + chain.invoke()生产环境推荐)。
  3. LCEL 语法 :理解了 | 操作符如何将多个组件串联成一条流水线。

掌握 PromptTemplate 是构建高质量 AI 应用的基础。无论是简单的问答,还是复杂的 RAG 系统,都需要通过精心设计的模板来引导模型输出我们想要的结果。

相关推荐
leonshi5 小时前
使用embedchain快速建立rag知识库,本地大模型
ai·rag·ollama
大流星11 小时前
LangChainJs之基础模型(一)
javascript·langchain
AIOps打工人11 小时前
我以为 LangChain 就是调用大模型,直到我写出第一条 Chain
langchain
大模型真好玩1 天前
LangChain DeepAgents 速通指南(十)—— DeepAgents Code 智能体服务核心源码解读
人工智能·langchain·agent
风雨中的小七2 天前
解密Prompt系列70. 从 MLA 到 CSA,聊聊大模型 Attention 的“瘦身”与“闪送”
prompt
花千树_0102 天前
多工具调用只是开始:用 Regnexe 构建真正会反思的 Java Agent
langchain·agent
大模型真好玩6 天前
LangChain DeepAgents 速通指南(九)—— 生产级智能体框架 DeepAgents Code 源码导读
人工智能·langchain·agent
早点睡啊8 天前
精读 LangChain 官方文档(二)Model 篇:把模型调用升级成工程化推理接口
人工智能·langchain
星始流年10 天前
从 Tool 到 Skill——基于 LangChain 的服务端Skill实现
前端·langchain·agent
codedx11 天前
LangChain 和 LangGraph 构建的 Agent 项目模版
后端·langchain·agent