LangChain 提供不同类型的 MessagePromptTemplate。最常用的有 AIMessagePromptTemplate、SystemMessagePromptTemplate 和 HumanMessagePromptTemplate,它们分别用于创建 AI 消息、系统消息和人类消息。但是,在聊天模型支持使用任意角色的聊天消息时,可以使用 ChatMessagePromptTemplate,该模板允许用户指定角色名称。
from langchain.prompts import ChatMessagePromptTemplate
prompt = "愿{subject}与你同在"
chat_message_prompt = ChatMessagePromptTemplate.from_template(role="绝地武士", template=prompt)
chat_message_prompt.format(subject="原力")
ChatMessage(content='愿原力与你同在', additional_kwargs={}, role='绝地武士')
此外,LangChain 还提供了 MessagesPlaceholder,它可以完全控制格式化期间要渲染的消息。当您不确定应该使用哪个角色来生成消息提示模板时,或者希望在格式化过程中插入一系列消息时,这将非常有用。
from langchain.prompts import MessagesPlaceholder
human_prompt = "用{word_count}个词总结我们目前的对话。"
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={})]
```