Chuyển đến nội dung chính

課程 4:LLM 的 Prompt Contract、JSON Schema 與回歸測試

為各使用情境定義 prompt contract,強制輸出 schema, 建構防止 prompt 或模型變更時品質漂移的測試套件。

🧠 AI & ML — L1 課程 4:Prompt Contract、 JSON Schema 與 LLM 回歸測試 Gemma 4 本地 AI 工程實戰 on Mac 第二部分:Integration — API、Prompting 與應用整合 xdev.asia

前言

許多團隊失敗不是因為模型太弱,而是因為 prompt 沒有明確的 contract。Prompt 一改,輸出就漂移,應用程式悄然崩壞。

1. 什麼是 Prompt Contract

Prompt contract 包含四個部分:

  • 角色與任務範圍
  • 輸入格式
  • 輸出格式
  • 資料不足時的降級行為

降級行為範例:不要編造,回傳精確的短語如「資料不足」。

2. 輸出用 JSON Schema

行動項目擷取的 schema 範例:

{
  "type": "object",
  "required": ["summary", "items"],
  "properties": {
    "summary": {"type": "string"},
    "items": {
      "type": "array",
      "items": {
        "type": "object",
        "required": ["task", "owner"],
        "properties": {
          "task": {"type": "string"},
          "owner": {"type": "string"},
          "deadline": {"type": "string"}
        }
      }
    }
  }
}

收到模型輸出後立即驗證 schema。

3. 設計 Golden Test

建立包含以下內容的測試檔案:

  • 輸入 prompt
  • 應包含的內容
  • 不應包含的內容
  • Schema pass/fail

每次更改 prompt 或模型時,重新執行整個測試套件。

4. 錯誤分類

  • 格式錯誤:不符合 schema
  • 接地性錯誤:不依據上下文
  • 安全錯誤:回傳機密資料
  • 指令錯誤:無視系統限制

明確的錯誤碼有助於追蹤長期趨勢。

5. Prompt 版本控制

套用以下規則:

  • 所有 prompt 附帶版本碼
  • 每次變更的簡要變更歷史
  • 品質下降時的快速回滾

不要直接修改生產環境的 prompt 而不儲存版本。

Demo 程式碼

Prompt contract 測試結果 — 6/6 通過:

Prompt Contract 測試

原始碼:03-prompt-contracts

總結