摘要: 本文介紹了langchain.prompts中基礎的提示詞模板的高級用法,包括利用PipelinePrompt組合Prompt使用,多模態場景、動態占位符的使用等進行了介紹。
文章目錄
- 1. 背景
- 2. PipelinePrompt
- 2.1 組合兩個Prompt模板
- 2.2 多模態模板
- 3. 聊天提示詞模板
- 4. 占位符MessagesPlaceholder
- 4.1 基本用法
- 4.2 多輪對話
- 4.3 可選占位符配置
- 4.4 動態示例選擇
1. 背景
在實際應用中提示詞通常并非單一使用,而是多種模板結合起來使用,尤其在大型的Agent中,好的提示詞模板設計,對后續的開發會起到事半功倍的效果。
2. PipelinePrompt
PipelinePrompt是LangChain框架中用于組合多個Prompt模板的核心組件,它通過模塊化設計實現Prompt的復用和靈活組裝。其核心思想類似于軟件開發中的管道模式(Pipeline Pattern),將多個處理步驟串聯成流水線,前序步驟的輸出作為后續步驟的輸入。
2.1 組合兩個Prompt模板
示例:
from langchain.prompts.pipeline import PipelinePromptTemplate
from langchain.prompts.prompt import PromptTemplate# 定義子模板1:系統指令
intro_template = PromptTemplate.from_template("你是一個專業翻譯,負責將{input_language}翻譯為{output_language}:"
)
# 定義子模板2:翻譯示例
example_template = PromptTemplate.from_template("示例:'{example_input}' -> '{example_output}'"
)# 組合為完整PipelinePrompt
full_prompt = PipelinePromptTemplate(final_prompt=PromptTemplate.from_template("{intro}\n{example}\n請翻譯:{text}"),pipeline_prompts=[("intro", intro_template),("example", example_template)]
)# 使用示例
print(full_prompt.format(input_language="英文",output_language="中文",example_input="Hello",example_output="你好",text="Good morning"
))
輸出:
你是一個專業翻譯,負責將英文翻譯為中文:
示例:'Hello' -> '你好'
請翻譯:Good morning
2.2 多模態模板
以下是一個結合視覺和文本的多模態PipelinePromptTemplate示例,用于生成圖片描述并回答相關問題。
from langchain.prompts.pipeline import PipelinePromptTemplate
from langchain.prompts import PromptTemplate
import base64
import httpx# 子模板1:圖片描述生成
vision_template = PromptTemplate.from_template("分析這張圖片:{image_base64}\n""請列出圖中3個最顯著的特征(如物體、顏色、動作)"
)# 子模板2:問題回答
qa_template = PromptTemplate.from_template("基于以下圖片特征:{vision_analysis}\n""回答用戶問題:{user_question}\n""要求:包含對圖片特征的引用"
)# 構建多模態流水線
multimodal_prompt = PipelinePromptTemplate(final_prompt=PromptTemplate.from_template("多模態問答系統:\n""{vision_part}\n""{qa_part}"),pipeline_prompts=[("vision_part", vision_template),("qa_part", qa_template)]
)# 使用示例(需替換真實圖片URL)
image_url = "https://example.com/park.jpg"
image_data = base64.b64encode(httpx.get(image_url).content).decode("utf-8")formatted_prompt = multimodal_prompt.format(image_base64=f"<<Image>>{image_data}",user_question="圖中人們在做什么活動?"
)
print(formatted_prompt)
該示例演示了如何分階段處理多模態輸入:先提取視覺特征,再結合特征回答問題。實際運行時需要接入多模態模型來處理圖像數據。
3. 聊天提示詞模板
? ?聊天模型中的四種消息:AIMessage、HumanMessage、SystemMessage、ChatMessage分別對應著4種聊天消息模板:AIMessagePromptTemplate、HumanMessagePromptTemplate、SystemMessagePromptTemplate、ChatMessagePromptTemplate;
? ?可以通過這些模板,構建引導整個會話流程。典型的工作流程:
- System設定角色和規則
- Human收集用戶輸入
- AI按預定格式響應
- 通過ChatPromptTemplate組合成完整對話鏈:
1. SystemMessagePromptTemplate? 設定AI角色和對話規則:
from langchain.prompts import SystemMessagePromptTemplatesystem_template = "你是一位專業心理咨詢師,用溫暖平和的方式回答用戶問題"
system_prompt = SystemMessagePromptTemplate.from_template(system_template)
# 輸出:SystemMessage(content='你是一位...', additional_kwargs={})
?2. HumanMessagePromptTemplate結構化用戶輸入:
from langchain.prompts import HumanMessagePromptTemplatehuman_template = "我的問題是關于{topic},具體情況:{details}"
human_prompt = HumanMessagePromptTemplate.from_template(human_template)
# 使用:human_prompt.format(topic="失眠", details="連續一周睡不著")
?3. AIMessagePromptTemplate控制AI響應格式:
from langchain.prompts import AIMessagePromptTemplateai_template = """建議方案:
1. {solution1}
2. {solution2}"""
ai_prompt = AIMessagePromptTemplate.from_template(ai_template)
# 輸出帶編號列表的響應
4. ChatPromptTemplate 構建完整對話流程:
from langchain.prompts import ChatPromptTemplatechat_template = ChatPromptTemplate.from_messages([system_prompt,human_prompt,ai_prompt
])chain = chat_template | ChatOpenAI()
chain.invoke({"topic": "焦慮", "details": "考前心慌","solution1": "深呼吸練習","solution2": "制定復習計劃"
})
5.多模態支持:
實際應用中,通常需要支持在單個PromptTemplate中組合文本、圖像URL等數據類型,例如構建包含圖像和文本的多模態消息。
edu_prompt = ChatPromptTemplate.from_messages([SystemMessage(content="你是數學輔導AI,需:\n1. 識別手寫答案\n2. 指出錯誤步驟"),# 保留最近3輪對話MessagesPlaceholder(variable_name="dialogue", optional=True),# 混合輸入HumanMessage(content=[{"type": "text", "text": "問題:{question}"},{"type": "image_url", "image_url": "{handwriting}"},{"type": "audio_url", "audio_url": "{voice_note}"}])
])# 調用示例(無歷史對話時)
prompt = edu_prompt.format_messages(question="求x2+2x+1=0的解",handwriting="https://example.com/student_work.jpg",voice_note="https://example.com/voice_q.mp3"
)
4. 占位符MessagesPlaceholder
? ?MessagesPlaceholder是LangChain中用于動態插入消息列表的占位符組件,屬于BaseMessagePromptTemplate的子類。它允許在構建聊天提示模板時預留位置,后續通過變量注入實際消息內容。
- 動態消息插入:支持在運行時填充任意數量的消息(如對話歷史)。
- 多角色兼容:可處理SystemMessage、HumanMessage、AIMessage等混合類型消息。
- 條件控制:通過optional參數控制占位符是否必填。
4.1 基本用法
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.messages import HumanMessage, SystemMessage# 定義包含占位符的模板
chat_prompt = ChatPromptTemplate.from_messages([SystemMessage(content="你是一個助手"),MessagesPlaceholder(variable_name="history"),HumanMessage(content="{input}")
])# 填充實際消息
formatted = chat_prompt.format_messages(history=[HumanMessage(content="你好"),AIMessage(content="有什么可以幫您?")],input="今天天氣如何"
)
4.2 多輪對話
結合ConversationBufferMemory實現上下文保持:
from langchain.memory import ConversationBufferMemorymemory = ConversationBufferMemory(return_messages=True)
memory.save_context({"input": "推薦一本小說"}, {"output": "《三體》值得一讀"}
)# 使用記憶中的歷史對話
prompt_with_history = chat_prompt.format_messages(history=memory.load_memory_variables({})["history"],input="作者是誰?"
)
4.3 可選占位符配置
optional_placeholder = MessagesPlaceholder(variable_name="history", optional=True
) # 未提供變量時返回空列表:ml-citation{ref="2" data="citationList"}
4.4 動態示例選擇
在Few-shot場景中,通過MessagesPlaceholder動態插入示例對話:
few_shot_prompt = ChatPromptTemplate.from_messages([SystemMessage(content="根據示例回答問題"),MessagesPlaceholder("examples"),HumanMessage(content="{question}")
])