Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

refactor(visualize): migrate Book blocks to validate+repair, drop LLM review

Bingxi Zhao (Frank)e8f0e77f830e
diff --git a/deeptutor/agents/visualize/agents/review_agent.py b/deeptutor/agents/visualize/agents/review_agent.py
index 0e6e3038e..2beb16c25 100644
--- a/deeptutor/agents/visualize/agents/review_agent.py
+++ b/deeptutor/agents/visualize/agents/review_agent.py
@@ -1,4 +1,4 @@
-"""Review stage: check and optionally optimise the generated code."""
+"""Repair stage: targeted fix after deterministic local validation fails."""
from __future__ import annotations
@@ -34,62 +34,13 @@ class ReviewAgent(BaseAgent):
user_input: str,
analysis: VisualizationAnalysis,
code: str,
- ) -> ReviewResult:
- # HTML pages are 8-16k tokens of full single-file documents; a second
- # LLM pass to "review" them costs another 30-60s with negligible
- # quality gain. Skip the LLM review for html and return the code as-is.
- if analysis.render_type == "html":
- return ReviewResult(
- optimized_code=code,
- changed=False,
- review_notes="Skipped LLM review for html render_type.",
- )
-
- system_prompt = self.get_prompt("system")
- user_template = self.get_prompt("user_template")
- if not system_prompt or not user_template:
- raise ValueError("ReviewAgent prompts are not configured.")
-
- user_prompt = user_template.format(
- user_input=user_input.strip(),
- render_type=analysis.render_type,
- analysis_json=json.dumps(analysis.model_dump(), ensure_ascii=False, indent=2),
- code=code,
- )
-
- chunks: list[str] = []
- async for chunk in self.stream_llm(
- user_prompt=user_prompt,
- system_prompt=system_prompt,
- response_format={"type": "json_object"},
- stage="reviewing",
- trace_meta=build_trace_metadata(
- call_id=new_call_id("viz-review"),
- phase="reviewing",
- label="Code review",
- call_kind="viz_code_review",
- trace_role="review",
- trace_kind="llm_output",
- ),
- ):
- chunks.append(chunk)
- response = "".join(chunks)
- return ReviewResult.model_validate(extract_json_object(response))
-
- async def repair(
- self,
- *,
- user_input: str,
- analysis: VisualizationAnalysis,
- code: str,
error: str,
) -> ReviewResult:
- """Targeted repair pass.
+ """Targeted repair pass — this agent's single job.
- Unlike :meth:`process` (an open-ended LLM review still used by the
- Book blocks), this is only invoked *after* a deterministic local
- validation has already failed, and is handed the concrete error so
- the model fixes one specific defect instead of re-judging everything.
+ Only invoked *after* the deterministic local validation has failed,
+ and handed the concrete error so the model fixes one specific defect
+ instead of re-judging everything (chat and Book share this path).
"""
system_prompt = self.get_prompt("repair_system")
user_template = self.get_prompt("repair_user_template")
diff --git a/deeptutor/agents/visualize/pipeline.py b/deeptutor/agents/visualize/pipeline.py
index 7810327c8..a3fd72c88 100644
--- a/deeptutor/agents/visualize/pipeline.py
+++ b/deeptutor/agents/visualize/pipeline.py
@@ -72,19 +72,6 @@ class VisualizePipeline:
analysis=analysis,
)
- async def run_review(
- self,
- *,
- user_input: str,
- analysis: VisualizationAnalysis,
- code: str,
- ) -> ReviewResult:
- return await self.review_agent.process(
- user_input=user_input,
- analysis=analysis,
- code=code,
- )
-
async def run_repair(
self,
*,
@@ -93,7 +80,7 @@ class VisualizePipeline:
code: str,
error: str,
) -> ReviewResult:
- return await self.review_agent.repair(
+ return await self.review_agent.process(
user_input=user_input,
analysis=analysis,
code=code,
diff --git a/deeptutor/agents/visualize/prompts/en/code_generator_agent.yaml b/deeptutor/agents/visualize/prompts/en/code_generator_agent.yaml
index b3d90909b..12d1dad9a 100644
--- a/deeptutor/agents/visualize/prompts/en/code_generator_agent.yaml
+++ b/deeptutor/agents/visualize/prompts/en/code_generator_agent.yaml
@@ -19,8 +19,8 @@ rules_general: |
- Use 2-3 colors at most. Color should encode meaning (category / state),
never decoration. Group same-kind elements under one color; use a neutral
gray for generic/structural/start/end elements.
- - One row holds at most 4 full-width boxes. 5+ boxes → shrink them, wrap to a
- second row, or split into an overview plus a detail figure.
+ - One row holds at most 4 full-width boxes. 5+ boxes → shrink them or wrap to
+ a second row.
- If the request lists 6+ components, do NOT cram them into one figure. Draw a
stripped overview with the main flow only, and state in the chat answer that
the user can ask for any sub-flow in detail.
@@ -82,6 +82,10 @@ rules_svg: |
- SVG `<text>` never wraps. If a label needs two lines, add an explicit
`<tspan x=... dy="1.2em">`. If it's long enough to need wrapping, it's too
long — shorten it.
+ - The host vertically centers every `<text>` on its `y` (dominant-baseline:
+ central — do not set it yourself). To center a label in a box: x = box
+ center with `text-anchor="middle"`, y = box center. For a title + subtitle
+ pair, y = center−9 and center+9.
viewBox checklist — verify before finalizing:
1. viewBox height = (bottom-most element's y + height) + 40px buffer.
@@ -103,6 +107,7 @@ rules_svg: |
not a diagram about it. Color encodes intensity (warm = active/hot, cool =
calm/cold, gray = inert). Shapes may overlap for depth; text never crosses a
stroke — place labels in quiet margins with thin leader lines.
+ - any other genre: follow the closest of the three styles above.
rules_chartjs: |
Render type: Chart.js. Output a STRICT JSON object (not a JavaScript object
diff --git a/deeptutor/agents/visualize/prompts/en/review_agent.yaml b/deeptutor/agents/visualize/prompts/en/review_agent.yaml
index 56b6e124d..b66887d11 100644
--- a/deeptutor/agents/visualize/prompts/en/review_agent.yaml
+++ b/deeptutor/agents/visualize/prompts/en/review_agent.yaml
@@ -1,53 +1,3 @@
-system: |
- You are a visualization code reviewer. Examine the generated code for correctness,
- completeness, and visual quality. Fix any issues you find.
-
- For SVG code, check:
- - Well-formed XML with proper xmlns
- - Correct viewBox and dimensions
- - Text readability (font size, contrast)
- - Proper use of colors and spacing
- - Missing or broken elements
-
- For Chart.js code, check:
- - Valid JavaScript object literal
- - Correct chart type and data structure
- - Proper labels, datasets, and options
- - Color accessibility and readability
- - Responsive configuration
-
- For Mermaid code, check:
- - Valid Mermaid.js syntax with correct diagram type keyword
- - No spaces in node IDs (use camelCase or underscores)
- - No reserved keywords (end, subgraph, graph) as bare node IDs
- - Clear and readable node labels and edge descriptions
- - Proper subgraph structure and nesting if used
- - No syntax errors that would cause rendering failure
-
- If the code is already good, return it unchanged with changed=false.
- If you make improvements, return the optimized code with changed=true.
-
- Return a JSON object. Do not include any text outside the JSON.
-
-user_template: |
- User request:
- {user_input}
-
- Render type: {render_type}
-
- Analysis:
- {analysis_json}
-
- Code to review:
- {code}
-
- Return JSON:
- {{
- "optimized_code": "the final code (same as input if no changes needed)",
- "changed": true or false,
- "review_notes": "what was checked or changed"
- }}
-
repair_system: |
You are a visualization code repair agent. The generated code failed a
deterministic local validation check, and you are given the exact error. Fix
diff --git a/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yaml b/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yaml
index 8443486e3..7780a7df0 100644
--- a/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yaml
+++ b/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yaml
@@ -14,7 +14,7 @@ rules_general: |
- 图中副标题最多 5 个词。细节放在对话正文里,不要塞进图里。
- 最多用 2-3 种颜色。颜色用来编码含义(类别 / 状态),绝不用于装饰。
同类元素共用一种颜色;通用 / 结构 / 起止节点用中性灰。
- - 一行最多放 4 个全宽方框。5 个以上 → 缩小、换到第二行,或拆成总览图 + 细节图。
+ - 一行最多放 4 个全宽方框。5 个以上 → 缩小或换到第二行。
- 如果请求列出 6 个以上组件,不要硬塞进一张图。先画只含主流程的精简总览,
并在对话正文里说明用户可以针对任意子流程要求展开细节。
@@ -68,6 +68,9 @@ rules_svg: |
就用 L 形折线绕开。
- SVG 的 `<text>` 不会自动换行。需要两行就用显式 `<tspan x=... dy="1.2em">`。
如果长到需要换行,说明它太长了——精简它。
+ - 宿主会把每个 `<text>` 在其 `y` 上垂直居中(dominant-baseline: central——
+ 你自己不要设置它)。让标签在框内居中:x = 框中心并配 `text-anchor="middle"`,
+ y = 框中心。标题 + 副标题成对时,y 分别取中心−9 和中心+9。
viewBox 终检清单——定稿前逐条核对:
1. viewBox 高度 = (最底部元素的 y + 高度)+ 40px 余量。
@@ -85,6 +88,7 @@ rules_svg: |
- illustrative:用空间隐喻建立直觉——画机制本身,而不是关于机制的图。颜色编码
强度(暖 = 活跃 / 热,冷 = 平静 / 冷,灰 = 惰性)。形状可重叠以表现层次;文字
绝不与笔画交叠——把标签放在安静的边缘,用细引导线指向。
+ - 其它 genre:参照以上三种里最接近的画法。
rules_chartjs: |
渲染类型:Chart.js。输出严格 JSON 对象(不是 JavaScript 对象字面量),作为配置
diff --git a/deeptutor/agents/visualize/prompts/zh/review_agent.yaml b/deeptutor/agents/visualize/prompts/zh/review_agent.yaml
index 5aecf4165..7ae0f0410 100644
--- a/deeptutor/agents/visualize/prompts/zh/review_agent.yaml
+++ b/deeptutor/agents/visualize/prompts/zh/review_agent.yaml
@@ -1,52 +1,3 @@
-system: |
- 你是一个可视化代码审查员。检查生成的代码的正确性、完整性和视觉质量,修复发现的任何问题。
-
- 对于 SVG 代码,检查:
- - 格式良好的 XML,包含正确的 xmlns
- - 正确的 viewBox 和尺寸
- - 文本可读性(字体大小、对比度)
- - 颜色和间距的合理使用
- - 缺失或损坏的元素
-
- 对于 Chart.js 代码,检查:
- - 有效的 JavaScript 对象字面量
- - 正确的图表类型和数据结构
- - 正确的标签、数据集和选项
- - 颜色的可访问性和可读性
- - 响应式配置
-
- 对于 Mermaid 代码,检查:
- - 有效的 Mermaid.js 语法,包含正确的图表类型关键词
- - 节点 ID 不包含空格(使用 camelCase 或下划线)
- - 不使用保留关键词(end、subgraph、graph)作为裸节点 ID
- - 清晰可读的节点标签和边描述
- - 正确的子图结构和嵌套(如使用)
- - 无会导致渲染失败的语法错误
-
- 如果代码已经很好,原样返回并设置 changed=false。
- 如果你做了改进,返回优化后的代码并设置 changed=true。
-
- 返回一个 JSON 对象,不要包含 JSON 以外的任何文本。
-
-user_template: |
- 用户请求:
- {user_input}
-
- 渲染类型:{render_type}
-
- 分析:
- {analysis_json}
-
- 待审查代码:
- {code}
-
- 返回 JSON:
- {{
- "optimized_code": "最终代码(如果无需更改则与输入相同)",
- "changed": true 或 false,
- "review_notes": "检查或修改的内容"
- }}
-
repair_system: |
你是一个可视化代码修复器。生成的代码未通过确定性的本地校验,并附上了确切的错误。
用最小的改动修复"那个具体缺陷",使代码有效且可渲染——不要重新设计、重新配色,
diff --git a/deeptutor/book/blocks/figure.py b/deeptutor/book/blocks/figure.py
index 70accb6a0..4aec7740c 100644
--- a/deeptutor/book/blocks/figure.py
+++ b/deeptutor/book/blocks/figure.py
@@ -4,6 +4,11 @@ Wraps :class:`deeptutor.agents.visualize.pipeline.VisualizePipeline` with
``render_mode="figure"`` so the LLM picks the best static rendering for the
chapter, but never falls back to interactive HTML (handled by the
``interactive`` block type).
+
+Like the chat capability, the draft is checked by the deterministic local
+``validate_visualization``; only on failure do we spend one targeted repair
+call. If the code still fails after repair we raise ``GenerationFailure`` so
+the book engine can retry, instead of baking a broken figure into the book.
"""
from __future__ import annotations
@@ -47,7 +52,9 @@ class FigureGenerator(BlockGenerator):
)
try:
+ from deeptutor.agents.visualize.models import ReviewResult
from deeptutor.agents.visualize.pipeline import VisualizePipeline
+ from deeptutor.agents.visualize.utils import validate_visualization
from deeptutor.services.llm.config import get_llm_config
llm_config = get_llm_config()
@@ -67,17 +74,29 @@ class FigureGenerator(BlockGenerator):
history_context=history_context,
analysis=analysis,
)
- review = await pipeline.run_review(
- user_input=user_input,
- analysis=analysis,
- code=code,
- )
+ ok, validation_error = validate_visualization(code, analysis.render_type)
+ if ok:
+ review = ReviewResult(
+ optimized_code=code,
+ changed=False,
+ review_notes="Passed local validation.",
+ )
+ else:
+ review = await pipeline.run_repair(
+ user_input=user_input,
+ analysis=analysis,
+ code=code,
+ error=validation_error,
+ )
except Exception as exc:
logger.warning(f"FigureGenerator failed: {exc}", exc_info=True)
raise GenerationFailure(f"figure generation failed: {exc}") from exc
final_code = review.optimized_code or code
render_type = analysis.render_type
+ final_ok, residual_error = validate_visualization(final_code, render_type)
+ if not final_ok:
+ raise GenerationFailure(f"figure failed validation after repair: {residual_error}")
lang_tag = {
"svg": "svg",
"mermaid": "mermaid",
diff --git a/deeptutor/book/blocks/interactive.py b/deeptutor/book/blocks/interactive.py
index f737b53af..c0e98e245 100644
--- a/deeptutor/book/blocks/interactive.py
+++ b/deeptutor/book/blocks/interactive.py
@@ -3,6 +3,12 @@
Wraps :class:`deeptutor.agents.visualize.pipeline.VisualizePipeline` with
``render_mode="html"``. The payload carries an HTML document the frontend
renders in an isolated iframe.
+
+The draft is checked by the deterministic local ``validate_visualization``.
+HTML has no repair pass (full single-file documents are too large for a
+useful targeted fix), so an unrenderable document raises
+``GenerationFailure`` and lets the book engine retry — better than baking a
+placeholder page into the book.
"""
from __future__ import annotations
@@ -48,6 +54,7 @@ class InteractiveGenerator(BlockGenerator):
try:
from deeptutor.agents.visualize.pipeline import VisualizePipeline
+ from deeptutor.agents.visualize.utils import validate_visualization
from deeptutor.services.llm.config import get_llm_config
llm_config = get_llm_config()
@@ -67,28 +74,25 @@ class InteractiveGenerator(BlockGenerator):
history_context=history_context,
analysis=analysis,
)
- review = await pipeline.run_review(
- user_input=user_input,
- analysis=analysis,
- code=code,
- )
except Exception as exc:
logger.warning(f"InteractiveGenerator failed: {exc}", exc_info=True)
raise GenerationFailure(f"interactive generation failed: {exc}") from exc
- final_code = review.optimized_code or code
+ ok, validation_error = validate_visualization(code, "html")
+ if not ok:
+ raise GenerationFailure(f"interactive html failed validation: {validation_error}")
return (
{
"render_type": "html",
- "code": {"language": "html", "content": final_code},
+ "code": {"language": "html", "content": code},
"description": analysis.description,
"chart_type": analysis.chart_type,
},
[],
{
- "review_changed": review.changed,
- "review_notes": review.review_notes,
+ "review_changed": False,
+ "review_notes": "Passed local validation.",
},
)
diff --git a/tests/core/test_capabilities_runtime.py b/tests/core/test_capabilities_runtime.py
index fa400ccdb..57b31902b 100644
--- a/tests/core/test_capabilities_runtime.py
+++ b/tests/core/test_capabilities_runtime.py
@@ -33,7 +33,10 @@ def _install_module(
monkeypatch.setitem(sys.modules, pkg_name, pkg)
if idx > 1:
parent = sys.modules[".".join(parts[: idx - 1])]
- setattr(parent, parts[idx - 1], pkg)
+ # monkeypatch (not raw setattr) so the parent package's
+ # attribute is restored on teardown and never leaks a fake
+ # submodule into later tests.
+ monkeypatch.setattr(parent, parts[idx - 1], pkg, raising=False)
module = types.ModuleType(fullname)
for key, value in attrs.items():
@@ -41,7 +44,7 @@ def _install_module(
monkeypatch.setitem(sys.modules, fullname, module)
if len(parts) > 1:
parent = sys.modules[".".join(parts[:-1])]
- setattr(parent, parts[-1], module)
+ monkeypatch.setattr(parent, parts[-1], module, raising=False)
return module
@@ -393,18 +396,6 @@ async def test_visualize_capability_passes_attachments_to_analysis_agent(
"data_description": self.data_description,
}
- class FakeReview:
- optimized_code = "<svg></svg>"
- changed = False
- review_notes = "ok"
-
- def model_dump(self) -> dict[str, Any]:
- return {
- "optimized_code": self.optimized_code,
- "changed": self.changed,
- "review_notes": self.review_notes,
- }
-
class FakeVisualizePipeline:
def __init__(self, **kwargs: Any) -> None:
captured["init"] = kwargs
@@ -415,11 +406,9 @@ async def test_visualize_capability_passes_attachments_to_analysis_agent(
async def run_code_generation(self, **kwargs: Any) -> str:
captured["code_generation"] = kwargs
- return "<svg></svg>"
-
- async def run_review(self, **kwargs: Any) -> FakeReview:
- captured["review"] = kwargs
- return FakeReview()
+ # Valid per validate_visualization (well-formed XML + camelCase
+ # viewBox), so the capability takes the no-repair path.
+ return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"></svg>'
monkeypatch.setattr(
visualize_pipeline,
diff --git a/web/components/visualize/svg-theme.css b/web/components/visualize/svg-theme.css
index d8a1108ff..7333f7e8a 100644
--- a/web/components/visualize/svg-theme.css
+++ b/web/components/visualize/svg-theme.css
@@ -28,6 +28,13 @@
);
}
+/* Vertical centering is guaranteed by the host so the model never has to
+ emit (and possibly misspell) dominant-baseline itself: every text is
+ centered on its y, and the codegen prompt instructs y = box/row center. */
+.dt-svg-root text {
+ dominant-baseline: central;
+}
+
/* Text roles */
.dt-svg-root text.t,
.dt-svg-root text.th {