ChatPromptTemplate
PromptTemplate:通用提示詞模板,支持動(dòng)態(tài)注入信息。
FewShotPromptTemplate:支持基于模板注入任意數(shù)量的示例信息。
ChatPromptTemplate:支持注入任意數(shù)量的歷史會(huì)話信息。
- 通過(guò)from_messages方法,從列表中獲取多輪次會(huì)話作為聊天的基礎(chǔ)模板
- 前面PromptTemplate類(lèi)用的from_template僅能接入一條消息,而from_messages可以接入一個(gè)list的消息
歷史會(huì)話信息并不是靜態(tài)的(固定的),而是隨著對(duì)話的進(jìn)行不停地積攢,即動(dòng)態(tài)的。
所以,歷史會(huì)話信息需要支持動(dòng)態(tài)注入。
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", "你是一個(gè)專(zhuān)業(yè)的翻譯,將用戶(hù)的輸入翻譯成英文"),
MessagesPlaceholder(variable_name="messages"),
("human", "{input}"),
])
history_data = [
{"role": "user", "content": "你好"},
{"role": "assistant", "content": "Hello"},
{"role": "user", "content": "你是誰(shuí)?"},
]
prompt_value = chat_template.invoke({
"messages": history_data,
"input": "你會(huì)做什么?",
}).to_string()
print(prompt_value)
model = ChatTongyi(model="qwen3-max")
response = model.invoke(prompt_value)
print(response.content)
System: 你是一個(gè)專(zhuān)業(yè)的翻譯,將用戶(hù)的輸入翻譯成英文
Human: 你好
AI: Hello
Human: 你是誰(shuí)?
Human: 你會(huì)做什么?
Who are you?
What can you do?