大模型学习·第41天:LangChain进阶——提示词模板与Chain链式调用

一、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

今日核心总结

  1. FewShotPromptTemplate:给模型示例,五参数控制模板
  2. ChatPromptTemplate :MessagesPlaceholder + invoke 动态填充历史
  3. Chain链式调用 :| 串联组件,输出自动转输入,都需是 Runnable 子类
  4. 输出解析器 :StrOutputParser 转字符串,JsonOutputParser 转字典
  5. 构建关键:注意前后组件输入输出类型兼容
相关推荐
努力的小郑4 小时前
数据查到了,回答去哪儿了?一次百炼 + LangChain 排查实录
后端·langchain·agent
David猪大卫5 小时前
【C++修炼】map 和 set 的使用
c语言·开发语言·数据结构·c++·经验分享·笔记·学习
HPtiger5 小时前
C++ 入门笔记:从 C 到 C++ 的核心过渡(命名空间、输入输出、缺省参数、重载、引用、内联)
c语言·c++·学习
用户3721574261356 小时前
C# 实现 Excel 单元格保护:锁定公式并允许编辑指定区域
c#·ai编程·编程语言
fengci.6 小时前
CTF2MISC中等部分
开发语言·前端·学习
YueTann8 小时前
mgtv5th-baseline学习
学习
蒸蒸yyyyzwd10 小时前
从后端面经学到的 3 个知识
笔记·学习
17岁的勇气10 小时前
Unity Shader unity文档学习笔记(二十二):shader变体
笔记·学习·unity
公子小六11 小时前
基于.NET的Windows窗体编程之WinForms数据持久化(1)
windows·microsoft·c#·.net·winforms
三雷科技12 小时前
第6章第4节:自定义分词器
开发语言·c#