PYTHON + LANGCHAIN 實戰課程

Unit 2: Prompt Engineering

掌握提示詞工程,讓 AI 精準輸出

PromptTemplate ChatPromptTemplate Few-shot Learning

什麼是 Prompt?

Prompt(提示詞)是你給 AI 的指令。好的 Prompt 決定 AI 輸出的品質。

差的 Prompt 好的 Prompt
幫我分析數據 請分析以下銷售數據,找出營收最高的前3個月份,並說明可能原因
寫程式 用 Python 寫一個函式,輸入是 CSV 路徑,輸出是該檔案的基本統計摘要
記住:越具體的指令,AI 的輸出越精準。

PromptTemplate 基礎用法

使用 PromptTemplate 建立可重複使用的提示詞模板:

# 匯入 PromptTemplate 提示模板類別
from langchain_core.prompts import PromptTemplate

# 建立模板,使用 {變數名} 作為佔位符(可動態填入內容)
template = PromptTemplate(
    input_variables=["product", "target"],  # 定義變數名稱列表
    template="請為 {product} 撰寫一段 50 字內的廣告文案,目標客群是 {target}"
)

# 使用 format 方法填入變數,產生完整 Prompt
prompt = template.format(product="藍牙耳機", target="上班族")
print(prompt)
# 輸出:請為 藍牙耳機 撰寫一段 50 字內的廣告文案,目標客群是 上班族

實作:PromptTemplate + LLM

# 匯入 LangChain OpenAI 聊天模型
from langchain_openai import ChatOpenAI
# 匯入 PromptTemplate 提示模板
from langchain_core.prompts import PromptTemplate

# 建立語言模型實例
llm = ChatOpenAI(model="gpt-5.6-luna")

# 建立資料分析專用模板(多行模板字串)
analysis_template = PromptTemplate(
    input_variables=["data_type", "focus"],  # 兩個動態變數
    template="""你是資料分析專家。
請針對 {data_type} 進行分析,重點關注 {focus}。
請用繁體中文回答,並以條列式呈現重點。"""
)

# 填入變數產生完整 Prompt
prompt = analysis_template.format(
    data_type="電商銷售數據",
    focus="季節性趨勢與客戶回購率"
)
# 將 Prompt 發送給 LLM 並取得回應
response = llm.invoke(prompt)
print(response.content)

ChatPromptTemplate 對話模板

針對聊天模型,可以設定 System、Human、AI 角色:

# 匯入 ChatPromptTemplate 對話提示模板
from langchain_core.prompts import ChatPromptTemplate

# 建立對話模板(可設定系統角色和使用者訊息)
chat_template = ChatPromptTemplate.from_messages([
    ("system", "你是一位專業的 {role},請用繁體中文回答"),  # 系統角色設定
    ("human", "{question}")  # 使用者問題
])

# 使用 format_messages 產生訊息列表
messages = chat_template.format_messages(
    role="股票分析師",
    question="台積電近期走勢如何?"
)

# 將訊息列表發送給 LLM
response = llm.invoke(messages)
print(response.content)

Few-shot Learning 範例學習

給 AI 幾個範例,讓它學習你期望的輸出格式:

# 匯入 Few-shot 提示模板和基本模板
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate

# 定義範例資料(讓 AI 學習輸入輸出的對應關係)
examples = [
    {"input": "台北今天很熱", "output": "天氣/觀察"},
    {"input": "這家餐廳超好吃", "output": "美食/正面評價"},
    {"input": "股票又跌了", "output": "財經/負面情緒"},
]

# 定義每個範例的格式模板
example_template = PromptTemplate(
    input_variables=["input", "output"],
    template="輸入:{input}\n分類:{output}"
)

# 建立 Few-shot 模板(結合範例和使用者輸入)
few_shot_prompt = FewShotPromptTemplate(
    examples=examples,            # 範例資料
    example_prompt=example_template,  # 範例格式
    prefix="請將以下句子分類(類別/情緒):",  # 提示開頭
    suffix="輸入:{user_input}\n分類:",       # 提示結尾(含使用者輸入)
    input_variables=["user_input"]  # 使用者輸入變數
)

# 產生完整 Prompt(包含範例引導)
prompt = few_shot_prompt.format(user_input="這部電影太精彩了")
print(prompt)

實作練習:建立數據摘要器

# 匯入 LangChain OpenAI 聊天模型
from langchain_openai import ChatOpenAI
# 匯入 ChatPromptTemplate 對話提示模板
from langchain_core.prompts import ChatPromptTemplate

# 建立語言模型實例
llm = ChatOpenAI(model="gpt-5.6-luna")

# 建立數據摘要專用模板(含系統角色設定和格式要求)
summary_template = ChatPromptTemplate.from_messages([
    ("system", """你是資料分析師。請根據以下數據產生摘要報告。
格式要求:
1. 關鍵發現(3-5 點)
2. 建議行動(2-3 點)
請用繁體中文回答。"""),
    ("human", "數據描述:{data_description}\n\n關鍵數字:{key_metrics}")
])

# 填入變數產生訊息列表
messages = summary_template.format_messages(
    data_description="某電商平台 2024 年 Q3 銷售數據",
    key_metrics="總營收 1.2 億,較去年同期成長 15%,客單價 850 元,回購率 42%"
)

# 發送給 LLM 並輸出摘要報告
response = llm.invoke(messages)
print(response.content)

Prompt 設計 5 大原則

1. 明確角色

"你是一位資深的..."

2. 具體任務

說明要做什麼、分析什麼

3. 格式要求

條列式、JSON、表格...

4. 範例引導

提供 1-3 個輸出範例

5. 限制條件

字數、語言、排除項目

Unit 2 總結

PromptTemplate

建立可重複使用的模板

ChatPromptTemplate

設定 System/Human 角色

Few-shot

用範例引導輸出格式

設計原則

角色、任務、格式、範例、限制

下一單元:Output Parsers - 讓 AI 輸出結構化數據

← 返回課程首頁