微信扫码
添加专属顾问
我要投稿
掌握LangChain提示词模板,轻松构建高效AI对话系统。 核心内容: 1. 提示词模板的基本概念与格式化原理 2. 字符串提示词模板的语法与应用场景 3. 聊天提示词模板的三种角色配置方法
提示词模板提供了一种结构化的方式来构建和管理提示词,可以将用户输入的内容格式化后传递给语言模型,帮助模型理解上下文并生成相关且连贯的输出。
其格式为:
固定文本{变量}
通过使用模板将实际值替换这些变量,动态生成最终的提示词。
PromptTemplate提示词模板用于创建简单的提示词,可以内嵌任意数量的变量,通过变量值格式化模板内容。
主要是为标准的文本生成任务设计的,用于生成非对话式的提示词,可以用于各种文本生成任务,例如文本撰写、摘要生成等。
其基础语法格式如下:
PromptTemplate.from_template(
"固定文本{变量}"
)
# 或
PromptTemplate(
input_variables=[变量1,...],
input_types={变量数据类型},
partial_variables={部分填充}, # 预先填充(部分填充)模板中的某些变量
template="固定文本:{变量1,...}"
)
示例代码如下:
from langchain_core.prompts import PromptTemplate # 引入字符串提示词模板
# 定义提示词模板
prompt_template = PromptTemplate.from_template(
"给我介绍一下{content}是什么?"
)
# 通过变量content变量格式化提示词模板
prompt=prompt_template.format(content="langchain")
print(prompt)
运行结果为:
给我介绍一下langchain是什么?
ChatPromptTemplate提示词模板用于构建聊天对话型应用提示词模板,为对话系统设计,用于生成对话式的提示词。
主要用于聊天机器人、对话模型等需要持续对话的场景。
其语法格式如下:
ChatPromptTemplate.from_messages([
("角色名","内容")
])
主要有三种角色:
示例代码如下:
from langchain_core.prompts import ChatPromptTemplate # 引入聊天提示词模板
# 定义提示词模板
prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一位人工智能助手,你的名字是{name}"),
("human", "你好"),
("ai", "谢谢"),
("human", "{user_input}")
])
print(prompt_template.format_messages(name="白巧克力",user_input="你的名字叫什么"))
运行结果如下:
[SystemMessage(content='你是一位人工智能助手,你的名字是白巧克力', additional_kwargs={}, response_metadata={}), HumanMessage(content='你好', additional_kwargs={}, response_metadata={}), AIMessage(content='谢谢', additional_kwargs={}, response_metadata={}), HumanMessage(content='你的名字叫什么', additional_kwargs={}, response_metadata={})]
在运行结果发现,角色system、human、ai分别对应着SystemMessage、HumanMessage、AIMessage。
所以上面代码可以改为:
from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate # 引入提示词模板
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
# 定义提示词模板
prompt_template = ChatPromptTemplate.from_messages([
# 使用系统提示词模板
SystemMessagePromptTemplate.from_template("你是一位人工智能助手,你的名字是{name}"),
HumanMessage(content="你好"),
AIMessage(content="谢谢"),
# 使用人工提示词模板
HumanMessagePromptTemplate.from_template("{user_input}")
])
print(prompt_template.format_messages(name="白巧克力", user_input="你的名字叫什么"))
当然AI提示词模板也可以通过AIMessagePromptTemplate实现,这里就不编写了。
MessagesPlaceholder提示模板可以在特定位置添加内容,其语法格式如下:
MessagesPlaceholder("变量")
示例代码如下:
from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate, \
MessagesPlaceholder
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
# 定义提示词模板
prompt_template = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template("你是一位人工智能助手,你的名字是{name}"),
MessagesPlaceholder('msgs'), # 使用MessagesPlaceholder插入其他角色传入的一组内容
AIMessage(content="谢谢"),
HumanMessagePromptTemplate.from_template("{user_input}")
])
print(prompt_template.invoke({"msgs":[HumanMessage(content="你好")],'name':"白巧克力", 'user_input':"你的名字叫什么"}))
运行结果如下:
[SystemMessage(content='你是一位人工智能助手,你的名字是白巧克力', additional_kwargs={}, response_metadata={}), HumanMessage(content='你好', additional_kwargs={}, response_metadata={}), AIMessage(content='谢谢', additional_kwargs={}, response_metadata={}), HumanMessage(content='你的名字叫什么', additional_kwargs={}, response_metadata={})]
少样本提示词模板(FewShotPromptTemplate)是指使用一组少量的示例来让模型更好地理解用户意图,从而更好地回答或执行任务。
例如:
Q:什么是白巧克力?
A:白巧克力是一种零食。
Q:什么是sotnaldcnasfjsl
A:不知道
Q:什么是语言模型?
A:
通过示例告诉模型:Q是问题,A是答案,按这种格式进行问答交互。
其基础语法格式如下:
FewShotPromptTemplate(
examples=示例,
example_prompt=提示词模板,
suffix="Question:{input}", # 提示词模板最后追加的内容
input_variables=['input'] # 定义suffix中包含的模板变量
)
示例代码如下:
from langchain_core.prompts import PromptTemplate, FewShotPromptTemplate
# 示例
examples = [
{
"question": "乾隆和曹操谁活得更久?",
"answer": """
这里是否需要跟进问题:是的。
追问:乾隆去世时几岁?
中间答案:乾隆去世时87岁。
追问:曹操去世时几岁?
中间答案:曹操去世时66岁。
所以最终答案是:乾隆
""",
},
{
"question": "小米手机的创始人什么时候出生?",
"answer": """
这里是否需要跟进问题:是的。
追问:小米手机的创始人是谁?
中间答案:小米手机由雷军创立。
跟进:雷军什么时候出生?
中间答案:雷军出生于1969年12月16日。
所以最终的答案是:1969年12月16日。
""",
},
{
"question": "乔治·华盛顿的外祖父是谁?",
"answer": """
这里是否需要跟进问题:是的。
追问:乔治·华盛顿的母亲是谁?
中间答案:乔治·华盛顿的母亲是玛丽·鲍尔·华盛顿。
追问:玛丽·鲍尔·华盛顿的父亲是谁?
中间答案:玛丽·鲍尔·华盛顿的父亲是约瑟夫·鲍尔
""",
}
]
# 提示词模板
example_prompt = PromptTemplate(
input_variables=["question", "answer"], template="Question:{question}\n{answer}"
)
# 少样本提示词模板
prompt = FewShotPromptTemplate(
examples=examples, # 示例样本
example_prompt=example_prompt, # 提示词模板
suffix="Question:{input}", # 提示词模板最后追加的内容
input_variables=['input'] # 定义suffix中包含的模板变量
)
print(prompt.format(input="乔治·华盛顿的外祖父是谁?"))
运行结果为上面的示例examples。
在使用FewShotPromptTemplate时,把所有示例都提交给大模型,这显然是不合理的,而且调用大模型的token是有限制的。
这时我们可以通过示例选择器ExampleSelector中的SemanticSimilarityExampleSelector类来根据输入的相似性选择小样本示例,避免把所有示例都提交给大模型。
SemanticSimilarityExampleSelector使用了嵌入模型计算输入和小样本示例之间的相似性后,使用向量数据库执行相似搜索,获取与输入相似的示例。
这里我们使用了网络上的文本嵌入模型,获取方式在下面了,大家可以下载:
通过网盘分享的文件:ge-large-zh-v1.5
链接: https://pan.baidu.com/s/1NXsppUk6PjTASb43qno3KA?pwd=bqkl 提取码: bqkl
需要安装:
pip install chromadb
pip install sentence-transformers
pip install langchain_huggingface
其语法格式如下:
SemanticSimilarityExampleSelector.from_examples(
# 可供选择的示例列表
examples,
# 生成嵌入的嵌入类,用于衡量语义相似性
embeddings,
# 存储嵌入和执行相似性搜索的VectorStore类
Chroma,
# 要生成示例数
k=1
)
示例代码如下:
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_community.vectorstores import Chroma
from langchain.prompts.example_selector import SemanticSimilarityExampleSelector
# 示例
examples = [
{
"question": "乾隆和曹操谁活得更久?",
"answer": """
这里是否需要跟进问题:是的。
追问:乾隆去世时几岁?
中间答案:乾隆去世时87岁。
追问:曹操去世时几岁?
中间答案:曹操去世时66岁。
所以最终答案是:乾隆
""",
},
{
"question": "小米手机的创始人什么时候出生?",
"answer": """
这里是否需要跟进问题:是的。
追问:小米手机的创始人是谁?
中间答案:小米手机由雷军创立。
跟进:雷军什么时候出生?
中间答案:雷军出生于1969年12月16日。
所以最终的答案是:1969年12月16日。
""",
},
{
"question": "乔治·华盛顿的外祖父是谁?",
"answer": """
这里是否需要跟进问题:是的。
追问:乔治·华盛顿的母亲是谁?
中间答案:乔治·华盛顿的母亲是玛丽·鲍尔·华盛顿。
追问:玛丽·鲍尔·华盛顿的父亲是谁?
中间答案:玛丽·鲍尔·华盛顿的父亲是约瑟夫·鲍尔
""",
}
]
# 模型
embeddings_path = "F:\model\ge-large-zh-v1.5"
# 加载、预训练模型生成文本嵌入类
embeddings = HuggingFaceEmbeddings(model_name=embeddings_path)
# 使用示例选择器
example_selector = SemanticSimilarityExampleSelector.from_examples(
examples,
embeddings,
Chroma,
k=1
)
question = '小米手机的创始人是谁'
selected_examples = example_selector.select_examples({"question": question})
print(f"最相似的示例:{question}")
for exmaple in selected_examples:
print("\\n")
for k,v in exmaple.items():
print(f'{k}:{v}')
运行结果如下:
这样就可以获取到最相似问题的示例。
接着就可以通过FewShotPromptTemplate将一组示例传递给模型,让模型更好地理解用户意图,从而更好地回答或执行任务。
示例代码如下:
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
# 提示词模板
example_prompt = PromptTemplate(
input_variables=["question", "answer"], template="Question:{question}\n{answer}"
)
# 少样本提示词模板
prompt = FewShotPromptTemplate(
example_selector=example_selector, # 示例样本
example_prompt=example_prompt, # 提示词模板
suffix="Question:{input}", # 提示词模板最后追加的内容
input_variables=['input'] # 定义suffix中包含的模板变量
)
print(prompt.format(input="乔治·华盛顿的外祖父是谁?"))
好了,LangChain教程——提示词模板就讲到这里了,下一篇我们学习LangChain教程——输出解析器。
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费场景POC验证,效果验证后签署服务协议。零风险落地应用大模型,已交付160+中大型企业
2025-07-03
继提示词工程、RAG技术浪潮后,LangChain领域中上下文工程正成为新的热门方向!
2025-07-01
LangChain教程——LangChain基本使用
2025-06-26
LangChain的OpenAI和ChatOpenAI,到底应该调用哪个?
2025-06-26
开发AI Agent到底用什么框架——LangGraph VS. LlamaIndex
2025-06-24
大模型开发基础:LangChain基础样例
2025-06-19
LangChain ReAct 中文解析器实现
2025-06-16
基于LangGraph多智能体框架的共享内存实现与探索
2025-06-16
一、LangGraph基础入门
2025-05-08
2025-05-06
2025-04-18
2025-06-05
2025-05-28
2025-04-13
2025-04-18
2025-05-19
2025-04-25
2025-05-28
2025-06-26
2025-06-13
2025-05-21
2025-05-19
2025-05-08
2025-05-06
2025-04-22
2025-04-18