Skip to content

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

refactor(visualize): structured prompts, local validate+repair, drop answer-now

Bingxi Zhao (Frank)517c90b11dfc
diff --git a/deeptutor/agents/visualize/agents/code_generator_agent.py b/deeptutor/agents/visualize/agents/code_generator_agent.py
index 6f6aaf892..51265528f 100644
--- a/deeptutor/agents/visualize/agents/code_generator_agent.py
+++ b/deeptutor/agents/visualize/agents/code_generator_agent.py
@@ -35,7 +35,20 @@ class CodeGeneratorAgent(BaseAgent):
history_context: str,
analysis: VisualizationAnalysis,
) -> str:
- system_prompt = self.get_prompt("system")
+ # Structured prompt assembly: every render type loads the shared
+ # base + general rules, plus exactly one format-specific rule block.
+ # This keeps the per-call prompt dense with the rules that matter for
+ # *this* format without ever paying for the union of all four.
+ # render_type here is always one of svg/chartjs/mermaid/html — manim
+ # is dispatched away in the capability layer before code generation.
+ system_parts = (
+ self.get_prompt("system_base"),
+ self.get_prompt("rules_general"),
+ self.get_prompt(f"rules_{analysis.render_type}"),
+ )
+ system_prompt = "\n\n".join(
+ part.strip() for part in system_parts if part and part.strip()
+ )
user_template = self.get_prompt("user_template")
if not system_prompt or not user_template:
raise ValueError("CodeGeneratorAgent prompts are not configured.")
diff --git a/deeptutor/agents/visualize/agents/review_agent.py b/deeptutor/agents/visualize/agents/review_agent.py
index 95c2a617a..0e6e3038e 100644
--- a/deeptutor/agents/visualize/agents/review_agent.py
+++ b/deeptutor/agents/visualize/agents/review_agent.py
@@ -75,3 +75,50 @@ class ReviewAgent(BaseAgent):
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.
+
+ 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.
+ """
+ system_prompt = self.get_prompt("repair_system")
+ user_template = self.get_prompt("repair_user_template")
+ if not system_prompt or not user_template:
+ raise ValueError("ReviewAgent repair prompts are not configured.")
+
+ user_prompt = user_template.format(
+ user_input=user_input.strip(),
+ render_type=analysis.render_type,
+ error=error.strip() or "(unspecified)",
+ 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-repair"),
+ phase="reviewing",
+ label="Code repair",
+ call_kind="viz_code_repair",
+ trace_role="review",
+ trace_kind="llm_output",
+ ),
+ ):
+ chunks.append(chunk)
+ response = "".join(chunks)
+ return ReviewResult.model_validate(extract_json_object(response))
diff --git a/deeptutor/agents/visualize/models.py b/deeptutor/agents/visualize/models.py
index 66ef70866..99112447d 100644
--- a/deeptutor/agents/visualize/models.py
+++ b/deeptutor/agents/visualize/models.py
@@ -49,6 +49,28 @@ class VisualizationAnalysis(BaseModel):
default="",
description="Why this render_type was chosen over the alternative.",
)
+ visual_genre: Literal[
+ "",
+ "flowchart",
+ "structural",
+ "illustrative",
+ "chart",
+ "stepper",
+ "interactive",
+ "mockup",
+ "art",
+ ] = Field(
+ default="",
+ description=(
+ "Teaching-oriented sub-type that drives the code-generation style, "
+ "routed on the user's intent (the verb), not the topic (the noun): "
+ "'flowchart'/'structural' for reference maps, 'illustrative' for "
+ "intuition/'how does X work' spatial metaphors, 'stepper' for "
+ "cyclic or staged walkthroughs, 'chart' for quantitative data, "
+ "'interactive'/'mockup'/'art' for the matching HTML/SVG experiences. "
+ "Empty when no sub-type applies."
+ ),
+ )
class ReviewResult(BaseModel):
diff --git a/deeptutor/agents/visualize/pipeline.py b/deeptutor/agents/visualize/pipeline.py
index 2a1fdaa41..7810327c8 100644
--- a/deeptutor/agents/visualize/pipeline.py
+++ b/deeptutor/agents/visualize/pipeline.py
@@ -85,5 +85,20 @@ class VisualizePipeline:
code=code,
)
+ async def run_repair(
+ self,
+ *,
+ user_input: str,
+ analysis: VisualizationAnalysis,
+ code: str,
+ error: str,
+ ) -> ReviewResult:
+ return await self.review_agent.repair(
+ user_input=user_input,
+ analysis=analysis,
+ code=code,
+ error=error,
+ )
+
__all__ = ["VisualizePipeline"]
diff --git a/deeptutor/agents/visualize/prompts/en/analysis_agent.yaml b/deeptutor/agents/visualize/prompts/en/analysis_agent.yaml
index 76b2d0618..9ccdfa8fa 100644
--- a/deeptutor/agents/visualize/prompts/en/analysis_agent.yaml
+++ b/deeptutor/agents/visualize/prompts/en/analysis_agent.yaml
@@ -1,6 +1,6 @@
system: |
- You are a visualization analyst. Given a user request and conversation history,
- decide the best rendering approach and produce a structured analysis.
+ You are a visualization analyst. Given a user request and conversation
+ history, decide the best rendering approach and produce a structured brief.
Choose between six render types:
- "svg": Custom illustration, schematic, or free-form graphic that needs
@@ -8,30 +8,42 @@ system: |
- "chartjs": Quantitative data that fits a standard chart type (bar, line,
pie, doughnut, radar, scatter, bubble, polar area).
- "mermaid": Structured diagram (flowchart, sequence diagram, class diagram,
- state diagram, ERD, Gantt, mindmap). Prefer mermaid over svg for these
- structured types.
- - "html": Interactive learning/explanation page — draggable demo, animation
- with controls, step-by-step walkthrough, clickable practice exercises.
+ state diagram, ERD, Gantt, mindmap). Prefer mermaid over svg for these.
+ - "html": Interactive learning page — draggable demo, animation with controls,
+ step-by-step walkthrough, clickable practice.
- "manim_video": User explicitly wants a math animation / video showing
- evolution over time (e.g. derivation unfolding step-by-step, dynamic
- geometric transformation, motion / limit visualisation). Rendered as MP4
- via Manim.
- - "manim_image": User wants Manim-rendered storyboard images (multiple
- high-quality static frames), not a dynamic video.
+ evolution over time. Rendered as MP4 via Manim.
+ - "manim_image": User explicitly wants Manim-rendered storyboard images.
Priority rules:
- 1. If a static figure (svg/chartjs/mermaid) is enough, prefer it — they're
- the fastest and cheapest.
+ 1. If a static figure (svg/chartjs/mermaid) is enough, prefer it — fastest and
+ cheapest.
2. Choose html only when "user interaction + state changes + mixed
text/graphics" is the core experience.
- 3. Choose manim_video only when the user explicitly wants animation / video
- / temporal evolution.
- 4. Choose manim_image only when the user explicitly wants Manim-styled
- static frames.
- 5. Do not default to manim just because the topic is mathematical — only
- when the user genuinely needs dynamic visualisation.
-
- Return your analysis as a single JSON object. Do not include any text outside the JSON.
+ 3. Choose manim_video / manim_image only when the user explicitly wants
+ animation / video / temporal evolution / Manim-styled frames. Do NOT pick
+ manim just because the topic is mathematical.
+
+ Then choose a `visual_genre` — route on the VERB (what the user wants to do),
+ not the NOUN (the topic). This drives HOW the figure is drawn:
+
+ | The user's intent | render_type | visual_genre |
+ |---|---|---|
+ | "how does X work" / "give me intuition" / "I don't get X" | svg or html | illustrative / interactive |
+ | "architecture" / "what are the parts" / "what's inside" | svg or mermaid | structural |
+ | "the process" / "the steps" / "what happens when" | mermaid or svg | flowchart |
+ | a cycle / staged walkthrough with per-stage detail | html | stepper |
+ | compare quantities / show data | chartjs | chart |
+ | relationships / schema / ERD | mermaid | structural |
+ | a UI screen / form / dashboard mockup | html | mockup |
+ | decorative illustration / pattern | svg | art |
+
+ Note the asymmetry: "how does X work" defaults to the illustrative/interactive
+ route (a spatial metaphor that conveys the mechanism), NOT a safe flowchart.
+ Reserve flowchart for genuine step sequences. Leave visual_genre "" only when
+ none applies.
+
+ Return your analysis as a single JSON object. No text outside the JSON.
user_template: |
User request:
@@ -43,19 +55,25 @@ user_template: |
Return JSON:
{{
"render_type": "svg" or "chartjs" or "mermaid" or "html" or "manim_video" or "manim_image",
+ "visual_genre": "flowchart" or "structural" or "illustrative" or "chart" or "stepper" or "interactive" or "mockup" or "art" or "",
"description": "High-level description of what the visualization should show",
"data_description": "Description of the data or elements to be visualized",
- "chart_type": "Chart.js chart type if chartjs; Mermaid diagram type if mermaid; an interaction tag (e.g. interactive / animation / walkthrough / quiz) if html; an animation-style tag (e.g. derivation / geometry / transformation) if manim_*; otherwise empty string",
+ "chart_type": "Chart.js chart type if chartjs; Mermaid diagram type if mermaid; an interaction tag (interactive / animation / walkthrough / quiz) if html; an animation-style tag (derivation / geometry / transformation) if manim_*; otherwise empty string",
"visual_elements": ["key visual elements or interactive modules to include"],
- "rationale": "Why this render_type was chosen"
+ "rationale": "Why this render_type and visual_genre were chosen (cite the user's verb)"
}}
system_fixed: |
- You are a visualization analyst. The user has already chosen the rendering type.
- Analyze the user request and conversation history to produce a structured brief
- for code generation. Do not change the render_type.
+ You are a visualization analyst. The user has already chosen the rendering
+ type. Analyze the request and conversation history to produce a structured
+ brief for code generation. Do not change the render_type.
+
+ Still choose a `visual_genre` that fits the request — route on the user's VERB
+ (what they want to do), not the topic. It tells the code generator HOW to draw
+ this render type: flowchart / structural / illustrative for svg or mermaid;
+ chart for chartjs; stepper / interactive / mockup for html. Use "" if none fit.
- Return your analysis as a single JSON object. Do not include any text outside the JSON.
+ Return your analysis as a single JSON object. No text outside the JSON.
user_template_fixed: |
User request:
@@ -69,9 +87,10 @@ user_template_fixed: |
Return JSON:
{{
"render_type": "{render_type}",
+ "visual_genre": "the genre that best fits this {render_type} and the user's intent, or empty string",
"description": "High-level description of what the visualization should show",
"data_description": "Description of the data or elements to be visualized",
- "chart_type": "Chart.js chart type if chartjs; Mermaid diagram type if mermaid; an interaction tag (e.g. interactive / animation / walkthrough / quiz) if html; otherwise empty string",
+ "chart_type": "Chart.js chart type if chartjs; Mermaid diagram type if mermaid; an interaction tag (interactive / animation / walkthrough / quiz) if html; otherwise empty string",
"visual_elements": ["key visual elements or interactive modules to include"],
"rationale": "Analysis notes"
}}
@@ -79,20 +98,20 @@ user_template_fixed: |
system_figure: |
You are a visualization analyst. The user wants a STATIC figure (no
interactivity). Choose between three render types ONLY:
- - "svg": Use when the visualization is a custom illustration, schematic, or any
- free-form graphic that requires precise coordinate-level control and does not
- fit a standard chart or structured diagram.
- - "chartjs": Use when the visualization involves quantitative data that fits a
- standard chart type (bar, line, pie, doughnut, radar, scatter, bubble, polar area).
- - "mermaid": Use when the visualization is a structured diagram such as a flowchart,
- sequence diagram, class diagram, state diagram, entity-relationship diagram,
- Gantt chart, mindmap, or any graph that can be expressed with Mermaid.js syntax.
- Prefer mermaid over svg for these structured diagram types.
+ - "svg": Custom illustration, schematic, or free-form graphic needing precise
+ coordinate-level control, not fitting a standard chart or structured diagram.
+ - "chartjs": Quantitative data fitting a standard chart type (bar, line, pie,
+ doughnut, radar, scatter, bubble, polar area).
+ - "mermaid": Structured diagram (flowchart, sequence, class, state, ERD, Gantt,
+ mindmap). Prefer mermaid over svg for these structured types.
+
+ DO NOT choose "html" — interactive pages are handled separately. Pick exactly
+ one of svg / chartjs / mermaid.
- DO NOT choose "html" — interactive HTML pages are handled by a separate
- block type. Pick exactly one of svg / chartjs / mermaid.
+ Also choose a `visual_genre` (flowchart / structural / illustrative / chart, or
+ "") that tells the code generator how to draw it, routing on the user's intent.
- Return your analysis as a single JSON object. Do not include any text outside the JSON.
+ Return your analysis as a single JSON object. No text outside the JSON.
user_template_figure: |
User request:
@@ -104,9 +123,10 @@ user_template_figure: |
Return JSON (render_type MUST be one of "svg", "chartjs", or "mermaid"):
{{
"render_type": "svg" or "chartjs" or "mermaid",
+ "visual_genre": "flowchart" or "structural" or "illustrative" or "chart" or "",
"description": "High-level description of what the figure should show",
"data_description": "Description of the data or elements to be visualized",
"chart_type": "Chart.js chart type if chartjs; Mermaid diagram type if mermaid; otherwise empty string",
"visual_elements": ["key visual elements to include"],
- "rationale": "Why this render_type was chosen"
+ "rationale": "Why this render_type and visual_genre were chosen"
}}
diff --git a/deeptutor/agents/visualize/prompts/en/answer_now.yaml b/deeptutor/agents/visualize/prompts/en/answer_now.yaml
deleted file mode 100644
index e762f74ce..000000000
--- a/deeptutor/agents/visualize/prompts/en/answer_now.yaml
+++ /dev/null
@@ -1,16 +0,0 @@
-system: |
- You are DeepTutor's visualization code generator. The user is waiting,
- so emit the final renderable code in one shot. Output strictly the JSON
- {"render_type": "svg|chartjs|mermaid", "code": "..."}, where ``code`` is
- the renderable source (SVG markup, Chart.js JS, or Mermaid DSL).
-
-user_template: |
- User request: {original}
-
- render_mode hint: {render_mode}
-
- {current_draft}
-
- {execution_trace}
-
- Emit the JSON now.
diff --git a/deeptutor/agents/visualize/prompts/en/code_generator_agent.yaml b/deeptutor/agents/visualize/prompts/en/code_generator_agent.yaml
index 0a7d331fb..b3d90909b 100644
--- a/deeptutor/agents/visualize/prompts/en/code_generator_agent.yaml
+++ b/deeptutor/agents/visualize/prompts/en/code_generator_agent.yaml
@@ -1,40 +1,159 @@
-system: |
- You are a visualization code generator. Based on the analysis, user request, and
- conversation history, produce the visualization code.
-
- Rules:
- - If render_type is "svg", output a complete, self-contained SVG string.
- The SVG must include the xmlns attribute and be well-formed XML.
- Use viewBox for responsive sizing. Prefer clean, modern aesthetics with
- readable fonts, clear colors, and proper spacing.
- - If render_type is "chartjs", output a valid JavaScript object literal that
- can be passed as the configuration to `new Chart(ctx, config)`.
- The config must include `type`, `data`, and `options` fields.
- Use modern color palettes and ensure labels are readable.
- - If render_type is "mermaid", output valid Mermaid.js diagram code.
- The code must start with a valid diagram type keyword (graph, flowchart,
- sequenceDiagram, classDiagram, stateDiagram-v2, erDiagram, gantt, mindmap, etc.).
- Use clear node labels and readable edge descriptions. Do NOT use spaces in
- node IDs — use camelCase or underscores. Avoid reserved keywords as node IDs.
- - If render_type is "html", output one complete, self-contained single-file HTML
- learning page.
- Technical constraints:
- * Must include everything from <!DOCTYPE html> to </html>.
- * Put all CSS inside <style>; put all JavaScript inside <script> before </body>.
- * Do NOT rely on external CDNs, fonts, or other resources (KaTeX is injected
- by the host page; use $...$ for inline math, $$...$$ for block math).
- * The page will render inside an iframe — use max-width: 100% and
- box-sizing: border-box, avoid fixed widths.
- * For long content use overflow-x: auto when needed; never let content be
- clipped.
- * Wrap all interactions inside DOMContentLoaded and use addEventListener;
- do NOT use inline onclick handlers.
- * Always check that an element exists before manipulating it.
- Within these constraints, freely choose layout, colors, visual style, and
- interaction patterns to make the page clear, beautiful, and easy to learn from.
- - Do NOT include any explanation outside the code fence.
- - Wrap the code in a fenced code block with the appropriate language tag
- (```svg, ```javascript, ```mermaid, or ```html).
+system_base: |
+ You are DeepTutor's visualization code generator. Given the analysis brief,
+ the user request, and the conversation history, output the renderable code
+ for ONE visualization.
+
+ Output contract:
+ - Output ONLY the code, wrapped in a single fenced code block with the right
+ language tag (```svg, ```javascript, ```mermaid, or ```html). No prose, no
+ explanation, no second block.
+ - The code must be complete and self-contained — it is rendered directly,
+ with nothing prepended or appended.
+
+rules_general: |
+ These rules apply to every render type.
+
+ Complexity budget (hard limits — a sparse, correct figure beats a dense one):
+ - A diagram subtitle is at most 5 words. Detail belongs in the surrounding
+ chat answer, not inside the figure.
+ - 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.
+ - 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.
+
+ Text:
+ - Sentence case everywhere (labels, headings, captions). Never Title Case,
+ never ALL CAPS.
+ - Every label must be readable: enough contrast, no text smaller than 11px.
+
+rules_svg: |
+ Render type: SVG. The figure is inlined into the page (not an <img>), so it
+ inherits the app's theme and font and can be interactive. Use the PRE-BUILT
+ classes below for color and text instead of hard-coded fills — that is what
+ makes the figure follow light/dark mode automatically.
+
+ - Root: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 W H">`. Always set
+ xmlns and a camelCase viewBox (`viewBox`, never `viewbox`); size via viewBox,
+ not a fixed width/height.
+ - Output EXACTLY ONE `<svg>`. If the figure has several parts, lay them out as
+ regions INSIDE that single svg (stacked rows, side-by-side columns, labeled
+ zones) — never emit multiple `<svg>` elements; separate svgs render as
+ disconnected fragments. Use `href` for internal refs, not `xlink:href` (or
+ declare `xmlns:xlink` on the root if you must use xlink).
+ - Well-formed XML: every tag closed, every attribute quoted, `&` as `&amp;`.
+ Output is parsed as strict XML — a stray unescaped char fails the whole figure.
+ - Do NOT draw a background rect and do NOT hard-code fill/font on text. The host
+ provides the background; the classes below provide theme-aware colors. Leave
+ the background transparent.
+
+ Pre-built classes (styled by the host — use these, never inline colors):
+ - Text: `class="t"` (14px), `class="th"` (14px medium, for titles), `class="ts"`
+ (12px, for subtitles/captions). Two sizes only. Every `<text>` carries one.
+ - Neutral: `class="box"` (container rect), `class="arr"` (arrow line — add
+ `marker-end="url(#arrow)"`), `class="leader"` (dashed leader line).
+ - Color ramp on a `<g>` or shape: one of `c-gray c-blue c-teal c-coral c-pink
+ c-purple c-green c-amber c-red`. It sets the shape's fill+stroke AND the color
+ of contained `<text>`, in both light and dark mode. Use 2-3 ramps max; gray
+ for neutral/structural/start/end. Prefer purple/teal/coral for generic
+ categories; reserve blue/green/amber/red for info/success/warning/error.
+ - Pattern: put a `c-*` ramp on a `<g>` wrapping the shape + its `<text>`; the
+ text picks up the matching readable color automatically.
+
+ Arrow marker — include once and reference with `marker-end="url(#arrow)"`:
+ `<defs><marker id="arrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M2 1L8 5L2 9" fill="none" stroke="context-stroke" stroke-width="1.5"/></marker></defs>`
+
+ Interactive (optional): to let a node deep-dive on click, put
+ `data-prompt="<a short follow-up question>"` on its `<g>` — clicking sends that
+ question to chat. Use it for nodes a learner would naturally want to expand.
+
+ Coordinate math — most SVG failures are arithmetic, so compute before drawing:
+ - Box width from the longest label: `width = max(title_chars*8, subtitle_chars*7) + 24`.
+ A 100px box holds ~10 subtitle chars. Special characters (formulas, ∑, ₆,
+ subscripts) are wider — add 30-50%.
+ - Tier packing: before placing a row of N boxes, check total width fits the
+ safe area (x=40..640). E.g. four 130px boxes + three 20px gaps = 580 ≤ 600.
+ If they don't fit, shrink or wrap — never let boxes overlap.
+ - Arrow routing: before drawing a line A→B, check it does not cross any other
+ box's interior or any label. If it would, use an L-shaped path detour.
+ - 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.
+
+ viewBox checklist — verify before finalizing:
+ 1. viewBox height = (bottom-most element's y + height) + 40px buffer.
+ 2. All content within x=0..W and y=0..H; never use negative coordinates.
+ 3. No unintended overlaps between unrelated boxes, labels, or arrows.
+ 4. `text-anchor="end"` extends LEFT from x — at small x it can run past x=0;
+ prefer `text-anchor="start"` and right-align the column.
+
+ Match the drawing to the teaching intent in `visual_genre`:
+ - flowchart: sequential steps / decisions. Boxes + arrows, single direction
+ (all top-down or all left-right), ≤5 nodes. A cycle is shown by a single
+ return arrow with a "↻ returns to start" note — NOT by arranging boxes on a
+ ring (ring layouts collide; if the cycle has per-stage detail, the analysis
+ should have chosen html stepper instead).
+ - structural: things inside things. Large rounded container rects (light
+ fill), smaller region rects inside (next shade or a related color), ≤2-3
+ nesting levels, 20px padding inside every container.
+ - illustrative: build intuition with a spatial metaphor — draw the mechanism,
+ 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.
+
+rules_chartjs: |
+ Render type: Chart.js. Output a STRICT JSON object (not a JavaScript object
+ literal) that is passed as the config to `new Chart(ctx, config)`:
+ - Double-quoted keys and string values. No function callbacks, no comments, no
+ trailing commas, no `undefined`. It must parse with `JSON.parse`.
+ - Must include `"type"` and `"data"`; include `"options"` for axis/legend
+ config. Pick the chart type that fits the data (bar / line / pie / doughnut /
+ radar / scatter / bubble / polarArea).
+ - Use a readable, modern color palette. Never rely on color alone to separate
+ series — for categorical data put the value/label in the data so the legend
+ is meaningful.
+ - Round any pre-computed numbers in the data; don't emit float artifacts.
+
+rules_mermaid: |
+ Render type: Mermaid.js. Output valid Mermaid DSL:
+ - The first non-empty line is a valid diagram keyword: graph / flowchart /
+ sequenceDiagram / classDiagram / stateDiagram-v2 / erDiagram / gantt /
+ mindmap / pie / journey / timeline.
+ - Node IDs contain no spaces — use camelCase or under_scores. Put display text
+ in brackets: `nodeId[Display label]`. Never use reserved words (end, graph,
+ subgraph, class) as bare node IDs.
+ - For database schemas / ERDs, use `erDiagram`; for class structure use
+ `classDiagram`. These are layout problems Mermaid solves for free — don't
+ hand-draw them in SVG.
+ - Keep labels short and readable; check the diagram type keyword matches the
+ structure you're describing.
+
+rules_html: |
+ Render type: HTML. Output one complete, self-contained single-file HTML page
+ for an interactive explainer, stepper, mockup, or clickable demo.
+ - Include everything from `<!DOCTYPE html>` to `</html>`. Put CSS in `<style>`
+ and JavaScript in `<script>`.
+ - Renders inside a sandboxed iframe (null origin). You MAY load libraries from
+ these CDNs only — cdn.jsdelivr.net, cdnjs.cloudflare.com, unpkg.com — anything
+ else is blocked. KaTeX is auto-injected (`$...$` / `$$...$$`). Good picks:
+ Chart.js for charts, d3 + topojson for data viz / maps.
+ - Geographic maps: fetch real topology, never hand-invent coordinates. US
+ states: `cdn.jsdelivr.net/npm/us-atlas@3/states-10m.json` (d3.geoAlbersUsa).
+ World: `cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json`
+ (d3.geoNaturalEarth1). Key your data on the file's real feature name/id.
+ - The host auto-sizes the iframe to your content height — do not set a fixed
+ body height; use `max-width: 100%` and `box-sizing: border-box`.
+ - Follow-up questions: call `sendPrompt("a short question")` (e.g. from a
+ button's onclick) to drop that question into the chat composer. Use it where
+ a learner would naturally want to dig deeper.
+ - For a cyclic or staged process, build a stepper: one panel per stage, dots or
+ pills showing position, a Next button that wraps from the last stage back to
+ the first. Each panel owns its own content so nothing collides.
+ - Within these constraints, choose layout, color, and interaction freely to
+ make the page clear, beautiful, and easy to learn from.
user_template: |
User request:
@@ -45,11 +164,12 @@ user_template: |
Render type: {render_type}
- Analysis:
+ Analysis brief (note `visual_genre` — it tells you which style of {render_type}
+ to produce):
{analysis_json}
- Generate the visualization code now. Wrap it in a fenced code block:
- - For SVG: ```svg ... ```
- - For Chart.js: ```javascript ... ```
- - For Mermaid: ```mermaid ... ```
- - For HTML: ```html ... ```
+ Generate the visualization code now, as a single fenced code block:
+ - SVG: ```svg ... ```
+ - Chart.js: ```javascript ... ```
+ - Mermaid: ```mermaid ... ```
+ - HTML: ```html ... ```
diff --git a/deeptutor/agents/visualize/prompts/en/review_agent.yaml b/deeptutor/agents/visualize/prompts/en/review_agent.yaml
index e9fb48583..56b6e124d 100644
--- a/deeptutor/agents/visualize/prompts/en/review_agent.yaml
+++ b/deeptutor/agents/visualize/prompts/en/review_agent.yaml
@@ -47,3 +47,42 @@ user_template: |
"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
+ THAT specific defect with the smallest change that makes the code valid and
+ renderable — do not redesign, restyle, or re-judge the rest.
+
+ - svg: return ONE well-formed `<svg>` with xmlns and a camelCase `viewBox`. If
+ the code has multiple `<svg>` elements, merge them into one (the parts become
+ internal regions). Use the pre-built classes (t/ts/th, box, arr, c-*) for
+ color and text — do not hard-code fills.
+ - chartjs: return STRICT JSON (double-quoted keys; no functions, comments, or
+ trailing commas) including "type" and "data".
+ - mermaid: start with a valid diagram keyword; node IDs without spaces.
+ - Preserve the original intent and content. Change only what's needed.
+
+ Return a JSON object. No text outside the JSON.
+
+repair_user_template: |
+ User request:
+ {user_input}
+
+ Render type: {render_type}
+
+ Validation error that must be fixed:
+ {error}
+
+ Analysis brief:
+ {analysis_json}
+
+ Code that failed validation:
+ {code}
+
+ Return JSON:
+ {{
+ "optimized_code": "the corrected, renderable code",
+ "changed": true or false,
+ "review_notes": "what was fixed"
+ }}
diff --git a/deeptutor/agents/visualize/prompts/zh/analysis_agent.yaml b/deeptutor/agents/visualize/prompts/zh/analysis_agent.yaml
index f80fe5a7c..11e2cecb6 100644
--- a/deeptutor/agents/visualize/prompts/zh/analysis_agent.yaml
+++ b/deeptutor/agents/visualize/prompts/zh/analysis_agent.yaml
@@ -1,20 +1,39 @@
system: |
- 你是一个可视化分析师。根据用户请求和对话历史,决定最佳的渲染方式并生成结构化分析。
+ 你是一个可视化分析师。根据用户请求和对话历史,决定最佳的渲染方式并生成结构化简报。
在六种渲染类型中选择:
- - "svg":当可视化是自定义插图、示意图或任何需要精确坐标控制的自由图形,且不适合标准图表或结构化图形时使用。
- - "chartjs":当可视化涉及可以用标准图表类型(柱状图、折线图、饼图、环形图、雷达图、散点图、气泡图、极坐标图)表示的定量数据时使用。
- - "mermaid":当可视化是结构化图形时使用,如流程图、序列图、类图、状态图、实体关系图、甘特图、思维导图或任何可以用 Mermaid.js 语法表达的图形。对于这些结构化图形类型,优先使用 mermaid 而非 svg。
- - "html":当用户需要一个交互式学习/讲解页面,例如可拖动的演示、带控件的动画、分步走读、可点击的练习题、概念可视化页面等。
- - "manim_video":当用户明确希望生成数学动画/视频,需要时间维度上的演化(例如逐步展开公式推导、动态展示几何变换、可视化运动/极限过程)时使用。这条路径会用 Manim 渲染成 MP4。
- - "manim_image":当用户希望生成由 Manim 渲染的高质量数学分镜图(多张定格图像),而非动态视频时使用。
-
- 选择优先级原则:
- 1. 如果一个静态图(svg/chartjs/mermaid)足够表达用户需求,优先选择静态图——它们最快且最便宜。
+ - "svg":自定义插图、示意图或需要坐标级控制的自由图形。
+ - "chartjs":适合标准图表类型(柱状图、折线图、饼图、环形图、雷达图、散点图、
+ 气泡图、极坐标图)的定量数据。
+ - "mermaid":结构化图形(流程图、序列图、类图、状态图、ERD、甘特图、思维导图)。
+ 对这些结构化类型,优先用 mermaid 而非 svg。
+ - "html":交互式学习页面——可拖动演示、带控件的动画、分步走读、可点击练习。
+ - "manim_video":用户明确希望生成展示时间演化的数学动画 / 视频。用 Manim 渲染成 MP4。
+ - "manim_image":用户明确希望生成 Manim 渲染的分镜静态图。
+
+ 选择优先级:
+ 1. 如果静态图(svg/chartjs/mermaid)足够,优先选它——最快最便宜。
2. 只有当"用户操作 + 状态变化 + 图文混排"是核心体验时才选 html。
- 3. 只有当用户明确表达"动画/视频/演变过程"等时间维度需求,才选 manim_video。
- 4. 只有当用户明确希望用 Manim 风格生成多张静态分镜,才选 manim_image。
- 5. 不要因为话题是数学就默认选 manim——除非用户确实需要动态演示。
+ 3. 只有当用户明确表达动画 / 视频 / 时间演化 / Manim 风格分镜时才选 manim_*。
+ 不要因为话题是数学就默认选 manim。
+
+ 然后选择 `visual_genre`——按"动词"(用户想做什么)路由,而非"名词"(话题)。
+ 它决定图怎么画:
+
+ | 用户意图 | render_type | visual_genre |
+ |---|---|---|
+ | "X 怎么运作" / "给我直觉" / "我不理解 X" | svg 或 html | illustrative / interactive |
+ | "架构" / "有哪些部分" / "里面有什么" | svg 或 mermaid | structural |
+ | "流程" / "步骤" / "……时会发生什么" | mermaid 或 svg | flowchart |
+ | 循环 / 带逐阶段细节的分步走读 | html | stepper |
+ | 对比数量 / 展示数据 | chartjs | chart |
+ | 关系 / 模式 / ERD | mermaid | structural |
+ | UI 界面 / 表单 / 仪表盘原型 | html | mockup |
+ | 装饰性插图 / 图案 | svg | art |
+
+ 注意这个不对称:「X 怎么运作」默认走 illustrative/interactive 路线(用空间隐喻
+ 传达机制),而不是保险的流程图。流程图只留给真正的步骤序列。没有合适的就把
+ visual_genre 留空 ""。
返回一个 JSON 对象,不要包含 JSON 以外的任何文本。
@@ -28,17 +47,22 @@ user_template: |
返回 JSON:
{{
"render_type": "svg" 或 "chartjs" 或 "mermaid" 或 "html" 或 "manim_video" 或 "manim_image",
+ "visual_genre": "flowchart" 或 "structural" 或 "illustrative" 或 "chart" 或 "stepper" 或 "interactive" 或 "mockup" 或 "art" 或 "",
"description": "可视化应展示的内容的高层描述",
"data_description": "要可视化的数据或元素的描述",
- "chart_type": "如果是 chartjs 则填写 Chart.js 图表类型;如果是 mermaid 则填写 Mermaid 图表类型;如果是 html 则填写交互形式(如 interactive / animation / walkthrough / quiz);如果是 manim_* 则填写动画风格简标(如 derivation / geometry / transformation);否则为空字符串",
+ "chart_type": "如果是 chartjs 填 Chart.js 图表类型;如果是 mermaid 填 Mermaid 图表类型;如果是 html 填交互形式(interactive / animation / walkthrough / quiz);如果是 manim_* 填动画风格简标(derivation / geometry / transformation);否则为空字符串",
"visual_elements": ["需要包含的关键视觉元素或交互模块"],
- "rationale": "为什么选择这种 render_type"
+ "rationale": "为什么选择这个 render_type 和 visual_genre(引用用户的动词)"
}}
system_fixed: |
- 你是一个可视化分析师。用户已经选择了渲染类型。
- 分析用户请求和对话历史,生成结构化的代码生成简报。
- 不要更改 render_type。
+ 你是一个可视化分析师。用户已经选择了渲染类型。分析用户请求和对话历史,生成
+ 结构化的代码生成简报。不要更改 render_type。
+
+ 仍然要选一个贴合请求的 `visual_genre`——按用户的"动词"(想做什么)而非话题路由。
+ 它告诉代码生成器这个渲染类型该怎么画:svg 或 mermaid 用 flowchart / structural /
+ illustrative;chartjs 用 chart;html 用 stepper / interactive / mockup。没有合适的
+ 就留空 ""。
返回一个 JSON 对象,不要包含 JSON 以外的任何文本。
@@ -54,20 +78,29 @@ user_template_fixed: |
返回 JSON:
{{
"render_type": "{render_type}",
+ "visual_genre": "最贴合这个 {render_type} 和用户意图的 genre,或空字符串",
"description": "可视化应展示的内容的高层描述",
"data_description": "要可视化的数据或元素的描述",
- "chart_type": "如果是 chartjs 则填写 Chart.js 图表类型;如果是 mermaid 则填写 Mermaid 图表类型;如果是 html 则填写交互形式(如 interactive / animation / walkthrough / quiz);否则为空字符串",
+ "chart_type": "如果是 chartjs 填 Chart.js 图表类型;如果是 mermaid 填 Mermaid 图表类型;如果是 html 填交互形式(interactive / animation / walkthrough / quiz);否则为空字符串",
"visual_elements": ["需要包含的关键视觉元素或交互模块"],
"rationale": "分析说明"
}}
system_figure: |
- 你是一个可视化分析师。用户需要一张静态图(不需要交互)。请仅在以下三种渲染类型中选择:
- - "svg":当可视化是自定义插图、示意图或任何需要精确坐标控制的自由图形,且不适合标准图表或结构化图形时使用。
- - "chartjs":当可视化涉及可以用标准图表类型(柱状图、折线图、饼图、环形图、雷达图、散点图、气泡图、极坐标图)表示的定量数据时使用。
- - "mermaid":当可视化是结构化图形时使用,如流程图、序列图、类图、状态图、实体关系图、甘特图、思维导图或任何可以用 Mermaid.js 语法表达的图形。对于这些结构化图形类型,优先使用 mermaid 而非 svg。
+ 你是一个可视化分析师。用户需要一张静态图(不需要交互)。请仅在以下三种渲染类型
+ 中选择:
+ - "svg":自定义插图、示意图或需要精确坐标级控制、不适合标准图表或结构化图形的
+ 自由图形。
+ - "chartjs":适合标准图表类型(柱状图、折线图、饼图、环形图、雷达图、散点图、
+ 气泡图、极坐标图)的定量数据。
+ - "mermaid":结构化图形(流程图、序列图、类图、状态图、ERD、甘特图、思维导图)。
+ 对这些结构化类型优先用 mermaid 而非 svg。
+
+ 禁止选择 "html":交互式页面由另一种独立类型处理。请从 svg / chartjs / mermaid
+ 三者中选其一。
- 禁止选择 "html":交互式 HTML 页面由另一种独立的 block 类型处理。请从 svg / chartjs / mermaid 三者中选择其一。
+ 同时选一个 `visual_genre`(flowchart / structural / illustrative / chart,或 ""),
+ 按用户意图路由,告诉代码生成器怎么画。
返回一个 JSON 对象,不要包含 JSON 以外的任何文本。
@@ -81,9 +114,10 @@ user_template_figure: |
返回 JSON(render_type 必须是 "svg" / "chartjs" / "mermaid" 之一):
{{
"render_type": "svg" 或 "chartjs" 或 "mermaid",
+ "visual_genre": "flowchart" 或 "structural" 或 "illustrative" 或 "chart" 或 "",
"description": "图示应展示的内容的高层描述",
"data_description": "要可视化的数据或元素的描述",
- "chart_type": "如果是 chartjs 则填写 Chart.js 图表类型;如果是 mermaid 则填写 Mermaid 图表类型;否则为空字符串",
+ "chart_type": "如果是 chartjs 填 Chart.js 图表类型;如果是 mermaid 填 Mermaid 图表类型;否则为空字符串",
"visual_elements": ["需要包含的关键视觉元素"],
- "rationale": "为什么选择这种 render_type"
+ "rationale": "为什么选择这个 render_type 和 visual_genre"
}}
diff --git a/deeptutor/agents/visualize/prompts/zh/answer_now.yaml b/deeptutor/agents/visualize/prompts/zh/answer_now.yaml
deleted file mode 100644
index 05c9f8c6e..000000000
--- a/deeptutor/agents/visualize/prompts/zh/answer_now.yaml
+++ /dev/null
@@ -1,17 +0,0 @@
-system: |
- 你是 DeepTutor 的可视化代码生成器。用户已经在等待,
- 请直接输出最终可渲染的代码。
- 严格输出 JSON:{"render_type": "svg|chartjs|mermaid",
- "code": "..."}。
- code 字段是可直接渲染的源代码(SVG 标签 / Chart.js JS 代码 / Mermaid 文本)。
-
-user_template: |
- 用户请求:{original}
-
- render_mode:{render_mode}
-
- {current_draft}
-
- {execution_trace}
-
- 立即输出符合 schema 的 JSON。
diff --git a/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yaml b/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yaml
index aba8ae9ac..8443486e3 100644
--- a/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yaml
+++ b/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yaml
@@ -1,34 +1,134 @@
-system: |
- 你是一个可视化代码生成器。根据分析结果、用户请求和对话历史生成可视化代码。
-
- 规则:
- - 如果 render_type 是 "svg",输出完整的、自包含的 SVG 字符串。
- SVG 必须包含 xmlns 属性并且是格式良好的 XML。
- 使用 viewBox 实现响应式尺寸。优先使用简洁现代的美学风格,
- 确保字体可读、颜色清晰、间距合适。
- - 如果 render_type 是 "chartjs",输出一个有效的 JavaScript 对象字面量,
- 可以作为配置传递给 `new Chart(ctx, config)`。
- 配置必须包含 `type`、`data` 和 `options` 字段。
- 使用现代配色方案并确保标签可读。
- - 如果 render_type 是 "mermaid",输出有效的 Mermaid.js 图表代码。
- 代码必须以有效的图表类型关键词开头(graph、flowchart、sequenceDiagram、
- classDiagram、stateDiagram-v2、erDiagram、gantt、mindmap 等)。
- 使用清晰的节点标签和可读的边描述。节点 ID 不要使用空格——使用
- camelCase 或下划线。避免使用保留关键词作为节点 ID。
- - 如果 render_type 是 "html",输出一个完整的、自包含的单文件 HTML 学习页面。
- 技术约束:
- * 必须从 <!DOCTYPE html> 写到 </html>
- * 所有 CSS 写在 <style> 中,所有 JavaScript 写在 </body> 前的 <script> 中
- * 不依赖外部 CDN、字体或其他资源(KaTeX 会由宿主页面自动注入;行内公式用
- $...$,块级公式用 $$...$$)
- * 页面会渲染在 iframe 中,必须响应式适配:使用 max-width: 100%、
- box-sizing: border-box,避免固定宽度
- * 长内容必要时用 overflow-x: auto,避免被截断
- * 所有交互必须包在 DOMContentLoaded 中,使用 addEventListener,禁止 onclick
- * 操作 DOM 前检查元素是否存在
- 在以上约束内自由决定布局、配色、视觉风格和交互形式,让页面清晰、美观、易学。
- - 不要在代码块之外包含任何解释。
- - 用带有适当语言标签的代码块包裹代码(```svg、```javascript、```mermaid 或 ```html)。
+system_base: |
+ 你是 DeepTutor 的可视化代码生成器。根据分析简报、用户请求和对话历史,
+ 为一个可视化输出可渲染的代码。
+
+ 输出契约:
+ - 只输出代码,用一个带正确语言标签的代码块包裹(```svg、```javascript、
+ ```mermaid 或 ```html)。不要解释、不要前言、不要第二个代码块。
+ - 代码必须完整且自包含——它会被直接渲染,前后不会再拼接任何内容。
+
+rules_general: |
+ 以下规则适用于所有渲染类型。
+
+ 复杂度预算(硬性上限——稀疏而正确的图胜过密集的图):
+ - 图中副标题最多 5 个词。细节放在对话正文里,不要塞进图里。
+ - 最多用 2-3 种颜色。颜色用来编码含义(类别 / 状态),绝不用于装饰。
+ 同类元素共用一种颜色;通用 / 结构 / 起止节点用中性灰。
+ - 一行最多放 4 个全宽方框。5 个以上 → 缩小、换到第二行,或拆成总览图 + 细节图。
+ - 如果请求列出 6 个以上组件,不要硬塞进一张图。先画只含主流程的精简总览,
+ 并在对话正文里说明用户可以针对任意子流程要求展开细节。
+
+ 文本:
+ - 全部用句首大写(标签、标题、说明)。不要每词首字母大写,不要全大写。
+ - 每个标签都要可读:对比度足够,字号不小于 11px。
+
+rules_svg: |
+ 渲染类型:SVG。图会内联到页面中(不再是 <img>),因此继承 app 的主题和字体,
+ 也可以交互。用下面的预置 class 来配色和排版,而不是写死 fill——这才能让图自动
+ 跟随明暗模式。
+
+ - 根元素:`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 W H">`。必须设
+ xmlns 和驼峰 viewBox(写 `viewBox`,不能写 `viewbox`);用 viewBox 控制尺寸,
+ 不要写死 width/height。
+ - 只输出一个 `<svg>`。如果图有多个部分,把它们作为同一个 svg 内部的区域来排版
+ (上下堆叠、左右分栏、带标签的分区)——绝不输出多个 `<svg>`;分开的 svg 会渲染成
+ 彼此割裂的碎片。内部引用用 `href` 而非 `xlink:href`(若必须用 xlink,在根上声明
+ `xmlns:xlink`)。
+ - 格式良好的 XML:每个标签闭合、每个属性带引号、`&` 写成 `&amp;`。输出按严格
+ XML 解析——一个未转义字符就会让整张图渲染失败。
+ - 不要画背景 `<rect>`,不要在 text 上写死 fill / 字体。背景由宿主提供;下面的
+ class 提供随明暗自适应的颜色。背景保持透明。
+
+ 预置 class(由宿主统一定义——用它们,绝不内联颜色):
+ - 文本:`class="t"`(14px)、`class="th"`(14px 中粗,用于标题)、`class="ts"`
+ (12px,用于副标题 / 说明)。只用两种字号。每个 `<text>` 都带一个。
+ - 中性:`class="box"`(容器框)、`class="arr"`(箭头线——加
+ `marker-end="url(#arrow)"`)、`class="leader"`(虚线引导线)。
+ - 颜色色板,加在 `<g>` 或形状上,从中选一个:`c-gray c-blue c-teal c-coral
+ c-pink c-purple c-green c-amber c-red`。它同时设置形状的 fill+stroke 和内部
+ `<text>` 的颜色,明暗模式都适配。最多用 2-3 个色板;灰色用于中性 / 结构 / 起止。
+ 通用类别优先用 purple/teal/coral;blue/green/amber/red 留给
+ 信息/成功/警告/错误语义。
+ - 用法:把 `c-*` 色板加在包住形状和 `<text>` 的 `<g>` 上,文字会自动取到对应的
+ 可读颜色。
+
+ 箭头 marker——包含一次,用 `marker-end="url(#arrow)"` 引用:
+ `<defs><marker id="arrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M2 1L8 5L2 9" fill="none" stroke="context-stroke" stroke-width="1.5"/></marker></defs>`
+
+ 交互(可选):想让某个节点点击后深入讲解,在它的 `<g>` 上加
+ `data-prompt="<一个简短的追问>"`——点击会把这个问题发送到对话。用于学习者自然
+ 会想展开的节点。
+
+ 坐标计算——SVG 大多数失败源于算术,所以先算后画:
+ - 框宽由最长标签决定:`width = max(标题字数*8, 副标题字数*7) + 24`。
+ 100px 的框约容纳 10 个副标题字符。特殊字符(公式、∑、₆、下标)更宽,加 30-50%。
+ - 行内排布:放一行 N 个框前,先核算总宽是否落在安全区(x=40..640)。例如四个
+ 130px 框 + 三个 20px 间隙 = 580 ≤ 600。放不下就缩小或换行——绝不让框重叠。
+ - 箭头走线:画 A→B 的线之前,确认它不穿过任何其他框的内部或任何标签。会穿过
+ 就用 L 形折线绕开。
+ - SVG 的 `<text>` 不会自动换行。需要两行就用显式 `<tspan x=... dy="1.2em">`。
+ 如果长到需要换行,说明它太长了——精简它。
+
+ viewBox 终检清单——定稿前逐条核对:
+ 1. viewBox 高度 = (最底部元素的 y + 高度)+ 40px 余量。
+ 2. 所有内容落在 x=0..W、y=0..H 内;绝不使用负坐标。
+ 3. 无关的框、标签、箭头之间没有意外重叠。
+ 4. `text-anchor="end"` 会从 x 向左延伸——x 较小时可能越过 x=0;优先用
+ `text-anchor="start"` 并把整列右对齐。
+
+ 按 `visual_genre` 指示的教学意图匹配画法:
+ - flowchart:顺序步骤 / 决策分支。框 + 箭头,单一方向(全部自上而下或全部从左
+ 到右),≤5 个节点。循环用一条返回箭头加 "↻ 回到起点" 的注记表示——不要把框
+ 排成环(环形布局会碰撞;若循环有逐阶段细节,分析阶段本应选 html stepper)。
+ - structural:包含关系。大的圆角容器框(浅填充),内部更小的区域框(更深一档或
+ 相关色),嵌套 ≤2-3 层,每个容器内留 20px 内边距。
+ - illustrative:用空间隐喻建立直觉——画机制本身,而不是关于机制的图。颜色编码
+ 强度(暖 = 活跃 / 热,冷 = 平静 / 冷,灰 = 惰性)。形状可重叠以表现层次;文字
+ 绝不与笔画交叠——把标签放在安静的边缘,用细引导线指向。
+
+rules_chartjs: |
+ 渲染类型:Chart.js。输出严格 JSON 对象(不是 JavaScript 对象字面量),作为配置
+ 传给 `new Chart(ctx, config)`:
+ - 键和字符串值都用双引号。不要函数回调、不要注释、不要尾逗号、不要 `undefined`。
+ 必须能被 `JSON.parse` 解析。
+ - 必须包含 `"type"` 和 `"data"`;坐标轴 / 图例配置放在 `"options"`。按数据选择
+ 合适的图表类型(bar / line / pie / doughnut / radar / scatter / bubble /
+ polarArea)。
+ - 用可读的现代配色。绝不只靠颜色区分系列——分类数据要把数值 / 标签放进数据里,
+ 让图例有意义。
+ - 数据里预先算好的数字要四舍五入,不要带出浮点误差。
+
+rules_mermaid: |
+ 渲染类型:Mermaid.js。输出有效的 Mermaid DSL:
+ - 第一行非空内容是有效的图表类型关键词:graph / flowchart / sequenceDiagram /
+ classDiagram / stateDiagram-v2 / erDiagram / gantt / mindmap / pie /
+ journey / timeline。
+ - 节点 ID 不含空格——用 camelCase 或下划线。显示文字放在方括号里:
+ `nodeId[显示标签]`。绝不用保留字(end、graph、subgraph、class)作为裸节点 ID。
+ - 数据库模式 / ERD 用 `erDiagram`;类结构用 `classDiagram`。这些布局问题
+ Mermaid 会自动解决——不要在 SVG 里手画。
+ - 标签简短可读;核对图表类型关键词与你描述的结构一致。
+
+rules_html: |
+ 渲染类型:HTML。输出一个完整、自包含的单文件 HTML 页面,用于交互式讲解、分步
+ 走读、UI 原型或可点击演示。
+ - 从 `<!DOCTYPE html>` 写到 `</html>`。所有 CSS 放在 `<style>`;所有 JavaScript
+ 放在 `</body>` 前的 `<script>` 里。
+ - 页面在沙箱 iframe(null origin)中渲染。只能从这些 CDN 加载库——
+ cdn.jsdelivr.net、cdnjs.cloudflare.com、unpkg.com,其它一律被拦截。KaTeX 由
+ 宿主自动注入(`$...$` / `$$...$$`)。推荐:Chart.js 做图表,d3 + topojson 做
+ 数据可视化 / 地图。
+ - 地理地图:拉取真实拓扑数据,绝不手编坐标。美国各州:
+ `cdn.jsdelivr.net/npm/us-atlas@3/states-10m.json`(d3.geoAlbersUsa)。
+ 世界:`cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json`
+ (d3.geoNaturalEarth1)。用文件里真实的 feature 名 / id 来对应数据。
+ - 宿主会按内容高度自动调整 iframe 高度——不要设固定的 body 高度;用
+ `max-width: 100%` 和 `box-sizing: border-box`。
+ - 追问:调用 `sendPrompt("一个简短的问题")`(例如从按钮的 onclick)把这个问题
+ 投到对话输入框。用在学习者自然会想深入的地方。
+ - 对循环或分阶段流程,构建 stepper:每个阶段一个面板,用圆点 / 药丸显示位置,
+ Next 按钮从最后一个阶段绕回第一个。每个面板自带内容,互不碰撞。
+ - 在以上约束内自由决定布局、配色和交互,让页面清晰、美观、易学。
user_template: |
用户请求:
@@ -39,11 +139,11 @@ user_template: |
渲染类型:{render_type}
- 分析:
+ 分析简报(注意 `visual_genre`——它告诉你要生成哪种风格的 {render_type}):
{analysis_json}
- 现在生成可视化代码。用代码块包裹:
- - SVG 使用:```svg ... ```
- - Chart.js 使用:```javascript ... ```
- - Mermaid 使用:```mermaid ... ```
- - HTML 使用:```html ... ```
+ 现在生成可视化代码,作为一个代码块:
+ - SVG 用:```svg ... ```
+ - Chart.js 用:```javascript ... ```
+ - Mermaid 用:```mermaid ... ```
+ - HTML 用:```html ... ```
diff --git a/deeptutor/agents/visualize/prompts/zh/review_agent.yaml b/deeptutor/agents/visualize/prompts/zh/review_agent.yaml
index 6d3316873..5aecf4165 100644
--- a/deeptutor/agents/visualize/prompts/zh/review_agent.yaml
+++ b/deeptutor/agents/visualize/prompts/zh/review_agent.yaml
@@ -46,3 +46,39 @@ user_template: |
"changed": true 或 false,
"review_notes": "检查或修改的内容"
}}
+
+repair_system: |
+ 你是一个可视化代码修复器。生成的代码未通过确定性的本地校验,并附上了确切的错误。
+ 用最小的改动修复"那个具体缺陷",使代码有效且可渲染——不要重新设计、重新配色,
+ 也不要重新评判其余部分。
+
+ - svg:返回一个格式良好的 `<svg>`,含 xmlns 和驼峰 `viewBox`。如果有多个 `<svg>`,
+ 合并成一个(各部分作为内部区域)。用预置 class(t/ts/th、box、arr、c-*)来配色和
+ 排版文本,不要写死 fill。
+ - chartjs:返回严格 JSON(键用双引号;无函数、注释或尾逗号),包含 "type" 和 "data"。
+ - mermaid:以有效的图表类型关键词开头;节点 ID 不含空格。
+ - 保留原有意图和内容。只改必要的部分。
+
+ 返回一个 JSON 对象,不要包含 JSON 以外的任何文本。
+
+repair_user_template: |
+ 用户请求:
+ {user_input}
+
+ 渲染类型:{render_type}
+
+ 必须修复的校验错误:
+ {error}
+
+ 分析简报:
+ {analysis_json}
+
+ 未通过校验的代码:
+ {code}
+
+ 返回 JSON:
+ {{
+ "optimized_code": "修正后、可渲染的代码",
+ "changed": true 或 false,
+ "review_notes": "修复了什么"
+ }}
diff --git a/deeptutor/agents/visualize/utils.py b/deeptutor/agents/visualize/utils.py
index 3884063fe..d970be97f 100644
--- a/deeptutor/agents/visualize/utils.py
+++ b/deeptutor/agents/visualize/utils.py
@@ -5,6 +5,29 @@ from __future__ import annotations
import json
import re
from typing import Any
+import xml.etree.ElementTree as ET
+
+_MERMAID_KEYWORDS = (
+ "graph",
+ "flowchart",
+ "sequenceDiagram",
+ "classDiagram",
+ "stateDiagram-v2",
+ "stateDiagram",
+ "erDiagram",
+ "gantt",
+ "mindmap",
+ "pie",
+ "journey",
+ "gitGraph",
+ "timeline",
+ "quadrantChart",
+ "requirementDiagram",
+ "sankey-beta",
+ "xychart-beta",
+ "block-beta",
+ "C4Context",
+)
def extract_json_object(text: str) -> dict[str, Any]:
@@ -130,9 +153,90 @@ def build_fallback_html(*, title: str, summary: str = "", note: str = "") -> str
</html>"""
+def _strip_outer_fence(text: str) -> str:
+ """Drop a single wrapping triple-backtick fence, if present."""
+ stripped = (text or "").strip()
+ match = re.match(r"^```[A-Za-z]*\s*\n?([\s\S]*?)\n?```$", stripped)
+ return match.group(1).strip() if match else stripped
+
+
+def validate_visualization(code: str, render_type: str) -> tuple[bool, str]:
+ """Cheap, deterministic, local render-ability check.
+
+ Returns ``(ok, error)``. When ``ok`` is False, ``error`` is a short,
+ LLM-actionable message used to drive a single repair pass — none of these
+ failures need an LLM call to *discover*. This replaces the generic LLM
+ review for the text render types: only when local validation fails do we
+ spend a model call (a targeted repair, not an open-ended review).
+ """
+ text = (code or "").strip()
+ if not text:
+ return False, "Generated code is empty."
+
+ if render_type == "svg":
+ if "<svg" not in text.lower():
+ return False, "SVG must contain a root <svg> element."
+ try:
+ root = ET.fromstring(text)
+ except ET.ParseError as exc:
+ return False, f"SVG is not well-formed XML: {exc}"
+ tag = root.tag.split("}")[-1].lower()
+ if tag != "svg":
+ return False, f"Root element must be <svg>, found <{tag}>."
+ # Case-sensitive: SVG only honors the camelCase ``viewBox``; a
+ # lowercase ``viewbox`` is ignored by the browser and collapses the
+ # figure, so it must NOT pass validation.
+ if "viewBox" not in root.attrib:
+ return False, (
+ "SVG root is missing a viewBox attribute (must be camelCase "
+ "`viewBox`, required for responsive scaling)."
+ )
+ return True, ""
+
+ if render_type == "chartjs":
+ candidate = _strip_outer_fence(text)
+ try:
+ config = json.loads(candidate)
+ except (json.JSONDecodeError, TypeError):
+ return False, (
+ "Chart.js config must be strict JSON: double-quoted keys, no "
+ "function callbacks, no comments, no trailing commas."
+ )
+ if not isinstance(config, dict):
+ return False, "Chart.js config must be a JSON object."
+ missing = [field for field in ("type", "data") if field not in config]
+ if missing:
+ return False, f"Chart.js config is missing required field(s): {', '.join(missing)}."
+ return True, ""
+
+ if render_type == "mermaid":
+ first_line = next((ln.strip() for ln in text.splitlines() if ln.strip()), "")
+ # `---` front-matter and `%%{init}` directives are valid lead-ins.
+ if (
+ first_line.startswith(_MERMAID_KEYWORDS)
+ or first_line.startswith("%%")
+ or first_line.startswith("---")
+ ):
+ return True, ""
+ return False, (
+ "Mermaid code must start with a valid diagram keyword (graph, "
+ "flowchart, sequenceDiagram, classDiagram, stateDiagram-v2, "
+ "erDiagram, gantt, mindmap, ...)."
+ )
+
+ if render_type == "html":
+ if is_valid_html_document(text):
+ return True, ""
+ return False, "Output does not look like a renderable HTML document."
+
+ # Unknown render types are not gated.
+ return True, ""
+
+
__all__ = [
"build_fallback_html",
"extract_code_block",
"extract_json_object",
"is_valid_html_document",
+ "validate_visualization",
]
diff --git a/deeptutor/capabilities/prompts/en/visualize.yaml b/deeptutor/capabilities/prompts/en/visualize.yaml
index 1f92c0d35..577676bd7 100644
--- a/deeptutor/capabilities/prompts/en/visualize.yaml
+++ b/deeptutor/capabilities/prompts/en/visualize.yaml
@@ -1,19 +1,19 @@
+# Visualize capability status messages (English)
+# Loaded by StatusI18n from the `status:` section.
status:
analyzing: "Analyzing visualization requirements..."
+ render_type_detected: "Render type: {render_type} — {description}"
generating: "Generating visualization code..."
code_generated: "Code generated."
- reviewing: "Reviewing and optimizing code..."
- html_ready_review_skipped: "HTML page ready (review skipped)."
+ validation_passed: "Looks good — passed local checks."
+ repairing: "Fixing a validation issue..."
+ code_repaired: "Fixed: {notes}"
+ repair_incomplete: "Repair attempted; residual issue: {error}"
+ repair_skipped_error: "Repair skipped — using draft as-is."
html_invalid_fallback: "HTML did not validate; using fallback template."
- code_optimized: "Code optimized: {notes}"
- code_no_changes: "Code looks good — no changes needed."
- review_skipped_error: "Review skipped — using draft as-is."
manim_code_prepared: "Manim code prepared."
manim_rendering: "Rendering {mode} with quality={quality}."
+ manim_retry: "Retry {attempt}: {error}"
manim_artifacts_one: "Prepared {count} artifact."
manim_artifacts_many: "Prepared {count} artifacts."
- manim_retry: "Retry {attempt}: {error}"
llm_call_failed: "LLM call failed."
- answer_now_skipped_analysis: "Answer-now: skipped analysis stage."
- answer_now_skipped_review: "Answer-now: skipped review stage."
- render_type_detected: "Render type: {render_type} — {description}"
diff --git a/deeptutor/capabilities/prompts/zh/visualize.yaml b/deeptutor/capabilities/prompts/zh/visualize.yaml
index 1a4e4d172..8a418d1b7 100644
--- a/deeptutor/capabilities/prompts/zh/visualize.yaml
+++ b/deeptutor/capabilities/prompts/zh/visualize.yaml
@@ -1,19 +1,19 @@
+# Visualize capability status messages (Chinese)
+# Loaded by StatusI18n from the `status:` section.
status:
analyzing: "正在分析可视化需求..."
+ render_type_detected: "渲染类型:{render_type} — {description}"
generating: "正在生成可视化代码..."
code_generated: "代码已生成。"
- reviewing: "正在审查并优化代码..."
- html_ready_review_skipped: "HTML 页面已就绪(已跳过审查)。"
- html_invalid_fallback: "HTML 校验未通过;已使用备用模板。"
- code_optimized: "代码已优化:{notes}"
- code_no_changes: "代码无需修改。"
- review_skipped_error: "审查阶段出错;已使用未审查的草稿。"
- manim_code_prepared: "Manim 代码已准备完成。"
- manim_rendering: "正在以 quality={quality} 渲染 {mode}。"
+ validation_passed: "通过本地校验,看起来没问题。"
+ repairing: "正在修复一处校验问题..."
+ code_repaired: "已修复:{notes}"
+ repair_incomplete: "已尝试修复;仍有遗留问题:{error}"
+ repair_skipped_error: "跳过修复——直接使用草稿。"
+ html_invalid_fallback: "HTML 未通过校验;使用兜底模板。"
+ manim_code_prepared: "Manim 代码已准备好。"
+ manim_rendering: "正在渲染 {mode},质量={quality}。"
+ manim_retry: "重试 {attempt}:{error}"
manim_artifacts_one: "已准备 {count} 个产物。"
manim_artifacts_many: "已准备 {count} 个产物。"
- manim_retry: "第 {attempt} 次重试:{error}"
llm_call_failed: "LLM 调用失败。"
- answer_now_skipped_analysis: "极速回答:已跳过分析阶段。"
- answer_now_skipped_review: "极速回答:已跳过审查阶段。"
- render_type_detected: "渲染类型:{render_type} — {description}"
diff --git a/deeptutor/capabilities/visualize.py b/deeptutor/capabilities/visualize.py
index 891208e00..d6b80c69c 100644
--- a/deeptutor/capabilities/visualize.py
+++ b/deeptutor/capabilities/visualize.py
@@ -65,9 +65,8 @@ class VisualizeCapability(BaseCapability):
from deeptutor.agents.visualize.pipeline import VisualizePipeline
from deeptutor.agents.visualize.utils import (
build_fallback_html,
- is_valid_html_document,
+ validate_visualization,
)
- from deeptutor.capabilities._answer_now import extract_answer_now_context
from deeptutor.services.llm.config import get_llm_config
request_config = validate_visualize_request_config(context.config_overrides)
@@ -77,20 +76,6 @@ class VisualizeCapability(BaseCapability):
llm_config_for_usage = get_llm_config()
usage = UsageTracker(model=getattr(llm_config_for_usage, "model", None))
- answer_now_payload = extract_answer_now_context(context)
- if answer_now_payload is not None:
- # Manim takes ~30-90s even on the fast path; answer-now's point is
- # to skip slow analysis when the user is impatient, so we redirect
- # explicit manim answer-now requests to the full path. The text
- # paths keep their dedicated fast-path implementation.
- if render_mode in _MANIM_RENDER_TYPES:
- pass # fall through to the full manim path below
- else:
- await self._run_answer_now(
- context, stream, answer_now_payload, usage=usage, i18n=i18n
- )
- return
-
llm_config = get_llm_config()
history_context = str(context.metadata.get("conversation_context_text", "") or "").strip()
@@ -158,86 +143,95 @@ class VisualizeCapability(BaseCapability):
stage="generating",
)
- # Stage 3: Review & optimise
+ # Stage 3: Validate locally; repair only on failure.
+ #
+ # The old generic LLM review is replaced by a deterministic, zero-cost
+ # local check (well-formed XML / strict-JSON / mermaid lint / HTML
+ # sanity). When it passes we ship the draft as-is — saving a whole
+ # serial LLM call. When it fails we spend one *targeted* repair call
+ # driven by the concrete error, not an open-ended re-judgement.
async with stream.stage("reviewing", source=self.name):
- if analysis.render_type == "html":
- # Skip the LLM review pass for html — it would cost another
- # 30-60s on a 10k-token document with negligible quality gain.
- # Instead, do a local sanity check and fall back to a minimal
- # template if the model returned something unrenderable.
- if is_valid_html_document(code):
- final_code = code
- review = ReviewResult(
- optimized_code=final_code,
- changed=False,
- review_notes="Skipped LLM review for html render_type.",
- )
- await stream.progress(
- message=i18n.t(
- "html_ready_review_skipped",
- "HTML page ready (review skipped).",
- ),
- source=self.name,
- stage="reviewing",
- )
- else:
- final_code = build_fallback_html(
- title=analysis.description or "Visualization",
- summary=analysis.data_description,
- note="The model did not return a renderable HTML document.",
- )
- review = ReviewResult(
- optimized_code=final_code,
- changed=True,
- review_notes="Used fallback HTML template.",
- )
- await stream.progress(
- message=i18n.t(
- "html_invalid_fallback",
- "HTML did not validate; using fallback template.",
- ),
- source=self.name,
- stage="reviewing",
- )
+ ok, validation_error = validate_visualization(code, analysis.render_type)
+ if ok:
+ final_code = code
+ review = ReviewResult(
+ optimized_code=final_code,
+ changed=False,
+ review_notes="Passed local validation.",
+ )
+ await stream.progress(
+ message=i18n.t(
+ "validation_passed",
+ "Looks good — passed local checks.",
+ ),
+ source=self.name,
+ stage="reviewing",
+ )
+ elif analysis.render_type == "html":
+ # html documents are 8-16k tokens; we don't run them through
+ # the repair loop — fall back to a minimal renderable template.
+ final_code = build_fallback_html(
+ title=analysis.description or "Visualization",
+ summary=analysis.data_description,
+ note="The model did not return a renderable HTML document.",
+ )
+ review = ReviewResult(
+ optimized_code=final_code,
+ changed=True,
+ review_notes=f"Used fallback HTML template ({validation_error}).",
+ )
+ await stream.progress(
+ message=i18n.t(
+ "html_invalid_fallback",
+ "HTML did not validate; using fallback template.",
+ ),
+ source=self.name,
+ stage="reviewing",
+ )
else:
await stream.thinking(
- i18n.t("reviewing", "Reviewing and optimizing code..."),
+ i18n.t("repairing", "Fixing a validation issue..."),
source=self.name,
stage="reviewing",
)
try:
- review = await pipeline.run_review(
+ review = await pipeline.run_repair(
user_input=context.user_message,
analysis=analysis,
code=code,
+ error=validation_error,
)
except Exception as exc:
- # Review wraps generated code inside a JSON string field;
- # large/complex SVGs trip JSON-mode escaping and crash the
- # whole turn. Fall back to the unreviewed draft so the user
- # still gets a rendered result.
- logger.warning("Visualize review failed (%s); using unreviewed draft.", exc)
+ # Repair wraps code inside a JSON string field; large/complex
+ # SVGs can trip JSON-mode escaping. Fall back to the draft so
+ # the user still gets a rendered result.
+ logger.warning(
+ "Visualize repair failed (%s); using unvalidated draft.", exc
+ )
review = ReviewResult(
optimized_code=code,
changed=False,
- review_notes=f"Review skipped due to error: {exc}",
+ review_notes=f"Repair skipped due to error: {exc}",
)
final_code = code
await stream.progress(
message=i18n.t(
- "review_skipped_error",
- "Review skipped — using draft as-is.",
+ "repair_skipped_error",
+ "Repair skipped — using draft as-is.",
),
source=self.name,
stage="reviewing",
)
else:
- final_code = review.optimized_code
- if review.changed:
+ final_code = review.optimized_code or code
+ repaired_ok, repaired_error = validate_visualization(
+ final_code, analysis.render_type
+ )
+ if repaired_ok:
await stream.progress(
message=i18n.t(
- "code_optimized",
- f"Code optimized: {review.review_notes}",
+ "code_repaired",
+ f"Fixed: {review.review_notes}",
notes=review.review_notes,
),
source=self.name,
@@ -246,8 +240,9 @@ class VisualizeCapability(BaseCapability):
else:
await stream.progress(
message=i18n.t(
- "code_no_changes",
- "Code looks good — no changes needed.",
+ "repair_incomplete",
+ f"Repair attempted; residual issue: {repaired_error}",
+ error=repaired_error,
),
source=self.name,
stage="reviewing",
@@ -498,149 +493,6 @@ class VisualizeCapability(BaseCapability):
usage=usage,
)
- async def _run_answer_now(
- self,
- context: UnifiedContext,
- stream: StreamBus,
- payload: dict[str, Any],
- *,
- usage: UsageTracker | None = None,
- i18n: StatusI18n | None = None,
- ) -> None:
- """
- Fast-path for ``visualize``: skip analysis + review and emit final
- code in a single structured LLM call. The result envelope mirrors
- the standard pipeline so ``VisualizationViewer`` renders it
- directly.
- """
- import json
- import re
-
- from deeptutor.capabilities._answer_now import (
- build_answer_now_trace_metadata,
- format_trace_summary,
- join_chunks,
- labeled_block,
- load_answer_now_prompts,
- make_skip_notice,
- stream_synthesis,
- )
-
- if i18n is None:
- i18n = StatusI18n(self.name, context.language)
- original = str(payload.get("original_user_message") or context.user_message).strip()
- partial = str(payload.get("partial_response") or "").strip()
- trace_summary = format_trace_summary(payload.get("events"), language=context.language)
-
- render_mode = (
- str(context.config_overrides.get("render_mode", "auto") or "auto").strip().lower()
- )
-
- prompts = load_answer_now_prompts("visualize", context.language)
- system_prompt = str(prompts.get("system", "")).strip()
- user_prompt = str(prompts.get("user_template", "")).format(
- original=original,
- render_mode=render_mode,
- current_draft=labeled_block("Current Draft", partial),
- execution_trace=labeled_block("Execution Trace", trace_summary),
- )
-
- trace_meta = build_answer_now_trace_metadata(
- capability=self.name, phase="generating", label="Answer now"
- )
- notice = make_skip_notice(
- capability=self.name,
- language=context.language,
- stages_skipped=["analyzing", "reviewing"],
- )
-
- # html pages are larger; bump the answer-now budget for that mode.
- is_html_mode = render_mode == "html"
- max_tokens = 16000 if is_html_mode else 2400
-
- chunks: list[str] = []
- async with stream.stage("generating", source=self.name, metadata=trace_meta):
- async for chunk in stream_synthesis(
- stream=stream,
- source=self.name,
- stage="generating",
- trace_meta=trace_meta,
- system_prompt=system_prompt,
- user_prompt=user_prompt,
- max_tokens=max_tokens,
- push_content=False,
- response_format={"type": "json_object"},
- ):
- chunks.append(chunk)
-
- raw = join_chunks(chunks).strip()
- # Strip optional code fences for resilience.
- if raw.startswith("```"):
- raw = re.sub(r"^```[a-zA-Z]*\n?", "", raw)
- if raw.endswith("```"):
- raw = raw[:-3].rstrip()
- try:
- parsed = json.loads(raw)
- except (json.JSONDecodeError, TypeError):
- parsed = {"render_type": "html" if is_html_mode else "svg", "code": raw}
- if not isinstance(parsed, dict):
- parsed = {
- "render_type": "html" if is_html_mode else "svg",
- "code": str(parsed),
- }
-
- default_type = "html" if is_html_mode else "svg"
- render_type = str(parsed.get("render_type") or default_type).strip().lower()
- if render_type not in {"svg", "chartjs", "mermaid", "html"}:
- render_type = default_type
- final_code = str(parsed.get("code") or "").strip()
-
- if render_type == "html":
- lang_tag = "html"
- elif render_type == "svg":
- lang_tag = "svg"
- elif render_type == "mermaid":
- lang_tag = "mermaid"
- else:
- lang_tag = "javascript"
- content_md = f"```{lang_tag}\n{final_code}\n```"
- body = (notice + "\n\n" + content_md).strip() if notice else content_md
- await stream.content(body, source=self.name, stage="generating")
-
- await emit_capability_result(
- stream,
- {
- "response": body,
- "render_type": render_type,
- "code": {
- "language": lang_tag,
- "content": final_code,
- },
- "analysis": {
- "render_type": render_type,
- "description": i18n.t(
- "answer_now_skipped_analysis",
- "Answer-now: skipped analysis stage.",
- ),
- "data_description": "",
- "chart_type": "",
- "visual_elements": [],
- "rationale": "",
- },
- "review": {
- "optimized_code": final_code,
- "changed": False,
- "review_notes": i18n.t(
- "answer_now_skipped_review",
- "Answer-now: skipped review stage.",
- ),
- },
- "metadata": {"answer_now": True},
- },
- source=self.name,
- usage=usage,
- )
-
def _build_trace_bridge(self, stream: StreamBus, i18n: StatusI18n | None = None):
async def _trace_bridge(update: dict[str, Any]) -> None:
event = str(update.get("event", "") or "")
diff --git a/tests/capabilities/test_answer_now.py b/tests/capabilities/test_answer_now.py
index 189af3ae0..0bd8e61b1 100644
--- a/tests/capabilities/test_answer_now.py
+++ b/tests/capabilities/test_answer_now.py
@@ -235,339 +235,6 @@ class TestJoinChunks:
# ---------------------------------------------------------------------------
-class TestChatAnswerNow:
- """``chat`` keeps its existing synthesizer; we only assert the high-
- level behavior so a future refactor of ``_stage_answer_now`` doesn't
- silently change the contract."""
-
- @pytest.mark.asyncio
- async def test_chat_synthesises_final_answer_from_partial_trace(self) -> None:
- from deeptutor.agents.chat import agentic_pipeline as ap_module
-
- async def _fake_stream(self: Any, _messages: Any, **_kwargs: Any):
- for chunk in ("Hello", " ", "world"):
- yield chunk
-
- cfg = _fake_llm_config()
-
- with (
- patch.object(
- ap_module.AgenticChatPipeline,
- "_stream_messages",
- _fake_stream,
- ),
- patch(
- "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
- return_value=cfg,
- ),
- ):
- from deeptutor.capabilities.chat import ChatCapability
-
- ctx = _build_context(
- capability="chat",
- payload={
- "original_user_message": "Explain Fourier",
- "partial_response": "We had begun to think about ...",
- "events": [{"type": "thinking", "stage": "thinking", "content": "warming up"}],
- },
- )
- bus = StreamBus()
- cap = ChatCapability()
- events = await _drain(bus, cap.run(ctx, bus))
-
- text = _content_text(events)
- assert "Hello" in text
- result = _result_event(events)
- assert result.metadata.get("answer_now") is True
- assert "Hello world" in str(result.metadata.get("response", ""))
-
- @pytest.mark.asyncio
- async def test_chat_answer_now_strips_protocol_label(self) -> None:
- from deeptutor.agents.chat import agentic_pipeline as ap_module
-
- async def _fake_stream(self: Any, _messages: Any, **_kwargs: Any):
- for chunk in ("``FI", "NISH``\n", "Hello now"):
- yield chunk
-
- cfg = _fake_llm_config()
-
- with (
- patch.object(
- ap_module.AgenticChatPipeline,
- "_stream_messages",
- _fake_stream,
- ),
- patch(
- "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
- return_value=cfg,
- ),
- ):
- from deeptutor.capabilities.chat import ChatCapability
-
- ctx = _build_context(
- capability="chat",
- payload={
- "original_user_message": "Explain Fourier",
- "partial_response": "Partial trace",
- "events": [],
- },
- )
- bus = StreamBus()
- cap = ChatCapability()
- events = await _drain(bus, cap.run(ctx, bus))
-
- text = _content_text(events)
- assert "FINISH" not in text
- assert text == "Hello now"
- result = _result_event(events)
- assert result.metadata.get("response") == "Hello now"
-
- @pytest.mark.asyncio
- async def test_chat_answer_now_strips_bare_protocol_label(self) -> None:
- from deeptutor.agents.chat import agentic_pipeline as ap_module
-
- async def _fake_stream(self: Any, _messages: Any, **_kwargs: Any):
- for chunk in ("FI", "NISH\n", "Hello bare"):
- yield chunk
-
- cfg = _fake_llm_config()
-
- with (
- patch.object(
- ap_module.AgenticChatPipeline,
- "_stream_messages",
- _fake_stream,
- ),
- patch(
- "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
- return_value=cfg,
- ),
- ):
- from deeptutor.capabilities.chat import ChatCapability
-
- ctx = _build_context(
- capability="chat",
- payload={
- "original_user_message": "Explain Fourier",
- "partial_response": "",
- "events": [],
- },
- )
- bus = StreamBus()
- cap = ChatCapability()
- events = await _drain(bus, cap.run(ctx, bus))
-
- text = _content_text(events)
- assert "FINISH" not in text
- assert text == "Hello bare"
- result = _result_event(events)
- assert result.metadata.get("response") == "Hello bare"
-
- @pytest.mark.asyncio
- async def test_chat_answer_now_strips_variable_backtick_protocol_label(self) -> None:
- from deeptutor.agents.chat import agentic_pipeline as ap_module
-
- async def _fake_stream(self: Any, _messages: Any, **_kwargs: Any):
- for chunk in ("```FI", "NISH```\n", "Hello fenced"):
- yield chunk
-
- cfg = _fake_llm_config()
-
- with (
- patch.object(
- ap_module.AgenticChatPipeline,
- "_stream_messages",
- _fake_stream,
- ),
- patch(
- "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
- return_value=cfg,
- ),
- ):
- from deeptutor.capabilities.chat import ChatCapability
-
- ctx = _build_context(
- capability="chat",
- payload={
- "original_user_message": "Explain Fourier",
- "partial_response": "",
- "events": [],
- },
- )
- bus = StreamBus()
- cap = ChatCapability()
- events = await _drain(bus, cap.run(ctx, bus))
-
- text = _content_text(events)
- assert "FINISH" not in text
- assert text == "Hello fenced"
- result = _result_event(events)
- assert result.metadata.get("response") == "Hello fenced"
-
- @pytest.mark.asyncio
- async def test_chat_answer_now_strips_spaced_protocol_label(self) -> None:
- from deeptutor.agents.chat import agentic_pipeline as ap_module
-
- async def _fake_stream(self: Any, _messages: Any, **_kwargs: Any):
- for chunk in ("\u200b`` FI", "NISH ``\n", "Hello spaced"):
- yield chunk
-
- cfg = _fake_llm_config()
-
- with (
- patch.object(
- ap_module.AgenticChatPipeline,
- "_stream_messages",
- _fake_stream,
- ),
- patch(
- "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
- return_value=cfg,
- ),
- ):
- from deeptutor.capabilities.chat import ChatCapability
-
- ctx = _build_context(
- capability="chat",
- payload={
- "original_user_message": "Explain Fourier",
- "partial_response": "",
- "events": [],
- },
- )
- bus = StreamBus()
- cap = ChatCapability()
- events = await _drain(bus, cap.run(ctx, bus))
-
- text = _content_text(events)
- assert "FINISH" not in text
- assert text == "Hello spaced"
- result = _result_event(events)
- assert result.metadata.get("response") == "Hello spaced"
-
- @pytest.mark.asyncio
- async def test_chat_answer_now_preserves_normal_word_prefix(self) -> None:
- from deeptutor.agents.chat import agentic_pipeline as ap_module
-
- async def _fake_stream(self: Any, _messages: Any, **_kwargs: Any):
- for chunk in ("FIN", "ISHED tasks stay visible."):
- yield chunk
-
- cfg = _fake_llm_config()
-
- with (
- patch.object(
- ap_module.AgenticChatPipeline,
- "_stream_messages",
- _fake_stream,
- ),
- patch(
- "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
- return_value=cfg,
- ),
- ):
- from deeptutor.capabilities.chat import ChatCapability
-
- ctx = _build_context(
- capability="chat",
- payload={
- "original_user_message": "Explain finished states",
- "partial_response": "",
- "events": [],
- },
- )
- bus = StreamBus()
- cap = ChatCapability()
- events = await _drain(bus, cap.run(ctx, bus))
-
- text = _content_text(events)
- assert text == "FINISHED tasks stay visible."
- result = _result_event(events)
- assert result.metadata.get("response") == "FINISHED tasks stay visible."
-
-
-class TestVisualizeAnswerNow:
- @pytest.mark.asyncio
- async def test_emits_renderable_code_envelope(self) -> None:
- cfg = _fake_llm_config()
- payload_json = json.dumps(
- {
- "render_type": "svg",
- "code": "<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'/>",
- }
- )
- with (
- patch.object(_answer_now, "get_llm_config", return_value=cfg),
- patch.object(_answer_now, "llm_stream", _make_stream_factory([payload_json])),
- ):
- from deeptutor.capabilities.visualize import VisualizeCapability
-
- ctx = _build_context(
- capability="visualize",
- payload={
- "original_user_message": "Draw a circle",
- "events": [],
- },
- config_overrides={"render_mode": "svg"},
- )
- bus = StreamBus()
- cap = VisualizeCapability()
- events = await _drain(bus, cap.run(ctx, bus))
-
- result = _result_event(events)
- assert result.metadata.get("render_type") == "svg"
- code = result.metadata.get("code") or {}
- assert code.get("language") == "svg"
- assert "<svg" in code.get("content", "")
- assert result.metadata.get("metadata", {}).get("answer_now") is True
-
- content = _content_text(events)
- assert "```svg" in content
-
- @pytest.mark.asyncio
- async def test_falls_back_to_svg_when_render_type_invalid(self) -> None:
- cfg = _fake_llm_config()
- payload_json = json.dumps({"render_type": "totally-bogus", "code": "x"})
- with (
- patch.object(_answer_now, "get_llm_config", return_value=cfg),
- patch.object(_answer_now, "llm_stream", _make_stream_factory([payload_json])),
- ):
- from deeptutor.capabilities.visualize import VisualizeCapability
-
- ctx = _build_context(
- capability="visualize",
- payload={"original_user_message": "x", "events": []},
- )
- bus = StreamBus()
- cap = VisualizeCapability()
- events = await _drain(bus, cap.run(ctx, bus))
-
- result = _result_event(events)
- assert result.metadata.get("render_type") == "svg"
-
- @pytest.mark.asyncio
- async def test_strips_code_fences_around_json(self) -> None:
- cfg = _fake_llm_config()
- fenced = '```json\n{"render_type": "mermaid", "code": "graph TD;A-->B"}\n```'
- with (
- patch.object(_answer_now, "get_llm_config", return_value=cfg),
- patch.object(_answer_now, "llm_stream", _make_stream_factory([fenced])),
- ):
- from deeptutor.capabilities.visualize import VisualizeCapability
-
- ctx = _build_context(
- capability="visualize",
- payload={"original_user_message": "diagram", "events": []},
- )
- bus = StreamBus()
- cap = VisualizeCapability()
- events = await _drain(bus, cap.run(ctx, bus))
-
- result = _result_event(events)
- assert result.metadata.get("render_type") == "mermaid"
- assert "graph TD" in (result.metadata.get("code") or {}).get("content", "")
-
-
class TestMathAnimatorAnswerNow:
"""Math animator's fast-path keeps the real ``code_generation`` +
``render`` stages — those are the whole point of the capability —
diff --git a/tests/capabilities/test_status_i18n_consistency.py b/tests/capabilities/test_status_i18n_consistency.py
new file mode 100644
index 000000000..033a064ae
--- /dev/null
+++ b/tests/capabilities/test_status_i18n_consistency.py
@@ -0,0 +1,66 @@
+"""Guards against StatusI18n status-message drift for the visualize capability.
+
+A capability that calls ``i18n.t("some_key", "default", ...)`` must have
+``some_key`` defined in ``capabilities/prompts/{en,zh}/<capability>.yaml`` under
+the ``status:`` section. If it isn't, ``StatusI18n.t`` silently falls back to the
+English ``default`` — so non-English users see English status text while the
+code looks fine. This drift actually happened during the visualize Stage-3
+rewrite (the yaml lagged the code: missing keys + orphan keys); these tests keep
+it from recurring.
+
+Scoped to ``visualize`` for now; the three checks are written generically and
+can be parametrized over more capabilities once their yamls use the same
+``status:`` layout.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+import yaml
+
+_REPO = Path(__file__).resolve().parents[2]
+_PROMPTS = _REPO / "deeptutor" / "capabilities" / "prompts"
+_CODE = _REPO / "deeptutor" / "capabilities" / "visualize.py"
+
+
+def _status_keys(lang: str) -> set[str]:
+ data = yaml.safe_load((_PROMPTS / lang / "visualize.yaml").read_text()) or {}
+ status = data.get("status") if isinstance(data, dict) else None
+ return set((status or {}).keys())
+
+
+def _code() -> str:
+ return _CODE.read_text()
+
+
+def test_en_zh_status_parity() -> None:
+ """en and zh must define the exact same set of status keys."""
+ en, zh = _status_keys("en"), _status_keys("zh")
+ assert en == zh, f"en/zh status keys differ: en-only={en - zh} zh-only={zh - en}"
+
+
+def test_code_i18n_keys_exist_in_yaml() -> None:
+ """Every literal i18n.t("key", ...) used in code must exist in the yaml,
+ otherwise zh users silently get the English default."""
+ used = set(re.findall(r'i18n\.t\(\s*"([^"]+)"', _code()))
+ yaml_keys = _status_keys("en")
+ missing = used - yaml_keys
+ assert not missing, (
+ "i18n keys used in visualize.py but missing from visualize.yaml "
+ f"(zh falls back to English): {sorted(missing)}"
+ )
+
+
+def test_no_orphan_yaml_keys() -> None:
+ """Every yaml status key must be referenced as a string literal somewhere in
+ the module. Tolerates dynamic dispatch (e.g.
+ ``artifact_key = "manim_artifacts_one" if ... else "manim_artifacts_many"``)
+ while still catching dead copy left behind by deleted code paths."""
+ code = _code()
+ orphans = {k for k in _status_keys("en") if f'"{k}"' not in code}
+ assert not orphans, (
+ "yaml status keys never referenced in visualize.py (dead copy): "
+ f"{sorted(orphans)}"
+ )