27.RAG開(kāi)發(fā)-14-ChatPromptTemplate的使用

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?
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容