乐于分享
好东西不私藏

LangChain 的两种模板引擎以及组合模板使用

LangChain 的两种模板引擎以及组合模板使用

点击上方↑↑↑又见清欢”关注我

作者 | 若水如风

来源 | 若水如风

(公众号ID:gh_6f1c1262723c)

               🌿人间有味是清欢🌿

在 LangChain 框架中,提示词模板(Prompt Templates)是管理大模型输入的核心组件。LangChain 提供了两种最基础的模板引擎:字符串提示模板(PromptTemplate)和聊天消息提示模板(ChatPromptTemplate)

一、两种核心模板引擎的区别与适用场景

这两种模板分别对应了不同类型的语言模型接口,其核心区别如下:

1. PromptTemplate(字符串模板)

   - 面向模型:传统的文本补全模型(LLMs),如早期的 GPT-3 DaVinci 等。

   - 底层结构:生成单一的纯文本字符串(String)。它本质上是对 Python f-string 的高级封装,支持变量插值。

   - 思维模型:“文本续写”(Next Token Prediction)。

   - 适用场景:简单的单轮指令任务、文本摘要、翻译或老旧模型的调用。

2. ChatPromptTemplate(聊天消息模板)

   - 面向模型:现代对话模型(Chat Models),如 GPT-4、Claude、通义千问等。

   - 底层结构:生成由不同角色组成的 BaseMessage 对象列表(List[BaseMessage])。

   - 思维模型:“角色扮演与对话”(Role-based Interaction)。

   - 适用场景:多轮对话系统、智能体(Agent)、需要明确区分 System/Human/AI 角色的复杂交互。

二、组合模板的使用方式

在实际开发中,复杂的业务逻辑往往需要将多个子模板拼接在一起。LangChain 提供了多种灵活的模板组合方式:

1. 使用 + 运算符直接拼接

LangChain 支持像处理普通字符串一样,使用 + 号将多个模板或静态文本片段组合起来。

from langchain_core.prompts import PromptTemplate

# 基础模板

prompt_a = PromptTemplate.from_template("请用一句话介绍{topic},要求通俗易懂n")

# 拼接附加条件

prompt_b = prompt_a + "内容不超过{length}个字"

# 最终渲染

final_prompt = prompt_b.format(topic="LangChain", length=100)

# 输出: "请用一句话介绍LangChain,要求通俗易懂n内容不超过100个字"

这种方式同样适用于 ChatPromptTemplate,可以将不同的消息类型(如 SystemMessage、HumanMessage)按顺序相加。

2. 使用 PipelinePromptTemplate 实现模块化复用

当提示词包含多个独立的逻辑模块(如角色设定、示例演示、实际提问)时,可以使用管道模板将它们组装成一个整体,极大提升了提示词的复用性和可维护性。

from langchain_core.prompts import PipelinePromptTemplate, PromptTemplate

# 定义完整的骨架模板

full_template = """{instruction}

{example}

{start}"""

full_prompt = PromptTemplate.from_template(full_template)

# 定义各个子模块模板

instruction_prompt = PromptTemplate.from_template("你正在模拟{person}。")

example_prompt = PromptTemplate.from_template("""下面是一个交互例子:

Q: {example_q}

A: {example_a}""")

start_prompt = PromptTemplate.from_template("""现在,你是一个真实的人,请回答用户的问题!

Q: {input}

A:""")

# 组装管道提示  

pipeline_prompt = PipelinePromptTemplate(

    final_prompt=full_prompt,

    pipeline_prompts=[

        ("instruction", instruction_prompt),

        ("example", example_prompt),

        ("start", start_prompt),

    ]

)

# 一次性传入所有参数进行渲染

print(pipeline_prompt.format(

    person="雷军",

    example_q="你最喜欢的汽车是什么?",

    example_a="小米su7",

    input="你最喜欢的手机是什么?"

))

3. 使用 MessagesPlaceholder 动态插入上下文

在处理带记忆的对话链时,MessagesPlaceholder 充当了一个动态的“占位符”,用于在固定模板中灵活插入历史对话记录(chat_history)。

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

chat_prompt = ChatPromptTemplate.from_messages([

    ("system", "你是一个乐于助人的AI助手"),

    MessagesPlaceholder("chat_history"), # 动态插入历史对话的位置

    ("human", "{input}")                 # 当前用户的提问

])

总结建议:随着 LLM 产业向 Chat Model 全面转移,除非有极其特殊的理由使用 Text Completion 模型,否则在日常开发中应始终优先选择 ChatPromptTemplate。它不仅具备更好的结构化支持和安全性,还能通过 MessagesPlaceholder 等机制轻松应对复杂的多轮对话需求。