ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

* LangChain 提示词模板详解:ChatPromptTemplate 的使用与高级特性

* LangChain 提示词模板详解:ChatPromptTemplate 的使用与高级特性 一、提示词模板Prompt Templates1.1 为什么推荐提示词模板在 LangChain 开发中构造提示词既可以直接使用 Python 字符串拼接如 f-string、format() 或也可以使用 LangChain 提供的 PromptTemplate 或 ChatPromptTemplate 。举例1字符串拼接方式1 # 字符串拼接 2 topic Python 3 difficulty 初学者 4 5 # 难以维护容易出错 6 prompt_str f你是一个{difficulty}级别的编程导师。请用简单易懂的语言解释{topic}。 7 8 response model.invoke(prompt_str) 9 print(fAI 回复{response.content}...\n)优点✅简单直接上手快适合临时 demo无额外学习成本缺点❌可读性差变量多时混乱不易维护修改容易出错无变量校验容易漏/拼错难以支持复杂场景多轮对话 / RAG / Few-shot举例2提示词模板1 from langchain.prompts import PromptTemplate 2 3 topic Python 4 difficulty 初学者 5 6 template PromptTemplate.from_template( 7 你是一个{difficulty}级别的编程导师。请用简单易懂的语言解释{topic}。 8 ) 9 10 # 使用模板生成提示词 11 prompt template.format(difficultydifficulty, topictopic) 12 13 response model.invoke(prompt) 14 print(fAI 回复{response.content}...\n)1 from langchain_core.prompts import ChatPromptTemplate 2 3 prompt_template ChatPromptTemplate([ 4 (system, 你是一个AI开发工程师. 你的名字是 {name}.), 5 (human, {user_input}) 6 ]) 7 8 #调用format()方法返回字符串 9 prompt prompt_template.invoke({name:小谷AI, user_input:你能帮我做什 么?}) 10 print(prompt) 11优点✅结构清晰变量占位易维护、可复用自动变量校验更安全支持复杂场景对话 / RAG / Agent可与 LangChain 生态无缝集成便于调试与日志追踪缺点❌有一定学习成本初期写法略复杂对极简单场景略“重”开发建议小项目 / 临时用 → 字符串拼接正式开发 / AI应用 → 提示词模板必选1.2 提示词机制演进LangChain 1.0的架构变革中核心的演进之一体现在 Prompt 机制上一个结构化的、富含元数据的消息列表已经取代单一字符串成为与模型交互的标准数据格式。1、旧时代LLM PromptTemplate输入与输出均为字符串① 模型接口对应于 LangChain 中的LLM类主要面向早期的文本补全模型。② 工作方式模型接受一个单一的字符串作为输人基于此预测并生成后续的文本内容文本补全。③ Prompt 工具核心工具是 PromptTemplate 。它的职责是接收一组变量并通过模板渲染最终输出一个完整的字符串。1 from langchain.prompts import PromptTemplate 2 3 prompt_template PromptTemplate.from_template( 4 请给我一个关于{topic}的{type}解释。 5 ) 6 7 #传入模板中的变量名 8 prompt prompt_template.format(type详细, topic量子力学) 9 10 print(prompt)④ 局限性当我们需要用这种方式模拟多轮聊天时开发者必须在字符串中手动拼接和伪造对话角色例如1 Human你好\nAI你好有什么我能帮忙的吗\nHuman...这种方式不仅导致Prompt 的结构混乱、难以维护也极易让模型混淆对话的边界与上下文影响生成质量。2、新时代ChatModelChatPromptTemplate输入与输出均为消息列表① 模型接口对应 LangChain 1.0 的主流接口 ChatModel。② 工作方式现代聊天模型 API 已原生支持角色概念。它们不再接受单一字符串而是要求输入一个结构化的消息列表。为构建复杂、可靠的多轮对话智能体系统奠定了坚实的基础。③ Prompt 工具ChatPromptTemplate 因此成为LangChain 1.0 中最核心的 Prompt工具。它的职责是接收变量并输出一个 List「BaseMessage消息列表该列表可直接传递给聊天模型。二者对比特性PromptTemplateChatPromptTemplate输出格式纯文本字符串消息列表角色支持❌ 无✅ system/user/assistant对话历史❌ 不支持✅ 支持适用场景简单提示聊天、对话、多轮交互因此用于生成消息列表的 ChatPromptTemplate也自然取代了生成字符串的 PromptTemplate成为构建现代LangChain 应用的首选工具。1.3 ChatPromptTemplate 的使用在LangChain 1.0中ChatPromptTemplate 是用于生成消息列表的核心组件。ChatPromptTemplate是创建聊天消息列表的提示模板。它比普通 PromptTemplate 更适合处理多角色、多轮次的对话场景。支持 System / Human / AI 等不同角色的消息模板。消息类型角色字符串含义用途“system”系统消息设定 AI 的行为、角色、规则“user” / “human”用户消息用户的输入/问题“assistant” / “ai”AI 消息AI 的回复用于对话历史1.3.1 两种实例化方式ChatPromptTemplate 可以通过初始化方法或 from_messages 方法来实例化提示词模板。实例化时需要传入 messages参数。常见类型是tuple构成的列表参数类型role : strcontent : str 方式1(推荐)调用from_messages()该方法允许传入一个由元组Tuple构成的列表列表中的每一个元组都代表一条具有特定角色的消息。举例11 # 导入相关依赖 2 from langchain_core.prompts import ChatPromptTemplate 3 4 # 定义聊天提示词模版 5 chat_template ChatPromptTemplate.from_messages( 6 [ 7 (system, 你是一个有帮助的AI机器人你的名字是{name}。), 8 (human, 你好最近怎么样), 9 (ai, 我很好谢谢), 10 (human, {user_input}), 11 ] 12 ) 13 14 # 格式化聊天提示词模版中的变量 15 prompt chat_template.invoke({name:小明, user_input:你叫什么名字}) 16 17 # 打印格式化后的聊天提示词模版内容 18 print(prompt)1 messages[SystemMessage(content你是一个有帮助的AI机器人你的名字是小明。, additional_kwargs{}, response_metadata{}), HumanMessage(content你好 最近怎么样, additional_kwargs{}, response_metadata{}), AIMessage(content我很好谢谢, additional_kwargs{}, response_metadata{}, tool_calls[], invalid_tool_calls[]), HumanMessage(content你叫什么名字, additional_kwargs{}, response_metadata{})]方式2使用实例初始化方法举例1 from langchain_core.prompts import ChatPromptTemplate 2 3 #参数类型这里使用的是tuple构成的list 4 prompt_template ChatPromptTemplate([ 5 # 字符串 role 字符串 content 6 (system, 你是一个AI开发工程师. 你的名字是 {name}.), 7 (human, 你能开发哪些AI应用?), 8 (ai, 我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等.), 9 (human, {user_input}) 10 ]) 11 12 #调用invoke()方法返回ChatPromptValue 13 prompt prompt_template.invoke({name:小谷AI, user_input:你能帮我做什 么?}) 14 print(prompt) 151 messages[SystemMessage(content你是一个AI开发工程师. 你的名字是 小谷AI., additional_kwargs{}, response_metadata{}), HumanMessage(content你能开 发哪些AI应用?, additional_kwargs{}, response_metadata{}), AIMessage(content我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理 等., additional_kwargs{}, response_metadata{}, tool_calls[], invalid_tool_calls[]), HumanMessage(content你能帮我做什么?, additional_kwargs{}, response_metadata{})]说明from_messages()的底层也是调用的类的__init()__方法1.3.2 模板调用的3种方式对比invoke() 、format() 、format_messages()方式1使用 invoke()返回ChatPromptValue1 from langchain_core.prompts import ChatPromptTemplate 2 3 #参数类型这里使用的是tuple构成的list 4 prompt_template ChatPromptTemplate([ 5 # 字符串 role 字符串 content 6 (system, 你是一个AI开发工程师. 你的名字是 {name}.), 7 (human, 你能开发哪些AI应用?), 8 (ai, 我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等.), 9 (human, {user_input}) 10 ]) 11 12 prompt prompt_template.invoke({name:小谷AI, user_input:你能帮我做什 么?}) 13 print(type(prompt)) 14 print(prompt) 15 print(len(prompt.messages))class ‘langchain_core.prompt_values.ChatPromptValue’messages[SystemMessage(content‘你是一个AI开发工程师. 你的名字是 小谷AI.’,additional_kwargs{}, response_metadata{}), HumanMessage(content‘你能开发哪些AI应用?’, additional_kwargs{}, response_metadata{}), AIMessage(content‘我能开发很多AI应用,比如聊天机器人, 图像识别, 自然语言处理等.’, additional_kwargs{}, response_metadata{}),HumanMessage(content‘你能帮我做什么?’, additional_kwargs{}, response_metadata{})]4方式2使用format()返回字符串1 from langchain_core.prompts import ChatPromptTemplate 2 3 #参数类型这里使用的是tuple构成的list 4 prompt_template ChatPromptTemplate([ 5 # 字符串 role 字符串 content 6 (system, 你是一个AI开发工程师. 你的名字是 {name}.), 7 (human, 你能开发哪些AI应用?), 8 (ai, 我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等.), 9 (human, {user_input}) 10 ]) 11 12 #方式1调用format()方法返回字符串 13 prompt prompt_template.format(name小谷AI, user_input你能帮我做什么?) 14 print(type(prompt)) 15 print(prompt)1 class str 2 3 System: 你是一个AI开发工程师. 你的名字是 小谷AI. 4 Human: 你能开发哪些AI应用? 5 AI: 我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等. 6 Human: 你能帮我做什么?方式3使用format_messages()返回消息列表1 from langchain_core.prompts import ChatPromptTemplate 2 3 prompt_template ChatPromptTemplate([ 4 (system, 你是一个AI开发工程师. 你的名字是 {name}.), 5 (human, 你能开发哪些AI应用?), 6 (ai, 我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理等.), 7 (human, {user_input}) 8 ]) 9 10 #调用format_messages()方法返回消息列表 11 prompt prompt_template.format_messages(name小谷AI, user_input你能帮我做 什么?) 12 print(type(prompt)) 13 print(prompt)1 class list 2 [SystemMessage(content你是一个AI开发工程师. 你的名字是 小谷AI., additional_kwargs{}, response_metadata{}), HumanMessage(content你能开 发哪些AI应用?, additional_kwargs{}, response_metadata{}), AIMessage(content我能开发很多AI应用, 比如聊天机器人, 图像识别, 自然语言处理 等., additional_kwargs{}, response_metadata{}, tool_calls[], invalid_tool_calls[]), HumanMessage(content你能帮我做什么?, additional_kwargs{}, response_metadata{})]1.3.3 结合LLM调用举例1 from dotenv import load_dotenv 2 from langchain_core.prompts import ChatPromptTemplate 3 import os 4 from langchain.chat_models import init_chat_model 5 6 ######1、提供大模型######### 7 load_dotenv(overrideTrue) 8 9 CLOSEAI_API_KEY os.getenv(CLOSEAI_API_KEY) 10 CLOSEAI_BASE_URL os.getenv(CLOSEAI_BASE_URL) 11 12 model init_chat_model( 13 modelgpt-5.4-mini, 14 model_provideropenai, 15 api_keyCLOSEAI_API_KEY, 16 base_urlCLOSEAI_BASE_URL 17 ) 18 19 ######2、提供提示词######### 20 chat_prompt ChatPromptTemplate.from_messages([ 21 (system, 你是一个数学家你可以计算任何算式), 22 (human, {text}), 23 ]) 24 25 26 # 输入提示 27 prompt_value chat_prompt.invoke({ 28 text:我今年18岁我的舅舅今年38岁我的爷爷今年72岁我和舅舅一共多少岁了 29 }) 30 31 32 ######3、结合提示词调用大模型######### 33 # 得到模型的输出 34 output model.invoke(prompt_value) 35 # 打印输出内容 36 print(output.content)1 你今年 18 岁舅舅今年 38 岁。 2 一共是 3 4 18 38 **56 岁** 5 6 所以你和舅舅一共 **56 岁**。1.3.4 更丰富的初始化参数类型前面讲了ChatPromptTemplate的两种创建方式。我们看到不管使用实例初始化方法还是使用from_messages()参数类型都是列表类型。列表中的元素可以是多种类型前面我们主要测试了元组类型。源码1 def __init__(self, 2 messages: Sequence[BaseMessagePromptTemplate | BaseMessage | BaseChatPromptTemplate | tuple[str | type, str | list[dict] | list[object]] | str | dict[str, Any]], 3 *, 4 template_format: Literal[f-string, mustache, jinja2] f- string, 5 **kwargs: Any) - None源码1 classmethod def from_messages(cls, 2 messages: Sequence[BaseMessagePromptTemplate | BaseMessage | BaseChatPromptTemplate | tuple[str | type, str | list[dict] | list[object]] | str | dict[str, Any]], 3 template_format: Literal[f-string, mustache, jinja2] f-string) 4 - ChatPromptTemplate结论参数是列表类型列表的元素可以是字符串、字典、字符串构成的元组、消息类型、提示词模板类型、消息提示词模板类型等类型1str列表类型列表参数格式是str类型不推荐因为默认角色都是human1 #1.导入相关依赖 2 from langchain_core.prompts import ChatPromptTemplate 3 4 # 2.定义聊天提示词模版 5 chat_template ChatPromptTemplate.from_messages( 6 [ 7 Hello, {name}! # 等价于 (human, Hello, {name}!) 8 ] 9 ) 10 11 # 3. 使用invoke执行 12 messages chat_template.invoke({name:小谷AI}) 13 14 # 4.打印格式化后的聊天提示词模版内容 15 print(messages)1 messages[HumanMessage(contentHello, 小谷AI!, additional_kwargs{}, response_metadata{})]类型2tuple列表类型列表参数格式是元组类型1 # 示例: 元组形式的消息 2 prompt ChatPromptTemplate.from_messages([ 3 (system, 你的名字是{role}.), 4 (human, 很高兴认识你), 5 ]) 6 7 print(prompt.invoke({role:小智}))1 messages[SystemMessage(content你的名字是小智., additional_kwargs{}, response_metadata{}), HumanMessage(content很高兴认识你, additional_kwargs{}, response_metadata{})]类型3dict列表类型列表参数格式是dict类型1 # 示例: 字典形式的消息 2 prompt ChatPromptTemplate.from_messages([ 3 {role: system, content: 你的名字是{role}.}, 4 {role: human, content:很高兴认识你}, 5 ]) 6 7 print(prompt.invoke({role:小智}))1 messages[SystemMessage(content你的名字是小智., additional_kwargs{}, response_metadata{}), HumanMessage(content很高兴认识你, additional_kwargs{}, response_metadata{})]类型4Message列表类型1 from langchain_core.messages import SystemMessage,HumanMessage 2 3 chat_prompt_template ChatPromptTemplate.from_messages([ 4 SystemMessage(content我是一个贴心的智能助手), 5 HumanMessage(content我的问题是:人工智能英文怎么说) 6 7 ]) 8 9 messages chat_prompt_template.invoke({}) 10 print(messages) 11 print(type(messages))messages[SystemMessage(content‘我是一个贴心的智能助手’, additional_kwargs{},response_metadata{}), HumanMessage(content‘我的问题是:人工智能英文怎么说’,additional_kwargs{}, response_metadata{})]class ‘langchain_core.prompt_values.ChatPromptValue’注意在XxxMessage中不能有占位符。即1 from langchain_core.messages import SystemMessage,HumanMessage 2 3 chat_prompt_template ChatPromptTemplate.from_messages([ 4 SystemMessage(content我是一个贴心的智能助手), 5 HumanMessage(content我的问题是:{word}英文怎么说) 6 7 ]) 8 9 messages chat_prompt_template.invoke({word:人工智能}) 10 print(messages) 11 print(type(messages))1 messages[SystemMessage(content我是一个贴心的智能助手, additional_kwargs {}, response_metadata{}), HumanMessage(content我的问题是:{word}英文怎么 说, additional_kwargs{}, response_metadata{})] 2 class langchain_core.prompt_values.ChatPromptValue类型5MessagePromptTemplate列表类型LangChain提供不同类型的MessagePromptTemplate。最常用的是SystemMessagePromptTemplate 、HumanMessagePromptTemplate 和AIMessagePromptTemplate 分别创建系统消息、人工消息和AI消息。基本概念HumanMessagePromptTemplate专用于生成用户消息HumanMessage的模板类模板化支持使用变量占位符可以在运行时填充具体值格式化能够将模板与输入变量结合生成最终的聊天消息输出类型生成 HumanMessage 对象content role“human” 设计目的 简化用户输入消息的模板化构造避免重复定义角色SystemMessagePromptTemplate、AIMessagePromptTemplate类似于上面不再赘述举例11 # 导入聊天消息类模板 2 from langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplate, SystemMessagePromptTemplate 3 4 # 创建消息模板 5 system_message_prompt SystemMessagePromptTemplate.from_template(你是一个 {role}) 6 7 human_message_prompt HumanMessagePromptTemplate.from_template(给我解释 {concept}用浅显易懂的语言) 8 9 # 组合成聊天提示模板 10 chat_prompt ChatPromptTemplate.from_messages([ 11 system_message_prompt, 12 human_message_prompt 13 ]) 14 15 # 格式化提示 16 formatted_messages chat_prompt.invoke({role:物理学家,concept:相对 论}) 17 print(formatted_messages)1 messages[SystemMessage(content你是一个物理学家, additional_kwargs{}, response_metadata{}), HumanMessage(content给我解释相对论用浅显易懂的语 言, additional_kwargs{}, response_metadata{})]类型6BaseChatPromptTemplate列表类型使用 BaseChatPromptTemplate可以理解为ChatPromptTemplate里嵌套了ChatPromptTemplate。举例1带参数1 from langchain_core.prompts import ChatPromptTemplate 2 3 # 使用 BaseChatPromptTemplate嵌套的 ChatPromptTemplate 4 nested_prompt_template1 ChatPromptTemplate.from_messages([ 5 (system, 我是一个人工智能助手我的名字叫{name}) 6 ]) 7 nested_prompt_template2 ChatPromptTemplate.from_messages([ 8 (human, 很高兴认识你,我的问题是{question}) 9 ]) 10 11 prompt_template ChatPromptTemplate.from_messages([ 12 nested_prompt_template1,nested_prompt_template2 13 ]) 14 15 prompt_template.invoke({name:小智,question:你为什么这么帅})1 ChatPromptValue(messages[SystemMessage(content我是一个人工智能助手我的名 字叫小智, additional_kwargs{}, response_metadata{}), HumanMessage(content很高兴认识你,我的问题是你为什么这么帅, additional_kwargs{}, response_metadata{})])举例2不带参数1 from langchain_core.prompts import ChatPromptTemplate 2 3 # 使用 BaseChatPromptTemplate嵌套的 ChatPromptTemplate 4 nested_prompt_template1 ChatPromptTemplate.from_messages([(system, 我是 一个人工智能助手)]) 5 nested_prompt_template2 ChatPromptTemplate.from_messages([(human, 很高兴 认识你)]) 6 7 prompt_template ChatPromptTemplate.from_messages([ 8 nested_prompt_template1,nested_prompt_template2 9 ]) 10 11 prompt_template.invoke({})1 ChatPromptValue(messages[SystemMessage(content我是一个人工智能助手, additional_kwargs{}, response_metadata{}), HumanMessage(content很高兴 认识你, additional_kwargs{}, response_metadata{})])举例3综合使用1 from langchain_core.prompts import ( 2 ChatPromptTemplate, 3 SystemMessagePromptTemplate, 4 HumanMessagePromptTemplate, 5 ) 6 from langchain_core.messages import SystemMessage, HumanMessage 7 8 # 示例 1: 使用 BaseMessage已实例化的消息 9 system_msg SystemMessage(content你是一个AI工程师。) 10 human_msg HumanMessage(content你好) 11 12 # 示例 2: 使用 BaseMessagePromptTemplate 13 system_prompt SystemMessagePromptTemplate.from_template(你是一个{role}.) 14 human_prompt HumanMessagePromptTemplate.from_template({user_input}) 15 16 # 示例 3: 使用 BaseChatPromptTemplate嵌套的 ChatPromptTemplate 17 nested_prompt ChatPromptTemplate.from_messages([(system, 嵌套提示词)]) 18 19 prompt ChatPromptTemplate.from_messages([ 20 system_msg, # MessageLike (BaseMessage) 21 human_msg, # MessageLike (BaseMessage) 22 system_prompt, # MessageLike (BaseMessagePromptTemplate) 23 human_prompt, # MessageLike (BaseMessagePromptTemplate) 24 nested_prompt, # MessageLike (BaseChatPromptTemplate) 25 ]) 26 27 prompt.invoke({role:人工智能专家,user_input:介绍一下大模型的应用场景})1 ChatPromptValue(messages[SystemMessage(content你是一个AI工程师。, additional_kwargs{}, response_metadata{}), HumanMessage(content你 好, additional_kwargs{}, response_metadata{}), SystemMessage(content你是一个人工智能专家., additional_kwargs{}, response_metadata{}), HumanMessage(content介绍一下大模型的应用场景, additional_kwargs{}, response_metadata{}), SystemMessage(content嵌套 提示词, additional_kwargs{}, response_metadata{})])1.4 高级特性1.4.1 部分变量预填充partial()预填充某些固定不变的变量创建模板的变体。使用场景某些变量在所有调用中都相同需要为不同用户/场景创建定制模板举例11 from langchain_core.prompts import ChatPromptTemplate 2 3 # 原始模板 4 template ChatPromptTemplate.from_messages([ 5 (system, 你是{role}目标用户是{audience}), 6 (user, {task}) 7 ]) 8 9 # 部分填充 10 customer_support_template template.partial( 11 role客服专员, 12 audience普通用户 13 ) 14 15 # 现在只需要提供 task 16 messages customer_support_template.invoke({task:解释退款政策}) 17 print(messages)1 messages[SystemMessage(content你是客服专员目标用户是普通用户, additional_kwargs{}, response_metadata{}), HumanMessage(content解释退 款政策, additional_kwargs{}, response_metadata{})]举例21 # 场景为不同部门创建专用模板 2 base_template ChatPromptTemplate.from_messages([ 3 (system, 你是{department}的{role}), 4 (user, {task}) 5 ]) 6 7 # IT 部门 8 it_template base_template.partial( 9 departmentIT 部门, 10 role技术支持 11 ) 12 13 # 销售部门 14 sales_template base_template.partial( 15 department销售部门, 16 role销售顾问 17 ) 18 19 sales_template.invoke({task:为什么每年年底汽车会促销})1 ChatPromptValue(messages[SystemMessage(content你是销售部门的销售顾问, additional_kwargs{}, response_metadata{}), HumanMessage(content为什么 每年年底汽车会促销, additional_kwargs{}, response_metadata{})])1.4.2 消息占位符当你不确定消息提示模板使用什么角色或者希望在格式化过程中插入消息列表时该怎么办 这就需要使用消息占位符负责在特定位置添加消息列表。使用场景多轮对话系统存储历史消息以及Agent的中间步骤处理此功能非常有用。方式1JSON形式举例11 from langchain_core.prompts import ChatPromptTemplate 2 3 template ChatPromptTemplate.from_messages( 4 [ 5 (system, 你是一个有用的AI助手), 6 (placeholder, {conversation}), 7 ] 8 ) 9 10 prompt_value template.invoke( 11 { 12 conversation: [ 13 (human, 你好!), 14 (ai, 今天我能帮你做什么), 15 (human, 你能给我做一个冰激凌吗), 16 (ai, 抱歉我没有这样的能力), 17 ] 18 } 19 ) 20 21 print(prompt_value)输出1 messages[SystemMessage(content你是一个有用的AI助手, additional_kwargs {}, response_metadata{}), HumanMessage(content你好!, additional_kwargs{}, response_metadata{}), AIMessage(content今天我能帮 你做什么, additional_kwargs{}, response_metadata{}, tool_calls[], invalid_tool_calls[]), HumanMessage(content你能给我做一个冰激凌吗, additional_kwargs{}, response_metadata{}), AIMessage(content抱歉我没 有这样的能力, additional_kwargs{}, response_metadata{}, tool_calls[], invalid_tool_calls[])]方式2MessagesPlaceholder实例举例11 from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder 2 from langchain_core.messages import HumanMessage 3 4 prompt_template ChatPromptTemplate.from_messages([ 5 (system, You are a helpful assistant), 6 MessagesPlaceholder(msgs) 7 ]) 8 prompt_template.invoke({msgs: [HumanMessage(contenthi!)]}) 9 10 # prompt_template.format_messages(msgs[HumanMessage(contenthi!)])1 ChatPromptValue(messages[SystemMessage(contentYou are a helpful assistant, additional_kwargs{}, response_metadata{}), HumanMessage(contenthi!, additional_kwargs{}, response_metadata {})])这将生成两条消息第一条是系统消息第二条是我们传入的 HumanMessage。 如果我们传入了 5 条消息那么总共会生成 6 条消息系统消息加上传入的 5 条消息。 这对于将一系列消息插入到特定位置非常有用。举例2存储对话历史内容1 from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder 2 3 prompt_template ChatPromptTemplate.from_messages( 4 [ 5 (system, 你是一个非常友好的AI助手), 6 MessagesPlaceholder(variable_namehistory), 7 (human, {question}) 8 ] 9 ) 10 11 prompt_template.invoke( 12 { 13 history: [ 14 (human, 5 2 ?), 15 (ai, 5 2 7) 16 ], 17 question: 结果再乘以4呢 18 } 19 )1 ChatPromptValue(messages[SystemMessage(content你是一个非常友好的AI助手, additional_kwargs{}, response_metadata{}), HumanMessage(content5 2 ?, additional_kwargs{}, response_metadata{}), AIMessage(content5 2 7, additional_kwargs{}, response_metadata{}, tool_calls[], invalid_tool_calls[]), HumanMessage(content结果再乘以4呢, additional_kwargs{}, response_metadata{})])1.4.3 可复用模板库在实际项目中建议创建模板库。举例1templates.py文件声明如下1 from langchain_core.prompts import ChatPromptTemplate 2 3 class PromptLibrary: 4 可复用的提示词模板库 5 6 TRANSLATOR ChatPromptTemplate.from_messages([ 7 (system, 你是专业翻译精通{source_lang}和{target_lang}), 8 (user, 翻译以下文本\n{text}) 9 ]) 10 11 CODE_REVIEWER ChatPromptTemplate.from_messages([ 12 (system, 你是{language}代码审查专家重点关注{focus}), 13 (user, 审查代码\n{language}\n{code}\n) 14 ]) 15 16 SUMMARIZER ChatPromptTemplate.from_messages([ 17 (system, 你是内容摘要专家), 18 (user, 将以下内容总结为{num}个要点\n{content}) 19 ]) 20 21 TUTOR ChatPromptTemplate.from_messages([ 22 (system, 你是{subject}导师学生水平{level}), 23 (user, {question}) 24 ])其它文件中使用1 from templates import PromptLibrary 2 3 messages PromptLibrary.TRANSLATOR.format_messages( 4 source_lang英语, 5 target_lang中文, 6 textHello World 7 )举例21 # templates/ 2 # ├── __init__.py 3 # ├── common.py # 通用模板 4 # ├── translation.py # 翻译相关 5 # └── coding.py # 编程相关 6 7 # common.py 8 from langchain_core.prompts import ChatPromptTemplate 9 10 FRIENDLY_ASSISTANT ChatPromptTemplate.from_messages([ 11 (system, 你是一个友好的助手), 12 (user, {input}) 13 ])1.4.4 模板组合将多个模板片段组合成复杂的提示词。方法 1字符串组合1 # 定义可复用的部分 2 role_part 你是一个{domain}专家。 3 style_part 回答风格{style}。 4 constraint_part 限制{constraint}。 5 6 # 组合 7 full_system role_part style_part constraint_part 8 9 template ChatPromptTemplate.from_messages([ 10 (system, full_system), 11 (user, {question}) 12 ])方法 2使用 运算符1 template1 ChatPromptTemplate.from_messages([ 2 (system, 你是助手) 3 ]) 4 5 template2 ChatPromptTemplate.from_messages([ 6 (user, {input}) 7 ]) 8 9 # 组合LangChain 1.0 支持 10 combined template1 template2
返回列表