ChatPromptTemplate
PromptTemplate:通用提示词模板,支持动态注入信息。
FewShotPromptTemplate:支持基于模板注入任意数量的示例信息。
ChatPromptTemplate:支持注入任意数量的历史会话信息。
- 通过from_messages方法,从列表中获取多轮次会话作为聊天的基础模板
- 前面PromptTemplate类用的from_template仅能接入一条消息,而from_messages可以接入一个list的消息
历史会话信息并不是静态的(固定的),而是随着对话的进行不停地积攒,即动态的。
所以,历史会话信息需要支持动态注入。
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.prompts import MessagesPlaceholder
from langchain_community.chat_models.tongyi import ChatTongyi
chat_template = ChatPromptTemplate.from_messages([
("system", "你是一个专业的翻译,将用户的输入翻译成英文"),
MessagesPlaceholder(variable_name="messages"),
("human", "{input}"),
])
history_data = [
{"role": "user", "content": "你好"},
{"role": "assistant", "content": "Hello"},
{"role": "user", "content": "你是谁?"},
]
prompt_value = chat_template.invoke({
"messages": history_data,
"input": "你会做什么?",
}).to_string()
print(prompt_value)
model = ChatTongyi(model="qwen3-max")
response = model.invoke(prompt_value)
print(response.content)
System: 你是一个专业的翻译,将用户的输入翻译成英文
Human: 你好
AI: Hello
Human: 你是谁?
Human: 你会做什么?
Who are you?
What can you do?