LLM
🧠 用 ChatPromptTemplate 打造 AI 對話角色!
2025-06-04 · — views
在跟 AI 打交道的世界裡,Prompt 就像是劇本,而 ChatPromptTemplate 就是導演,幫你安排每個角色該說什麼、怎麼說 🎬。
這篇文章會帶你了解:
-
💬 如何用
ChatPromptTemplate建立多角色的對話流程 -
🧑🤝🧑
System、Human、AI角色的三種寫法 -
🔍
.invoke()vs.format_messages()的差異與適用場景
🎭 三種建立 ChatPromptTemplate 的方式
ChatPromptTemplate 是 LangChain 裡非常實用的一個工具,讓我們可以把 prompt 結構化,支援多角色聊天。來看看這三種寫法👇
🧱 模板寫法 #1:使用角色模板物件
template_1 = ChatPromptTemplate.from_messages(
[
SystemMessagePromptTemplate.from_template("你是個聊天助理,請根據問題做回應。"),
HumanMessagePromptTemplate.from_template("{input}"),
AIMessagePromptTemplate.from_template("這是AI的回應。"),
]
)
🍱 模板寫法 #2:用 tuple 簡潔表示
template_2 = ChatPromptTemplate.from_messages(
[
("system", "你是個聊天助理,請根據問題做回應。"),
("human", "{input}"),
("ai", "這是AI的回應。"),
]
)
📦 模板寫法 #3:直接給 Message 物件
template_3 = ChatPromptTemplate.from_messages(
[
SystemMessage(content="你是個聊天助理,請根據問題做回應。"),
HumanMessage(content="{input}"),
AIMessage(content="這是AI的回應。"),
]
)
🧪 invoke() vs format_messages() 大對決!
建好Template後, 我們可以透過invoke() 或 format_messages()的function把變數填進去, 但兩者回傳的值稍有不同
prompt_invoke = template_1.invoke({"input": "hello world, this is a test of the AzureChatOpenAI model."})
prompt_format = template_1.format_messages(input="hello world, this is a test of the AzureChatOpenAI model.")
pprint(prompt_invoke) # returns a runnable object that can be invoked
pprint(prompt_format) # returns a list of BaseMessage objects
### result
.invoke() -> returns a runnable object that can be invoked
ChatPromptValue(
messages=[
SystemMessage(content='你是個聊天助理,請根據問題做回應。', additional_kwargs={}, response_metadata={}),
HumanMessage(
content='hello world, this is a test of the AzureChatOpenAI model.',
additional_kwargs={},
response_metadata={}
),
AIMessage(content='這是AI的回應。', additional_kwargs={}, response_metadata={})
]
)
------------
.format_messages() -> return a list of BaseMessage objects
[
SystemMessage(content='你是個聊天助理,請根據問題做回應。', additional_kwargs={}, response_metadata={}),
HumanMessage(
content='hello world, this is a test of the AzureChatOpenAI model.',
additional_kwargs={},
response_metadata={}
),
AIMessage(content='這是AI的回應。', additional_kwargs={}, response_metadata={})
]
來張簡單的比較表 👇
| 方法 | 回傳內容 | 適合用途 | 說明 |
|---|---|---|---|
.invoke() | 可直接丟進 LLM 的 runnable 物件 | 一步完成格式化+推論 🧠 | 內建觸發模型,像是快捷鍵 |
.format_messages() | 回傳一組 BaseMessage 列表 | 需要先格式化再自定處理 🛠️ | 拿到 raw message,靈活加工 |
🤖 ChatPromptTemplate 的魔法
你可以透過這種方式打造一個「多輪對話」、「指定語氣」、「不同角色扮演」的系統,比如客服助理、醫療諮詢師,甚至是戀愛諮詢員(?)💘
🧩 小結論
-
ChatPromptTemplate超適合組織多角色對話 -
3 種建立方式,看你需求自由選
-
.invoke()vs.format_messages()各有優勢
👉 有了這些工具,設計 prompt 就像在導戲一樣,讓 AI 更聰明、更有個性!