mermaid-diagram
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMermaid Diagram Generator
Mermaid 图表生成器
Generate high-quality Mermaid diagram code based on user requirements, with file output and verification.
根据用户需求生成高质量Mermaid图表代码,支持文件输出与语法验证。
Constants
常量定义
- OUTPUT_DIR = — Output directory for all generated files
figures/ - MAX_ITERATIONS = 3 — Maximum refinement rounds for syntax errors
- OUTPUT_DIR = — 所有生成文件的输出目录
figures/ - MAX_ITERATIONS = 3 — 语法错误的最大修正轮次
Workflow: MUST EXECUTE ALL STEPS
工作流程:必须执行所有步骤
Step 0: Pre-flight Check
步骤0:前期检查
bash
undefinedbash
undefinedCreate output directory
Create output directory
mkdir -p figures
undefinedmkdir -p figures
undefinedStep 1: Understand Requirements & Select Diagram Type
步骤1:理解需求并选择图表类型
Parse the input: $ARGUMENTS
- Analyze user description to determine the most suitable diagram type
- Read the corresponding syntax reference documentation (see Diagram Type Reference below)
- If the diagram involves mathematical notation (formulas, equations, Greek letters, subscripts, superscripts, fractions, matrices, etc.), apply the math syntax rules from the Math Formulas in Diagrams section below
- Identify all components, connections, and data flow
- Plan the diagram structure
解析输入参数:$ARGUMENTS
- 分析用户描述,确定最适合的图表类型
- 阅读对应图表类型的语法参考文档(见下方图表类型参考)
- 如果图表涉及数学符号(公式、方程、希腊字母、下标、上标、分数、矩阵等),请应用下方「图表中的数学公式」章节的语法规则
- 识别所有组件、连接关系和数据流
- 规划图表结构
Step 2: Read Documentation
步骤2:查阅文档
Select the appropriate diagram type based on the use case. Use your built-in knowledge of Mermaid syntax, or fetch up-to-date docs via the context7 MCP server if needed.
| Type | Use Cases |
|---|---|
| Flowchart | Processes, decisions, steps |
| Sequence Diagram | Interactions, messaging, API calls |
| Class Diagram | Class structure, inheritance, associations |
| State Diagram | State machines, state transitions |
| ER Diagram | Database design, entity relationships |
| Gantt Chart | Project planning, timelines |
| Pie Chart | Proportions, distributions |
| Mindmap | Hierarchical structures, knowledge graphs |
| Timeline | Historical events, milestones |
| Git Graph | Branches, merges, versions |
| Quadrant Chart | Four-quadrant analysis |
| Requirement Diagram | Requirements traceability |
| C4 Diagram | System architecture (C4 model) |
| Sankey Diagram | Flow, conversions |
| XY Chart | Line charts, bar charts |
| Block Diagram | System components, modules |
| Packet Diagram | Network protocols, data structures |
| Kanban | Task management, workflows |
| Architecture Diagram | System architecture |
| Radar Chart | Multi-dimensional comparison |
| Treemap | Hierarchical data visualization |
| User Journey | User experience flows |
| ZenUML | Sequence diagrams (code style) |
根据使用场景选择合适的图表类型。可借助内置的Mermaid语法知识,或通过context7 MCP服务器获取最新文档。
| 图表类型 | 适用场景 |
|---|---|
| 流程图 | 流程、决策、步骤展示 |
| 序列图 | 交互、消息传递、API调用 |
| 类图 | 类结构、继承关系、关联关系 |
| 状态图 | 状态机、状态转换 |
| ER图 | 数据库设计、实体关系 |
| 甘特图 | 项目规划、时间线 |
| 饼图 | 比例、分布展示 |
| 思维导图 | 层级结构、知识图谱 |
| 时间线图 | 历史事件、里程碑 |
| Git图 | 分支、合并、版本记录 |
| 四象限图 | 四象限分析 |
| 需求图 | 需求可追溯性 |
| C4图 | 系统架构(C4模型) |
| 桑基图 | 流量、转化分析 |
| XY图 | 折线图、柱状图 |
| 块图 | 系统组件、模块展示 |
| 数据包图 | 网络协议、数据结构 |
| 看板图 | 任务管理、工作流 |
| 架构图 | 系统架构 |
| 雷达图 | 多维度对比 |
| 树状图 | 层级数据可视化 |
| 用户旅程图 | 用户体验流程 |
| ZenUML | 序列图(代码风格) |
Configuration & Themes
配置与主题
- Theming - Custom colors and styles
- Directives - Diagram-level configuration
- Layouts - Layout direction and spacing
- Configuration - Global settings
- Math - LaTeX math support (see Math Formulas in Diagrams section below)
- 主题设置 - 自定义颜色与样式
- 指令 - 图表级配置
- 布局 - 布局方向与间距
- 全局配置 - 全局设置
- 数学公式 - LaTeX数学支持(见下方「图表中的数学公式」章节)
Step 3: Generate Mermaid Code & Save Files
步骤3:生成Mermaid代码并保存文件
Generate the Mermaid code following the reference specification, then save TWO files:
按照参考规范生成Mermaid代码,然后保存两个文件:
File 1: figures/<diagram-name>.mmd
— Raw Mermaid source
figures/<diagram-name>.mmd文件1:figures/<diagram-name>.mmd
— 原始Mermaid源码
figures/<diagram-name>.mmdThe file contains ONLY the raw Mermaid code (no markdown fences). Example:
.mmdflowchart TD
A[Start] --> B{Condition}
B -->|Yes| C[Execute]
B -->|No| D[End]
C --> D.mmd文件仅包含原始Mermaid代码(无Markdown围栏)。示例:
flowchart TD
A[Start] --> B{Condition}
B -->|Yes| C[Execute]
B -->|No| D[End]
C --> DFile 2: figures/<diagram-name>.md
— Markdown with embedded Mermaid
figures/<diagram-name>.md文件2:figures/<diagram-name>.md
— 嵌入Mermaid的Markdown文件
figures/<diagram-name>.mdThe file wraps the same code in a mermaid code block for preview rendering, plus a title and description. Example:
.mdmarkdown
undefined.md文件将相同代码包裹在mermaid代码块中,用于预览渲染,并包含标题和描述。示例:
markdown
undefinedDiagram Title
Diagram Title
Brief description of what this diagram shows.
mermaid flowchart TD A[Start] --> B{Condition} B -->|Yes| C[Execute] B -->|No| D[End] C --> D
**Naming convention**: Use a descriptive kebab-case name derived from the user's request (e.g., `auth-flow`, `system-architecture`, `database-er`).Brief description of what this diagram shows.
mermaid flowchart TD A[Start] --> B{Condition} B -->|Yes| C[Execute] B -->|No| D[End] C --> D
**命名规范**:根据用户请求使用描述性的短横线分隔命名(例如:`auth-flow`、`system-architecture`、`database-er`)。Step 4: Verify Mermaid Syntax (MANDATORY)
步骤4:验证Mermaid语法(必须执行)
Claude MUST verify the generated Mermaid code by running the Mermaid CLI ().
mmdcbash
undefinedClaude必须通过运行Mermaid CLI()验证生成的Mermaid代码。
mmdcbash
undefinedCheck if mermaid-cli is available
Check if mermaid-cli is available
if command -v mmdc &> /dev/null; then
# Render to PNG to verify syntax is correct
mmdc -i figures/<diagram-name>.mmd -o figures/<diagram-name>.png -b transparent
echo "✅ Syntax valid — PNG rendered to figures/<diagram-name>.png"
else
# Try npx as fallback
npx -y @mermaid-js/mermaid-cli@latest -i figures/<diagram-name>.mmd -o figures/<diagram-name>.png -b transparent
echo "✅ Syntax valid — PNG rendered to figures/<diagram-name>.png"
fi
**If the verification fails:**
1. Read the error message carefully
2. Fix the syntax issue in both `.mmd` and `.md` files
3. Re-run verification
4. Repeat up to MAX_ITERATIONS (3) timesif command -v mmdc &> /dev/null; then
# Render to PNG to verify syntax is correct
mmdc -i figures/<diagram-name>.mmd -o figures/<diagram-name>.png -b transparent
echo "✅ Syntax valid — PNG rendered to figures/<diagram-name>.png"
else
# Try npx as fallback
npx -y @mermaid-js/mermaid-cli@latest -i figures/<diagram-name>.mmd -o figures/<diagram-name>.png -b transparent
echo "✅ Syntax valid — PNG rendered to figures/<diagram-name>.png"
fi
**如果验证失败:**
1. 仔细阅读错误信息
2. 修复.mmd和.md文件中的语法问题
3. 重新运行验证
4. 重复操作直至达到MAX_ITERATIONS(3次)Step 5: Claude STRICT Visual Review & Scoring (MANDATORY)
步骤5:Claude严格视觉审查与评分(必须执行)
After successful rendering, Claude MUST read the generated PNG and perform a STRICT review:
markdown
undefined渲染成功后,Claude必须查看生成的PNG并执行严格审查:
markdown
undefinedClaude's STRICT Review of <diagram-name>
Claude对<diagram-name>的严格审查
What I See
图表内容描述
[Describe the rendered diagram in DETAIL - every block, every arrow, every label]
[详细描述渲染后的图表 - 每个块、每个箭头、每个标签]
Files Generated
生成的文件
- — Raw Mermaid source
figures/<diagram-name>.mmd - — Markdown with embedded diagram
figures/<diagram-name>.md - — Rendered PNG (if mmdc available)
figures/<diagram-name>.png
- — 原始Mermaid源码
figures/<diagram-name>.mmd - — 嵌入图表的Markdown文件
figures/<diagram-name>.md - — 渲染后的PNG(若mmdc可用)
figures/<diagram-name>.png
═══════════════════════════════════════════════════════════════
═══════════════════════════════════════════════════════════════
STRICT VERIFICATION CHECKLIST (ALL must pass for score ≥ 9)
严格验证检查清单(所有项必须通过才能获得≥9分)
═══════════════════════════════════════════════════════════════
═══════════════════════════════════════════════════════════════
A. File Correctness
A. 文件正确性
- file contains valid Mermaid syntax (no markdown fences)
.mmd - file has the mermaid code wrapped in
.mdfencesmermaid - and
.mmdcontain IDENTICAL Mermaid code.md - Diagram renders without errors (via mmdc)
- .mmd文件包含有效的Mermaid语法(无Markdown围栏)
- .md文件将mermaid代码包裹在围栏中
mermaid - .mmd和.md文件包含完全相同的Mermaid代码
- 图表可无错误渲染(通过mmdc)
B. Arrow Correctness Verification (CRITICAL - any failure = score ≤ 6)
B. 箭头正确性验证(关键 - 任何失败=得分≤6)
Check EACH arrow:
- Arrow 1: [Source] → [Target] — Does it point to the CORRECT target?
- Arrow 2: [Source] → [Target] — Does it point to the CORRECT target?
- ... (check ALL arrows)
检查每个箭头:
- 箭头1:[源节点] → [目标节点] — 指向正确的目标?
- 箭头2:[源节点] → [目标节点] — 指向正确的目标?
- ...(检查所有箭头)
C. Block Content Verification (any failure = score ≤ 7)
C. 块内容验证(任何失败=得分≤7)
Check EACH block/node:
- Block 1 "[Name]": Has correct label? Content correct?
- Block 2 "[Name]": Has correct label? Content correct?
- ... (check ALL blocks)
检查每个块/节点:
- 块1 "[名称]": 标签正确?内容正确?
- 块2 "[名称]": 标签正确?内容正确?
- ...(检查所有块)
D. Completeness
D. 完整性
- All components from user requirements are present
- All connections/arrows are correct
- Node labels are meaningful and match requirements
- 用户需求中的所有组件均已包含
- 所有连接/箭头均正确
- 节点标签有意义且符合需求
E. Visual Quality
E. 视觉质量
- Layout is clean and readable
- Color scheme is professional (not rainbow)
- Text is readable at normal zoom
- Proper spacing (not cramped, not sparse)
- Data flow is traceable in 5 seconds
- 布局清晰易读
- 配色方案专业(非彩虹色)
- 文本在正常缩放比例下可读
- 间距合理(不过于拥挤或稀疏)
- 数据流可在5秒内追踪
═══════════════════════════════════════════════════════════════
═══════════════════════════════════════════════════════════════
Issues Found (BE SPECIFIC)
发现的问题(具体描述)
- [Issue 1]: [EXACTLY what is wrong] → [How to fix]
- [Issue 2]: [EXACTLY what is wrong] → [How to fix]
- [问题1]:[具体错误内容] → [修复方案]
- [问题2]:[具体错误内容] → [修复方案]
Score: X/10
评分:X/10
Score Breakdown Guide:
评分指南:
- 10: Perfect. No issues. Publication-ready.
- 9: Excellent. Minor issues that don't affect understanding.
- 8: Good but has noticeable issues (layout, styling).
- 7: Usable but has clear problems (wrong arrows, missing labels).
- 6: Has arrow direction errors or missing major components.
- 1-5: Major issues. Unacceptable.
- 10:完美无瑕疵,可直接用于发布。
- 9:优秀,仅存在不影响理解的微小问题。
- 8:良好,但存在明显问题(布局、样式)。
- 7:可用,但存在明确问题(箭头错误、标签缺失)。
- 6:存在箭头方向错误或缺失主要组件。
- 1-5:存在重大问题,不可接受。
Verdict
结论
[ ] ACCEPT (score ≥ 9 AND all critical checks pass)
[ ] FIX (score < 9 OR any critical check fails — list EXACT fixes needed)
**If FIX: apply corrections to both `.mmd` and `.md` files, re-render, and re-verify. Loop until ACCEPT or MAX_ITERATIONS reached.**[ ] 接受(得分≥9且所有关键检查通过)
[ ] 需要修复(得分<9或任何关键检查失败 — 列出具体修复需求)
**如果需要修复:** 对.mmd和.md文件应用修正,重新渲染并验证。循环直至接受或达到最大迭代次数。Step 6: Final Output Summary
步骤6:最终输出摘要
When accepted, present to user:
✅ Mermaid diagram generated successfully!
Files:
figures/<diagram-name>.mmd — Raw Mermaid source (use with mmdc, editors, CI)
figures/<diagram-name>.md — Markdown preview (renders on GitHub, VS Code, etc.)
figures/<diagram-name>.png — Rendered image (if mmdc was available)
To re-render manually:
mmdc -i figures/<diagram-name>.mmd -o figures/<diagram-name>.png当图表被接受后,向用户展示:
✅ Mermaid图表生成成功!
生成的文件:
figures/<diagram-name>.mmd — 原始Mermaid源码(适用于mmdc、编辑器、CI流程)
figures/<diagram-name>.md — Markdown预览文件(可在GitHub、VS Code等平台渲染)
figures/<diagram-name>.png — 渲染后的图片(若mmdc可用)
手动重新渲染命令:
mmdc -i figures/<diagram-name>.mmd -o figures/<diagram-name>.pngArchitecture Diagram Best Practices
架构图最佳实践
When generating diagrams, apply these layout techniques for complex diagrams:
architecture-beta生成图表时,对复杂图表应用以下布局技巧:
architecture-betaUse Junctions for Layout Control
使用连接点控制布局
Think of the diagram as an invisible grid. Use nodes as virtual anchor points on that grid to precisely control where each component is placed. This is especially useful when a direct edge between two services produces unexpected positioning.
junctionInstead of connecting services directly:
lb:R --> L:scim
lb:R --> L:webapiRoute through junctions to control vertical/horizontal placement:
junction j_lb_r
lb:R -- L:j_lb_r
junction j_scim_l
j_lb_r:T -- B:j_scim_l
j_scim_l:R --> L:scim
junction j_webapi_l
j_lb_r:B -- T:j_webapi_l
j_webapi_l:R --> L:webapiPlace junctions on all four sides of components to anchor them logically on the grid.
将图表视为隐形网格。使用节点作为网格上的虚拟锚点,精确控制每个组件的位置。当两个服务之间的直接连接导致位置异常时,此方法尤为有用。
junction不要直接连接服务:
lb:R --> L:scim
lb:R --> L:webapi通过连接点路由以控制垂直/水平位置:
junction j_lb_r
lb:R -- L:j_lb_r
junction j_scim_l
j_lb_r:T -- B:j_scim_l
j_scim_l:R --> L:scim
junction j_webapi_l
j_lb_r:B -- T:j_webapi_l
j_webapi_l:R --> L:webapi在组件的四个方向放置连接点,将其逻辑锚定在网格上。
Use Edges out of Groups for Floating Components
使用组外边缘定位浮动组件
For services that have no logical connection to other nodes (e.g. a deployment tool, a monitoring agent), use a junction combined with the modifier to position them without adding a semantically incorrect edge:
{group}junction j_acd_t
j_algolia_proc_b{group}:B -- T:j_acd_t
j_acd_t:B -- T:acdThis anchors below its intended neighbor without implying a real relationship.
acd对于与其他节点无逻辑连接的服务(如部署工具、监控代理),使用连接点结合修饰符定位,避免添加语义错误的连接:
{group}junction j_acd_t
j_algolia_proc_b{group}:B -- T:j_acd_t
j_acd_t:B -- T:acd此方法可将锚定在预期邻居下方,同时不暗示实际关系。
acdCVPR/ICLR/NeurIPS Style Guide (for Academic Diagrams)
CVPR/ICLR/NeurIPS学术图表规范
When the diagram is intended for academic papers, apply these style standards:
当图表用于学术论文时,应用以下样式标准:
Visual Standards
视觉标准
- Clean white background — No decorative patterns or gradients (unless subtle)
- Sans-serif fonts — Arial, Helvetica, or Computer Modern; minimum 14pt
- Subtle color palette — Not rainbow colors; use 3-5 coordinated colors
- Print-friendly — Must be readable in grayscale (many reviewers print papers)
- Professional borders — Thin (2-3px), solid colors, not flashy
- 纯白色背景 — 无装饰性图案或渐变(除非非常细微)
- 无衬线字体 — Arial、Helvetica或Computer Modern;最小14pt
- 简约配色方案 — 避免彩虹色;使用3-5种协调颜色
- 适合打印 — 在灰度模式下仍可读(许多审稿人会打印论文)
- 专业边框 — 细边框(2-3px)、纯色,不花哨
Layout Standards
布局标准
- Horizontal flow — Left-to-right is the standard for pipelines
- Clear grouping — Use subtle background boxes to group related modules
- Consistent sizing — Similar components should have similar sizes
- Balanced whitespace — Not cramped, not sparse
- 水平流向 — 从左到右是流水线的标准流向
- 清晰分组 — 使用细微背景框分组相关模块
- 尺寸一致 — 相似组件应具有相似尺寸
- 间距平衡 — 不过于拥挤或稀疏
Arrow Standards (MOST CRITICAL)
箭头标准(最关键)
- Thick strokes — 4-6px minimum (thin arrows disappear when printed)
- Clear arrowheads — Large, filled triangular heads
- Dark colors — Black or dark gray (#333333); avoid colored arrows
- Labeled — Every arrow should indicate what data flows through it
- No crossings — Reorganize layout to avoid arrow crossings
- CORRECT DIRECTION — Arrows must point to the RIGHT target!
- 粗线条 — 最小4-6px(细箭头在打印时会消失)
- 清晰箭头头 — 大尺寸、填充的三角形箭头头
- 深色 — 黑色或深灰色(#333333);避免彩色箭头
- 带标签 — 每个箭头应标注流经的数据
- 无交叉 — 重新组织布局避免箭头交叉
- 方向正确 — 箭头必须指向正确的目标!
Color Palette (Academic Professional)
学术专业配色方案
- Inputs: Green (#10B981 / #34D399)
- Encoders: Blue (#2563EB / #3B82F6)
- Fusion: Purple (#7C3AED / #8B5CF6)
- Outputs: Orange (#EA580C / #F97316)
- Arrows: Black or dark gray (#333333 / #1F2937)
- Background: Pure white (#FFFFFF)
- 输入:绿色(#10B981 / #34D399)
- 编码器:蓝色(#2563EB / #3B82F6)
- 融合模块:紫色(#7C3AED / #8B5CF6)
- 输出:橙色(#EA580C / #F97316)
- 箭头:黑色或深灰色(#333333 / #1F2937)
- 背景:纯白色(#FFFFFF)
What to AVOID
需避免的情况
- Rainbow color schemes (too many colors)
- Thin, hairline arrows
- Heavy drop shadows or glowing effects
- 3D effects / perspective
- Excessive decorative icons
- Small text that's unreadable when printed
- 彩虹配色方案(过多颜色)
- 细如发丝的箭头
- 厚重阴影或发光效果
- 3D效果/透视
- 过多装饰性图标
- 打印后无法阅读的小字体
Math Formulas in Diagrams (KaTeX)
图表中的数学公式(KaTeX)
Mermaid supports rendering mathematical expressions via KaTeX (v10.9.0+). When the diagram content involves math (formulas, equations, Greek letters, subscripts/superscripts, fractions, matrices, operators, etc.), use KaTeX notation instead of plain-text approximations.
Mermaid支持通过KaTeX(v10.9.0+)渲染数学表达式。当图表内容涉及数学(公式、方程、希腊字母、下标/上标、分数、矩阵、运算符等)时,使用KaTeX语法而非纯文本近似。
Supported Diagram Types for Math
支持数学公式的图表类型
Math rendering with is supported in:
$$...$$- Flowcharts (/
flowchart) — in node labels and edge labelsgraph - Sequence Diagrams — in participant aliases, messages, and notes
使用的数学渲染支持以下图表类型:
$$...$$- 流程图 (/
flowchart) — 节点标签和边缘标签graph - 序列图 — 参与者别名、消息和注释
Syntax Rules
语法规则
-
Wrap math expressions indelimiters inside quoted strings:
$$A["$$x^2$$"] -->|"$$\sqrt{x+3}$$"| B("$$\frac{1}{2}$$") -
Node labels with math MUST be quoted — useor
["$$...$$"]:("$$...$$")scaledDot["$$\text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V$$"] -
Mix text and math by placingonly around the math portion:
$$layer1["Linear Layer $$W_1 x + b_1$$"] -
Usefor non-math text inside a
\text{}block:$$node["$$\text{Attention}(Q, K, V)$$"]
-
将数学表达式包裹在分隔符中,并放入引号内:
$$A["$$x^2$$"] -->|"$$\sqrt{x+3}$$"| B("$$\frac{1}{2}$$") -
包含数学公式的节点标签必须加引号 — 使用或
["$$...$$"]:("$$...$$")scaledDot["$$\text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V$$"] -
混合文本与数学公式 — 仅对数学部分使用包裹:
$$layer1["Linear Layer $$W_1 x + b_1$$"] -
使用包裹数学块中的非数学文本:
\text{}node["$$\text{Attention}(Q, K, V)$$"]
Common Math Patterns for ML/Science Diagrams
ML/科学图表常用数学模式
| Concept | KaTeX Syntax | Renders As |
|---|---|---|
| Subscript | | W_Q |
| Superscript | | x² |
| Fraction | | QK^T / sqrt(d_k) |
| Greek letters | | α, β, γ |
| Square root | | √d_k |
| Summation | | Σx_i |
| Matrix | | 2x2 matrix |
| Softmax | | softmax(z_i) |
| Norm | | ‖x‖₂ |
| Hat/tilde | | ŷ, x̃ |
| 概念 | KaTeX语法 | 渲染效果 |
|---|---|---|
| 下标 | | W_Q |
| 上标 | | x² |
| 分数 | | QK^T / √d_k |
| 希腊字母 | | α, β, γ |
| 平方根 | | √d_k |
| 求和 | | Σx_i |
| 矩阵 | | 2x2矩阵 |
| Softmax | | softmax(z_i) |
| 范数 | | ‖x‖₂ |
| 帽子/波浪线 | | ŷ, x̃ |
Example: Attention Mechanism with Math
示例:带数学公式的注意力机制
flowchart TD
Q["$$Q \in \mathbb{R}^{n \times d_k}$$"]
K["$$K \in \mathbb{R}^{n \times d_k}$$"]
V["$$V \in \mathbb{R}^{n \times d_v}$$"]
scores["$$\frac{QK^T}{\sqrt{d_k}}$$"]
softmax["$$\text{softmax}(\cdot)$$"]
output["$$\text{Attention}(Q,K,V)$$"]
Q --> scores
K --> scores
scores --> softmax
softmax --> weighted["$$\alpha V$$"]
V --> weighted
weighted --> outputflowchart TD
Q["$$Q \in \mathbb{R}^{n \times d_k}$$"]
K["$$K \in \mathbb{R}^{n \times d_k}$$"]
V["$$V \in \mathbb{R}^{n \times d_v}$$"]
scores["$$\frac{QK^T}{\sqrt{d_k}}$$"]
softmax["$$\text{softmax}(\cdot)$$"]
output["$$\text{Attention}(Q,K,V)$$"]
Q --> scores
K --> scores
scores --> softmax
softmax --> weighted["$$\alpha V$$"]
V --> weighted
weighted --> outputWhen to Use Math vs Plain Text
何时使用数学公式vs纯文本
- Use math when the diagram is for academic/technical audiences and precision matters (papers, lectures, technical docs)
- Use plain text (for line breaks) when the diagram is for general audiences or when math would add visual clutter without improving clarity
<br/> - Default behavior: If the user's request contains mathematical notation, equations, or Greek symbols, automatically use KaTeX math rendering. Otherwise, use plain text labels.
- 使用数学公式:当图表面向学术/技术受众且需要精确表达时(论文、讲座、技术文档)
- 使用纯文本:当图表面向普通受众或数学公式会增加视觉混乱而无实际帮助时(使用换行)
<br/> - 默认行为:如果用户请求包含数学符号、方程或希腊字母,自动使用KaTeX渲染;否则使用纯文本标签。
Gotchas
注意事项
- The delimiters must be inside quoted strings — unquoted
$$will break parsing$$ - Backslashes in KaTeX (,
\frac, etc.) work normally in Mermaid strings\sqrt - Very long formulas may overflow node boxes — break them with (newline in KaTeX) or simplify
\\ - Always verify rendering with — some KaTeX expressions may not render in all environments
mmdc
- 分隔符必须在引号内 — 未加引号的
$$会导致解析失败$$ - KaTeX中的反斜杠(、
\frac等)在Mermaid字符串中可正常使用\sqrt - 过长公式可能溢出节点框 — 使用(KaTeX中的换行符)拆分或简化公式
\\ - 始终通过验证渲染效果 — 部分KaTeX表达式可能无法在所有环境中渲染
mmdc
Code Quality Rules
代码质量规则
Generated Mermaid code MUST:
- Have correct syntax that renders directly
- Have clear structure with proper line breaks and indentation
- Use semantic node naming (not ,
A,B— useC,authServer, etc.)userDB - Include styling when needed to improve visual appearance
- Use for line breaks inside node labels — never use
<br/>, which renders as literal text\n - Avoid special characters in labels that break Mermaid parsing (wrap in quotes if needed)
生成的Mermaid代码必须满足:
- 语法正确,可直接渲染
- 结构清晰,具有适当的换行和缩进
- 使用语义化节点命名(避免使用、
A、B— 应使用C、authServer等)userDB - 必要时添加样式以提升视觉效果
- 在节点标签中使用换行 — 切勿使用
<br/>,否则会被渲染为文本\n - 避免使用会破坏Mermaid解析的特殊字符(必要时用引号包裹)
Output Structure
输出结构
figures/
├── <diagram-name>.mmd # Raw Mermaid source (no markdown fences)
├── <diagram-name>.md # Markdown with embedded mermaid block
└── <diagram-name>.png # Rendered PNG (if mmdc available)figures/
├── <diagram-name>.mmd # 原始Mermaid源码(无Markdown围栏)
├── <diagram-name>.md # 嵌入Mermaid块的Markdown文件
└── <diagram-name>.png # 渲染后的PNG(若mmdc可用)Key Rules (MUST FOLLOW)
核心规则(必须遵守)
- ALWAYS save files to directory — Never just output code in chat
figures/ - ALWAYS generate BOTH and
.mmdfiles — They must contain identical Mermaid code.md - ALWAYS read the reference documentation before generating code for a diagram type
- ALWAYS verify syntax — Run mmdc or manually validate before accepting
- ALWAYS review the rendered PNG — Read the image and perform STRICT scoring
- NEVER accept score < 9 — Keep refining until excellence
- VERIFY EVERY ARROW DIRECTION — Wrong direction = automatic fail (score ≤ 6)
- VERIFY EVERY BLOCK CONTENT — Wrong content = automatic fail (score ≤ 7)
- BE SPECIFIC in feedback — "Arrow from A to B points wrong" not "arrow is wrong"
- FIX errors before accepting — Do not deliver broken diagrams
- Use descriptive file names — kebab-case derived from the diagram content
User requirements: $ARGUMENTS
- 始终将文件保存至目录 — 切勿仅在聊天中输出代码
figures/ - 始终生成和
.mmd两种文件 — 两者必须包含完全相同的Mermaid代码.md - 生成代码前务必查阅参考文档
- 始终验证语法 — 运行mmdc或手动验证后再确认
- 始终查看渲染后的PNG — 读取图片并执行严格评分
- 绝不接受得分<9的图表 — 持续优化直至达到优秀标准
- 验证每个箭头的方向 — 方向错误直接判定失败(得分≤6)
- 验证每个块的内容 — 内容错误直接判定失败(得分≤7)
- 反馈需具体 — 明确说明“从A到B的箭头方向错误”而非“箭头有问题”
- 修复错误后再确认 — 绝不交付有问题的图表
- 使用描述性文件名 — 根据图表内容使用短横线分隔命名
用户需求:$ARGUMENTS