【LangChain系列 9】Prompt模版——MessagePromptTemplate

原文地址:【LangChain系列 9】Prompt模版——MessagePromptTemplate

本文速读:

  • MessagePromptTemplate

  • MessagesPlaceholder

在对话模型(chat model) 中, prompt主要是封装在Message中,LangChain提供了一些MessagePromptTemplate,方便我们直接使用Message生成prompt。

01 MessagePromptTemplate


LangChain提供了几种类别的MessagePromptTemplate,比较常见的有:

  • AIMessagePromptTemplate

  • SystemMessagePromptTemplate

  • HumanMessagePromptTemplate

上面3种分别表示固定某种角色的Message模版,如果你需要自己来指定任意角色的话可以用ChatMessagePromptTemplate,这样就可以指定角色的名称,比如下面的代码,指定了角色名称为 Jedi。

from langchain.prompts import ChatMessagePromptTemplate

prompt = "May the {subject} be with you"

chat_message_prompt = ChatMessagePromptTemplate.from_template(role="Jedi", template=prompt)
chat_message_prompt.format(subject="force")
ChatMessage(content='May the force be with you', additional_kwargs={}, role='Jedi')

02 MessagesPlaceholder


同时,LangChain还为Message提供了占用符,我们可以使用MessagesPlaceholder来作为Message在占位符,这样我们可以根据实际的需要,在格式化prompt的时候动态地插入Message。

from langchain.prompts import MessagesPlaceholder

human_prompt = "Summarize our conversation so far in {word_count} words."
human_message_template = HumanMessagePromptTemplate.from_template(human_prompt)

chat_prompt = ChatPromptTemplate.from_messages([MessagesPlaceholder(variable_name="conversation"), human_message_template])

human_message = HumanMessage(content="What is the best way to learn programming?")
ai_message = AIMessage(content="""\
1. Choose a programming language: Decide on a programming language that you want to learn.

2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.

3. Practice, practice, practice: The best way to learn programming is through hands-on experience\
""")

chat_prompt.format_prompt(conversation=[human_message, ai_message], word_count="10").to_messages()
[HumanMessage(content='What is the best way to learn programming?', additional_kwargs={}),
 AIMessage(content='1. Choose a programming language: Decide on a programming language that you want to learn. \n\n2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.\n\n3. Practice, practice, practice: The best way to learn programming is through hands-on experience', additional_kwargs={}),
 HumanMessage(content='Summarize our conversation so far in 10 words.', additional_kwargs={})]

比如在上述代码中,在chat_prompt中定义了一个名为conversation的Message占位符,然后当chat_prompt调用format方法的时候,动态地将human_message,ai_message插入到占位符位置,从而替换占位符。

本文小结

MessagePromptTemplate在对话模型有着非常重要的作用,可以通过它来生成prompt;同时还可以通过MessagesPlaceholder实现占位符功能。

 更多最新文章,请关注公众号:大白爱爬山

### 使用 MessagePromptTemplate 及其相关实现 `MessagePromptTemplate` 是 LangChain 提供的一个类,用于定义聊天消息模板。它继承自 `BaseStringMessagePromptTemplate` 类[^2],并允许开发者通过模板化的方式动态生成特定类型的聊天消息。 以下是关于如何使用 `MessagePromptTemplate` 和其子类的相关说明: #### 1. 基本概念 `MessagePromptTemplate` 主要用于创建不同角色的消息模板(如系统消息、用户消息和助手消息)。这些模板可以被组合到更大的 `ChatPromptTemplate` 中,从而构建完整的多轮对话结构。 常见的子类包括: - **SystemMessagePromptTemplate**: 定义系统的指导信息。 - **HumanMessagePromptTemplate**: 定义用户的输入信息。 - **AIMessagePromptTemplate**: 定义模型的响应信息。 #### 2. 创建 SystemMessagePromptTemplate 实例 下面是一个简单的例子,展示如何创建一个 `SystemMessagePromptTemplate` 并将其嵌入到 `ChatPromptTemplate` 中: ```python from langchain.prompts import ( ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate, ) # 定义系统消息模板 system_message_prompt = SystemMessagePromptTemplate.from_template( template="You are a helpful assistant that re-writes the user's text to sound more upbeat." ) # 定义用户消息模板 human_message_prompt = HumanMessagePromptTemplate.from_template(template="{text}") # 将两者组合成 ChatPromptTemplate chat_prompt_template = ChatPromptTemplate.from_messages([ system_message_prompt, human_message_prompt ]) # 格式化消息 messages = chat_prompt_template.format_messages(text="I don't like eating tasty things") print(messages) ``` 上述代码展示了如何利用 `SystemMessagePromptTemplate` 设置上下文环境,并结合 `HumanMessagePromptTemplate` 动态生成用户输入的内容[^3]。 #### 3. 自定义 MessagePromptTemplate 如果需要更复杂的逻辑,可以通过扩展 `MessagePromptTemplate` 来实现自己的定制版本。例如,假设我们需要根据某些条件动态调整消息内容: ```python from typing import Any from pydantic.v1 import BaseModel from langchain.schema.messages import BaseMessage, SystemMessage from langchain.prompts.prompt import PromptTemplate class CustomMessagePromptTemplate(BaseModel, MessagePromptTemplate): prompt: PromptTemplate def format(self, **kwargs: Any) -> BaseMessage: formatted_text = self.prompt.format(**kwargs) return SystemMessage(content=formatted_text) custom_message_template = CustomMessagePromptTemplate(prompt=PromptTemplate.from_template("Custom instruction: {instruction}")) chat_prompt_template = ChatPromptTemplate.from_messages([custom_message_template]) result = chat_prompt_template.format_messages(instruction="Be polite and formal.") print(result) ``` 此示例演示了如何基于现有功能开发新的 `MessagePromptTemplate` 子类来满足特殊需求。 #### 4. 组合多种类型的消息 实际应用中通常会涉及多个不同类型的消息模板。以下是如何将它们集成在一起的例子: ```python from langchain.prompts.chat import ( ChatPromptTemplate, SystemMessagePromptTemplate, AIMessagePromptTemplate, HumanMessagePromptTemplate, ) template_system = "You will be acting as an expert in programming languages." template_human = "{question}" template_ai = "The answer is {answer}" prompt_system = SystemMessagePromptTemplate.from_template(template_system) prompt_human = HumanMessagePromptTemplate.from_template(template_human) prompt_ai = AIMessagePromptTemplate.from_template(template_ai) combined_chat_prompt = ChatPromptTemplate.from_messages([ prompt_system, prompt_human, prompt_ai ]) final_result = combined_chat_prompt.format_messages(question="What is Python?", answer="A versatile high-level language.") for msg in final_result: print(f"{msg.type}: {msg.content}") ``` 这段脚本显示了一个典型的三部分交互流程——先由系统设定主题,接着接收来自人类的问题最后给出 AI 的解答。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值