【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实现占位符功能。

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

你可能感兴趣的:(LangChain,langchain,prompt,chatgpt)