iT邦幫忙

2025 iThome 鐵人賽

DAY 28
0
自我挑戰組

從讀書筆記到可落地 AI:LangChain、LangSmith 與 Agent 工具 30 講系列 第 28

Day 28|Agent Design - Context - 用DSPy提高System Prompt的可維護性(4/5)

  • 分享至 

  • xImage
  •  

目標先講清楚:
Drew Breunig怎麼做到將一大串的system prompt使用DSPy去結構化,提高system prompt維護性

DSPy可以做到什麼?

Day 10 提到:「長而清楚的結構化提示」雖然能提高表現,但Drew Breunig提到這樣的長字串可讀性、可維護性、跨模型可攜性都很糟。
Drew Breunig 分析了 OpenAI SWE-Bench 的 prompt 組成:
https://ithelp.ithome.com.tw/upload/images/20251013/20178568s2jRvUEkdP.png

並示範用 DSPy 把「字串中的結構與規則」抽回程式模組管理。核心思路是:

  1. Part 1.: 把任務、輸入/輸出與格式(Task, Instructions, Formating Instructions),從一大段字串 prompt 中抽出來,轉換成DSPy的 Signature 與 Module 裡。
  2. Part 2.: 用 MIPROv2 以評測資料自動優化指令(Detailed Context & Instructions),並支援換模型後的再優化

Part 1.把任務、輸入/輸出與格式變成「Signature + Module」

理念:DSPY提供許多Module(挖空的Prompt template),使用者只需要專注在輸入、輸出的結構跟「描述」處理邏輯
https://ithelp.ithome.com.tw/upload/images/20251013/201785682yvNGUsBf7.jpg

流程

https://ithelp.ithome.com.tw/upload/images/20251013/20178568C9kMHnXbji.png

範例(以 Place Match 為例)

  • 目的:要判斷 place_oneplace_two 是否同一地點,並給出信心等級。

https://ithelp.ithome.com.tw/upload/images/20251013/2017856805J0Z5prug.jpg

  • Step 1. 定義 Signature-輸入/輸出/任務 -> PlaceMatcher(dspy.Signature)
  • Step 2. 選擇 Module-predict,將Signature帶入模板化的Prompt -> dspy. Predict (PlaceMatcher)

相關程式碼

DSPy組的Prompt,由 Signature + Module 組出,執行過程中不會顯示

可以使用adapter.format(signature, demos, inputs)查看

Your input fields are:  
1. `place_one` (Place): {...JSON schema...}  
2. `place_two` (Place): {...JSON schema...}  
  
Your output fields are:  
1. `match` (bool): Do the two places refer to the same place?  
2. `match_confidence` (Literal['low', 'medium', 'high'])  
  
All interactions will be structured in the following way...  
  
[[ ## place_one ## ]]  
{place_one}  
  
[[ ## place_two ## ]]  
{place_two}  
  
[[ ## match ## ]]  
{match}  
  
[[ ## match_confidence ## ]]  
{match_confidence}  
  
[[ ## completed ## ]]  
  
In adhering to this structure, your objective is:   
Verify that the text is based on the provided context.  

使用者訊息

[[ ## place_one ## ]]  
{"address": "123 Main St", "name": "Coffee Shop"}  
  
[[ ## place_two ## ]]  
{"address": "123 Main Street", "name": "Coffee Shop"}  
  
Respond with the corresponding output fields...  

模型回覆(經 JSONAdapter 解析)

{  
  "match": true,  
  "match_confidence": "high"  
}

重點:Signature 明確定義欄位與任務;Module 保證訊息骨架與輸出格式一致。從此不再手改 700 行字串,而是用程式宣告與型別來治理。


Part 2.用 MIPROv2 自動優化指令(可重跑以適配新模型)

理念

  1. 當你有了穩定的 Signature/Module 後,並且已經設計好驗證的資料集(D26D27的方式),使用DSPy的優化器-MIPROv2,可以讓模型用 eval data(驗證資料集)產生包含few-shot的指令。
  2. 只要換掉模型,重跑一次優化,就能得到適配新模型的最佳 prompt(因為會使用驗證資料跑新的Prompt的測試),不必手調長字串。

流程

https://ithelp.ithome.com.tw/upload/images/20251013/20178568x7vTe1COii.png

範例

https://ithelp.ithome.com.tw/upload/images/20251013/20178568ClHxbFGuwn.jpg

  1. 你有一批標註好的 place-match 範例(trainset)與指標(matcher)。
  2. 定義:
    • prompt_model:產生指令候選(寫 prompt 的「作者」)
    • task_model:執行任務與優化(實際跑任務的「選手」)
  3. MIPROv2 會先從trainset中引導 few-shot 候選(輸出正確的樣本會被保留)。
  4. 它用資料摘要、程式摘要與隨機提示技巧,生成多個指令候選
  5. 在驗證集上做多輪 prompt bake-off(小批量評測 + 週期性完整評測),以 貝葉斯優化找出最佳「指令 × few-shot」組合
  6. 需要換模型時,只要改成新模型,重跑優化即可得到新贏家。

輸出的結果

# example output
artifact = {
  "signature": "PlaceMatcher",
  "instruction": """
Given two records representing places or businesses—each with at least a name and address—analyze...
(這裡是一大段經過優化的指令文字,約數百 tokens)
""",
  "few_shot_examples": [
    {
      "inputs": {
        "place_one": {"name": "Peachtree Café", "address": "123 Peachtree St NE, Atlanta"},
        "place_two": {"name": "Peach Tree Coffee & Cafe", "address": "125 Peachtree Street NE, Atlanta"}
      },
      "gold_output": {"match": True, "match_confidence": "medium"}
    },
    {
      "inputs": { ... },
      "gold_output": { ... }
    }
  ],
  "settings": {
    "task_model": "gpt-4o-mini@2025-xx-xx",
    "prompt_model": "gpt-4o@2025-xx-xx",
    "search/trials": 48,
    "metric": "F1_place_match"
  }
}

# 假設框架提供 save/load(名稱依版本)
dspy.save(matcher_opt, "place_matcher_opt.json")
# 之後可:
matcher_opt = dspy.load("place_matcher_opt.json")

實務上你會把 matcher_opt(優化後模組)直接上線使用。當新模型出現時,只需替換 task_model,再跑一次三步驟優化,自動產出對新模型最合適的指令+示例


DSPy不只這些

  1. DSPy提供了6個核心模組(Modules)和10個優化器(Optimizers),分別適用於不同的AI任務情境
  2. 優化器(Optimizers)可以組合使用以獲得更好效果。

接下來要做什麼

agents的context包含很多的資料,因此,針對「LangChain 1.0」推出的新概念:Agent Middleware(代理中介層)- 目標是解決傳統 agent 抽象在進入生產環境時「無法精細控制 context engineering」的痛點,感到好奇.


參考資源

  1. Let the Model Write the Prompt
  2. 一文讲清楚什么是DSPy,为什么你开发 Agent 或 AI 应用需要它
  3. DSPy-Github

上一篇
Day 27|Agent Design - Agent Service Evaluation - 用LangSmith實現
系列文
從讀書筆記到可落地 AI:LangChain、LangSmith 與 Agent 工具 30 講28
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言