Skip to content

Latest commit

 

History

History
2832 lines (2451 loc) · 117 KB

File metadata and controls

2832 lines (2451 loc) · 117 KB

Neurosymbolic Forge 設計文檔

專案名稱: Neurosymbolic Forge (NSForge)
套件名稱: nsforge-mcp
版本: 0.1.0 (Draft)
日期: 2026-01-01
狀態: 設計階段

Where Neural Meets Symbolic


目錄

  1. 專案概述
  2. 背景知識
  3. 系統架構
  4. 核心組件
  5. MCP 工具定義
  6. 使用場景與範例
  7. 技術選型
  8. 實作計劃
  9. 參考資料

1. 專案概述

1.1 目標

建立一個 MCP (Model Context Protocol) Server,提供符號推理能力,讓 AI Agent 能夠:

  • 進行精確的數學符號運算(微積分、代數、方程求解等)
  • 處理物理、化學、熱力學等領域的公式推導
  • 分析演算法複雜度
  • 驗證推導過程的正確性

1.2 核心價值

傳統 LLM 方式 本專案方式
LLM 直接生成答案 LLM 生成結構化請求 → 符號引擎計算
每次結果可能不同 相同輸入 = 相同輸出(高度可再現性)
可能計算錯誤 數學正確性有保障
推導過程不透明 完整推導步驟可追蹤
無法驗證 可反向驗證結果

1.3 設計哲學

Neural-Symbolic AI 核心理念:

┌─────────────────────────────────────────────────────────────────┐
│                                                                 │
│   LLM (Neural)              Engine (Symbolic)                   │
│   ════════════              ═════════════════                   │
│                                                                 │
│   ✓ 理解模糊的自然語言      ✓ 精確執行邏輯運算                  │
│   ✓ 靈活處理多種輸入格式    ✓ 保證計算正確性                    │
│   ✓ 解釋結果給用戶          ✓ 提供推導步驟                      │
│                                                                 │
│   結合後:LLM 做「理解與翻譯」,Engine 做「精確計算」           │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

2. 背景知識

2.1 什麼是符號推理?

符號推理(Symbolic Reasoning)是使用明確的符號和規則進行邏輯運算的方法。

符號表示 vs 符號推理

概念 說明 範例
符號表示 用結構化符號描述知識(靜態) ∫ x² dx 寫在紙上
符號推理 對符號執行邏輯運算(動態) 計算出 x³/3 + C

與 Pseudo Code 的關係

Pseudo Code ──→ Parser ──→ 結構化表示 ──→ 執行引擎 ──→ 結果
   (靜態)                    (AST)          (動態)      (確定)
  • Pseudo Code 本身只是符號「表示」
  • 需要 Parser 解析 + Engine 執行,才產生「推理」

2.2 現有系統參考

Wolfram Alpha / Mathematica

自然語言 ──→ NL Parser ──→ Wolfram Language ──→ Symbolic Engine ──→ 結果
                          (符號表示)          (50+年研究)
  • 優點:涵蓋範圍廣、結果精確
  • 缺點:閉源、需要授權

Code Interpreter (OpenAI)

用戶請求 ──→ LLM 生成 Python ──→ Runtime 執行 ──→ 結果
                              (含 SymPy)
  • 優點:靈活、開放
  • 缺點:LLM 生成代碼可能出錯

Semantic Kernel (Microsoft)

Kernel
├── Semantic Functions (LLM prompts)
├── Native Functions (程式碼)
└── Planner (自動規劃)
  • 優點:統一框架、易於擴展
  • 缺點:需要自行整合計算引擎

3. 系統架構

3.1 整體架構圖

┌─────────────────────────────────────────────────────────────────────────────┐
│                  Neurosymbolic Forge (NSForge) MCP Server                   │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   AI Agent (LLM)                                                            │
│      │                                                                      │
│      │ MCP Protocol (JSON-RPC)                                              │
│      ▼                                                                      │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                        MCP Server                                   │    │
│  │                                                                     │    │
│  │   ┌─────────────────────────────────────────────────────────────┐   │    │
│  │   │                 Tool Layer (工具層)                         │   │    │
│  │   │                                                             │   │    │
│  │   │  symbolic_calculate  │  physics_formula  │  verify_derivation│   │    │
│  │   │  chemistry_calc      │  algorithm_analyze│  explain_concept │   │    │
│  │   └─────────────────────────────────────────────────────────────┘   │    │
│  │                              │                                      │    │
│  │                              ▼                                      │    │
│  │   ┌─────────────────────────────────────────────────────────────┐   │    │
│  │   │              Parser Layer (解析層)                          │   │    │
│  │   │                                                             │   │    │
│  │   │  • LaTeX Parser       • ASCII Math Parser                   │   │    │
│  │   │  • Natural Language   • Expression Tokenizer                │   │    │
│  │   └─────────────────────────────────────────────────────────────┘   │    │
│  │                              │                                      │    │
│  │                              ▼                                      │    │
│  │   ┌─────────────────────────────────────────────────────────────┐   │    │
│  │   │              Engine Layer (引擎層)                          │   │    │
│  │   │                                                             │   │    │
│  │   │  ┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐   │   │    │
│  │   │  │  SymPy    │ │ SciPy     │ │ Pint      │ │ Rule      │   │   │    │
│  │   │  │ (符號)    │ │ (數值)    │ │ (單位)    │ │ Engine    │   │   │    │
│  │   │  └───────────┘ └───────────┘ └───────────┘ └───────────┘   │   │    │
│  │   │                                                             │   │    │
│  │   └─────────────────────────────────────────────────────────────┘   │    │
│  │                              │                                      │    │
│  │                              ▼                                      │    │
│  │   ┌─────────────────────────────────────────────────────────────┐   │    │
│  │   │              Knowledge Layer (知識層)                       │   │    │
│  │   │                                                             │   │    │
│  │   │  • 物理公式庫     • 化學反應規則    • 數學定理庫           │   │    │
│  │   │  • 單位轉換表     • 常數定義        • 演算法模式庫         │   │    │
│  │   └─────────────────────────────────────────────────────────────┘   │    │
│  │                              │                                      │    │
│  │                              ▼                                      │    │
│  │   ┌─────────────────────────────────────────────────────────────┐   │    │
│  │   │           🆕 Derivation Planner (推導規劃層)                │   │    │
│  │   │                                                             │   │    │
│  │   │  • 推導策略選擇   • 公式依賴圖譜    • 多步驟編排           │   │    │
│  │   │  • 中間結果管理   • 推導模板庫      • 交互式澄清           │   │    │
│  │   └─────────────────────────────────────────────────────────────┘   │    │
│  │                                                                     │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

3.2 資料流程

用戶自然語言
    │
    ▼
┌─────────────────┐
│   AI Agent      │  理解意圖,決定使用哪個工具
│   (LLM)         │  
└────────┬────────┘
         │ MCP Tool Call
         ▼
┌─────────────────┐
│   Tool Layer    │  接收結構化請求
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  Parser Layer   │  解析表達式(LaTeX/ASCII/NL)
│                 │  生成 AST 或結構化命令
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  Engine Layer   │  執行符號運算
│  (SymPy etc.)   │  生成推導步驟
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  Response       │  格式化結果
│  Formatter      │  包含 LaTeX、步驟、驗證
└────────┬────────┘
         │
         ▼
    返回給 Agent

3.3 🆕 多步推導架構(關鍵設計)

問題:SymPy 的侷限性

SymPy 是優秀的符號計算引擎,但它是「執行器」而非「規劃器」:

SymPy 能做的:                         SymPy 不會做的:
────────────────                       ────────────────
✅ diff(x**3, x) → 3x²                 ❌ 不知道「下一步該用什麼公式」
✅ integrate(x**2, x) → x³/3           ❌ 不知道「這個結果要代入哪裡」
✅ solve(x**2 - 4, x) → [-2, 2]        ❌ 不知道「還需要哪些中間步驟」
✅ simplify(expr)                      ❌ 不知道「什麼時候推導完成」

解決方案:Derivation Planner(推導規劃器)

┌─────────────────────────────────────────────────────────────────────────────┐
│                        多步推導架構                                         │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   問題輸入                                                                  │
│      │                                                                      │
│      ▼                                                                      │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │              Problem Analyzer(問題分析器)                         │    │
│  │                                                                     │    │
│  │  • 識別問題類型(碰撞、熱力學、電路...)                            │    │
│  │  • 提取已知量和未知量                                               │    │
│  │  • 識別需要的物理定律/公式                                          │    │
│  │  • 檢查參數完整性                                                   │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│      │                                                                      │
│      ▼                                                                      │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │              Derivation Planner(推導規劃器)                       │    │
│  │                                                                     │    │
│  │  輸入:問題類型 + 已知/未知量 + 可用公式                            │    │
│  │  輸出:推導計劃(步驟序列)                                         │    │
│  │                                                                     │    │
│  │  ┌─────────────────────────────────────────────────────────────┐    │    │
│  │  │  Formula Knowledge Graph(公式知識圖譜)                    │    │    │
│  │  │                                                             │    │    │
│  │  │   動量守恆 ──────→ 碰撞後速度                               │    │    │
│  │  │      │                  │                                   │    │    │
│  │  │      ▼                  ▼                                   │    │    │
│  │  │   能量守恆 ──────→ 能量損失                                 │    │    │
│  │  │      │                  │                                   │    │    │
│  │  │      ▼                  ▼                                   │    │    │
│  │  │   彈簧力學 ←───── 速度變化 ───→ 張力計算                    │    │    │
│  │  │                                                             │    │    │
│  │  └─────────────────────────────────────────────────────────────┘    │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│      │                                                                      │
│      ▼                                                                      │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │              Step Executor(步驟執行器)                            │    │
│  │                                                                     │    │
│  │  For each step in plan:                                             │    │
│  │    1. 準備輸入(從前步結果或已知量)                                │    │
│  │    2. 呼叫 SymPy 執行計算                                           │    │
│  │    3. 驗證結果(維度檢查、合理性)                                  │    │
│  │    4. 儲存中間結果                                                  │    │
│  │    5. 更新推導狀態                                                  │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│      │                                                                      │
│      ▼                                                                      │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │              Result Assembler(結果組裝器)                         │    │
│  │                                                                     │    │
│  │  • 組合所有步驟的推導過程                                           │    │
│  │  • 生成最終表達式                                                   │    │
│  │  • 產生驗證(反向推導檢查)                                         │    │
│  │  • 格式化輸出(LaTeX + 步驟說明)                                   │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

公式知識圖譜(Formula Knowledge Graph)

這是多步推導的核心:記錄公式之間的「依賴關係」和「轉換路徑」。

# 知識圖譜結構範例
formula_graph = {
    "collision_velocity": {
        "formula": "v_final = (m1*v1 + m2*v2) / (m1 + m2)",
        "inputs": ["m1", "m2", "v1", "v2"],
        "outputs": ["v_final"],
        "prerequisites": [],  # 不需要前置公式
        "domain": "mechanics",
        "tags": ["collision", "momentum"]
    },
    
    "velocity_change": {
        "formula": "delta_v = v_initial - v_final",
        "inputs": ["v_initial", "v_final"],
        "outputs": ["delta_v"],
        "prerequisites": ["collision_velocity"],  # 需要先算碰撞後速度
        "domain": "mechanics",
        "tags": ["kinematics"]
    },
    
    "spring_extension": {
        "formula": "x = delta_v * sqrt(m/k)",
        "inputs": ["delta_v", "m", "k"],
        "outputs": ["x"],
        "prerequisites": ["velocity_change"],  # 需要先算速度變化
        "domain": "mechanics",
        "tags": ["spring", "energy"]
    },
    
    "spring_force": {
        "formula": "F = k * x",
        "inputs": ["k", "x"],
        "outputs": ["F"],
        "prerequisites": ["spring_extension"],
        "domain": "mechanics",
        "tags": ["spring", "force"]
    }
}

推導計劃生成演算法

class DerivationPlanner:
    def __init__(self, formula_graph):
        self.graph = formula_graph
    
    def plan_derivation(self, known_vars: set, target_var: str) -> List[Step]:
        """
        使用 BFS/DFS 在公式圖譜中找出推導路徑
        
        Args:
            known_vars: 已知變數集合 {"m1", "m2", "v1", "v2", "k"}
            target_var: 目標變數 "F" (張力)
        
        Returns:
            推導步驟列表
        """
        # 找出能產生 target_var 的公式
        target_formulas = self._find_formulas_producing(target_var)
        
        plan = []
        for formula in target_formulas:
            # 檢查這個公式的輸入是否都可得
            missing = set(formula["inputs"]) - known_vars
            
            if not missing:
                # 所有輸入都已知,可以直接計算
                plan.append(Step(formula=formula, reason="直接計算"))
            else:
                # 需要先推導缺少的變數
                for var in missing:
                    sub_plan = self.plan_derivation(known_vars, var)
                    plan.extend(sub_plan)
                    known_vars.add(var)  # 現在這個變數已知了
                plan.append(Step(formula=formula, reason="代入前步結果"))
        
        return plan
    
    def check_completeness(self, known_vars: set, target_var: str) -> dict:
        """
        檢查是否有足夠的已知量來推導目標
        
        Returns:
            {
                "complete": True/False,
                "missing": ["var1", "var2"],  # 缺少的變數
                "suggestions": ["可以假設...", "需要用戶提供..."]
            }
        """
        # ... 分析邏輯

推導模板(Derivation Templates)

對於常見問題類型,預定義推導流程:

derivation_templates = {
    "collision_force": {
        "description": "碰撞過程中的力分析",
        "steps": [
            {
                "name": "momentum_conservation",
                "description": "應用動量守恆求碰撞後速度",
                "formula": "collision_velocity",
                "comment": "假設碰撞時間極短,外力可忽略"
            },
            {
                "name": "velocity_change",
                "description": "計算速度變化量",
                "formula": "velocity_change",
                "comment": "這是人/物體需要經歷的減速"
            },
            {
                "name": "deceleration_analysis",
                "description": "分析減速過程",
                "formula": "spring_extension",
                "comment": "用能量守恆求安全帶伸長量"
            },
            {
                "name": "force_calculation",
                "description": "計算最大張力",
                "formula": "spring_force",
                "comment": "F = kx,在最大伸長時張力最大"
            }
        ],
        "required_inputs": ["m1", "m2", "v", "m_person", "k"],
        "output": "F_max"
    },
    
    "thermodynamic_work": {
        "description": "熱力學過程做功計算",
        "steps": [
            # ... 類似結構
        ]
    }
}

交互式澄清(Interactive Clarification)

當推導無法繼續時,產生有意義的問題:

class InteractiveClarifier:
    def generate_clarification(self, derivation_state) -> dict:
        """
        根據推導狀態,生成需要澄清的問題
        """
        if derivation_state.missing_vars:
            return {
                "type": "missing_parameters",
                "message": f"缺少以下參數:{derivation_state.missing_vars}",
                "questions": [
                    f"請提供 {var} 的值或合理估計" 
                    for var in derivation_state.missing_vars
                ],
                "suggestions": self._suggest_defaults(derivation_state)
            }
        
        if derivation_state.ambiguous_path:
            return {
                "type": "multiple_approaches",
                "message": "有多種推導方法可用",
                "options": [
                    {"name": "方法A", "description": "使用能量守恆", "pros": "精確", "cons": "需要更多參數"},
                    {"name": "方法B", "description": "使用動量-衝量", "pros": "簡單", "cons": "需要假設碰撞時間"}
                ],
                "question": "您希望使用哪種方法?"
            }
        
        if derivation_state.assumption_needed:
            return {
                "type": "assumption_required", 
                "message": "需要做出假設才能繼續",
                "assumptions": [
                    {"name": "理想彈簧", "description": "安全帶為理想彈簧,無阻尼"},
                    {"name": "剛性連接", "description": "人與車剛性連接,同速運動"}
                ],
                "question": "以上假設是否合理?"
            }

完整範例:車輛碰撞問題的多步推導

# 輸入
problem = {
    "type": "collision_force_analysis",
    "known": {
        "m": "70 kg",      # 人的質量
        "M1": "1500 kg",   # 車1質量
        "M2": "2000 kg",   # 車2質量
        "v": "50 km/h",    # 初速度
        "theta": "45°",    # 碰撞角度
        "k": "5000 N/m",   # 安全帶彈性係數
        "eta": "0.7"       # 能量保留比例
    },
    "find": ["T_max", "material_strength"]
}

# Derivation Planner 輸出的推導計劃
derivation_plan = [
    Step(1, "動量守恆(碰撞後速度)", 
         formula="v' = M1*v*cos(θ) / (M1+M2)",
         inputs=["M1", "M2", "v", "theta"],
         output="v_final"),
    
    Step(2, "速度變化量",
         formula="Δv = v*cos(θ) - v'",
         inputs=["v", "theta", "v_final"],
         output="delta_v"),
    
    Step(3, "能量守恆(安全帶伸長)",
         formula="x = Δv * sqrt(m/k)",
         inputs=["delta_v", "m", "k"],
         output="x"),
    
    Step(4, "最大張力",
         formula="T_max = k * x = Δv * sqrt(m*k)",
         inputs=["delta_v", "m", "k"],
         output="T_max"),
    
    Step(5, "材料強度要求",
         formula="σ_required = T_max * SF",
         inputs=["T_max", "SF=3.0"],
         output="material_strength")
]

# 每一步都由 SymPy 精確執行
for step in derivation_plan:
    result = sympy_engine.execute(step)
    step.result = result
    step.verification = sympy_engine.verify(result)

這個架構解決了什麼問題?

┌─────────────────────────────────────────────────────────────────────────────┐
│                        問題 → 解決方案                                      │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ❌ 問題 1:「下一步該用什麼公式?」                                        │
│  ✅ 解決:Formula Knowledge Graph 記錄公式依賴關係                          │
│          Derivation Planner 自動規劃推導路徑                                │
│                                                                             │
│  ❌ 問題 2:「這個結果要代入哪裡?」                                        │
│  ✅ 解決:每個公式定義 inputs/outputs                                       │
│          Step Executor 自動傳遞中間結果                                     │
│                                                                             │
│  ❌ 問題 3:「參數不夠怎麼辦?」                                            │
│  ✅ 解決:check_completeness() 預先檢查                                     │
│          Interactive Clarifier 產生有意義的問題                             │
│                                                                             │
│  ❌ 問題 4:「有多種推導方法怎麼選?」                                      │
│  ✅ 解決:Derivation Templates 提供標準流程                                 │
│          Agent 可以詢問用戶偏好                                             │
│                                                                             │
│  ❌ 問題 5:「推導過程對不對?」                                            │
│  ✅ 解決:每步都由 SymPy 精確執行                                           │
│          Result Assembler 提供完整推導鏈                                    │
│          可進行維度分析和反向驗證                                           │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

3.4 🆕 推導 DSL(Derivation Domain-Specific Language)

為什麼需要 Pseudo Code 風格的推導語言?

傳統方式的問題:
─────────────────────────────────────────────────────────────────────────────
  「對 RC 低通濾波器,求截止頻率和相位延遲」
  
  這句話隱含了太多步驟:
  1. 建立電路模型(哪種拓撲?)
  2. 選擇分析方法(時域?頻域?)
  3. 推導傳遞函數
  4. 求出截止頻率
  5. 計算相位響應
  6. 從相位響應導出群延遲
  
  → 每一步都可能有多種做法,LLM 直接生成答案容易出錯
─────────────────────────────────────────────────────────────────────────────

DSL 的解決方案:
─────────────────────────────────────────────────────────────────────────────
  用結構化的「推導腳本」明確描述每一步,
  每步都可以被符號引擎驗證執行
─────────────────────────────────────────────────────────────────────────────

推導 DSL 語法設計

# derivation_script.yaml - 推導腳本範例

derivation:
  name: "RC低通濾波器頻率響應分析"
  domain: "circuit_analysis"
  
  # 宣告符號
  symbols:
    - {name: R, type: positive_real, unit: ohm, description: "電阻"}
    - {name: C, type: positive_real, unit: farad, description: "電容"}
    - {name: s, type: complex, description: "Laplace 變數"}
    - {name: omega, type: positive_real, unit: rad/s, description: "角頻率"}
    - {name: f, type: positive_real, unit: Hz, description: "頻率"}
  
  # 推導步驟
  steps:
    - id: step_1
      action: define_circuit
      description: "定義 RC 低通濾波器電路"
      circuit:
        topology: series_RC
        input: V_in
        output: V_out  # 跨電容的電壓
      
    - id: step_2
      action: derive_transfer_function
      description: "推導傳遞函數 H(s) = V_out/V_in"
      method: voltage_divider
      formula: |
        Z_C = 1/(s*C)
        Z_R = R
        H(s) = Z_C / (Z_R + Z_C)
      result: H_s
      
    - id: step_3
      action: simplify
      description: "化簡傳遞函數"
      input: H_s
      expected_form: "1 / (1 + s*R*C)"
      result: H_s_simplified
      
    - id: step_4
      action: substitute
      description: "代入 s = jω 得到頻率響應"
      input: H_s_simplified
      substitution: {s: I*omega}  # I 是虛數單位
      result: H_jw
      
    - id: step_5
      action: solve_for
      description: "求截止頻率(|H| = 1/√2 時)"
      equation: "Abs(H_jw) = 1/sqrt(2)"
      solve_for: omega
      result: omega_c
      verification: "omega_c = 1/(R*C)"
      
    - id: step_6
      action: derive_phase
      description: "計算相位響應"
      input: H_jw
      operation: arg  # 取幅角
      result: phi_omega
      expected: "-atan(omega * R * C)"
      
    - id: step_7
      action: derive_group_delay
      description: "計算群延遲(相位對頻率的導數)"
      formula: "tau_g = -d(phi_omega)/d(omega)"
      input: phi_omega
      result: group_delay
      
  # 最終輸出
  outputs:
    - {name: H_s, description: "傳遞函數", latex: "H(s) = \\frac{1}{1+sRC}"}
    - {name: omega_c, description: "截止角頻率", latex: "\\omega_c = \\frac{1}{RC}"}
    - {name: f_c, description: "截止頻率", latex: "f_c = \\frac{1}{2\\pi RC}"}
    - {name: phi_omega, description: "相位響應", latex: "\\phi(\\omega) = -\\arctan(\\omega RC)"}
    - {name: group_delay, description: "群延遲", latex: "\\tau_g = \\frac{RC}{1+(\\omega RC)^2}"}

DSL 執行引擎

class DerivationDSLEngine:
    """推導 DSL 解釋器"""
    
    def __init__(self):
        self.symbol_table = {}  # 符號表
        self.results = {}       # 中間結果
        self.trace = []         # 執行追蹤
    
    def execute_script(self, script: dict) -> DerivationResult:
        """執行推導腳本"""
        
        # 1. 初始化符號
        self._init_symbols(script["symbols"])
        
        # 2. 逐步執行
        for step in script["steps"]:
            result = self._execute_step(step)
            self.results[step["result"]] = result
            self.trace.append({
                "step_id": step["id"],
                "description": step["description"],
                "input": step.get("input"),
                "result": result,
                "latex": sympy.latex(result)
            })
        
        # 3. 組裝輸出
        return DerivationResult(
            outputs=self._format_outputs(script["outputs"]),
            trace=self.trace,
            verification=self._verify_results(script)
        )
    
    def _execute_step(self, step: dict):
        """執行單一推導步驟"""
        action = step["action"]
        
        if action == "derive_transfer_function":
            return self._derive_transfer_function(step)
        elif action == "simplify":
            expr = self.results[step["input"]]
            return sympy.simplify(expr)
        elif action == "substitute":
            expr = self.results[step["input"]]
            subs = {sympy.Symbol(k): self._parse_expr(v) 
                    for k, v in step["substitution"].items()}
            return expr.subs(subs)
        elif action == "solve_for":
            return self._solve_equation(step)
        elif action == "derive_phase":
            expr = self.results[step["input"]]
            return sympy.arg(expr)
        elif action == "derive_group_delay":
            phi = self.results[step["input"]]
            omega = self.symbol_table["omega"]
            return -sympy.diff(phi, omega)
        # ... 更多 action 類型

3.5 🆕 系統級推導範例:Audio Amplifier 電路分析

問題描述

場景:修改 Audio Amplifier 電路
─────────────────────────────────────────────────────────────────────────────
原始電路:
  • 單級訊號放大 (Voltage Gain)
  • 小濾波電容 C1
  • 有負回授 (Negative Feedback)

修改後:
  • 加入功率放大級 (Power Stage)
  • 更大的濾波電容 C2 >> C1
  • 移除負回授 (Open Loop)

問題:
  1. 這些修改如何影響頻率響應?
  2. 對音訊延遲有什麼影響?
  3. 會產生什麼失真?
─────────────────────────────────────────────────────────────────────────────

推導腳本:音頻放大器頻率響應分析

derivation:
  name: "音頻放大器修改後的頻率響應分析"
  domain: "circuit_analysis"
  
  # === 符號定義 ===
  symbols:
    # 原始電路參數
    - {name: R_in, type: positive_real, unit: ohm, description: "輸入電阻"}
    - {name: R_load, type: positive_real, unit: ohm, description: "負載電阻"}
    - {name: C1, type: positive_real, unit: farad, description: "原濾波電容"}
    - {name: C2, type: positive_real, unit: farad, description: "新濾波電容 (C2 >> C1)"}
    - {name: A_ol, type: positive_real, description: "開環增益"}
    - {name: beta, type: positive_real, description: "回授係數"}
    
    # 頻率變數
    - {name: s, type: complex, description: "Laplace 變數"}
    - {name: f, type: positive_real, unit: Hz, description: "頻率"}
    - {name: omega, type: positive_real, unit: rad/s, description: "角頻率"}
  
  # === 系統建模 ===
  systems:
    original_amp:
      description: "原始放大器(有負回授)"
      blocks:
        - {type: gain, value: A_ol, name: "開環增益"}
        - {type: lowpass_rc, R: R_in, C: C1, name: "輸入濾波"}
        - {type: feedback, beta: beta, name: "負回授"}
      topology: "input → lowpass_rc → gain → output, output → feedback → input"
      
    modified_amp:
      description: "修改後放大器(無負回授 + 大電容)"
      blocks:
        - {type: gain, value: A_ol, name: "開環增益"}
        - {type: lowpass_rc, R: R_in, C: C2, name: "輸入濾波(大電容)"}
        - {type: power_stage, gain: A_p, name: "功率放大級"}
      topology: "input → lowpass_rc → gain → power_stage → output"
  
  # === 推導步驟 ===
  steps:
    # --- Part 1: 原始電路分析 ---
    - id: orig_1
      action: derive_transfer_function
      system: original_amp
      description: "原始電路傳遞函數(含負回授)"
      method: feedback_formula  # H = A / (1 + A*beta)
      result: H_original
      
    - id: orig_2
      action: find_cutoff_frequency
      input: H_original
      description: "原始電路截止頻率"
      result: f_c_original
      expected: "f_c_original = (1 + A_ol*beta) / (2*pi*R_in*C1)"
      note: "負回授擴展了頻寬!"
      
    - id: orig_3
      action: derive_phase
      input: H_original
      description: "原始電路相位響應"
      result: phi_original
      
    # --- Part 2: 修改後電路分析 ---
    - id: mod_1
      action: derive_transfer_function
      system: modified_amp
      description: "修改後傳遞函數(無回授)"
      method: cascade  # H = H1 * H2 * H3
      result: H_modified
      
    - id: mod_2
      action: find_cutoff_frequency
      input: H_modified
      description: "修改後截止頻率"
      result: f_c_modified
      expected: "f_c_modified = 1 / (2*pi*R_in*C2)"
      note: "C2 >> C1,截止頻率大幅下降"
      
    - id: mod_3
      action: derive_phase
      input: H_modified
      description: "修改後相位響應"
      result: phi_modified
      
    # --- Part 3: 比較分析 ---
    - id: compare_1
      action: compute_ratio
      description: "截止頻率變化比例"
      formula: "f_c_original / f_c_modified"
      result: freq_ratio
      interpretation: |
        若 C2 = 10*C1 且移除負回授:
        freq_ratio ≈ (1 + A_ol*beta) * (C2/C1)
        假設 A_ol*beta = 100, C2/C1 = 10
        → 截止頻率下降約 1000 倍!
      
    - id: compare_2
      action: derive_group_delay
      inputs: [phi_original, phi_modified]
      description: "群延遲比較"
      result: [tau_g_original, tau_g_modified]
      
    - id: compare_3
      action: evaluate_at_frequency
      description: "在 1kHz(音頻中頻)的延遲"
      inputs: [tau_g_original, tau_g_modified]
      at: {f: 1000}  # 1 kHz
      result: [delay_original_1k, delay_modified_1k]
      
    # --- Part 4: 實際影響評估 ---
    - id: impact_1
      action: analyze_audio_impact
      description: "對音頻的實際影響"
      analysis:
        frequency_response:
          - "低頻增強:大電容降低低頻截止點"
          - "高頻衰減:截止頻率下降導致高頻滾降"
        phase_distortion:
          - "相位失真增加:無負回授時相位更非線性"
          - "群延遲不均勻:不同頻率延遲不同"
        amplitude:
          - "增益增加:移除負回授後增益從 A/(1+Aβ) 變為 A"
          - "可能過載:需要降低輸入或加衰減"
      
  # === 數值範例 ===
  numerical_example:
    parameters:
      R_in: 10e3      # 10 kΩ
      C1: 100e-12     # 100 pF
      C2: 1e-6        # 1 µF (大 10000 倍)
      A_ol: 1000      # 開環增益 60 dB
      beta: 0.1       # 回授係數
      A_p: 10         # 功率級增益
      
    results:
      original:
        closed_loop_gain: "A_ol / (1 + A_ol*beta) = 1000/101 ≈ 9.9"
        bandwidth: "(1 + A_ol*beta) / (2π*R_in*C1) ≈ 161 kHz"
        delay_at_1k: "< 1 µs"
        
      modified:
        total_gain: "A_ol * A_p = 10000 (80 dB)"
        bandwidth: "1 / (2π*R_in*C2) ≈ 16 Hz"  # 極窄!
        delay_at_1k: "~100 µs - 取決於極點位置"
        
    warnings:
      - "⚠️ 截止頻率 16 Hz 太低,會嚴重衰減音頻"
      - "⚠️ 開環運作增益過高,易飽和失真"
      - "⚠️ 相位響應非線性增加"
      
    recommendations:
      - "減小 C2 或增加並聯電阻以提高截止頻率"
      - "加入局部負回授穩定增益"
      - "考慮多極點補償以平坦化群延遲"

  # === 輸出 ===
  outputs:
    - name: frequency_response_comparison
      description: "頻率響應對比(Bode 圖數據)"
      format: plot_data
      
    - name: phase_response_comparison
      description: "相位響應對比"
      format: plot_data
      
    - name: group_delay_comparison
      description: "群延遲對比"
      format: plot_data
      
    - name: summary_table
      description: "參數對比表"
      columns: [Parameter, Original, Modified, Change]

DSL 執行結果範例

當 Agent 要求分析這個電路修改時,MCP Server 返回:

{
  "analysis_type": "audio_amplifier_modification",
  
  "transfer_functions": {
    "original": {
      "latex": "H_{orig}(s) = \\frac{A_{ol}}{(1 + A_{ol}\\beta)(1 + sR_{in}C_1)}",
      "sympy": "A_ol / ((1 + A_ol*beta) * (1 + s*R_in*C1))"
    },
    "modified": {
      "latex": "H_{mod}(s) = \\frac{A_{ol} \\cdot A_p}{1 + sR_{in}C_2}",
      "sympy": "A_ol * A_p / (1 + s*R_in*C2)"
    }
  },
  
  "cutoff_frequencies": {
    "original": {
      "formula": "f_c = (1 + A_ol*beta) / (2*pi*R_in*C1)",
      "numerical": "161 kHz",
      "comment": "負回授擴展頻寬"
    },
    "modified": {
      "formula": "f_c = 1 / (2*pi*R_in*C2)",
      "numerical": "16 Hz",
      "comment": "⚠️ 遠低於音頻範圍下限 20 Hz"
    }
  },
  
  "group_delay": {
    "original": {
      "formula_latex": "\\tau_g = \\frac{R_{in}C_1}{1 + (\\omega R_{in}C_1)^2}",
      "at_1kHz": "< 1 µs",
      "variation_20Hz_20kHz": "negligible"
    },
    "modified": {
      "formula_latex": "\\tau_g = \\frac{R_{in}C_2}{1 + (\\omega R_{in}C_2)^2}",
      "at_1kHz": "~100 µs",
      "variation_20Hz_20kHz": "significant (頻率依賴)"
    }
  },
  
  "audio_impact_assessment": {
    "frequency_response": {
      "severity": "critical",
      "issues": [
        "截止頻率 16 Hz 會衰減絕大部分音頻內容",
        "1 kHz 處已有 -36 dB 衰減",
        "20 kHz 處幾乎完全衰減"
      ]
    },
    "phase_distortion": {
      "severity": "moderate", 
      "issues": [
        "不同頻率的延遲差異會造成時域失真",
        "影響瞬態響應(打擊樂器、齒音)"
      ]
    },
    "gain_stability": {
      "severity": "high",
      "issues": [
        "開環增益 80 dB 極易飽和",
        "對輸入變化極度敏感"
      ]
    }
  },
  
  "recommendations": [
    {
      "priority": 1,
      "action": "減小濾波電容",
      "suggestion": "C2 = 1 nF → f_c ≈ 16 kHz",
      "tradeoff": "減少低頻濾波效果"
    },
    {
      "priority": 2,
      "action": "恢復部分負回授",
      "suggestion": "加入局部回授 beta_local = 0.01",
      "benefit": "穩定增益、擴展頻寬"
    },
    {
      "priority": 3,
      "action": "多級設計",
      "suggestion": "將大電容拆分為多個小電容級聯",
      "benefit": "更平坦的群延遲"
    }
  ],
  
  "derivation_trace": [
    {"step": 1, "action": "建立原始電路模型", "status": ""},
    {"step": 2, "action": "推導閉環傳遞函數", "status": ""},
    {"step": 3, "action": "求截止頻率(閉環)", "status": ""},
    {"step": 4, "action": "建立修改後電路模型", "status": ""},
    {"step": 5, "action": "推導開環傳遞函數", "status": ""},
    {"step": 6, "action": "求截止頻率(開環)", "status": ""},
    {"step": 7, "action": "計算群延遲", "status": ""},
    {"step": 8, "action": "評估音頻影響", "status": ""}
  ]
}

這個範例展示的 DSL 優勢

┌─────────────────────────────────────────────────────────────────────────────┐
│                     Pseudo Code DSL 的價值                                  │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  1️⃣ 明確的推導步驟                                                          │
│     • 每一步都有清晰的 action 定義                                          │
│     • 輸入輸出關係明確                                                      │
│     • 可以驗證每步的正確性                                                  │
│                                                                             │
│  2️⃣ 系統級建模                                                              │
│     • 可以描述電路拓撲(blocks + topology)                                 │
│     • 支援多系統比較(original vs modified)                                │
│     • 支援級聯、回授等複雜結構                                              │
│                                                                             │
│  3️⃣ 領域知識嵌入                                                            │
│     • 內建 lowpass_rc, feedback 等電路原語                                  │
│     • 自動套用正確的公式(如閉環增益公式)                                  │
│     • 提供物理直覺的解釋                                                    │
│                                                                             │
│  4️⃣ 可追蹤可重現                                                            │
│     • derivation_trace 記錄每步                                             │
│     • 可以重新執行得到相同結果                                              │
│     • 可以修改參數重新計算                                                  │
│                                                                             │
│  5️⃣ Agent 友善                                                              │
│     • 結構化輸入讓 LLM 更容易生成正確腳本                                   │
│     • 豐富的輸出讓 Agent 能給用戶完整解釋                                   │
│     • 錯誤訊息明確,便於 Agent 修正                                         │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

4. 核心組件

4.1 Parser Layer(解析層)

負責將各種格式的輸入轉換為統一的內部表示。

4.1.1 支援的輸入格式

格式 範例 用途
LaTeX \frac{d}{dx}(x^3) 學術文檔、論文
ASCII Math d/dx (x^3) 快速輸入
程式風格 diff(x**3, x) 程式設計師
自然語言 對 x³ 微分 一般用戶

4.1.2 內部表示 (IR)

# 統一的內部表示格式
{
    "operation": "diff",           # 操作類型
    "expression": "x**3 + 2*x",    # SymPy 格式表達式
    "variable": "x",               # 操作變數
    "options": {                   # 額外選項
        "order": 1,                # 微分階數
        "evaluate": True           # 是否求值
    },
    "metadata": {
        "original_input": "\\frac{d}{dx}(x^3 + 2x)",
        "input_format": "latex"
    }
}

4.2 Engine Layer(引擎層)

執行實際的符號運算。

4.2.1 SymPy Engine(核心)

class SymPyEngine:
    """基於 SymPy 的符號計算引擎"""
    
    supported_operations = [
        # 微積分
        "diff",        # 微分
        "integrate",   # 積分
        "limit",       # 極限
        "series",      # 級數展開
        
        # 代數
        "simplify",    # 簡化
        "expand",      # 展開
        "factor",      # 因式分解
        "solve",       # 解方程
        
        # 線性代數
        "matrix_ops",  # 矩陣運算
        "eigenvalue",  # 特徵值
        
        # 其他
        "substitute",  # 代入
        "evaluate",    # 求值
    ]

4.2.2 Physics Module(物理模組)

class PhysicsModule:
    """物理公式與推導"""
    
    domains = {
        "mechanics": [
            "kinematic_equations",  # 運動學方程
            "newton_laws",          # 牛頓定律
            "work_energy",          # 功與能
            "momentum",             # 動量
        ],
        "thermodynamics": [
            "ideal_gas_law",        # 理想氣體定律
            "first_law",            # 熱力學第一定律
            "entropy",              # 熵
            "carnot_cycle",         # 卡諾循環
        ],
        "electromagnetism": [
            "coulomb_law",          # 庫倫定律
            "ohm_law",              # 歐姆定律
            "maxwell_equations",    # 馬克士威方程
        ],
    }

4.2.3 Chemistry Module(化學模組)

class ChemistryModule:
    """化學計算"""
    
    functions = [
        "balance_equation",     # 配平化學方程式
        "molar_mass",           # 分子量計算
        "stoichiometry",        # 化學計量
        "equilibrium",          # 平衡常數
        "ph_calculation",       # pH 計算
    ]

4.2.4 Algorithm Module(演算法模組)

class AlgorithmModule:
    """演算法分析"""
    
    functions = [
        "solve_recurrence",     # 解遞迴關係
        "master_theorem",       # 主定理分析
        "big_o_analysis",       # 複雜度分析
        "amortized_analysis",   # 攤還分析
    ]

4.3 Knowledge Layer(知識層)

存儲領域知識和規則。

# 物理常數
CONSTANTS = {
    "c": {"value": 299792458, "unit": "m/s", "name": "光速"},
    "h": {"value": 6.62607015e-34, "unit": "J·s", "name": "普朗克常數"},
    "k_B": {"value": 1.380649e-23, "unit": "J/K", "name": "波茲曼常數"},
    "R": {"value": 8.314462618, "unit": "J/(mol·K)", "name": "氣體常數"},
    "N_A": {"value": 6.02214076e23, "unit": "1/mol", "name": "亞佛加厥常數"},
    # ...
}

# 公式模板
FORMULA_TEMPLATES = {
    "ideal_gas_law": {
        "formula": "P*V = n*R*T",
        "variables": ["P", "V", "n", "R", "T"],
        "description": "理想氣體狀態方程",
    },
    # ...
}

5. MCP 工具定義

5.1 symbolic_calculate

用途: 執行符號數學計算

{
    "name": "symbolic_calculate",
    "description": "執行符號數學計算,包括微積分、代數、方程求解等。結果保證數學正確性。",
    "inputSchema": {
        "type": "object",
        "properties": {
            "operation": {
                "type": "string",
                "enum": ["diff", "integrate", "limit", "series", "simplify", 
                         "expand", "factor", "solve", "substitute"],
                "description": "操作類型"
            },
            "expression": {
                "type": "string",
                "description": "數學表達式(支援 LaTeX、ASCII Math、程式風格)"
            },
            "variable": {
                "type": "string",
                "description": "操作變數(如 x, t, theta)"
            },
            "options": {
                "type": "object",
                "description": "額外選項,如積分上下限、微分階數等"
            }
        },
        "required": ["operation", "expression"]
    }
}

回傳格式:

{
    "success": true,
    "input": {
        "operation": "integrate",
        "expression": "x^2",
        "variable": "x"
    },
    "result": {
        "symbolic": "x**3/3",
        "latex": "\\frac{x^3}{3}",
        "pretty": "x³/3"
    },
    "steps": [
        {"step": 1, "description": "套用冪次規則", "result": "∫x^n dx = x^(n+1)/(n+1)"},
        {"step": 2, "description": "代入 n=2", "result": "x^3/3"},
        {"step": 3, "description": "加上積分常數", "result": "x^3/3 + C"}
    ],
    "verification": {
        "method": "differentiation",
        "check": "d/dx(x³/3) = x²",
        "passed": true
    }
}

5.2 physics_formula

用途: 物理公式計算與推導

{
    "name": "physics_formula",
    "description": "物理公式計算與推導,支援力學、熱力學、電磁學等領域。",
    "inputSchema": {
        "type": "object",
        "properties": {
            "domain": {
                "type": "string",
                "enum": ["mechanics", "thermodynamics", "electromagnetism", 
                         "optics", "quantum", "relativity"],
                "description": "物理領域"
            },
            "formula": {
                "type": "string",
                "description": "公式名稱或表達式"
            },
            "known_values": {
                "type": "object",
                "description": "已知量及其值(含單位)"
            },
            "solve_for": {
                "type": "string",
                "description": "要求解的變數"
            },
            "show_derivation": {
                "type": "boolean",
                "default": true,
                "description": "是否顯示推導過程"
            }
        },
        "required": ["domain", "formula"]
    }
}

5.3 verify_derivation

用途: 驗證數學/物理推導的正確性

{
    "name": "verify_derivation",
    "description": "驗證一系列推導步驟是否邏輯正確。",
    "inputSchema": {
        "type": "object",
        "properties": {
            "steps": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "from": {"type": "string"},
                        "to": {"type": "string"},
                        "justification": {"type": "string"}
                    }
                },
                "description": "推導步驟列表"
            },
            "assumptions": {
                "type": "array",
                "items": {"type": "string"},
                "description": "前提假設"
            }
        },
        "required": ["steps"]
    }
}

5.4 chemistry_calculate

用途: 化學計算

{
    "name": "chemistry_calculate",
    "description": "化學相關計算,包括配平方程式、計量計算、平衡常數等。",
    "inputSchema": {
        "type": "object",
        "properties": {
            "operation": {
                "type": "string",
                "enum": ["balance", "molar_mass", "stoichiometry", 
                         "equilibrium", "ph", "redox"],
                "description": "操作類型"
            },
            "input": {
                "type": "string",
                "description": "化學式或方程式"
            },
            "conditions": {
                "type": "object",
                "description": "反應條件(溫度、濃度等)"
            }
        },
        "required": ["operation", "input"]
    }
}

5.5 algorithm_analyze

用途: 演算法複雜度分析

{
    "name": "algorithm_analyze",
    "description": "分析演算法的時間/空間複雜度。",
    "inputSchema": {
        "type": "object",
        "properties": {
            "analysis_type": {
                "type": "string",
                "enum": ["recurrence", "big_o", "amortized", "space"],
                "description": "分析類型"
            },
            "expression": {
                "type": "string",
                "description": "遞迴關係式或複雜度表達式"
            },
            "method": {
                "type": "string",
                "enum": ["master_theorem", "substitution", "recursion_tree", "iteration"],
                "description": "分析方法"
            }
        },
        "required": ["analysis_type", "expression"]
    }
}

5.6 unit_convert

用途: 單位換算

{
    "name": "unit_convert",
    "description": "物理量單位換算,支援國際單位制和常用單位。",
    "inputSchema": {
        "type": "object",
        "properties": {
            "value": {
                "type": "number",
                "description": "數值"
            },
            "from_unit": {
                "type": "string",
                "description": "原始單位"
            },
            "to_unit": {
                "type": "string",
                "description": "目標單位"
            }
        },
        "required": ["value", "from_unit", "to_unit"]
    }
}

6. 使用場景與範例

6.1 微積分計算

用戶請求: 「計算 ∫(x² + 3x)dx 並驗證結果」

Agent 呼叫:

{
    "tool": "symbolic_calculate",
    "arguments": {
        "operation": "integrate",
        "expression": "x^2 + 3*x",
        "variable": "x"
    }
}

MCP 返回:

{
    "success": true,
    "result": {
        "symbolic": "x**3/3 + 3*x**2/2",
        "latex": "\\frac{x^3}{3} + \\frac{3x^2}{2} + C"
    },
    "steps": [
        {"step": 1, "action": "分解積分", "result": "∫x² dx + ∫3x dx"},
        {"step": 2, "action": "對 x² 積分", "result": "x³/3"},
        {"step": 3, "action": "對 3x 積分", "result": "3x²/2"},
        {"step": 4, "action": "合併並加常數", "result": "x³/3 + 3x²/2 + C"}
    ],
    "verification": {
        "method": "differentiation",
        "result": "d/dx(x³/3 + 3x²/2 + C) = x² + 3x ✓",
        "passed": true
    }
}

6.2 熱力學推導

用戶請求: 「理想氣體等溫膨脹做的功是多少?從 V1 膨脹到 V2」

Agent 呼叫:

{
    "tool": "physics_formula",
    "arguments": {
        "domain": "thermodynamics",
        "formula": "isothermal_work",
        "known_values": {
            "process": "isothermal",
            "V1": "V1",
            "V2": "V2"
        },
        "solve_for": "W",
        "show_derivation": true
    }
}

MCP 返回:

{
    "success": true,
    "result": {
        "symbolic": "n*R*T*ln(V2/V1)",
        "latex": "W = nRT \\ln\\left(\\frac{V_2}{V_1}\\right)",
        "alternative": "W = P_1 V_1 \\ln\\left(\\frac{V_2}{V_1}\\right)"
    },
    "derivation": [
        {"step": 1, "description": "等溫過程,PV = nRT = 常數"},
        {"step": 2, "description": "P = nRT/V"},
        {"step": 3, "description": "功的定義: W = ∫P dV"},
        {"step": 4, "description": "代入: W = ∫(nRT/V) dV"},
        {"step": 5, "description": "積分: W = nRT ln(V)|_{V1}^{V2}"},
        {"step": 6, "description": "結果: W = nRT ln(V2/V1)"}
    ],
    "notes": [
        "V2 > V1 時,W > 0,系統對外做功",
        "可用 P1V1 代替 nRT(等溫條件下相等)"
    ]
}

6.3 演算法複雜度分析

用戶請求: 「分析 T(n) = 2T(n/2) + n 的時間複雜度」

Agent 呼叫:

{
    "tool": "algorithm_analyze",
    "arguments": {
        "analysis_type": "recurrence",
        "expression": "T(n) = 2*T(n/2) + n",
        "method": "master_theorem"
    }
}

MCP 返回:

{
    "success": true,
    "analysis": {
        "recurrence": "T(n) = 2T(n/2) + n",
        "standard_form": "T(n) = aT(n/b) + f(n)",
        "parameters": {
            "a": 2,
            "b": 2,
            "f(n)": "n"
        },
        "method": "Master Theorem",
        "calculation": {
            "log_b_a": "log₂(2) = 1",
            "n^log_b_a": "n¹ = n",
            "compare": "f(n) = n = Θ(n^log_b_a)"
        },
        "case": "Case 2: f(n) = Θ(n^(log_b(a)))",
        "result": {
            "symbolic": "Theta(n * log(n))",
            "latex": "T(n) = \\Theta(n \\log n)"
        }
    },
    "examples": [
        "這是 Merge Sort 的時間複雜度",
        "n=1000 時約需 10,000 次操作"
    ]
}

6.4 化學方程式配平

用戶請求: 「配平 Fe + O2 → Fe2O3」

Agent 呼叫:

{
    "tool": "chemistry_calculate",
    "arguments": {
        "operation": "balance",
        "input": "Fe + O2 -> Fe2O3"
    }
}

MCP 返回:

{
    "success": true,
    "result": {
        "balanced": "4Fe + 3O2 → 2Fe2O3",
        "coefficients": {"Fe": 4, "O2": 3, "Fe2O3": 2}
    },
    "verification": {
        "Fe": {"left": 4, "right": 4, "balanced": true},
        "O": {"left": 6, "right": 6, "balanced": true}
    }
}

6.5 🌟 複雜物理問題:車輛碰撞與安全帶張力計算

這個範例展示了本專案的核心價值:引導 Agent 進行精確的符號推導,並在參數不足時與用戶互動討論

問題描述

質量 m 的人在質量 M₁ 的車子內,以速度 v 去碰撞到質量 M₂ 的靜止車輛。 碰撞角度為 45°,假設非完美碰撞(損失 30% 動能)。 安全帶的彈性係數為 k,請問:

  1. 碰撞後車輛的速度?
  2. 人受到的安全帶張力 T 為多少?
  3. 材料耐受性應該為何?

工作流程圖

┌─────────────────────────────────────────────────────────────────────────────┐
│                        複雜物理問題處理流程                                  │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  用戶提問(自然語言)                                                       │
│       │                                                                     │
│       ▼                                                                     │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │ Step 1: Agent 分析問題,識別所需物理概念                            │    │
│  │                                                                     │    │
│  │  • 動量守恆(考慮角度)                                             │    │
│  │  • 能量守恆(非彈性碰撞,損失 30%)                                 │    │
│  │  • 彈簧力學(安全帶張力)                                           │    │
│  │  • 牛頓第二定律(人的減速)                                         │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│       │                                                                     │
│       ▼                                                                     │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │ Step 2: Agent 檢查參數完整性                                        │    │
│  │                                                                     │    │
│  │  ✓ 已知: m, M₁, M₂, v, θ=45°, η=0.7 (保留70%能量), k               │    │
│  │  ✗ 缺少: 碰撞時間 Δt 或 安全帶伸長量 x                              │    │
│  │                                                                     │    │
│  │  → Agent 向用戶詢問缺少的參數或合理假設                             │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│       │                                                                     │
│       ▼                                                                     │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │ Step 3: 呼叫 MCP 符號推導工具(分步進行)                           │    │
│  │                                                                     │    │
│  │  Tool 1: physics_formula (碰撞後速度)                               │    │
│  │  Tool 2: physics_formula (人的減速度)                               │    │
│  │  Tool 3: symbolic_calculate (安全帶張力)                            │    │
│  │  Tool 4: symbolic_calculate (材料安全係數)                          │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│       │                                                                     │
│       ▼                                                                     │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │ Step 4: 整合結果,提供完整解答                                      │    │
│  │                                                                     │    │
│  │  • 符號解(公式)                                                   │    │
│  │  • 數值解(代入具體數字)                                           │    │
│  │  • 推導步驟(可追蹤驗證)                                           │    │
│  │  • 工程建議(安全係數)                                             │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

Step 1: Agent 分析問題並識別缺少參數

Agent 內部分析:

問題類型: 碰撞力學 + 安全帶張力
涉及物理概念:
  1. 二維非彈性碰撞(動量守恆 + 能量損失)
  2. 人在車內的相對運動(減速過程)
  3. 彈簧力學(安全帶 F = kx)

參數檢查:
  ✓ m   - 人的質量
  ✓ M₁  - 車輛 1 質量
  ✓ M₂  - 車輛 2 質量
  ✓ v   - 初始速度
  ✓ θ   - 碰撞角度 (45°)
  ✓ η   - 能量保留比例 (0.7)
  ✓ k   - 安全帶彈性係數
  
  ⚠️ 需要確認:
  - 碰撞類型: 完全非彈性 or 部分非彈性?
  - 安全帶模型: 簡單彈簧 or 含阻尼?
  - 人的初始狀態: 與車同速?

Agent 向用戶詢問:

我分析了您的問題,需要確認幾個參數:

1. 碰撞後兩車是否黏在一起(完全非彈性)還是分開(部分非彈性)?
2. 安全帶是否考慮阻尼效應?還是簡化為理想彈簧?
3. 是否需要考慮安全帶的預緊力?

另外,為了計算材料耐受性,我建議:
- 使用安全係數 SF = 2.0(一般工程標準)
- 或 SF = 3.0(安全關鍵應用)

請確認這些假設是否合理。

Step 2: 呼叫 MCP 工具進行符號推導

Tool Call 1: 碰撞後速度計算

{
    "tool": "physics_formula",
    "arguments": {
        "domain": "mechanics",
        "formula": "inelastic_collision_2d",
        "known_values": {
            "m1": "M1",
            "m2": "M2",
            "v1": "v",
            "v2": "0",
            "theta": "45",
            "energy_retention": "0.7",
            "collision_type": "partially_inelastic"
        },
        "solve_for": ["v1_final", "v2_final"],
        "show_derivation": true
    }
}

MCP 返回:

{
    "success": true,
    "problem_setup": {
        "description": "二維部分非彈性碰撞",
        "coordinate_system": "x: 碰撞方向, y: 垂直方向",
        "initial_conditions": {
            "車1": "v₁ᵢ = v·cos(45°)x̂ + v·sin(45°)ŷ",
            "車2": "v₂ᵢ = 0"
        }
    },
    "derivation": [
        {
            "step": 1,
            "title": "動量守恆(x 方向)",
            "equation": "M₁·v·cos(θ) = M₁·v₁ₓ' + M₂·v₂ₓ'",
            "latex": "M_1 v \\cos\\theta = M_1 v_{1x}' + M_2 v_{2x}'"
        },
        {
            "step": 2,
            "title": "動量守恆(y 方向)",
            "equation": "M₁·v·sin(θ) = M₁·v₁ᵧ' + M₂·v₂ᵧ'",
            "latex": "M_1 v \\sin\\theta = M_1 v_{1y}' + M_2 v_{2y}'"
        },
        {
            "step": 3,
            "title": "能量條件(保留 70%)",
            "equation": "½M₁v₁'² + ½M₂v₂'² = 0.7 × ½M₁v²",
            "latex": "\\frac{1}{2}M_1 v_1'^2 + \\frac{1}{2}M_2 v_2'^2 = 0.7 \\times \\frac{1}{2}M_1 v^2"
        },
        {
            "step": 4,
            "title": "求解聯立方程",
            "note": "需要額外條件(如碰撞係數 e)來唯一確定解"
        }
    ],
    "result": {
        "v1_final": {
            "symbolic": "v * M1 * (1 + e*cos(2*theta)) / (2*(M1 + M2))",
            "latex": "v_1' = \\frac{M_1 v (1 + e\\cos 2\\theta)}{2(M_1 + M_2)}",
            "note": "e 為恢復係數,由能量條件確定"
        },
        "velocity_change": {
            "symbolic": "Delta_v = v - v1_final",
            "description": "車1(含人)的速度變化量"
        }
    },
    "assumptions_required": [
        "需要恢復係數 e 或更多約束條件",
        "建議簡化為正向碰撞以獲得封閉解"
    ]
}

Tool Call 2: 簡化模型 - 正向碰撞

Agent 決定先用簡化模型,再討論角度修正:

{
    "tool": "physics_formula",
    "arguments": {
        "domain": "mechanics",
        "formula": "inelastic_collision_1d",
        "known_values": {
            "m1": "M1",
            "m2": "M2",
            "v1": "v",
            "v2": "0",
            "energy_retention": "0.7"
        },
        "solve_for": "v_final",
        "show_derivation": true
    }
}

MCP 返回:

{
    "success": true,
    "derivation": [
        {
            "step": 1,
            "title": "動量守恆",
            "equation": "M₁·v = (M₁ + M₂)·v'",
            "result": "v' = M₁·v / (M₁ + M₂)"
        },
        {
            "step": 2,
            "title": "速度變化量",
            "equation": "Δv = v - v' = v·M₂/(M₁ + M₂)",
            "latex": "\\Delta v = \\frac{M_2 v}{M_1 + M_2}"
        },
        {
            "step": 3,
            "title": "角度修正(45° 碰撞)",
            "equation": "Δv_eff = Δv · cos(45°) = Δv / √2",
            "note": "有效減速沿碰撞方向"
        }
    ],
    "result": {
        "velocity_change": {
            "symbolic": "M2 * v / (M1 + M2)",
            "with_angle": "M2 * v * cos(theta) / (M1 + M2)",
            "latex": "\\Delta v = \\frac{M_2 v \\cos\\theta}{M_1 + M_2}"
        }
    }
}

Tool Call 3: 安全帶張力計算

{
    "tool": "symbolic_calculate",
    "arguments": {
        "operation": "derive",
        "context": "seatbelt_tension",
        "given": {
            "mass": "m",
            "velocity_change": "Delta_v",
            "spring_constant": "k",
            "model": "energy_conservation"
        },
        "derive": ["extension_x", "tension_T", "deceleration_a"],
        "show_derivation": true
    }
}

MCP 返回:

{
    "success": true,
    "derivation": [
        {
            "step": 1,
            "title": "能量守恆",
            "description": "人的動能轉換為安全帶彈性位能",
            "equation": "½m(Δv)² = ½kx²",
            "latex": "\\frac{1}{2}m(\\Delta v)^2 = \\frac{1}{2}kx^2"
        },
        {
            "step": 2,
            "title": "求安全帶伸長量",
            "equation": "x = Δv·√(m/k)",
            "latex": "x = \\Delta v \\sqrt{\\frac{m}{k}}"
        },
        {
            "step": 3,
            "title": "最大張力(在最大伸長時)",
            "equation": "T_max = k·x = Δv·√(m·k)",
            "latex": "T_{max} = k \\cdot x = \\Delta v \\sqrt{mk}"
        },
        {
            "step": 4,
            "title": "等效減速度",
            "equation": "a = T_max/m = Δv·√(k/m)",
            "latex": "a = \\frac{T_{max}}{m} = \\Delta v \\sqrt{\\frac{k}{m}}"
        }
    ],
    "result": {
        "extension": {
            "symbolic": "Delta_v * sqrt(m/k)",
            "latex": "x = \\Delta v \\sqrt{\\frac{m}{k}}"
        },
        "max_tension": {
            "symbolic": "Delta_v * sqrt(m*k)",
            "latex": "T_{max} = \\Delta v \\sqrt{mk}",
            "expanded": "(M2 * v * cos(theta) / (M1 + M2)) * sqrt(m * k)"
        },
        "deceleration": {
            "symbolic": "Delta_v * sqrt(k/m)",
            "latex": "a = \\Delta v \\sqrt{\\frac{k}{m}}",
            "unit": "m/s²"
        }
    },
    "complete_formula": {
        "T_max": {
            "symbolic": "M2 * v * cos(theta) * sqrt(m * k) / (M1 + M2)",
            "latex": "T_{max} = \\frac{M_2 v \\cos\\theta \\sqrt{mk}}{M_1 + M_2}"
        }
    }
}

Tool Call 4: 材料安全係數計算

{
    "tool": "symbolic_calculate",
    "arguments": {
        "operation": "engineering_design",
        "context": "material_strength",
        "given": {
            "max_load": "T_max",
            "safety_factor": "SF"
        },
        "calculate": "required_strength"
    }
}

MCP 返回:

{
    "success": true,
    "result": {
        "required_strength": {
            "symbolic": "T_max * SF",
            "latex": "\\sigma_{required} = T_{max} \\times SF"
        },
        "with_values": {
            "SF_2.0": "T_max × 2.0(一般應用)",
            "SF_3.0": "T_max × 3.0(安全關鍵)"
        }
    },
    "engineering_notes": [
        "安全帶通常設計為承受 3G 以上減速",
        "建議材料抗拉強度 > 3 × T_max",
        "需考慮動態載荷因子(通常 1.5-2.0)"
    ]
}

Step 3: Agent 整合結果

最終回答(Agent 提供給用戶):

## 🚗 車輛碰撞安全帶張力分析結果

### 問題設定
- 人的質量: m
- 車輛 1 質量: M₁
- 車輛 2 質量: M₂  
- 初速度: v
- 碰撞角度: θ = 45°
- 能量損失: 30%(保留 70%)
- 安全帶彈性係數: k

### 📐 推導結果

#### 1. 速度變化量

$$\Delta v = \frac{M_2 v \cos\theta}{M_1 + M_2}$$

#### 2. 安全帶伸長量

$$x = \Delta v \sqrt{\frac{m}{k}} = \frac{M_2 v \cos\theta}{M_1 + M_2} \sqrt{\frac{m}{k}}$$

#### 3. 最大張力 ⭐

$$T_{max} = \frac{M_2 v \cos\theta \sqrt{mk}}{M_1 + M_2}$$

#### 4. 人承受的減速度

$$a = \frac{T_{max}}{m} = \frac{M_2 v \cos\theta}{M_1 + M_2} \sqrt{\frac{k}{m}}$$

### 🔧 材料設計建議

| 應用等級 | 安全係數 SF | 材料強度要求 |
|---------|------------|-------------|
| 一般應用 | 2.0 | $\geq 2 \times T_{max}$ |
| 安全關鍵 | 3.0 | $\geq 3 \times T_{max}$ |
| 航空標準 | 4.0 | $\geq 4 \times T_{max}$ |

### 📊 數值計算範例

若代入具體數值:
- m = 70 kg(人)
- M₁ = 1500 kg(小轎車)
- M₂ = 2000 kg(另一車)
- v = 50 km/h = 13.89 m/s
- k = 5000 N/m
- θ = 45°

**計算結果**:
- Δv = 5.61 m/s
- x = 0.66 m(安全帶伸長)
- T_max = 3,318 N
- a = 47.4 m/s² ≈ 4.8 G
- 材料強度(SF=3): ≥ 9,954 N

### ⚠️ 注意事項

1. 此模型簡化為理想彈簧,實際安全帶有預緊器和限力器
2. 未考慮人體撞擊方向盤/氣囊的情況
3. 4.8G 減速度在人體可承受範圍內(短時間)
4. 建議進行更精確的有限元素分析

---
*所有計算均由符號引擎執行,結果可重現且可驗證*

這個範例展示的價值

┌─────────────────────────────────────────────────────────────────────────────┐
│                         本專案的核心價值                                    │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  1️⃣ 精確的符號推導                                                          │
│     • 公式推導由符號引擎執行,不是 LLM 猜測                                 │
│     • 每個步驟都可追蹤、可驗證                                              │
│     • 結果 100% 可重現                                                      │
│                                                                             │
│  2️⃣ 智能參數檢查                                                            │
│     • Agent 自動識別缺少的參數                                              │
│     • 主動與用戶討論假設條件                                                │
│     • 提供合理的預設值建議                                                  │
│                                                                             │
│  3️⃣ 分步推導透明化                                                          │
│     • 從基本物理定律出發                                                    │
│     • 每步推導都有物理意義說明                                              │
│     • 便於學習和教學                                                        │
│                                                                             │
│  4️⃣ 符號解 + 數值解結合                                                     │
│     • 先得到通用公式(符號解)                                              │
│     • 再代入具體數值計算                                                    │
│     • 支援參數敏感性分析                                                    │
│                                                                             │
│  5️⃣ 工程實務整合                                                            │
│     • 提供安全係數建議                                                      │
│     • 包含實際應用注意事項                                                  │
│     • 連結到進階分析方法                                                    │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

6.6 🏥 藥物動力學推導範例(Pharmacokinetics)

這個範例展示如何用 Derivation DSL 處理臨床藥理學問題,包括藥物吸收、分布、代謝和排除的完整建模。

問題描述

場景:口服藥物的藥動學分析
─────────────────────────────────────────────────────────────────────────────
已知條件:
  • 劑量 D = 100 mg(口服)
  • 生體可用率 F = 0.7(30% 首渡效應)
  • 分布體積 Vd = 0.5 L/kg
  • 消除速率常數 k_el = 0.1 /hr
  • 體重 BW = 70 kg
  • 血腦屏障通透性 P_BBB = 0.05
  • 腦組織分配係數 Kp_brain = 2.0
  • 最低有效濃度 C_min = 5 mg/L
  • 目標穩態濃度 C_ss_target = 20 mg/L

問題:
  1. 口服後系統可用劑量?
  2. 血漿濃度隨時間變化?
  3. 腦部藥物濃度?
  4. 藥效持續時間?
  5. 維持穩態需要的點滴速率?
  6. 負荷劑量?
─────────────────────────────────────────────────────────────────────────────

推導腳本:藥物動力學分析

derivation:
  name: "口服藥物藥動學分析"
  domain: "pharmacokinetics"
  level: "3.5"  # 多步推導 + ODE
  
  # === 符號定義 ===
  symbols:
    # 藥物參數
    - {name: D, type: positive_real, unit: mg, description: "口服劑量"}
    - {name: F, type: fraction, unit: dimensionless, description: "生體可用率 (0-1)"}
    - {name: Vd, type: positive_real, unit: L/kg, description: "分布體積"}
    - {name: k_el, type: positive_real, unit: 1/hr, description: "消除速率常數"}
    - {name: BW, type: positive_real, unit: kg, description: "體重"}
    
    # 血腦屏障參數
    - {name: P_BBB, type: fraction, unit: dimensionless, description: "BBB 通透性係數"}
    - {name: Kp_brain, type: positive_real, unit: dimensionless, description: "腦組織分配係數"}
    
    # 治療參數
    - {name: C_min, type: positive_real, unit: mg/L, description: "最低有效濃度"}
    - {name: C_ss_target, type: positive_real, unit: mg/L, description: "目標穩態濃度"}
    
    # 時間變數
    - {name: t, type: positive_real, unit: hr, description: "時間"}
    
    # 導出量
    - {name: C, type: positive_real, unit: mg/L, description: "血漿藥物濃度"}
    - {name: C_brain, type: positive_real, unit: mg/L, description: "腦部藥物濃度"}
  
  # === 推導步驟 ===
  steps:
    # --- Part 1: 基本藥動學 ---
    - id: pk_1
      action: calculate_systemic_dose
      description: "計算系統可用劑量(首渡效應後)"
      formula: "D_systemic = D × F"
      inputs: [D, F]
      result: D_systemic
      note: "首渡效應:肝臟首次代謝減少藥物進入系統循環的量"
      
    - id: pk_2
      action: calculate_initial_concentration
      description: "計算初始血漿濃度"
      formula: "C_0 = D_systemic / (Vd × BW)"
      inputs: [D_systemic, Vd, BW]
      result: C_0
      unit: mg/L
      
    - id: pk_3
      action: derive_concentration_profile
      description: "推導血漿濃度隨時間變化(一室模型)"
      model: "one_compartment_first_order"
      differential_equation: "dC/dt = -k_el × C"
      initial_condition: "C(0) = C_0"
      method: "separation_of_variables"
      derivation:
        - step: "分離變數: dC/C = -k_el dt"
        - step: "兩邊積分: ln(C) = -k_el × t + const"
        - step: "代入初始條件: ln(C_0) = const"
        - step: "解出: C(t) = C_0 × e^(-k_el × t)"
      result: C_t
      formula: "C(t) = C_0 × exp(-k_el × t)"
      
    - id: pk_4
      action: calculate_half_life
      description: "計算半衰期"
      formula: "t_half = ln(2) / k_el"
      inputs: [k_el]
      result: t_half
      unit: hr
      note: "濃度降至一半所需時間"
      
    - id: pk_5
      action: calculate_clearance
      description: "計算清除率"
      formula: "CL = k_el × Vd × BW"
      inputs: [k_el, Vd, BW]
      result: CL
      unit: L/hr
      note: "單位時間內清除的血漿體積"
      
    # --- Part 2: 血腦屏障穿透 ---
    - id: bbb_1
      action: derive_brain_concentration
      description: "計算腦部藥物濃度"
      model: "equilibrium_partitioning"
      formula: "C_brain = C_plasma × Kp_brain × P_BBB"
      inputs: [C_t, Kp_brain, P_BBB]
      result: C_brain_t
      note: "假設快速平衡,腦濃度追隨血漿濃度"
      
    - id: bbb_2
      action: calculate_brain_to_plasma_ratio
      description: "腦/血漿濃度比"
      formula: "R_bp = Kp_brain × P_BBB"
      inputs: [Kp_brain, P_BBB]
      result: R_bp
      note: "實際腦部穿透效率"
      
    # --- Part 3: 療效持續時間 ---
    - id: duration_1
      action: solve_for_time
      description: "求藥效持續時間(濃度降至 C_min)"
      equation: "C(t_end) = C_min"
      substitution: "C_0 × exp(-k_el × t_end) = C_min"
      solve_for: t_end
      derivation:
        - step: "取對數: ln(C_0) - k_el × t_end = ln(C_min)"
        - step: "移項: t_end = (ln(C_0) - ln(C_min)) / k_el"
        - step: "簡化: t_end = ln(C_0/C_min) / k_el"
      result: t_duration
      formula: "t_duration = (1/k_el) × ln(C_0 / C_min)"
      
    # --- Part 4: 連續點滴設計 ---
    - id: infusion_1
      action: derive_steady_state
      description: "連續點滴穩態濃度"
      model: "constant_rate_infusion"
      differential_equation: "dC/dt = R_infusion/V - k_el × C"
      steady_state_condition: "dC/dt = 0"
      derivation:
        - step: "穩態時 dC/dt = 0"
        - step: "R_infusion/V = k_el × C_ss"
        - step: "C_ss = R_infusion / (k_el × V)"
        - step: "或 C_ss = R_infusion / CL"
      result: C_ss
      formula: "C_ss = R_infusion / CL"
      
    - id: infusion_2
      action: solve_for_infusion_rate
      description: "求達到目標濃度的點滴速率"
      equation: "C_ss_target = R_infusion / CL"
      solve_for: R_infusion
      result: R_infusion_required
      formula: "R_infusion = C_ss_target × CL"
      unit: mg/hr
      
    - id: infusion_3
      action: calculate_loading_dose
      description: "計算負荷劑量(立即達到目標濃度)"
      formula: "D_loading = C_target × Vd × BW"
      inputs: [C_ss_target, Vd, BW]
      result: D_loading
      unit: mg
      note: "給予負荷劑量後開始維持點滴"
      
    - id: infusion_4
      action: derive_approach_to_steady_state
      description: "點滴濃度隨時間變化"
      model: "loading_dose_plus_infusion"
      formula: "C(t) = C_ss × (1 - exp(-k_el × t)) + C_loading × exp(-k_el × t)"
      note: "若有負荷劑量,則 C_loading = C_ss_target"
      result: C_infusion_t
      
  # === 數值計算範例 ===
  numerical_example:
    parameters:
      D: 100        # mg
      F: 0.7        # 生體可用率
      Vd: 0.5       # L/kg
      k_el: 0.1     # /hr
      BW: 70        # kg
      P_BBB: 0.05   # BBB 通透性
      Kp_brain: 2.0 # 腦分配係數
      C_min: 5      # mg/L
      C_ss_target: 20  # mg/L
      
    calculations:
      step_1:
        name: "系統可用劑量"
        formula: "D_systemic = D × F = 100 × 0.7"
        result: "70 mg"
        
      step_2:
        name: "分布體積(總)"
        formula: "V = Vd × BW = 0.5 × 70"
        result: "35 L"
        
      step_3:
        name: "初始濃度"
        formula: "C_0 = D_systemic / V = 70 / 35"
        result: "2 mg/L"
        
      step_4:
        name: "半衰期"
        formula: "t_half = ln(2) / k_el = 0.693 / 0.1"
        result: "6.93 hr"
        
      step_5:
        name: "清除率"
        formula: "CL = k_el × V = 0.1 × 35"
        result: "3.5 L/hr"
        
      step_6:
        name: "腦/血漿比"
        formula: "R_bp = Kp_brain × P_BBB = 2.0 × 0.05"
        result: "0.10 (10% 穿透)"
        
      step_7:
        name: "藥效持續時間"
        formula: "t_duration = ln(C_0/C_min) / k_el = ln(2/5) / 0.1"
        result: "無法持續(C_0 < C_min!需要更高劑量)"
        note: "⚠️ 初始濃度 2 mg/L 低於最低有效濃度 5 mg/L"
        
      step_8:
        name: "維持目標濃度的點滴速率"
        formula: "R_infusion = C_ss_target × CL = 20 × 3.5"
        result: "70 mg/hr"
        
      step_9:
        name: "負荷劑量"
        formula: "D_loading = C_ss_target × V = 20 × 35"
        result: "700 mg"
        
    clinical_interpretation:
      problem_identified: |
        口服 100 mg 無法達到有效濃度!
        - 初始濃度 C_0 = 2 mg/L < C_min = 5 mg/L
        - 原因:首渡效應 (30%) + 大分布體積
        
      recommendations:
        - option_1: "增加口服劑量至 250 mg → C_0 ≈ 5 mg/L"
        - option_2: "使用靜脈注射(避開首渡效應)"
        - option_3: "採用負荷劑量 700 mg + 持續點滴 70 mg/hr"
        
      safety_check:
        - "確認藥物的最大安全劑量"
        - "監測 700 mg 負荷劑量是否超過安全上限"
        - "考慮分次給藥以降低峰值濃度風險"
  
  # === 輸出 ===
  outputs:
    - name: concentration_profile
      description: "血漿濃度-時間曲線"
      formula_latex: "C(t) = C_0 e^{-k_{el}t}"
      plot_type: "exponential_decay"
      
    - name: brain_concentration
      description: "腦部濃度-時間曲線"
      formula_latex: "C_{brain}(t) = R_{bp} \\cdot C_0 e^{-k_{el}t}"
      
    - name: infusion_design
      description: "點滴治療方案"
      components:
        - "負荷劑量: D_loading"
        - "維持速率: R_infusion"
        - "達穩態時間: ~5 × t_half"
        
    - name: pk_parameters_summary
      description: "藥動學參數總表"
      columns: [Parameter, Symbol, Value, Unit, Clinical Meaning]

DSL 執行結果範例

當 Agent 請求分析藥動學問題時,MCP Server 返回:

{
  "analysis_type": "pharmacokinetics_oral_drug",
  "model": "one_compartment_first_order",
  
  "pk_parameters": {
    "D_systemic": {"value": 70, "unit": "mg", "formula": "D × F"},
    "V_total": {"value": 35, "unit": "L", "formula": "Vd × BW"},
    "C_0": {"value": 2, "unit": "mg/L", "formula": "D_systemic / V"},
    "t_half": {"value": 6.93, "unit": "hr", "formula": "ln(2) / k_el"},
    "CL": {"value": 3.5, "unit": "L/hr", "formula": "k_el × V"}
  },
  
  "concentration_equations": {
    "plasma": {
      "latex": "C(t) = 2 \\cdot e^{-0.1t} \\text{ mg/L}",
      "sympy": "2 * exp(-0.1*t)"
    },
    "brain": {
      "latex": "C_{brain}(t) = 0.2 \\cdot e^{-0.1t} \\text{ mg/L}",
      "sympy": "0.2 * exp(-0.1*t)",
      "note": "R_bp = 0.10"
    }
  },
  
  "therapeutic_assessment": {
    "efficacy_achievable": false,
    "issue": "C_0 (2 mg/L) < C_min (5 mg/L)",
    "duration_above_Cmin": "0 hr (never reaches therapeutic level)"
  },
  
  "infusion_design": {
    "loading_dose": {"value": 700, "unit": "mg", "formula": "C_target × V"},
    "maintenance_rate": {"value": 70, "unit": "mg/hr", "formula": "C_ss × CL"},
    "time_to_steady_state": {"value": 34.65, "unit": "hr", "formula": "5 × t_half"}
  },
  
  "clinical_recommendations": [
    {
      "priority": 1,
      "issue": "口服劑量不足",
      "solution": "增加口服劑量至 ≥250 mg 或改用靜脈給藥",
      "calculation": "需要 C_0 ≥ 5 mg/L → D_systemic ≥ 175 mg → D_oral ≥ 250 mg"
    },
    {
      "priority": 2,
      "issue": "需要快速達到療效",
      "solution": "靜脈負荷劑量 700 mg + 維持點滴 70 mg/hr",
      "caution": "確認 700 mg 未超過最大安全劑量"
    },
    {
      "priority": 3,
      "issue": "腦部濃度偏低",
      "solution": "腦/血漿比僅 0.10,可能需要更高血漿濃度才能達到 CNS 療效",
      "calculation": "若需腦部 1 mg/L,血漿需達 10 mg/L"
    }
  ],
  
  "derivation_trace": [
    {"step": 1, "action": "計算系統可用劑量", "result": "70 mg", "status": ""},
    {"step": 2, "action": "計算分布體積", "result": "35 L", "status": ""},
    {"step": 3, "action": "計算初始濃度", "result": "2 mg/L", "status": ""},
    {"step": 4, "action": "推導濃度-時間方程", "result": "C(t)=C₀e^(-k_el×t)", "status": ""},
    {"step": 5, "action": "計算半衰期", "result": "6.93 hr", "status": ""},
    {"step": 6, "action": "計算清除率", "result": "3.5 L/hr", "status": ""},
    {"step": 7, "action": "計算腦部穿透", "result": "R_bp = 0.10", "status": ""},
    {"step": 8, "action": "評估療效持續時間", "result": "無法達標", "status": "⚠️"},
    {"step": 9, "action": "設計點滴方案", "result": "700 mg + 70 mg/hr", "status": ""}
  ],
  
  "warnings": [
    "⚠️ 口服劑量無法達到有效濃度",
    "⚠️ 負荷劑量 700 mg 需確認安全性",
    "⚠️ 腦部穿透率低,CNS 療效可能受限"
  ]
}

藥動學範例展示的價值

┌─────────────────────────────────────────────────────────────────────────────┐
│                     藥動學 DSL 的臨床應用價值                               │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  1️⃣ 完整的 ADME 建模                                                        │
│     • Absorption: 首渡效應、生體可用率                                      │
│     • Distribution: 分布體積、組織分配                                      │
│     • Metabolism: 清除率                                                    │
│     • Excretion: 消除速率、半衰期                                           │
│                                                                             │
│  2️⃣ ODE 符號求解                                                            │
│     • 一室模型微分方程自動推導                                              │
│     • 解析解生成(非數值近似)                                              │
│     • 可擴展到多室模型                                                      │
│                                                                             │
│  3️⃣ 特殊屏障穿透                                                            │
│     • 血腦屏障 (BBB) 建模                                                   │
│     • 組織分配係數整合                                                      │
│     • CNS 藥物設計支援                                                      │
│                                                                             │
│  4️⃣ 臨床決策支援                                                            │
│     • 自動檢測劑量不足                                                      │
│     • 負荷劑量計算                                                          │
│     • 點滴速率優化                                                          │
│                                                                             │
│  5️⃣ 安全性整合                                                              │
│     • 提醒確認最大安全劑量                                                  │
│     • 標示潛在風險                                                          │
│     • 支援治療藥物監測 (TDM) 決策                                           │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

7. 技術選型

7.1 核心依賴

組件 技術 用途 選擇理由
MCP Server Python + mcp MCP 協議實現 官方支援
符號計算 SymPy 數學符號運算 Python 生態最成熟
數值計算 NumPy/SciPy 數值解、優化 業界標準
單位處理 Pint 物理量單位 功能完整、易用
LaTeX 解析 latex2sympy2 LaTeX → SymPy 專門用途
化學計算 chempy 化學計量 專門用途

7.2 專案結構

nsforge-mcp/
├── pyproject.toml              # 專案配置
├── README.md                   # 說明文檔
│
├── src/
│   └── nsforge/
│       ├── __init__.py
│       ├── server.py           # MCP Server 主程式
│       │
│       ├── tools/              # MCP 工具定義
│       │   ├── __init__.py
│       │   ├── symbolic.py     # symbolic_calculate
│       │   ├── physics.py      # physics_formula
│       │   ├── chemistry.py    # chemistry_calculate
│       │   ├── algorithm.py    # algorithm_analyze
│       │   └── verify.py       # verify_derivation
│       │
│       ├── parsers/            # 解析器
│       │   ├── __init__.py
│       │   ├── latex_parser.py
│       │   ├── ascii_parser.py
│       │   └── nl_parser.py    # 自然語言(可選)
│       │
│       ├── engines/            # 計算引擎
│       │   ├── __init__.py
│       │   ├── sympy_engine.py
│       │   ├── physics_engine.py
│       │   ├── chemistry_engine.py
│       │   └── algorithm_engine.py
│       │
│       ├── knowledge/          # 知識庫
│       │   ├── __init__.py
│       │   ├── constants.py    # 物理/化學常數
│       │   ├── formulas.py     # 公式模板
│       │   └── rules.py        # 推導規則
│       │
│       └── utils/              # 工具函數
│           ├── __init__.py
│           ├── formatter.py    # 結果格式化
│           └── validator.py    # 輸入驗證
│
├── tests/                      # 測試
│   ├── test_symbolic.py
│   ├── test_physics.py
│   └── ...
│
└── docs/                       # 文檔
    ├── api.md
    └── examples.md

7.3 依賴清單

# pyproject.toml
[project]
name = "nsforge-mcp"
version = "0.1.0"
description = "Neurosymbolic Forge - Where Neural Meets Symbolic"
requires-python = ">=3.10"

dependencies = [
    "mcp>=1.0.0",               # MCP Server SDK
    "sympy>=1.12",              # 符號計算
    "numpy>=1.24",              # 數值計算
    "scipy>=1.10",              # 科學計算
    "pint>=0.22",               # 單位處理
    "latex2sympy2>=1.9",        # LaTeX 解析
    "chempy>=0.8",              # 化學計算
]

[project.optional-dependencies]
dev = [
    "pytest>=7.0",
    "pytest-asyncio>=0.21",
]

8. 實作計劃

Phase 1: 基礎架構(Week 1-2)

  • 建立專案結構
  • 實作 MCP Server 框架
  • 實作基本的表達式解析器
  • 實作 SymPy Engine 基礎功能

交付物: 可運行的 MCP Server,支援基本微積分

Phase 2: 核心功能(Week 3-4)

  • 完整的 symbolic_calculate 工具
  • LaTeX 解析支援
  • 推導步驟生成
  • 結果驗證功能

交付物: 完整的數學符號計算功能

Phase 3: 領域擴展(Week 5-6)

  • physics_formula 工具
  • chemistry_calculate 工具
  • 知識庫建立(公式、常數)

交付物: 物理化學計算支援

Phase 4: 進階功能(Week 7-8)

  • algorithm_analyze 工具
  • verify_derivation 工具
  • 單位換算功能
  • 錯誤處理優化

交付物: 完整的符號推理 MCP Server

Phase 5: 測試與文檔(Week 9-10)

  • 單元測試
  • 整合測試
  • API 文檔
  • 使用範例

交付物: 生產就緒版本


9. 參考資料

9.1 核心概念

9.2 MCP 相關

9.3 符號計算


附錄 A: 術語表

術語 英文 說明
符號推理 Symbolic Reasoning 使用明確符號和規則進行邏輯運算
符號計算 Symbolic Computation 對數學符號進行代數運算
神經符號 AI Neural-Symbolic AI 結合神經網路與符號推理的 AI
AST Abstract Syntax Tree 抽象語法樹
DSL Domain Specific Language 領域特定語言
MCP Model Context Protocol 模型上下文協議
CAS Computer Algebra System 計算機代數系統

附錄 B: Gap 分析與 MVP 定義

B.1 能力分層分析

┌─────────────────────────────────────────────────────────────────────────────┐
│                    符號推導系統的能力分層                                    │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  層級          誰能做?              可靠性        現有工具                  │
│  ═══════════════════════════════════════════════════════════════════════   │
│                                                                             │
│  ① 公式表達     Agent ✓              高           LaTeX, SymPy, Lean4       │
│     (靜態)      人類 ✓                                                      │
│                                                                             │
│  ② 單步計算     SymPy ✓              100%         SymPy, Mathematica        │
│     diff(x³)    Mathematica ✓                                               │
│                                                                             │
│  ③ 推導規劃     Agent ⚠️             不確定       ← 這是 GAP!              │
│     「下一步    人類 ✓                             沒有通用工具              │
│      用什麼                                                                 │
│      公式?」                                                               │
│                                                                             │
│  ④ 推導驗證     Lean4 ✓              100%         Lean4, Coq, Isabelle      │
│     「這步對    人類 ⚠️                           (但需要形式化)           │
│      不對?」                                                               │
│                                                                             │
│  ⑤ 結果解釋     Agent ✓              高           LLM                       │
│                 人類 ✓                                                      │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

B.2 核心 Gap:推導規劃

工具 能做 不能做
SymPy 執行每一步計算 不知道「下一步該做什麼」
Lean4 驗證每一步正確 不會自動規劃(除非有 tactic)
LLM 規劃推導策略 可能出錯、無法保證正確

B.3 解決方案:Neural-Symbolic 混合架構

┌─────────────────────────────────────────────────────────────────────────────┐
│                     務實的 Neural-Symbolic 方案                             │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   ┌─────────────┐                                                           │
│   │   Agent     │ ← 做「推導規劃」(選擇策略、決定步驟)                    │
│   │   (LLM)     │    可能出錯,但可以透過驗證修正                           │
│   └──────┬──────┘                                                           │
│          │ 輸出推導腳本 (DSL/YAML)                                          │
│          ▼                                                                  │
│   ┌─────────────┐                                                           │
│   │  MCP Server │                                                           │
│   │             │                                                           │
│   │  ┌────────────────────────────────────────────────────────────────┐    │
│   │  │  Derivation Planner                                            │    │
│   │  │  • 公式知識圖譜(知道公式之間的依賴)                          │    │
│   │  │  • 檢查步驟是否合理                                            │    │
│   │  │  • 發現缺少的變數                                              │    │
│   │  └────────────────────────────────────────────────────────────────┘    │
│   │             │                                                           │
│   │             ▼                                                           │
│   │  ┌────────────────────────────────────────────────────────────────┐    │
│   │  │  Step Executor (SymPy)                                         │    │
│   │  │  • 執行每一步計算(100% 正確)                                 │    │
│   │  │  • 記錄中間結果                                                │    │
│   │  └────────────────────────────────────────────────────────────────┘    │
│   │             │                                                           │
│   │             ▼                                                           │
│   │  ┌────────────────────────────────────────────────────────────────┐    │
│   │  │  Verifier(可選:Lean4)                                       │    │
│   │  │  • 維度檢查                                                    │    │
│   │  │  • 反向驗證(微分驗積分)                                      │    │
│   │  │  • 形式證明(Lean4 - 進階)                                    │    │
│   │  └────────────────────────────────────────────────────────────────┘    │
│   └─────────────┘                                                           │
│          │                                                                  │
│          ▼                                                                  │
│   驗證過的推導結果(可追蹤、可重現)                                        │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

B.4 MVP 最小可行產品定義

┌─────────────────────────────────────────────────────────────────────────────┐
│                        MVP 最小可行產品                                      │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ✅ MVP 必做:                                                               │
│  ──────────────────────────────────────────────────────────────────────    │
│  1. DSL Parser       - 解析 Agent 輸出的推導腳本                            │
│  2. Step Executor    - 用 SymPy 執行每一步                                  │
│  3. Basic Verifier   - 維度檢查 + 反向驗證                                  │
│  4. Formula KB       - 先做 3-5 個領域的核心公式                            │
│  5. MCP Wrapper      - 包裝成 Agent 可呼叫的工具                            │
│                                                                             │
│  ⏸️ 暫不實作:                                                               │
│  ──────────────────────────────────────────────────────────────────────    │
│  - Lean4 形式驗證(技術複雜度高)                                           │
│  - 自動推導規劃(讓 Agent + 人協作)                                        │
│  - 完整公式庫(從題目逐步擴充)                                             │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

B.5 推導規劃策略選項

選項 優點 缺點 適用場景
A. Agent + 人(推薦) 靈活、可處理各種問題 Agent 可能選錯策略 複雜/新穎問題
B. 預定義模板 100% 可靠 只能處理已知問題類型 標準問題
C. 自動定理證明 理論上完美 技術難度極高 研究階段

決策:採用 A + B 混合方案 - 常見問題用模板,複雜問題讓 Agent 規劃 + 驗證

B.6 驗證層級

層級 做法 成本 MVP 納入
基本 維度檢查 + 數值帶入驗證
中等 反向運算驗證(微分驗積分)
嚴格 Lean4 形式證明

附錄 C: 更新日誌

版本 日期 變更
0.1.0 2026-01-01 初始設計文檔
0.1.1 2026-01-01 新增 6.6 藥動學範例
0.1.2 2026-01-01 新增附錄 B: Gap 分析與 MVP 定義
0.1.3 2026-01-01 專案更名為 Neurosymbolic Forge (NSForge)