Langchain Template 全面指南

作者:前端小东日期:2025/11/17

概述

LangChain Template 是 LangChain 提示工程的核心组件,用于动态生成模型的输入。

🎯 Template 的核心概念:

Template 本质是一个带有占位符的文本字符串,这些占位符会在运行时被具体的值填充。它的主要目的是将提示逻辑业务数据分离。

模板分类

1. 🎯 基础模板类(Core Templates)

(1) PromptTemplate

最基础的文本模板

1from langchain.prompts import PromptTemplate
2
3# 创建模板的两种方式
4# 方式1: 使用 from_template (推荐)
5template = PromptTemplate.from_template("请把{text}翻译成{language}")
6result = template.format(text="Hello", language="中文")
7print(result)  # 输出: "请把Hello翻译成中文"
8
9# 方式2: 传统创建方式
10template = PromptTemplate(
11    input_variables=["text", "language"],
12    template="请把{text}翻译成{language}"
13)
14
15# 实际应用示例
16translation_template = PromptTemplate.from_template(
17    "将以下{source_lang}文本翻译成{target_lang}:{text}"
18)
19translation_result = translation_template.format(
20    source_lang="英文",
21    target_lang="中文", 
22    text="Hello, how are you?"
23)
24

(2) ChatPromptTemplate

聊天消息模板(最常用)

1from langchain.prompts import ChatPromptTemplate
2
3# 创建聊天提示模板
4chat_prompt = ChatPromptTemplate.from_messages([
5    ("system", "你是一个{role}"),
6    ("human", "请回答:{question}")
7])
8
9# 格式化模板
10messages = chat_prompt.format_messages(
11    role="数学老师",
12    question="什么是勾股定理?"
13)
14
15# 实际应用:客服机器人模板
16customer_service_prompt = ChatPromptTemplate.from_messages([
17    ("system", "你是{company}的客服代表,专门处理{department}问题"),
18    ("human", "我遇到了一个问题:{issue_description}"),
19    ("ai", "我很理解您的情况,让我来帮您解决。"),
20    ("human", "具体的细节是:{details}")
21])
22

2. 👥 消息模板类(Message Templates)

这些是 ChatPromptTemplate 的组成部分:

1from langchain.prompts import (
2    SystemMessagePromptTemplate,
3    HumanMessagePromptTemplate,
4    AIMessagePromptTemplate,
5    FunctionMessagePromptTemplate
6)
7
8# 创建各种消息模板
9system_template = SystemMessagePromptTemplate.from_template(
10    "你是{role},具有{expertise}专业知识"
11)
12human_template = HumanMessagePromptTemplate.from_template(
13    "我的问题是:{question}"
14)
15ai_template = AIMessagePromptTemplate.from_template(
16    "根据我的知识,{answer}"
17)
18
19# 组合使用
20chat_prompt = ChatPromptTemplate.from_messages([
21    system_template, 
22    human_template,
23    ai_template
24])
25
26# 完整示例:编程助手
27programming_prompt = ChatPromptTemplate.from_messages([
28    SystemMessagePromptTemplate.from_template(
29        "你是{language}编程专家,擅长{domain}开发"
30    ),
31    HumanMessagePromptTemplate.from_template(
32        "请帮我解决这个编程问题:{problem}"
33    ),
34    AIMessagePromptTemplate.from_template(
35        "我会按照以下思路解决:{approach}"
36    ),
37    HumanMessagePromptTemplate.from_template(
38        "具体实现代码是?"
39    )
40])
41

3. 🎪 高级模板类(Advanced Templates)

(7) FewShotPromptTemplate

少样本学习模板

1from langchain.prompts import FewShotPromptTemplate, PromptTemplate
2
3# 定义示例数据
4examples = [
5    {
6        "input": "The weather is nice today", 
7        "output": "今天天气很好"
8    },
9    {
10        "input": "I love programming", 
11        "output": "我喜欢编程"
12    },
13    {
14        "input": "The meeting starts at 3 PM", 
15        "output": "会议下午三点开始"
16    }
17]
18
19# 定义单个示例的模板
20example_template = PromptTemplate.from_template(
21    "英文: {input}\n中文: {output}"
22)
23
24# 创建少样本提示模板
25few_shot_prompt = FewShotPromptTemplate(
26    examples=examples,
27    example_prompt=example_template,
28    prefix="请根据以下示例将英文翻译成中文:",
29    suffix="英文: {input}\n中文:",
30    input_variables=["input"]
31)
32
33# 使用示例
34result = few_shot_prompt.format(input="Thank you for your help")
35print("=== 生成的提示 ===")
36print(result)
37
38# 实际应用:情感分析少样本模板
39sentiment_examples = [
40    {"text": "这个产品太棒了!", "sentiment": "正面"},
41    {"text": "服务很差,很不满意", "sentiment": "负面"},
42    {"text": "还可以,一般般", "sentiment": "中性"}
43]
44
45sentiment_template = FewShotPromptTemplate(
46    examples=sentiment_examples,
47    example_prompt=PromptTemplate.from_template(
48        "文本: {text}\n情感: {sentiment}"
49    ),
50    prefix="分析以下文本的情感倾向:",
51    suffix="文本: {text}\n情感:",
52    input_variables=["text"]
53)
54

(8) FewShotChatMessagePromptTemplate

聊天版的少样本模板

1from langchain.prompts import FewShotChatMessagePromptTemplate, ChatPromptTemplate
2
3# 定义聊天示例
4chat_examples = [
5    {
6        "input": "今天的天气怎么样?",
7        "output": "我无法获取实时天气信息,请查看天气预报应用。"
8    },
9    {
10        "input": "现在几点了?",
11        "output": "我无法获取当前时间,请查看您的设备时钟。"
12    },
13    {
14        "input": "我的快递到哪里了?", 
15        "output": "我无法查询物流信息,请使用快递公司的官方应用查询。"
16    }
17]
18
19# 创建示例模板
20example_prompt = ChatPromptTemplate.from_messages([
21    ("human", "{input}"),
22    ("ai", "{output}")
23])
24
25# 创建少样本聊天模板
26few_shot_chat = FewShotChatMessagePromptTemplate(
27    examples=chat_examples,
28    example_prompt=example_prompt
29)
30
31# 组合到完整提示中
32final_prompt = ChatPromptTemplate.from_messages([
33    ("system", "你是一个有帮助的AI助手,请礼貌地回答用户问题。"),
34    few_shot_chat,
35    ("human", "{user_input}")
36])
37
38# 使用示例
39messages = final_prompt.format_messages(
40    user_input="我的银行余额是多少?"
41)
42

4. 🧩 特殊用途模板

(9) MessagesPlaceholder

消息占位符(用于动态插入消息)

1from langchain.prompts import MessagesPlaceholder, ChatPromptTemplate
2
3# 创建带消息占位符的模板
4prompt_with_history = ChatPromptTemplate.from_messages([
5    ("system", "你是专业的{expert_role}"),
6    MessagesPlaceholder(variable_name="chat_history"),
7    ("human", "{current_question}")
8])
9
10# 模拟对话历史
11chat_history = [
12    {"role": "human", "content": "什么是Python?"},
13    {"role": "ai", "content": "Python是一种编程语言。"}
14]
15
16# 格式化模板
17messages = prompt_with_history.format_messages(
18    expert_role="编程教师",
19    chat_history=chat_history,
20    current_question="Python有什么特点?"
21)
22
23# 实际应用:带记忆的对话系统
24memory_prompt = ChatPromptTemplate.from_messages([
25    ("system", """你是{assistant_name},具有以下特点:
26    - 专业领域: {expertise}
27    - 回答风格: {style}
28    - 语言: {language}"""),
29    
30    MessagesPlaceholder(variable_name="conversation_history"),
31    ("human", "{current_input}")
32])
33

🔗 Template 关系图谱

1PromptTemplate (基类)
23    ├── ChatPromptTemplate (组合多个消息)
4    │       ├── SystemMessagePromptTemplate
5    │       ├── HumanMessagePromptTemplate  
6    │       ├── AIMessagePromptTemplate
7    │       └── FunctionMessagePromptTemplate
89    ├── FewShotPromptTemplate (包含example_prompt)
1011    └── FewShotChatMessagePromptTemplate (专门用于聊天)
12

🎯 核心关系说明

关系1:包含关系

1# FewShotPromptTemplate 包含 PromptTemplate
2examples = [
3    {"input": "hello", "output": "你好"},
4    {"input": "goodbye", "output": "再见"}
5]
6
7example_prompt = PromptTemplate.from_template(
8    "输入: {input}\n输出: {output}"
9)
10
11few_shot_prompt = FewShotPromptTemplate(
12    example_prompt=example_prompt,  # 包含关系
13    examples=examples,
14    prefix="翻译任务:",
15    suffix="输入: {input}\n输出:",
16    input_variables=["input"]
17)
18
19# ChatPromptTemplate 包含 MessagePromptTemplates
20system_template = SystemMessagePromptTemplate.from_template("系统: {role}")
21human_template = HumanMessagePromptTemplate.from_template("用户: {question}")
22
23chat_prompt = ChatPromptTemplate.from_messages([
24    system_template,    # 包含关系
25    human_template      # 包含关系
26])
27

关系2:组合关系

1from langchain.prompts import ChatPromptTemplate, FewShotChatMessagePromptTemplate
2
3# 创建少样本部分
4few_shot_examples = [
5    {"input": "如何学习编程?", "output": "建议从基础语法开始..."},
6    {"input": "最好的编程语言?", "output": "这取决于你的目标..."}
7]
8
9few_shot_section = FewShotChatMessagePromptTemplate(
10    example_prompt=ChatPromptTemplate.from_messages([
11        ("human", "{input}"),
12        ("ai", "{output}")
13    ]),
14    examples=few_shot_examples
15)
16
17# FewShotChatMessagePromptTemplate 作为 ChatPromptTemplate 的一部分
18final_prompt = ChatPromptTemplate.from_messages([
19    ("system", "你是{teacher_type}老师"),
20    few_shot_section,  # 组合关系
21    MessagesPlaceholder(variable_name="history"),  # 组合关系
22    HumanMessagePromptTemplate.from_template("{current_input}")
23])
24
25# 使用组合模板
26formatted_messages = final_prompt.format_messages(
27    teacher_type="编程",
28    history=[],
29    current_input="如何调试代码?"
30)
31

🛠️ 实际使用场景对比

场景1:简单文本生成 → PromptTemplate

1# 诗歌生成
2poem_template = PromptTemplate.from_template("""
3请以{style}风格写一首关于{topic}的诗。
4
5要求:
6- 意境: {mood}
7- 长度: {length}
8- 语言: {language}
9
10诗歌:
11""")
12
13poem_prompt = poem_template.format(
14    style="浪漫",
15    topic="春天", 
16    mood="欢快",
17    length="八句",
18    language="中文"
19)
20

场景2:聊天对话 → ChatPromptTemplate + MessageTemplates

1# 专业咨询对话
2system_msg = SystemMessagePromptTemplate.from_template("""
3你是{profession}顾问,具有以下资质:
4- 经验: {experience}
5- 专长: {specialization} 
6- 认证: {certifications}
7""")
8
9human_msg = HumanMessagePromptTemplate.from_template("""
10我的咨询问题是:{question}
11
12背景信息:
13{context}
14""")
15
16chat_prompt = ChatPromptTemplate.from_messages([system_msg, human_msg])
17
18# 使用示例
19messages = chat_prompt.format_messages(
20    profession="法律",
21    experience="10年",
22    specialization="合同法",
23    certifications="律师执业证",
24    question="合同违约如何处理?",
25    context="甲方未按约定时间付款"
26)
27

场景3:示例学习 → FewShotPromptTemplate

1# 代码生成少样本学习
2code_examples = [
3    {
4        "requirement": "计算列表平均值",
5        "code": "def calculate_average(numbers):\n    return sum(numbers) / len(numbers)"
6    },
7    {
8        "requirement": "反转字符串", 
9        "code": "def reverse_string(s):\n    return s[::-1]"
10    }
11]
12
13code_template = FewShotPromptTemplate(
14    examples=code_examples,
15    example_prompt=PromptTemplate.from_template(
16        "需求: {requirement}\n代码: {code}"
17    ),
18    prefix="请根据示例编写Python代码:",
19    suffix="需求: {requirement}\n代码:",
20    input_variables=["requirement"]
21)
22
23code_prompt = code_template.format(
24    requirement="检查字符串是否是回文"
25)
26

场景4:复杂聊天 + 示例 → 组合使用

1# 1. 创建少样本部分
2few_shot_examples = [
3    {
4        "situation": "用户询问个人隐私信息",
5        "response": "出于安全考虑,我无法访问或提供个人隐私信息。"
6    },
7    {
8        "situation": "用户要求违法帮助", 
9        "response": "抱歉,我无法提供任何违法或不道德行为的帮助。"
10    }
11]
12
13few_shot_section = FewShotChatMessagePromptTemplate(
14    example_prompt=ChatPromptTemplate.from_messages([
15        ("human", "情境: {situation}"),
16        ("ai", "回复: {response}")
17    ]),
18    examples=few_shot_examples
19)
20
21# 2. 创建完整聊天提示
22final_prompt = ChatPromptTemplate.from_messages([
23    SystemMessagePromptTemplate.from_template("""
24    你是{assistant_name},安全准则:
25    - {safety_guidelines}
26    - 始终遵守{regulations}
27    """),
28    
29    few_shot_section,  # 包含少样本示例
30    
31    MessagesPlaceholder(variable_name="conversation_history"),  # 动态历史
32    
33    HumanMessagePromptTemplate.from_template("当前查询: {current_query}")
34])
35
36# 使用示例
37messages = final_prompt.format_messages(
38    assistant_name="安全助手",
39    safety_guidelines="不分享个人信息,不提供违法建议",
40    regulations="AI使用规范",
41    conversation_history=[],
42    current_query="你能告诉我别人的电话号码吗?"
43)
44

📝 使用频率总结

Template 类型用途使用频率
PromptTemplate基础文本模板⭐⭐⭐⭐
ChatPromptTemplate聊天消息组合⭐⭐⭐⭐⭐
SystemMessagePromptTemplate系统消息⭐⭐⭐⭐
HumanMessagePromptTemplate用户消息⭐⭐⭐⭐
AIMessagePromptTemplateAI消息⭐⭐⭐
FewShotPromptTemplate少样本学习⭐⭐⭐
FewShotChatMessagePromptTemplate聊天少样本⭐⭐
MessagesPlaceholder动态消息占位⭐⭐

总结

LangChain Template 提供了强大而灵活的提示工程能力:

  • 🎯 精准控制: 通过模板精确控制模型输入,确保提示的一致性
  • ♻️ 可复用性: 一次创建,多处使用,提高开发效率
  • 🔧 模块化: 像搭积木一样组合模板,支持复杂场景
  • 🛡️ 可靠性: 类型安全和错误检查,减少运行时错误
  • 🚀 高效开发: 加速 AI 应用开发流程,降低维护成本

掌握 LangChain Template 是构建高质量大模型应用的关键技能,它让提示工程从艺术走向工程化。


Langchain Template 全面指南》 是转载文章,点击查看原文


相关推荐


蓝桥杯备战记录:图论中关键边识别与DFS应用
akai1472025/11/16

一、问题背景与核心思路 问题描述 给定一个无向连通图和n对点,要求找到一条边,使得删除该边后所有n对点之间的路径都不连通。这类问题在图论中被称为关键边(Bridge)​或必经边问题。 核心算法思想 ​公共边识别​:寻找所有n对点路径上的公共边​边计数法​:统计每条边被多少对点的路径所经过​关键边判定​:计数等于n的边即为所求的关键边 二、DFS实现关键边识别 算法框架 vector<int> adj[MAXN]; // 邻接表存图 int edge_count[MAXN][MA


Jetpack Compose Navigation 2.x 详解
雨白2025/11/15

简单的页面跳转 在 Compose 中,我们可以借助 State 实现一个非常简单的屏幕内容切换效果。 class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent {


深度测评解析 CANN:从 ACL 到自定义算子,解锁昇腾计算的全部潜能
wei_shuo2025/11/14

深度测评解析 CANN:从 ACL 到自定义算子,解锁昇腾计算的全部潜能 CANN 核心价值解读:统一计算底座与全场景适配 ✅端到端栈级支持:CANN 覆盖驱动、运行时、算子加速库、编译器及上层框架适配的全套工具链,大幅降低模型向昇腾硬件移植的工程成本 ✅开发者定制接口:ACL 提供 C/C++、Python 双接口,兼顾快速原型验证与生产级接入;AOL(aclnn)算子性能强,支持两段式调用,方便做内存、离线编译优化 ✅可控资源调度与并发:通过 Device/Context/Stream


Python 的内置函数 input
IMPYLH2025/11/13

Python 内建函数列表 > Python 的内置函数 input Python 的内置函数 input() 是一个用于获取用户输入的标准函数,它会暂停程序执行,等待用户在控制台输入内容并按回车键确认。这个函数在交互式程序和需要用户参与的脚本中非常有用。 基本用法 input() 函数的基本语法如下: user_input = input([prompt]) 其中: prompt 是一个可选参数,用于显示提示信息,告诉用户需要输入什么内容函数返回用户输入的内容,以字符串形式保存


C++笔记——STL list
报错小能手2025/11/11

1. list 基本概念 什么是list? 双向链表:每个元素包含指向前后元素的指针,形成链式结构 核心特性(与vector/deque对比): 特性vectordequelist随机访问✅ O(1)✅ O(1)❌ O(n)头部插入删除❌ O(n)✅ O(1)✅ O(1)尾部插入删除✅ O(1)✅ O(1)✅ O(1)中间插入删除❌ O(n)❌ O(n)✅ O(1)内存布局连续分段连续完全分散 2. list 的基本使用 头文件和声明: cpp #include <list


各个系统的 docker安装
Qayrup2025/11/9

docker简介 Docker 是一组平台即服务的产品,它基于操作系统层级的虚拟化技术,将软件与其依赖项打包为容器。本文将介绍在 CentOS 8 操作系统中安装 Docker 服务,并解决镜像源无法访问的问题。 centos8 安装 1 检查版本 Docker 要求 CentOS 的内核版本至少高于 3.10,可以用命令uname -r查看 2 安装 Docker 所需依赖 //执行命令yum install -y yum-utils device-mapper-persistent-dat


理解PostgreSQL中的数据块
WarriorTan2025/11/7

PG的数据块大小,默认是8KB,可以调整为16K或者 32K吗? PostgreSQL的数据块大小默认为8KB,可以将其调整为16KB或32KB。数据块大小需要在‌编译安装‌PostgreSQL时通过配置参数指定,例如使用configure.ac中的--with-blocksize选项进行设置 。需要注意的是,一旦数据库初始化完成,数据块大小就无法再修改 。 数据块的行指针都包括哪些信息? 具体来说,行指针是一个32位的数字,其结构被划分为三个部分: 行内容的偏移量‌:占用15位(bit


C#.NET Random 深入解析:随机数生成原理与最佳实践
唐青枫2025/11/4

简介 Random 是 .NET 中 System 命名空间提供的一个类,用于生成伪随机数。它广泛应用于需要随机化操作的场景,如生成随机数据、模拟、游戏开发或测试用例生成。 伪随机数生成 在计算机中,Random 类用于生成伪随机数,这些数值在一定程度上看起来是随机的,但它们实际上是通过数学公式从一个初始种子值计算得到的,因此称之为“伪随机数”。 广泛应用 Random 类常用于游戏开发、模拟、加密等场景。在许多应用中,生成随机数或随机选择某个元素是常见的需求。 注意: Random


设计模式的原则有哪些?
你的人类朋友2025/10/31

前言 温馨提示 对于原本不太熟悉设计模式的人来说(比如在下),这些内容是需要一定的时间消化的!慢慢来 😆 👋 你好啊,我是你的人类朋友! 今天说说设计模式的原则有哪些! 在开发用户权限系统时,你是否遇到过这样的问题: 当创建新的管理员用户类型时,发现它无法兼容普通用户的所有方法,导致系统中到处需要判断用户类型? 让我们了解设计模式的基本原则,构建更健壮的软件架构~ 健壮是啥意思? 健壮是指软件系统在面对变化和复杂性时,能够保持稳定运行的能力。也就是耐造的能力。 正文 SOLID 原则


Java的包装类
麦麦鸡腿堡2025/10/29

包装类(Wrapper)的分类: 1.针对八种基本数据类型相应的引用类型--包装类 2.有了类的特点,就可以调用类中的方法 *黄色框内都是number的子类,number是Ojbect子类,黑色框中的包装类是独立的,Ojbect子类 //boolean-Boolean-父类Object //char-Character-父类Object //byte-Byte-父类number-父类Object //int-Integer-父类number-父类Object //long-Long

首页编辑器站点地图

Copyright © 2025 聚合阅读

License: CC BY-SA 4.0