【LangChain系列 11】Prompt模版——拼装组合

原文地址:【LangChain系列 11】Prompt模版------拼装组合

本文速读:

  • 多prompt模版组合

  • 单prompt模版拼装

在平常业务开发中,我们常常需要把一些公共模块提取出来作为一个独立的部分,然后将业务中去将这些模块进行组合。在LLM应用开发中,我们也会需要采用这种思想,比如将一些公共的promt模版独立出来,这样prompt模版就可以更好地复用,减少不必要的代码,保持代码和逻辑的简洁。

LangChain对prompt模版的组合提供两种方式:

  1. 针对多个prompt模版进行组合。

  2. 将多个部分拼装成一个prompt模版。

01 多prompt模版组合

LangChain提供了PipelinePrompt来进行多prompt模版组合。一个PipelinePrompt包含两个部分:

  • 最终的prompt模版:最终生成的prompt模版。

  • 待组合的prompt模版:它是一个列表,列表里的每一项包含一个名字和一个prompt模版。

如下面代码所示,full_prompt就是最终的 prompt模版,input_prompts就是 待组合的prompt模版;将input_prompts中的prompt模版最终组合成了full_prompt。

ini 复制代码
from langchain.prompts.pipeline import PipelinePromptTemplate
from langchain.prompts.prompt import PromptTemplate

full_template = """{introduction}

{example}

{start}"""
full_prompt = PromptTemplate.from_template(full_template)

introduction_template = """You are impersonating {person}."""
introduction_prompt = PromptTemplate.from_template(introduction_template)

example_template = """Here's an example of an interaction: 

Q: {example_q}
A: {example_a}"""
example_prompt = PromptTemplate.from_template(example_template)

start_template = """Now, do this for real!

Q: {input}
A:"""
start_prompt = PromptTemplate.from_template(start_template)

input_prompts = [
    ("introduction", introduction_prompt),
    ("example", example_prompt),
    ("start", start_prompt)
]
pipeline_prompt = PipelinePromptTemplate(final_prompt=full_prompt, pipeline_prompts=input_prompts)
print(pipeline_prompt.input_variables)

输出结果:

css 复制代码
['example_a', 'person', 'example_q', 'input']

执行下面代码:

ini 复制代码
print(pipeline_prompt.format(
    person="Elon Musk",
    example_q="What's your favorite car?",
    example_a="Tesla",
    input="What's your favorite social media site?"
))

输出结果:

rust 复制代码
    You are impersonating Elon Musk.
    Here's an example of an interaction: 
    
    Q: What's your favorite car?
    A: Tesla
    Now, do this for real!
    
    Q: What's your favorite social media site?
    A:
    

02 单prompt模版拼装

单prompt模版拼装是指将多个部分拼装成一个完整的prompt模版,一般来说是将字符串与prompt模版拼成一个新的prompt模版。下面主要介绍字符串prompt模版和对话prompt模版这两种模版的拼装,通过两个代码示例来介绍它们的用法。

字符串prompt模版

在下面代码中,将一个字符串prompt模版和两个字符串通过 + 拼装起来。

swift 复制代码
from langchain.prompts import PromptTemplate

prompt = (
    PromptTemplate.from_template("Tell me a joke about {topic}")
    + ", make it funny"
    + "\n\nand in {language}"
)
print(prompt)

输出结果:

ini 复制代码
PromptTemplate(input_variables=['language', 'topic'], output_parser=None, partial_variables={}, template='Tell me a joke about {topic}, make it funny\n\nand in {language}', template_format='f-string', validate_template=True)

执行代码:

ini 复制代码
print(prompt.format(topic="sports", language="spanish"))

输出结果:

vbnet 复制代码
'Tell me a joke about sports, make it funny\n\nand in spanish'

同样,我们可以在LLMChain中使用这个拼装的prompt。

ini 复制代码
from langchain.chat_models import ChatOpenAI
from langchain.chains import LLMChain

model = ChatOpenAI()
chain = LLMChain(llm=model, prompt=prompt)
chain.run(topic="sports", language="spanish")

执行代码,输出结果:

arduino 复制代码
'¿Por qué el futbolista llevaba un paraguas al partido?\n\nPorque pronosticaban lluvia de goles.'

对话prompt模版

在下面代码中,将对话prompt中的Message和字符串通过 + 进行拼装,形成一个新的prompt模版,不仅可以将Message进行拼装,而且可以将MessagePrompt进行拼装,不过先要将MessagePrompt中的变量进行赋值。

ini 复制代码
from langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate
from langchain.schema import HumanMessage, AIMessage, SystemMessage

prompt = SystemMessage(content="You are a nice pirate")
new_prompt = (
    prompt
    + HumanMessage(content="hi")
    + AIMessage(content="what?")
    + "{input}"
)
print(new_prompt.format_messages(input="i said hi"))

输出结果:

python 复制代码
    [SystemMessage(content='You are a nice pirate', additional_kwargs={}),
     HumanMessage(content='hi', additional_kwargs={}, example=False),
     AIMessage(content='what?', additional_kwargs={}, example=False),
     HumanMessage(content='i said hi', additional_kwargs={}, example=False)]

同样地,可以在LLMChain中使用它:

javascript 复制代码
from langchain.chat_models import ChatOpenAI
from langchain.chains import LLMChain

model = ChatOpenAI()
chain = LLMChain(llm=model, prompt=new_prompt)
chain.run("i said hi")

执行代码,输出结果:

vbnet 复制代码
'Oh, hello! How can I assist you today?'

本文小结

本文主要介绍了prompt模版的拼装组合,既可以将多个prompt模版进行组合,也可以对单个prompt模版进行拼装。

相关推荐
我是人机不吃鸭梨2 分钟前
Flutter AI 集成革命(2025版):从 Gemini 模型到智能表单验证器的终极方案
开发语言·javascript·人工智能·flutter·microsoft·架构
编码小哥2 分钟前
OpenCV阈值分割技术:全局阈值与自适应阈值
人工智能·opencv·计算机视觉
AI即插即用7 分钟前
即插即用系列 | CVPR 2025 FDConv:频域动态卷积,打破密集预测任务的参数效率瓶颈
图像处理·人工智能·深度学习·神经网络·计算机视觉·cnn·视觉检测
呆萌很9 分钟前
NVIDIA CUDA Toolkit 安装
人工智能
熊猫钓鱼>_>13 分钟前
「源力觉醒 创作者计划」_巅峰对话:文心4.5 vs DeepSeek R1 vs 通义Qwen3.0 谁最符合中国人体验?
ai·大模型·llm·多模态·deepseek-r1·文心4.5·qwen3.0
天庭鸡腿哥16 分钟前
Vivo出品,干趴付费!
人工智能·语音识别
code 旭16 分钟前
神经网络+激活函数+损失函数 三合一速查表
人工智能·深度学习·神经网络
一个处女座的程序猿17 分钟前
LLMs之VF:《Asking LLMs to Verify First is Almost Free Lunch》翻译与解读
llm·verify first
laplace012319 分钟前
讲清楚 Prompt, Agent, MCP 是什么+大模型测评流程
人工智能·语言模型·prompt·transformer
Gofarlic_oms126 分钟前
区块链存证节点搭建:金融行业审计证据链构建指南
运维·人工智能·金融·数据挖掘·区块链·需求分析·devops