一、FewShotPromptTemplate(少样本提示词模板)
给模型几个示例,让它按格式回答。示例越多,输出越精准。
python
from langchain_core.prompts import PromptTemplate, FewShotPromptTemplate
example_template = PromptTemplate.from_template("单词:{word},反义词:{antonym}")
examples_data = [
{"word": "大", "antonym": "小"},
{"word": "上", "antonym": "下"}
]
few_shot = FewShotPromptTemplate(
example_prompt=example_template,
examples=examples_data,
prefix="告知我单词的反义词,提供如下示例:",
suffix="基于前面的示例,{input_word}的反义词是?",
input_variables=['input_word']
)
五个核心参数 :example_prompt(示例模板)、examples(示例数据)、prefix(前导说明)、suffix(后置问题)、input_variables(变量列表)。
二、ChatPromptTemplate(聊天提示词模板)
支持注入多轮历史会话,用 MessagesPlaceholder 占位,运行时动态填充。
python
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
chat_template = ChatPromptTemplate.from_messages([
("system", "你是一个边塞诗人,可以作诗"),
MessagesPlaceholder("history"),
("human", "请再来一首唐诗")
])
history_data = [
("human", "你来写一个唐诗"),
("ai", "床前明月光,疑是地上霜..."),
]
prompt_text = chat_template.invoke({"history": history_data})
三种模板对比 :PromptTemplate 通用单条、FewShotPromptTemplate 支持示例、ChatPromptTemplate 支持多轮历史。三者都有 format 和 invoke 方法。
三、Chain链式调用(核心!)
用 | 串联组件,前一个输出自动成为后一个输入。所有组件必须是 Runnable 接口子类。
python
chain = prompt_template | model | parser
result = chain.invoke({"变量": "值"}) # 一次性返回
for chunk in chain.stream({"变量": "值"}): # 流式输出
print(chunk.content, end="")
| 的本质 :a | b 调用 a.__or__(b),Runnable 基类重写了 __or__,让组件可串联。链的类型是 RunnableSequence,本身也是 Runnable,可继续追加组件。
四、输出解析器
转成需要的格式,都是 Runnable 子类,可加入链:
python
from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
str_parser = StrOutputParser() # AIMessage → 字符串
json_parser = JsonOutputParser() # AIMessage → 字典
多段链示例:
python
chain = first_prompt | model | json_parser | second_prompt | model | str_parser
今日核心总结
- FewShotPromptTemplate:给模型示例,五参数控制模板
- ChatPromptTemplate :
MessagesPlaceholder+invoke动态填充历史 - Chain链式调用 :
|串联组件,输出自动转输入,都需是 Runnable 子类 - 输出解析器 :
StrOutputParser转字符串,JsonOutputParser转字典 - 构建关键:注意前后组件输入输出类型兼容