| name | nsforge-code-generation |
| description | 程式碼/報告生成:Python 函數、LaTeX、Markdown 報告、SymPy 腳本。觸發詞:生成程式碼, generate, 寫成函數, LaTeX, 報告, export。 |
NSForge 程式碼生成 Skill
觸發條件
當用戶說:
- 「生成程式碼」「generate code」「寫成函數」
- 「Python 函數」「create function」
- 「LaTeX」「論文格式」「數學排版」
- 「報告」「report」「文檔」「documentation」
- 「匯出」「export」「輸出」
必備工具
這個 Skill 使用 nsforge-mcp 的以下工具:
| 輸出類型 | 工具 | 說明 |
|---|---|---|
| Python 函數 | generate_python_function |
可執行的計算函數 |
| LaTeX 公式 | generate_latex_derivation |
論文級數學排版 |
| Markdown 報告 | generate_derivation_report |
完整推導報告 |
| SymPy 腳本 | generate_sympy_script |
可重現的計算腳本 |
執行流程
┌─────────────────────────────────────────────────────────────┐
│ 程式碼生成選擇指南 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 用戶需求分析: │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ 「寫成 Python 函數」 │ │
│ │ → generate_python_function(...) │ │
│ │ │ │
│ │ 「給我 LaTeX 格式」 │ │
│ │ → generate_latex_derivation(...) │ │
│ │ │ │
│ │ 「生成完整報告」 │ │
│ │ → generate_derivation_report(...) │ │
│ │ │ │
│ │ 「可重現的腳本」 │ │
│ │ → generate_sympy_script(...) │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
詳細工具說明
generate_python_function
目的:從推導步驟生成可執行的 Python 函數
⚠️ 重要:生成的程式碼使用 SymPy 進行計算,不是 Agent 自己編寫!
參數:
name(必須): 函數名稱description(必須): 函數說明(會變成 docstring)parameters(必須): 參數列表steps(必須): 計算步驟return_vars(必須): 返回變數
使用方式:
generate_python_function(
name="calculate_elimination_rate",
description="Calculate temperature-corrected drug elimination rate",
parameters=[
{"name": "C_0", "type": "float", "description": "Initial concentration (mg/L)"},
{"name": "k_ref", "type": "float", "description": "Reference rate constant (1/h)"},
{"name": "E_a", "type": "float", "description": "Activation energy (J/mol)"},
{"name": "T", "type": "float", "description": "Temperature (K)"},
{"name": "T_ref", "type": "float", "description": "Reference temperature (K)"},
{"name": "t", "type": "float", "description": "Time (h)"}
],
steps=[
{
"description": "Calculate temperature-corrected rate constant",
"expression": "k_ref * exp(E_a/R * (1/T_ref - 1/T))",
"result_var": "k"
},
{
"description": "Calculate concentration at time t",
"expression": "C_0 * exp(-k * t)",
"result_var": "C"
}
],
return_vars=["k", "C"]
)
輸出範例:
from sympy import symbols, exp, Rational
import sympy
# Physical constant
R = 8.314 # J/(mol·K)
def calculate_elimination_rate(C_0: float, k_ref: float, E_a: float,
T: float, T_ref: float, t: float) -> tuple:
"""
Calculate temperature-corrected drug elimination rate.
Parameters
----------
C_0 : float
Initial concentration (mg/L)
k_ref : float
Reference rate constant (1/h)
E_a : float
Activation energy (J/mol)
T : float
Temperature (K)
T_ref : float
Reference temperature (K)
t : float
Time (h)
Returns
-------
tuple
(k, C) - Rate constant and concentration
Derivation
----------
Generated by NSForge from verified derivation.
Source: temp_corrected_elimination
"""
# Step 1: Calculate temperature-corrected rate constant
k = k_ref * sympy.exp(E_a/R * (1/T_ref - 1/T))
# Step 2: Calculate concentration at time t
C = C_0 * sympy.exp(-k * t)
return float(k), float(C)
generate_latex_derivation
目的:生成 LaTeX 格式的推導過程
參數:
steps(必須): 推導步驟列表title(可選): 標題author(可選): 作者include_preamble(可選): 是否包含 LaTeX 前導
使用方式:
generate_latex_derivation(
steps=[
{"description": "Start with one-compartment model", "expression": "C = C_0 e^{-kt}"},
{"description": "Apply Arrhenius equation", "expression": "k = k_{ref} e^{\\frac{E_a}{R}(\\frac{1}{T_{ref}} - \\frac{1}{T})}"},
{"description": "Substitute k", "expression": "C = C_0 e^{-k_{ref} e^{\\frac{E_a}{R}(\\frac{1}{T_{ref}} - \\frac{1}{T})} \\cdot t}"}
],
title="Temperature-Corrected Elimination",
include_preamble=False
)
輸出範例:
\subsection{Temperature-Corrected Elimination}
\textbf{Step 1:} Start with one-compartment model
\begin{equation}
C = C_0 e^{-kt}
\end{equation}
\textbf{Step 2:} Apply Arrhenius equation
\begin{equation}
k = k_{ref} e^{\frac{E_a}{R}(\frac{1}{T_{ref}} - \frac{1}{T})}
\end{equation}
\textbf{Step 3:} Substitute k
\begin{equation}
C = C_0 e^{-k_{ref} e^{\frac{E_a}{R}(\frac{1}{T_{ref}} - \frac{1}{T})} \cdot t}
\end{equation}
generate_derivation_report
目的:生成完整的 Markdown 推導報告
參數:
title(必須): 報告標題given(必須): 已知條件/輸入steps(必須): 推導步驟result(必須): 最終結果assumptions(可選): 假設條件limitations(可選): 限制條件references(可選): 參考文獻include_verification(可選): 是否包含驗證章節
使用方式:
generate_derivation_report(
title="Temperature-Corrected Drug Elimination Rate",
given=[
"One-compartment pharmacokinetic model: $C = C_0 e^{-kt}$",
"Arrhenius temperature dependence: $k = k_{ref} e^{\\frac{E_a}{R}(\\frac{1}{T_{ref}} - \\frac{1}{T})}$"
],
steps=[
{"description": "Start with base model", "expression": "C = C_0 e^{-kt}"},
{"description": "Substitute Arrhenius k", "expression": "C = C_0 e^{-k_{ref} e^{...} \\cdot t}"}
],
result="$C(t, T) = C_0 \\exp\\left(-k_{ref} e^{\\frac{E_a}{R}(\\frac{1}{T_{ref}} - \\frac{1}{T})} \\cdot t\\right)$",
assumptions=["First-order elimination", "Arrhenius temperature dependence"],
limitations=["Valid for 32-42°C"],
references=["Goodman & Gilman's Pharmacology"],
include_verification=True
)
輸出範例:
# Temperature-Corrected Drug Elimination Rate
## Given
- One-compartment pharmacokinetic model: $C = C_0 e^{-kt}$
- Arrhenius temperature dependence: $k = k_{ref} e^{\frac{E_a}{R}(\frac{1}{T_{ref}} - \frac{1}{T})}$
## Derivation
### Step 1: Start with base model
$$C = C_0 e^{-kt}$$
### Step 2: Substitute Arrhenius k
$$C = C_0 e^{-k_{ref} e^{...} \cdot t}$$
## Result
$$C(t, T) = C_0 \exp\left(-k_{ref} e^{\frac{E_a}{R}(\frac{1}{T_{ref}} - \frac{1}{T})} \cdot t\right)$$
## Assumptions
1. First-order elimination
2. Arrhenius temperature dependence
## Limitations
- Valid for 32-42°C
## Verification
✅ Dimensional analysis: Passed
✅ Symbolic verification: Passed
## References
1. Goodman & Gilman's Pharmacology
---
*Generated by NSForge on 2026-01-02*
generate_sympy_script
目的:生成可重現推導的獨立 SymPy 腳本
參數:
expressions(必須): 表達式列表operations(必須): 操作列表
使用方式:
generate_sympy_script(
expressions=[
{"name": "C_base", "expr": "C_0 * exp(-k*t)", "description": "One-compartment model"},
{"name": "k_arrhenius", "expr": "k_ref * exp(E_a/R * (1/T_ref - 1/T))", "description": "Arrhenius k"}
],
operations=[
{"op": "substitute", "input": "C_base", "var": "k", "replacement": "k_arrhenius"},
{"op": "simplify", "input": "result"}
]
)
輸出範例:
#!/usr/bin/env python3
"""
NSForge Generated Script: One-compartment model with temperature correction
This script reproduces the derivation steps using SymPy.
Generated on: 2026-01-02
"""
from sympy import symbols, exp, simplify, pprint
# Define symbols
C_0, k, t, k_ref, E_a, R, T_ref, T = symbols('C_0 k t k_ref E_a R T_ref T', positive=True, real=True)
# Step 1: Define base expressions
print("=" * 60)
print("Step 1: Define base expressions")
print("=" * 60)
# One-compartment model
C_base = C_0 * exp(-k*t)
print("\nC_base (One-compartment model):")
pprint(C_base)
# Arrhenius k
k_arrhenius = k_ref * exp(E_a/R * (1/T_ref - 1/T))
print("\nk_arrhenius (Arrhenius k):")
pprint(k_arrhenius)
# Step 2: Substitute k
print("\n" + "=" * 60)
print("Step 2: Substitute k with Arrhenius expression")
print("=" * 60)
result = C_base.subs(k, k_arrhenius)
print("\nAfter substitution:")
pprint(result)
# Step 3: Simplify
print("\n" + "=" * 60)
print("Step 3: Simplify")
print("=" * 60)
final_result = simplify(result)
print("\nFinal result:")
pprint(final_result)
# Numerical example
print("\n" + "=" * 60)
print("Numerical Example")
print("=" * 60)
values = {
C_0: 100, # mg/L
k_ref: 0.1, # 1/h
E_a: 50000, # J/mol
R: 8.314, # J/(mol·K)
T_ref: 310, # K (37°C)
T: 312, # K (39°C, fever)
t: 2 # hours
}
numerical_result = float(final_result.subs(values))
print(f"\nWith C_0=100 mg/L, T=39°C, t=2h:")
print(f"C = {numerical_result:.2f} mg/L")
何時需要 SymPy-MCP
生成程式碼時,某些場景需要先用 sympy-mcp 進行計算:
| 場景 | 先用 SymPy-MCP | 再用 NSForge |
|---|---|---|
| ODE 解析解 → 函數 | dsolve_ode |
generate_python_function |
| 矩陣運算 → 腳本 | matrix_* |
generate_sympy_script |
| 單位換算 → 報告 | convert_to_units |
generate_derivation_report |
| 複雜簡化 → LaTeX | simplify_expression |
generate_latex_derivation |
整合範例:ODE → Python 函數
# Step 1: 用 SymPy-MCP 解 ODE
intro("t", ["real", "positive"], [])
intro("k", ["real", "positive"], [])
introduce_function("C")
expr = introduce_expression("Derivative(C(t), t) + k*C(t)")
solution = dsolve_ode(expr, "C")
# → C(t) = C1*exp(-k*t)
# Step 2: 用 NSForge 生成函數
generate_python_function(
name="solve_first_order_elimination",
description="Solution to dC/dt = -kC (first-order elimination)",
parameters=[
{"name": "C_0", "type": "float", "description": "Initial concentration"},
{"name": "k", "type": "float", "description": "Elimination rate constant"},
{"name": "t", "type": "float", "description": "Time"}
],
steps=[
{"description": "Apply analytical solution", "expression": "C_0 * exp(-k*t)", "result_var": "C"}
],
return_vars=["C"]
)
整合範例:矩陣 → SymPy 腳本
# Step 1: 用 SymPy-MCP 做矩陣計算
A = create_matrix([[1, 2], [3, 4]], "A")
eigenvals = matrix_eigenvalues("A")
eigenvecs = matrix_eigenvectors("A")
# Step 2: 生成可重現的腳本
generate_sympy_script(
expressions=[
{"name": "A", "expr": "Matrix([[1, 2], [3, 4]])", "description": "2x2 matrix"}
],
operations=[
{"op": "eigenvalues", "input": "A"},
{"op": "eigenvectors", "input": "A"}
]
)
常見使用場景
場景 1:「把這個公式寫成 Python 函數」
# 假設已有推導結果
generate_python_function(
name="arrhenius_rate",
description="Calculate rate constant using Arrhenius equation",
parameters=[
{"name": "k_ref", "type": "float", "description": "Reference rate (1/s)"},
{"name": "E_a", "type": "float", "description": "Activation energy (J/mol)"},
{"name": "T", "type": "float", "description": "Temperature (K)"}
],
steps=[
{"description": "Arrhenius equation", "expression": "k_ref * exp(E_a/R * (1/T_ref - 1/T))", "result_var": "k"}
],
return_vars=["k"]
)
Agent 回應:
已生成 Python 函數
arrhenius_rate,包含:
- 完整的 docstring 說明
- 類型標註
- SymPy 計算(確保精確度)
- 推導來源標記
場景 2:「給我 LaTeX 格式寫論文用」
generate_latex_derivation(
steps=[...],
title="Temperature-Corrected Elimination Rate",
include_preamble=True # 包含完整 LaTeX 文件結構
)
Agent 回應:
已生成 LaTeX 格式,可直接貼入論文。 包含:
- 編號方程式
- 步驟說明
- 標準學術排版
場景 3:「生成完整報告」
generate_derivation_report(
title="...",
given=[...],
steps=[...],
result="...",
include_verification=True
)
Agent 回應:
已生成 Markdown 報告,包含:
- 問題陳述
- 推導步驟(含公式)
- 假設與限制
- 驗證結果
- 參考文獻
場景 4:「我想重現這個推導」
generate_sympy_script(
expressions=[...],
operations=[...]
)
Agent 回應:
已生成獨立 Python 腳本,可以:
- 直接執行重現推導
- 修改參數測試
- 作為教學材料
最佳實踐
- 函數生成:確保參數說明完整,便於使用
- LaTeX 生成:確認數學符號正確轉義
- 報告生成:包含足夠的上下文說明
- 腳本生成:加入數值範例便於驗證
相關 Skills
nsforge-derivation-workflow: 先推導,再生成程式碼nsforge-verification-suite: 驗證後再生成報告nsforge-formula-management: 從已存檔公式生成sympy-mcp: 複雜計算支援(ODE、矩陣)