聊天信息提示词模板(char prompt template)
聊天模型以聊天信息作为输入,这个聊天消息列表的内容也可以通过提示词模板进行管理。
这些聊天消息与原始字符不同,因为每个消息都与“角色role”关联。
列如,在OpenAI的Chat Completion API中,OpenAI的聊天模板,给不同的聊天信息定义了三种角色类型,分别是助手(Assisant)、人类(human)、或系统(System)角色:
以下是创建聊天信息模板的例子
这个例子是通过文本描述来定义系统、助手等,关键字必须
Use one of 'human', 'user', 'ai', 'assistant', or 'system'
from langchain_ollama import ChatOllama
from langchain_core.prompts import ChatPromptTemplate
llm = ChatOllama(
model="deepseek-r1:7b",
)
chat_prompt = ChatPromptTemplate.from_messages([
("system", "你是西天取经的人工智能助手,你的名字叫齐天智能"),
("human", "你好"),
("ai", "您好,我是西天取经的人工智能助手,请问有什么可以帮助您?"),
("human", "{user_input}")
])
message = chat_prompt.format(user_input="你叫什么")
response = llm.invoke(message)
print(llm.invoke(message).content)
实际开发中,这个方式多一些,比较清晰
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
from langchain_core.prompts import HumanMessagePromptTemplate
chat_template = ChatPromptTemplate.from_messages(
[SystemMessage(
content=("你是西天取经的人工智能助手,你的名字叫齐天智能")
),
HumanMessage(
content=("你好")
),
AIMessage(
content=("您好,我是西天取经的人工智能助手,请问有什么可以帮助您?")
),
HumanMessagePromptTemplate.from_template("{text}"),
]
)
message = chat_template.format_messages(text="你叫什么")
print(message)
print("----------------------")
print(llm.invoke(message).content)
这个提示词模板负责在特定位置添加消息列表。
在前面两段中,我们看到了如何格式化两条消息,每条消息都是一个字符串,但是我们希望用户传入一个消息列表,我们将其插入到特定位置,该怎么办?
这里可以使用MessagesPlaceholder的方式
如下代码,这将会生成两条消息,第一条是系统消息,第二条是我们传入的HumanMessage。 如果我们传入了5条消息,那么总共会生成6条消息(系统消息加上传入的5条消息)、这对于将一系列消息插入到特定位置非常有用。
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_core.prompts import MessagesPlaceholder, MessagesPlaceholder
prompt_template = ChatPromptTemplate.from_messages(
[SystemMessage(
content=("你是西天取经的人工智能助手,你的名字叫齐天智能")
),
# 你可以传入一组消息
MessagesPlaceholder("msgs"),
HumanMessagePromptTemplate.from_template("{text}"),
]
)
message = prompt_template.invoke({"msgs":[HumanMessage(content="你好"),
AIMessage(content="您好,我是西天取经的人工智能助手,请问有什么可以帮助您?")],
"text": "你叫什么"})
# print("----------------")
print(llm.invoke(message).content )
LangChain 中用于构建聊天模型提示的类,它允许用户通过定义一系列消息模板来生成对话内容。
主要用于:创建聊天模型的输入提示,这些提示由多个消息组成,每个消息都有一个角色(如系统、用户或 AI)。它支持动态填充变量,能够根据输入参数生成具体的聊天消息列表。
从消息列表创建 ChatPromptTemplate 实例
根据输入参数格式化消息模板,生成具体的聊天消息列表。
SystemMessage
、HumanMessage
或 AIMessage
的实例。格式化提示模板,返回一个 PromptValue
对象,可以转换为字符串或消息列表。
**参数:**一个字典,包含模板中需要填充的变量及其值。
prompt_value = chat_template.format_prompt(name="Bob", user_input="What is your name?")
print(prompt_value.to_messages())
以AIMessage类
为例:
AIMessage
是 LangChain 中的一种消息类型,表示由 AI 模型生成的消息。一般LLM的回答,都是AIMessage
类
记一下以下几个参数
AIMessage(content="Hello, how can I help you today?")
AIMessage(content="Here is the answer.", role="assistant")
AIMessage(
content="I need to call the weather API.",
additional_kwargs={"tool_calls": [{"type": "weather_api", "args": {"location": "Beijing"}}]}
)