LangChain 提示词工程

LangChain 提示词工程

LangChain提供了一系列组件来设计、优化和管理提示词(Prompts)来有效驱动大语言模型完成复杂任务的一套方法和实践

  • zero-shot(无样本)提示词模板

    • 基础通用提示词模版,模板将具体的用户输入和固定指令分离,使提示可复用
  • few-shot(少样本)示例选择器

    • 根据不同的输入,动态选择最相关的示例放入提示词中,以指导模型
  • 输出解析器

    • 定义模型输出的结构,并负责将模型的文本输出解析成结构化数据(如Json对象等)
  • 提示词组合

    • 将多个简单的提示词模版或组件串联起来,构建复杂的提示流程
  • chain 链

    • LangChain的核心概念。将LLM、提示词模版、工具、其他链等按顺序组合成一个完整的工作流
    • 提示词在链中通常是链的起点或核心环节

通用prompt(zero-shot)

提示词优化在模型应用中非常重要,LangChain提供了PromptTemplate类,用来协助优化提示词。

PromptTemplate表示提示词模版,可以构建一个自定义的基础提示词模版,支持变量的注入,最终生成所需的提示词

标准写法

from langchain_core.prompts import PromptTemplate
from langchain_community.llms.tongyi import Tongyi
prompt_template = PromptTemplate.from_template(
    "我的邻居姓{lastname}, 刚生了{gender}, 帮忙起个名字,请简略回答"
)

# 变量注入, 生成最终的提示词
prompt_text = prompt_template.format(lastname="张",gender="女儿")

print(prompt_text)

model = Tongyi(model="qwen-plus-2025-12-01")
res = model.invoke(prompt_text)
print(res)

image

基于chain链的写法

from langchain_core.prompts import PromptTemplate
from langchain_community.llms.tongyi import Tongyi
prompt_template = PromptTemplate.from_template(
    "我的邻居姓{lastname}, 刚生了{gender}, 帮忙起个名字,请简略回答"
)

model = Tongyi(model="qwen-plus-2025-12-01")

# 生成链
chain = prompt_template | model
# 基于链 调用模型获取结果
res = chain.invoke(input={"lastname": "赵", "gender": "女儿"})
print(res)

LangChain核心的链式写法,后续学习

总结

基于PromptTemplate类可以得到提示词模版,支持基于模版注入变量得到最终提示词。

  • zero-shot思想下,可以基于PromptTemplate直接完成
  • few-shot思想下,需要更换为FewShotPromptTemplate(后续学习)

PS: 使用PromptTemplate还不如自己手动拼接字符串

  • 使用Template模板构建提示词,在大型工程中更容易做标准化模板
  • Template模板类,支持LangChain框架的链式调用

FewShotPromptTemplate 示例选择器 提示词模板

参数

from langchain_core.prompts import FewShotPromptTemplate

FewShotPromptTemplate(
    examples=None,
    example_prompt=None,
    prefix=None,
    suffix=None,
    input_variables=None,
)
  • examples:示例数据,list内套字典
  • example_prompt:示例数据的提示词模板
  • prefix:组装提示词,示例数据前内容
  • prefix:组装提示词,示例数据后的内容
  • input_variable:列表,注入的变量列表

调用示例

from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
from langchain_community.llms.tongyi import Tongyi

example_template = PromptTemplate.from_template("单词:{word}, 反义词:{antonym}")

example_data = [
    {"word": "高兴", "antonym": "难过"},
    {"word": "大", "antonym": "小"},
    {"word": "快", "antonym": "慢"},
]

few_shot_prompt = FewShotPromptTemplate(
    examples=example_data,
    example_prompt=example_template,
    prefix="给出给定词的反义词,有如下示例:",
    suffix="基于示例告诉我: {input_word} 的反义词时什么? 简要回答",
    input_variables=["input_word"],
)

# 生成最终的提示词
prompt_text = few_shot_prompt.invoke(input={"input_word": "帅"}).to_string()

print(prompt_text) # 输出最终的提示词字符串

model = Tongyi(model="qwen-plus-2025-12-01")

res = model.invoke(input=prompt_text)

print(res)

结果如下
image

模版类的format和invoke方法

在PromptTemplate(通用提示词模版)和FewShotPromptTemplate(FewShot提示词模版)的使用中,我们使用了模版对象的format方法

prompt_text = prompt_template.format(lastname="张",gender="女儿")

以及invoke方法

prompt_text = few_shot_prompt.invoke(input={"input_word": "帅"}).to_string()

PromptTemplate、FewShotPromptTemplate、ChatPromptTemplate都拥有format和invoke这2类方法

image

区别

区别 format invoke
功能 纯字符串替换,机械站位符生成提示词 Runnable接口标准方法,解析占位符生成提示词
返回值 字符串 PromptValue对象
传参 .format(k=v, k=v,...) .invoke({"k": "v", "k": "v", ...})
解析 支持解析{}占位符 支持解析{}占位符和MessagePlaceholder结构化占位符

ChatPromptTemplate

  • PromptTemplate: 通用提示词模板,支持动态注入信息
  • FewShotPromptTemplate:支持基于模板注入任意数量的示例信息
  • ChatPromptTemplate:支持注入任意数量的历史会话信息

通过from_messages方法,从列表中获取多轮次会话作为聊天的基础模板

前面的PromptTemplate类用的from_template仅能接入一条消息,而from_message可以接入一个list的消息

历史会话信息不是静态的,而是随着对话的进行不断地积攒,历史会话信息需要支持动态注入

  • MessagePlaceholder作为占位
    • 提供history作为占位的key
  • 基于invoke动态注入历史会话记录(format无法注入必须使用invoke
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_community.chat_models.tongyi import ChatTongyi
chat_template = ChatPromptTemplate.from_messages(
    [
        ("system", "你是一个唐朝诗人"),
        ("ai", "我是一个唐朝诗人,只写唐诗"),
        MessagesPlaceholder(variable_name="history"),
        ("human", "写一首宋词"),
    ]
)

history_data = [
    ("human", "写一首唐诗"),
    ("ai", "床前明月光,疑是地上霜。举头望明月,低头思故乡。"),
    ("human", "再写一首宋词"),
    ("ai", "我不会写宋词,我只写唐诗"),
]

prompt_value = chat_template.invoke({"history": history_data})

print(prompt_value.to_string())

model = ChatTongyi(model="deepseek-v3.2")

res = model.invoke(input=prompt_value.to_string())

print(res.content)

结果:
image

posted @ 2026-03-02 15:38  风陵南  阅读(87)  评论(0)    收藏  举报