為什麼 Prompt Engineering 是核心技能?
上一課我們學會了呼叫 Gemini API,但「能呼叫」和「用得好」之間有巨大的鴻溝。同一個模型,不同的 prompt 可以讓輸出品質天差地別——這就是 Prompt Engineering 的價值。
對雲端工程師來說,Prompt Engineering 不只是「跟 AI 聊天的技巧」,而是系統設計的一部分。你的 prompt 決定了 AI 應用的輸出品質、一致性和可靠性,直接影響使用者體驗和商業價值。
本課目標
- 掌握 zero-shot、few-shot、chain-of-thought 三種核心策略
- 學會用 JSON mode 產出結構化輸出,讓 AI 回應可程式化處理
- 理解溫度(temperature)和 top-p 等參數如何影響輸出
- 建立可在生產環境使用的 prompt 模板
Zero-shot vs Few-shot Prompting
Zero-shot:直接提問
最簡單的方式——不給範例,直接問模型:
from google import genai
client = genai.Client(vertexai=True, project='YOUR_PROJECT', location='us-central1')
response = client.models.generate_content(
model='gemini-3.1-flash',
contents='將以下句子分類為「正面」「負面」或「中性」:\n\n「這家餐廳的服務態度很差,但食物還不錯。」'
)
print(response.text)
# 可能輸出:中性(或「混合」,格式不確定)
Zero-shot 簡單快速,但輸出格式不可控——有時回答「中性」,有時回答「這句話偏向中性,因為…」。
Few-shot:給範例引導
提供幾個輸入-輸出範例,讓模型理解你期望的格式和邏輯:
prompt = """將句子分類為「正面」「負面」或「中性」。只回答分類標籤,不要解釋。
範例:
句子:今天天氣真好,心情很棒!
分類:正面
句子:這部電影太無聊了,浪費我兩小時。
分類:負面
句子:明天會議改到下午三點。
分類:中性
句子:這家餐廳的服務態度很差,但食物還不錯。
分類:"""
response = client.models.generate_content(
model='gemini-3.1-flash',
contents=prompt
)
print(response.text)
# 輸出:中性
Few-shot 的威力在於範例即規格——你不需要用長篇文字描述輸出格式,幾個範例就能讓模型精確理解。
Few-shot 的最佳實踐
| 原則 | 說明 |
|---|---|
| 3-5 個範例 | 通常足夠,太多反而增加 token 成本 |
| 涵蓋邊界情況 | 範例應包含常見和邊界案例 |
| 格式一致 | 所有範例的格式必須完全一致 |
| 標籤多樣 | 確保每種分類標籤至少出現一次 |
💡 提示:Few-shot prompting 是成本效益最高的品質提升方式。在考慮微調(fine-tuning)之前,先嘗試 few-shot。
Chain-of-Thought(CoT)推理
對於需要邏輯推理的任務,直接問答容易出錯。Chain-of-Thought 讓模型在回答之前先「思考」,展示推理過程:
基本 CoT
prompt = """你是一位 GCP 架構師。根據以下需求,推薦最適合的資料庫服務。
需求:
- 全球部署的電商平台
- 需要跨區域的強一致性
- 每秒 10,000 筆交易
- 99.999% 可用性要求
請一步步分析,最後給出推薦。"""
response = client.models.generate_content(
model='gemini-3.1-flash',
contents=prompt
)
print(response.text)
模型會輸出類似:
讓我逐步分析這些需求:
1. 全球部署 → 需要多區域資料庫
2. 跨區域強一致性 → 排除最終一致性的選項(Firestore multi-region、Bigtable)
3. 每秒 10,000 筆交易 → 需要水平擴展能力,Cloud SQL 單實例可能不夠
4. 99.999% 可用性 → 只有 Cloud Spanner 的 multi-region 配置能達到
推薦:Cloud Spanner(multi-region configuration)
Zero-shot CoT 的魔法咒語
不想寫範例?只需在 prompt 結尾加上一句話:
prompt = """一家公司的 GCP 月帳單從 $5,000 飆升到 $15,000,主要增加來源是 Compute Engine。
工程師發現有 20 台 VM 在週末和夜間閒置。
請問最有效的成本優化策略是什麼?
請一步步思考(Let's think step by step)。"""
「一步步思考」這六個字能讓推理品質顯著提升,特別是在數學運算和多步邏輯判斷的任務上。
結構化輸出:JSON Mode
在生產環境中,AI 的輸出需要被程式碼解析。自由格式的文字回應難以可靠地解析——JSON mode 解決了這個問題。
使用 response_mime_type
from google import genai
from google.genai import types
import json
client = genai.Client(vertexai=True, project='YOUR_PROJECT', location='us-central1')
response = client.models.generate_content(
model='gemini-3.1-flash',
config=types.GenerateContentConfig(
response_mime_type='application/json'
),
contents="""分析以下 GCP 架構,回傳 JSON 格式的評估結果。
架構描述:
- 前端:Cloud Run(單區域 us-central1)
- 資料庫:Cloud SQL(無 HA)
- 快取:無
- CDN:無
- 監控:僅 Cloud Logging
JSON 格式要求:
{
"overall_score": 1-10 的整數,
"strengths": ["優點清單"],
"weaknesses": ["弱點清單"],
"recommendations": [
{"priority": "high/medium/low", "action": "建議動作", "reason": "原因"}
]
}"""
)
# 直接解析為 Python dict
result = json.loads(response.text)
print(f"架構評分:{result['overall_score']}/10")
for rec in result['recommendations']:
print(f" [{rec['priority']}] {rec['action']}")
使用 response_schema(更嚴格)
如果需要更嚴格的型別保證,可以定義 schema:
from google import genai
from google.genai import types
client = genai.Client(vertexai=True, project='YOUR_PROJECT', location='us-central1')
response = client.models.generate_content(
model='gemini-3.1-flash',
config=types.GenerateContentConfig(
response_mime_type='application/json',
response_schema={
'type': 'object',
'properties': {
'service_name': {'type': 'string'},
'category': {'type': 'string', 'enum': ['compute', 'storage', 'database', 'network', 'ai']},
'monthly_cost_usd': {'type': 'number'},
'is_serverless': {'type': 'boolean'}
},
'required': ['service_name', 'category', 'is_serverless']
}
),
contents='描述 Cloud Run 這個 GCP 服務。'
)
print(response.text)
# {"service_name": "Cloud Run", "category": "compute", "monthly_cost_usd": 0, "is_serverless": true}
💡 提示:在生產環境中,永遠使用 JSON mode。自由格式的文字輸出看起來很好,但一旦格式偶爾變化,你的解析程式碼就會崩潰。
溫度與取樣參數
模型的輸出不是確定性的——同一個 prompt 多次執行可能得到不同結果。以下參數控制輸出的「隨機程度」:
| 參數 | 範圍 | 效果 |
|---|---|---|
| temperature | 0.0 - 2.0 | 越低越確定(適合分類、擷取),越高越創意(適合寫作、腦力激盪) |
| top_p | 0.0 - 1.0 | 控制取樣的候選 token 範圍,越小越集中 |
| top_k | 1 - 40 | 限制每一步只從前 k 個 token 中選擇 |
| max_output_tokens | 1 - 8192+ | 限制輸出長度,防止成本失控 |
實用設定指南
from google.genai import types
# 精確任務(分類、擷取、JSON 輸出)
precise_config = types.GenerateContentConfig(
temperature=0.1,
top_p=0.8,
max_output_tokens=1024
)
# 創意任務(文案撰寫、腦力激盪)
creative_config = types.GenerateContentConfig(
temperature=1.2,
top_p=0.95,
max_output_tokens=2048
)
# 程式碼生成(平衡精確與多樣性)
code_config = types.GenerateContentConfig(
temperature=0.3,
top_p=0.9,
max_output_tokens=4096
)
| 場景 | 建議 temperature | 理由 |
|---|---|---|
| 分類 / 情感分析 | 0.0 - 0.2 | 需要一致且確定的結果 |
| 資料擷取 / JSON | 0.0 - 0.1 | 格式必須嚴格遵守 |
| 技術問答 | 0.3 - 0.5 | 平衡準確性與表達多樣性 |
| 文案 / 行銷內容 | 0.8 - 1.2 | 鼓勵創意和多樣性 |
| 腦力激盪 | 1.0 - 1.5 | 最大化創意發散 |
Prompt 模板化
在生產環境中,prompt 應該是參數化模板,而非硬編碼的字串:
from google import genai
from google.genai import types
client = genai.Client(vertexai=True, project='YOUR_PROJECT', location='us-central1')
# 定義可重用的 prompt 模板
GCP_REVIEW_TEMPLATE = """你是一位 GCP 認證架構師,負責審查雲端架構設計。
## 架構資訊
- 服務列表:{services}
- 可用性目標:{availability_target}
- 預算限制:{budget}
- 合規需求:{compliance}
## 審查要求
請從以下面向評估此架構:
1. 可靠性(是否達到可用性目標)
2. 安全性(是否符合合規需求)
3. 成本效益(是否在預算內)
4. 可維護性(營運複雜度是否合理)
以 JSON 格式回傳評估結果。"""
def review_architecture(services, availability, budget, compliance):
prompt = GCP_REVIEW_TEMPLATE.format(
services=services,
availability_target=availability,
budget=budget,
compliance=compliance
)
response = client.models.generate_content(
model='gemini-3.1-flash',
config=types.GenerateContentConfig(
temperature=0.2,
response_mime_type='application/json'
),
contents=prompt
)
return response.text
# 使用
result = review_architecture(
services='Cloud Run, Cloud SQL (no HA), Cloud Storage',
availability='99.99%',
budget='$500/月',
compliance='個資法'
)
print(result)
模板化的好處:
- 可版本控制 — prompt 變更可追蹤和回滾
- 可測試 — 相同輸入應產出一致品質的輸出
- 可重用 — 不同場景共享相同的評估框架
- 關注點分離 — 業務邏輯和 prompt 設計分離
常見反模式與修正
| 反模式 | 問題 | 修正 |
|---|---|---|
| 模糊指令 | 「幫我分析這個」 | 明確指定分析維度:「從成本、效能、安全三個面向分析」 |
| 過長 prompt | 3000 字的巨型 prompt | 拆分為 system instruction + 精簡 user prompt |
| 無格式要求 | 輸出格式每次不同 | 使用 JSON mode 或 few-shot 範例固定格式 |
| 忽略負面指令 | 「不要做 X」效果差 | 改為正面指令:「只做 Y」 |
| 缺乏角色設定 | AI 回答泛泛而談 | 用 system instruction 設定專家角色 |
實戰練習:GCP 服務分類器
結合本課所學,建構一個能自動分類 GCP 服務問題並路由至正確文件的工具:
from google import genai
from google.genai import types
import json
client = genai.Client(vertexai=True, project='YOUR_PROJECT', location='us-central1')
CLASSIFIER_SYSTEM = """你是 GCP 技術支援分類系統。根據使用者問題,判斷:
1. 問題類別(compute / storage / database / network / security / ai / billing)
2. 相關 GCP 服務(最多 3 個)
3. 緊急程度(critical / high / medium / low)
4. 建議的第一步行動"""
def classify_question(question: str) -> dict:
response = client.models.generate_content(
model='gemini-3.1-flash',
config=types.GenerateContentConfig(
system_instruction=CLASSIFIER_SYSTEM,
temperature=0.1,
response_mime_type='application/json',
response_schema={
'type': 'object',
'properties': {
'category': {'type': 'string'},
'services': {'type': 'array', 'items': {'type': 'string'}},
'urgency': {'type': 'string', 'enum': ['critical', 'high', 'medium', 'low']},
'first_action': {'type': 'string'}
},
'required': ['category', 'services', 'urgency', 'first_action']
}
),
contents=question
)
return json.loads(response.text)
# 測試
questions = [
"我的 Cloud SQL 突然連不上了,應用全部掛掉",
"想知道 BigQuery 的計費方式",
"如何設定 VPC 防火牆規則允許特定 IP"
]
for q in questions:
result = classify_question(q)
print(f"\n問題:{q}")
print(f" 類別:{result['category']} 緊急:{result['urgency']}")
print(f" 服務:{', '.join(result['services'])}")
print(f" 建議:{result['first_action']}")
重點整理
| 技巧 | 適用場景 | 核心要點 |
|---|---|---|
| Zero-shot | 簡單任務、快速原型 | 最簡單但輸出格式不可控 |
| Few-shot | 分類、格式化、風格模仿 | 3-5 個範例,涵蓋邊界情況 |
| Chain-of-Thought | 邏輯推理、多步決策 | 「一步步思考」顯著提升推理品質 |
| JSON mode | 生產環境、API 回應 | 永遠優於自由文字,可靠且可解析 |
| 溫度控制 | 所有場景 | 精確任務低溫(0-0.2),創意任務高溫(0.8-1.2) |
| Prompt 模板化 | 生產環境 | 參數化、可版本控制、可測試 |
核心原則:
- 先 few-shot,再考慮 fine-tuning — few-shot 成本為零且效果顯著
- 生產環境必用 JSON mode — 自由格式文字是不定時炸彈
- temperature 不是越低越好 — 看任務類型,創意任務需要高溫
- Prompt 是程式碼 — 應該版本控制、測試、程式碼審查
下一步
在下一課中,我們將探討 RAG(Retrieval-Augmented Generation)架構——學習如何用 Vertex AI Search 和 Agent Builder 讓 AI 在你的企業資料上精準回答,大幅減少幻覺問題。