DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat: add visualize capability with Chart.js/SVG rendering pipeline
Bingxi Zhao (Frank)df844b82168d
diff --git a/README.md b/README.mdindex 7b3673643..fd9ce5c4c 100644--- a/README.md+++ b/README.md@@ -41,7 +41,7 @@> **[2026.4.7]** [v1.0.0-beta.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.2) — Runtime cache invalidation for hot settings reload, MinerU nested output support, mimic WebSocket fix, Python 3.11+ minimum, and CI improvements.-> **[2026.4.4]** [v1.0.0-beta.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.1) — Agent-native architecture rewrite (DeepTutor 2.0) with two-layer plugin model (Tools + Capabilities), CLI & SDK entry points, TutorBot multi-channel bot agent, Co-Writer, Guided Learning, and persistent memory.+> **[2026.4.4]** [v1.0.0-beta.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.0-beta.1) — Agent-native architecture rewrite (~200k lines) with two-layer plugin model (Tools + Capabilities), CLI & SDK entry points, TutorBot multi-channel bot agent, Co-Writer, Guided Learning, and persistent memory.<details><summary><b>Past releases</b></summary>diff --git a/deeptutor/agents/math_animator/prompts/en/code_generator_agent.yaml b/deeptutor/agents/math_animator/prompts/en/code_generator_agent.yamlindex 9d039bddd..68876f4fb 100644--- a/deeptutor/agents/math_animator/prompts/en/code_generator_agent.yaml+++ b/deeptutor/agents/math_animator/prompts/en/code_generator_agent.yaml@@ -3,7 +3,20 @@ generate_system: |Produce runnable Python Manim code.Rules:- For video mode, return one complete Manim script with at least one renderable Scene subclass.- - For image mode, return YON_IMAGE anchor blocks only, and each block must contain a standalone renderable Manim script.+ - For image mode, return YON_IMAGE anchor blocks only, and each block must contain a standalone renderable Manim script. Format:+ ### YON_IMAGE_1_START ###+ from manim import *+ class Scene1(Scene):+ def construct(self):+ ...+ ### YON_IMAGE_1_END ###+ ### YON_IMAGE_2_START ###+ from manim import *+ class Scene2(Scene):+ def construct(self):+ ...+ ### YON_IMAGE_2_END ###+ Anchor numbering starts at 1. The code field must contain nothing outside YON_IMAGE anchor blocks.- Do not include commentary outside the JSON response.- Every geometric point, path point, and vertex passed to Manim must be 3D; do not use `[x, y]` when `[x, y, 0]` is required.- When positions come from axes or planes, prefer helpers such as `axes.c2p(...)` and `plane.c2p(...)` so the result is a valid 3D point.@@ -59,6 +72,7 @@ retry_system: |If the error mentions `self.camera.frame`, repair by either:1) changing the scene base class to `MovingCameraScene`, or2) removing camera-frame animation while keeping the teaching flow.+ If the error mentions `YON_IMAGE`, the image-mode code is missing anchor markers. Wrap the code in `### YON_IMAGE_n_START ###` / `### YON_IMAGE_n_END ###` blocks and ensure the code field contains nothing outside those anchor blocks.retry_user_template: |User request:diff --git a/deeptutor/agents/math_animator/prompts/zh/code_generator_agent.yaml b/deeptutor/agents/math_animator/prompts/zh/code_generator_agent.yamlindex f763c2ea5..bfcf9d37e 100644--- a/deeptutor/agents/math_animator/prompts/zh/code_generator_agent.yaml+++ b/deeptutor/agents/math_animator/prompts/zh/code_generator_agent.yaml@@ -3,7 +3,20 @@ generate_system: |你要生成可运行的 Python Manim 代码。要求:- video 模式:返回一个完整的 Manim 脚本,至少包含一个可渲染的 Scene 子类。- - image 模式:必须严格输出若干个 YON_IMAGE 锚点代码块,每个代码块内都必须是独立可渲染的 Manim 脚本。+ - image 模式:必须严格输出若干个 YON_IMAGE 锚点代码块,每个代码块内都必须是独立可渲染的 Manim 脚本。格式如下:+ ### YON_IMAGE_1_START ###+ from manim import *+ class Scene1(Scene):+ def construct(self):+ ...+ ### YON_IMAGE_1_END ###+ ### YON_IMAGE_2_START ###+ from manim import *+ class Scene2(Scene):+ def construct(self):+ ...+ ### YON_IMAGE_2_END ###+ 锚点编号从 1 开始递增。code 字段中除了 YON_IMAGE 锚点块外不能有其他代码。- 不要输出解释性文字。- Manim 中所有几何点、路径点、顶点坐标都必须是 3D 形式;不要传 `[x, y]`,要传 `[x, y, 0]`。- 如果坐标来自坐标轴或数轴映射,优先使用 `axes.c2p(...)`、`plane.c2p(...)` 等返回 3D 点的方法。@@ -60,6 +73,7 @@ retry_system: |若报错与 `self.camera.frame` 相关,必须二选一修复:1) 把场景类改为 `MovingCameraScene`;或2) 删除相机动画语句并保留原教学逻辑。+ 若报错包含 `YON_IMAGE`,说明 image 模式下代码缺少锚点标记。必须把代码重新包裹在 `### YON_IMAGE_n_START ###` / `### YON_IMAGE_n_END ###` 中,且 code 字段中除锚点块外不能有其他内容。retry_user_template: |用户需求:diff --git a/deeptutor/agents/visualize/__init__.py b/deeptutor/agents/visualize/__init__.pynew file mode 100644index 000000000..1e1e9ee43--- /dev/null+++ b/deeptutor/agents/visualize/__init__.py@@ -0,0 +1,5 @@+"""Visualize agents and pipeline."""++from .pipeline import VisualizePipeline++__all__ = ["VisualizePipeline"]diff --git a/deeptutor/agents/visualize/agents/__init__.py b/deeptutor/agents/visualize/agents/__init__.pynew file mode 100644index 000000000..1dd2f0133--- /dev/null+++ b/deeptutor/agents/visualize/agents/__init__.py@@ -0,0 +1,11 @@+"""Agent building blocks for the visualize capability."""++from .analysis_agent import AnalysisAgent+from .code_generator_agent import CodeGeneratorAgent+from .review_agent import ReviewAgent++__all__ = [+ "AnalysisAgent",+ "CodeGeneratorAgent",+ "ReviewAgent",+]diff --git a/deeptutor/agents/visualize/agents/analysis_agent.py b/deeptutor/agents/visualize/agents/analysis_agent.pynew file mode 100644index 000000000..4265e685d--- /dev/null+++ b/deeptutor/agents/visualize/agents/analysis_agent.py@@ -0,0 +1,74 @@+"""Analysis stage: decide SVG vs Chart.js and produce a structured brief."""++from __future__ import annotations++from deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.trace import build_trace_metadata, new_call_id++from ..models import VisualizationAnalysis+from ..utils import extract_json_object+++class AnalysisAgent(BaseAgent):+ def __init__(+ self,+ api_key: str | None = None,+ base_url: str | None = None,+ api_version: str | None = None,+ language: str = "zh",+ ) -> None:+ super().__init__(+ module_name="visualize",+ agent_name="analysis_agent",+ api_key=api_key,+ base_url=base_url,+ api_version=api_version,+ language=language,+ )++ async def process(+ self,+ *,+ user_input: str,+ history_context: str,+ render_mode: str = "auto",+ ) -> VisualizationAnalysis:+ if render_mode in ("svg", "chartjs"):+ system_prompt = self.get_prompt("system_fixed")+ user_template = self.get_prompt("user_template_fixed")+ else:+ system_prompt = self.get_prompt("system")+ user_template = self.get_prompt("user_template")+ if not system_prompt or not user_template:+ raise ValueError("AnalysisAgent prompts are not configured.")++ format_kwargs: dict[str, str] = {+ "user_input": user_input.strip(),+ "history_context": history_context.strip() or "(none)",+ }+ if render_mode in ("svg", "chartjs"):+ format_kwargs["render_type"] = render_mode++ user_prompt = user_template.format(**format_kwargs)++ chunks: list[str] = []+ async for chunk in self.stream_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ response_format={"type": "json_object"},+ stage="analyzing",+ trace_meta=build_trace_metadata(+ call_id=new_call_id("viz-analysis"),+ phase="analyzing",+ label="Visualization analysis",+ call_kind="viz_analysis",+ trace_role="analyze",+ trace_kind="llm_output",+ ),+ ):+ chunks.append(chunk)+ response = "".join(chunks)+ result = VisualizationAnalysis.model_validate(extract_json_object(response))+ if render_mode in ("svg", "chartjs"):+ result.render_type = render_mode # type: ignore[assignment]+ return resultdiff --git a/deeptutor/agents/visualize/agents/code_generator_agent.py b/deeptutor/agents/visualize/agents/code_generator_agent.pynew file mode 100644index 000000000..e10c01688--- /dev/null+++ b/deeptutor/agents/visualize/agents/code_generator_agent.py@@ -0,0 +1,68 @@+"""Code generation stage: produce SVG or Chart.js code from the analysis."""++from __future__ import annotations++import json++from deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.trace import build_trace_metadata, new_call_id++from ..models import VisualizationAnalysis+from ..utils import extract_code_block+++class CodeGeneratorAgent(BaseAgent):+ def __init__(+ self,+ api_key: str | None = None,+ base_url: str | None = None,+ api_version: str | None = None,+ language: str = "zh",+ ) -> None:+ super().__init__(+ module_name="visualize",+ agent_name="code_generator_agent",+ api_key=api_key,+ base_url=base_url,+ api_version=api_version,+ language=language,+ )++ async def process(+ self,+ *,+ user_input: str,+ history_context: str,+ analysis: VisualizationAnalysis,+ ) -> str:+ system_prompt = self.get_prompt("system")+ user_template = self.get_prompt("user_template")+ if not system_prompt or not user_template:+ raise ValueError("CodeGeneratorAgent prompts are not configured.")++ user_prompt = user_template.format(+ user_input=user_input.strip(),+ history_context=history_context.strip() or "(none)",+ render_type=analysis.render_type,+ analysis_json=json.dumps(analysis.model_dump(), ensure_ascii=False, indent=2),+ )++ chunks: list[str] = []+ async for chunk in self.stream_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ stage="generating",+ trace_meta=build_trace_metadata(+ call_id=new_call_id("viz-codegen"),+ phase="generating",+ label="Code generation",+ call_kind="viz_code_generation",+ trace_role="generate",+ trace_kind="llm_output",+ ),+ ):+ chunks.append(chunk)+ response = "".join(chunks)++ lang_hint = "svg" if analysis.render_type == "svg" else "javascript"+ return extract_code_block(response, lang_hint) or extract_code_block(response)diff --git a/deeptutor/agents/visualize/agents/review_agent.py b/deeptutor/agents/visualize/agents/review_agent.pynew file mode 100644index 000000000..6391c4aed--- /dev/null+++ b/deeptutor/agents/visualize/agents/review_agent.py@@ -0,0 +1,67 @@+"""Review stage: check and optionally optimise the generated code."""++from __future__ import annotations++import json++from deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.trace import build_trace_metadata, new_call_id++from ..models import ReviewResult, VisualizationAnalysis+from ..utils import extract_json_object+++class ReviewAgent(BaseAgent):+ def __init__(+ self,+ api_key: str | None = None,+ base_url: str | None = None,+ api_version: str | None = None,+ language: str = "zh",+ ) -> None:+ super().__init__(+ module_name="visualize",+ agent_name="review_agent",+ api_key=api_key,+ base_url=base_url,+ api_version=api_version,+ language=language,+ )++ async def process(+ self,+ *,+ user_input: str,+ analysis: VisualizationAnalysis,+ code: str,+ ) -> ReviewResult:+ 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))diff --git a/deeptutor/agents/visualize/models.py b/deeptutor/agents/visualize/models.pynew file mode 100644index 000000000..ae1d3eae7--- /dev/null+++ b/deeptutor/agents/visualize/models.py@@ -0,0 +1,51 @@+"""Data models for the visualize pipeline."""++from __future__ import annotations++from typing import Literal++from pydantic import BaseModel, Field+++class VisualizationAnalysis(BaseModel):+ """Output of the analysis stage."""++ render_type: Literal["svg", "chartjs"] = Field(+ description="Whether to render as raw SVG or as a Chart.js configuration.",+ )+ description: str = Field(+ default="",+ description="High-level description of what the visualization should show.",+ )+ data_description: str = Field(+ default="",+ description="Description of the data or elements to be visualized.",+ )+ chart_type: str = Field(+ default="",+ description="Chart.js chart type (bar, line, pie, doughnut, radar, etc.) when render_type is chartjs.",+ )+ visual_elements: list[str] = Field(+ default_factory=list,+ description="Key visual elements to include (shapes, labels, axes, colors, etc.).",+ )+ rationale: str = Field(+ default="",+ description="Why this render_type was chosen over the alternative.",+ )+++class ReviewResult(BaseModel):+ """Output of the review / optimization stage."""++ optimized_code: str = Field(+ description="The final (potentially optimized) visualization code.",+ )+ changed: bool = Field(+ default=False,+ description="Whether the reviewer made modifications.",+ )+ review_notes: str = Field(+ default="",+ description="Notes on what was checked or changed.",+ )diff --git a/deeptutor/agents/visualize/pipeline.py b/deeptutor/agents/visualize/pipeline.pynew file mode 100644index 000000000..4724e041b--- /dev/null+++ b/deeptutor/agents/visualize/pipeline.py@@ -0,0 +1,85 @@+"""Orchestrates the three-stage visualization generation flow."""++from __future__ import annotations++from typing import Any, Callable++from .agents import AnalysisAgent, CodeGeneratorAgent, ReviewAgent+from .models import ReviewResult, VisualizationAnalysis+++class VisualizePipeline:+ def __init__(+ self,+ *,+ api_key: str | None,+ base_url: str | None,+ api_version: str | None,+ language: str = "zh",+ trace_callback: Callable[[dict[str, Any]], Any] | None = None,+ ) -> None:+ self.analysis_agent = AnalysisAgent(+ api_key=api_key,+ base_url=base_url,+ api_version=api_version,+ language=language,+ )+ self.code_agent = CodeGeneratorAgent(+ api_key=api_key,+ base_url=base_url,+ api_version=api_version,+ language=language,+ )+ self.review_agent = ReviewAgent(+ api_key=api_key,+ base_url=base_url,+ api_version=api_version,+ language=language,+ )+ self.set_trace_callback(trace_callback)++ def set_trace_callback(self, callback: Callable[[dict[str, Any]], Any] | None) -> None:+ for agent in (self.analysis_agent, self.code_agent, self.review_agent):+ agent.set_trace_callback(callback)++ async def run_analysis(+ self,+ *,+ user_input: str,+ history_context: str,+ render_mode: str = "auto",+ ) -> VisualizationAnalysis:+ return await self.analysis_agent.process(+ user_input=user_input,+ history_context=history_context,+ render_mode=render_mode,+ )++ async def run_code_generation(+ self,+ *,+ user_input: str,+ history_context: str,+ analysis: VisualizationAnalysis,+ ) -> str:+ return await self.code_agent.process(+ user_input=user_input,+ history_context=history_context,+ 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,+ )+++__all__ = ["VisualizePipeline"]diff --git a/deeptutor/agents/visualize/prompts/en/analysis_agent.yaml b/deeptutor/agents/visualize/prompts/en/analysis_agent.yamlnew file mode 100644index 000000000..90ecad3dd--- /dev/null+++ b/deeptutor/agents/visualize/prompts/en/analysis_agent.yaml@@ -0,0 +1,55 @@+system: |+ You are a visualization analyst. Given a user request and conversation history,+ decide the best rendering approach and produce a structured analysis.++ Choose between two render types:+ - "svg": Use when the visualization is a diagram, flowchart, illustration, schematic,+ concept map, architecture diagram, or any free-form graphic that does not represent+ quantitative data in a standard chart form.+ - "chartjs": Use when the visualization involves quantitative data that fits a+ standard chart type (bar, line, pie, doughnut, radar, scatter, bubble, polar area).++ Return your analysis as a single JSON object. Do not include any text outside the JSON.++user_template: |+ User request:+ {user_input}++ Conversation history:+ {history_context}++ Return JSON:+ {{+ "render_type": "svg" or "chartjs",+ "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 render_type is chartjs, otherwise empty string",+ "visual_elements": ["key visual elements to include"],+ "rationale": "Why this render_type was chosen"+ }}++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.++ Return your analysis as a single JSON object. Do not include any text outside the JSON.++user_template_fixed: |+ User request:+ {user_input}++ Conversation history:+ {history_context}++ The render type is fixed to: {render_type}++ Return JSON:+ {{+ "render_type": "{render_type}",+ "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 render_type is chartjs, otherwise empty string",+ "visual_elements": ["key visual elements to include"],+ "rationale": "Analysis notes"+ }}diff --git a/deeptutor/agents/visualize/prompts/en/code_generator_agent.yaml b/deeptutor/agents/visualize/prompts/en/code_generator_agent.yamlnew file mode 100644index 000000000..8f16bca78--- /dev/null+++ b/deeptutor/agents/visualize/prompts/en/code_generator_agent.yaml@@ -0,0 +1,32 @@+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.+ - Do NOT include any explanation outside the code fence.+ - Wrap the code in a fenced code block with the appropriate language tag+ (```svg or ```javascript).++user_template: |+ User request:+ {user_input}++ Conversation history:+ {history_context}++ Render type: {render_type}++ Analysis:+ {analysis_json}++ Generate the visualization code now. Wrap it in a fenced code block:+ - For SVG: ```svg ... ```+ - For Chart.js: ```javascript ... ```diff --git a/deeptutor/agents/visualize/prompts/en/review_agent.yaml b/deeptutor/agents/visualize/prompts/en/review_agent.yamlnew file mode 100644index 000000000..44a6ccb5a--- /dev/null+++ b/deeptutor/agents/visualize/prompts/en/review_agent.yaml@@ -0,0 +1,41 @@+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++ 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"+ }}diff --git a/deeptutor/agents/visualize/prompts/zh/analysis_agent.yaml b/deeptutor/agents/visualize/prompts/zh/analysis_agent.yamlnew file mode 100644index 000000000..5bd7248da--- /dev/null+++ b/deeptutor/agents/visualize/prompts/zh/analysis_agent.yaml@@ -0,0 +1,51 @@+system: |+ 你是一个可视化分析师。根据用户请求和对话历史,决定最佳的渲染方式并生成结构化分析。++ 在两种渲染类型中选择:+ - "svg":当可视化是流程图、示意图、概念图、架构图或任何不适合标准图表形式的自由图形时使用。+ - "chartjs":当可视化涉及可以用标准图表类型(柱状图、折线图、饼图、环形图、雷达图、散点图、气泡图、极坐标图)表示的定量数据时使用。++ 返回一个 JSON 对象,不要包含 JSON 以外的任何文本。++user_template: |+ 用户请求:+ {user_input}++ 对话历史:+ {history_context}++ 返回 JSON:+ {{+ "render_type": "svg" 或 "chartjs",+ "description": "可视化应展示的内容的高层描述",+ "data_description": "要可视化的数据或元素的描述",+ "chart_type": "如果 render_type 是 chartjs 则填写 Chart.js 图表类型,否则为空字符串",+ "visual_elements": ["需要包含的关键视觉元素"],+ "rationale": "为什么选择这种 render_type"+ }}++system_fixed: |+ 你是一个可视化分析师。用户已经选择了渲染类型。+ 分析用户请求和对话历史,生成结构化的代码生成简报。+ 不要更改 render_type。++ 返回一个 JSON 对象,不要包含 JSON 以外的任何文本。++user_template_fixed: |+ 用户请求:+ {user_input}++ 对话历史:+ {history_context}++ 渲染类型已固定为:{render_type}++ 返回 JSON:+ {{+ "render_type": "{render_type}",+ "description": "可视化应展示的内容的高层描述",+ "data_description": "要可视化的数据或元素的描述",+ "chart_type": "如果 render_type 是 chartjs 则填写 Chart.js 图表类型,否则为空字符串",+ "visual_elements": ["需要包含的关键视觉元素"],+ "rationale": "分析说明"+ }}diff --git a/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yaml b/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yamlnew file mode 100644index 000000000..97f4488cd--- /dev/null+++ b/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yaml@@ -0,0 +1,30 @@+system: |+ 你是一个可视化代码生成器。根据分析结果、用户请求和对话历史生成可视化代码。++ 规则:+ - 如果 render_type 是 "svg",输出完整的、自包含的 SVG 字符串。+ SVG 必须包含 xmlns 属性并且是格式良好的 XML。+ 使用 viewBox 实现响应式尺寸。优先使用简洁现代的美学风格,+ 确保字体可读、颜色清晰、间距合适。+ - 如果 render_type 是 "chartjs",输出一个有效的 JavaScript 对象字面量,+ 可以作为配置传递给 `new Chart(ctx, config)`。+ 配置必须包含 `type`、`data` 和 `options` 字段。+ 使用现代配色方案并确保标签可读。+ - 不要在代码块之外包含任何解释。+ - 用带有适当语言标签的代码块包裹代码(```svg 或 ```javascript)。++user_template: |+ 用户请求:+ {user_input}++ 对话历史:+ {history_context}++ 渲染类型:{render_type}++ 分析:+ {analysis_json}++ 现在生成可视化代码。用代码块包裹:+ - SVG 使用:```svg ... ```+ - Chart.js 使用:```javascript ... ```diff --git a/deeptutor/agents/visualize/prompts/zh/review_agent.yaml b/deeptutor/agents/visualize/prompts/zh/review_agent.yamlnew file mode 100644index 000000000..d584abe10--- /dev/null+++ b/deeptutor/agents/visualize/prompts/zh/review_agent.yaml@@ -0,0 +1,40 @@+system: |+ 你是一个可视化代码审查员。检查生成的代码的正确性、完整性和视觉质量,修复发现的任何问题。++ 对于 SVG 代码,检查:+ - 格式良好的 XML,包含正确的 xmlns+ - 正确的 viewBox 和尺寸+ - 文本可读性(字体大小、对比度)+ - 颜色和间距的合理使用+ - 缺失或损坏的元素++ 对于 Chart.js 代码,检查:+ - 有效的 JavaScript 对象字面量+ - 正确的图表类型和数据结构+ - 正确的标签、数据集和选项+ - 颜色的可访问性和可读性+ - 响应式配置++ 如果代码已经很好,原样返回并设置 changed=false。+ 如果你做了改进,返回优化后的代码并设置 changed=true。++ 返回一个 JSON 对象,不要包含 JSON 以外的任何文本。++user_template: |+ 用户请求:+ {user_input}++ 渲染类型:{render_type}++ 分析:+ {analysis_json}++ 待审查代码:+ {code}++ 返回 JSON:+ {{+ "optimized_code": "最终代码(如果无需更改则与输入相同)",+ "changed": true 或 false,+ "review_notes": "检查或修改的内容"+ }}diff --git a/deeptutor/agents/visualize/utils.py b/deeptutor/agents/visualize/utils.pynew file mode 100644index 000000000..722d56ad4--- /dev/null+++ b/deeptutor/agents/visualize/utils.py@@ -0,0 +1,83 @@+"""Utility helpers for the visualize pipeline."""++from __future__ import annotations++import json+import re+from typing import Any+++def extract_json_object(text: str) -> dict[str, Any]:+ """Extract a JSON object from raw model output."""+ raw = (text or "").strip()+ if not raw:+ return {}++ fenced = re.findall(r"```(?:json)?\s*([\s\S]*?)\s*```", raw)+ candidates = fenced + [raw]++ for candidate in candidates:+ try:+ parsed = json.loads(candidate)+ if isinstance(parsed, dict):+ return parsed+ except json.JSONDecodeError:+ parsed = _decode_first_json_object(candidate)+ if parsed is not None:+ return parsed++ start = raw.find("{")+ end = raw.rfind("}")+ if start != -1 and end != -1 and end > start:+ snippet = raw[start : end + 1]+ try:+ return json.loads(snippet)+ except json.JSONDecodeError:+ parsed = _decode_first_json_object(snippet)+ if parsed is not None:+ return parsed++ raise json.JSONDecodeError("No JSON object found", raw, 0)+++def _decode_first_json_object(text: str) -> dict[str, Any] | None:+ decoder = json.JSONDecoder()+ stripped = (text or "").lstrip()+ if not stripped:+ return None++ starts = [0]+ brace_index = stripped.find("{")+ if brace_index > 0:+ starts.append(brace_index)++ for start in starts:+ try:+ parsed, _end = decoder.raw_decode(stripped[start:])+ except json.JSONDecodeError:+ continue+ if isinstance(parsed, dict):+ return parsed+ return None+++def extract_code_block(text: str, language: str = "") -> str:+ """Extract a fenced code block from LLM output.++ If *language* is given the block must start with that tag;+ otherwise any triple-backtick fence is accepted.+ """+ if language:+ pattern = rf"```{re.escape(language)}\s*\n([\s\S]*?)\n```"+ else:+ pattern = r"```[A-Za-z]*\s*\n([\s\S]*?)\n```"+ match = re.search(pattern, text or "", re.IGNORECASE)+ if match:+ return match.group(1).strip()+ return (text or "").strip()+++__all__ = [+ "extract_code_block",+ "extract_json_object",+]diff --git a/deeptutor/api/main.py b/deeptutor/api/main.pyindex 1a0dc36b0..5ee7c6d12 100644--- a/deeptutor/api/main.py+++ b/deeptutor/api/main.py@@ -14,23 +14,17 @@ from deeptutor.services.path_service import get_path_servicelogger = get_logger("API")-class _ProgressWsAccessFilter(logging.Filter):- """Suppress noisy uvicorn access logs for progress WebSocket endpoints.+class _SuppressWsNoise(logging.Filter):+ """Suppress noisy uvicorn logs for WebSocket connection churn."""- These endpoints are polled every few seconds by the frontend for every KB,- generating hundreds of ``connection open`` / ``connection closed`` lines- that drown out useful output.- """-- _SUPPRESSED_FRAGMENTS = ("progress/ws", "connection open", "connection closed")+ _SUPPRESSED = ("connection open", "connection closed")def filter(self, record: logging.LogRecord) -> bool:msg = record.getMessage()- return not any(f in msg for f in self._SUPPRESSED_FRAGMENTS)+ return not any(f in msg for f in self._SUPPRESSED)-for _uv_name in ("uvicorn.access", "uvicorn.error"):- logging.getLogger(_uv_name).addFilter(_ProgressWsAccessFilter())+logging.getLogger("uvicorn.error").addFilter(_SuppressWsNoise())CONFIG_DRIFT_ERROR_TEMPLATE = ("Configuration Drift Detected: Capability tool references {drift} are not "@@ -152,6 +146,24 @@ app = FastAPI(redirect_slashes=False,)+# Log only non-200 requests (uvicorn access_log is disabled in run_server.py)+_access_logger = logging.getLogger("uvicorn.access")++[email protected]("http")+async def selective_access_log(request, call_next):+ response = await call_next(request)+ if response.status_code != 200:+ _access_logger.info(+ '%s - "%s %s" %d',+ request.client.host if request.client else "-",+ request.method,+ request.url.path,+ response.status_code,+ )+ return response++# Configure CORSapp.add_middleware(CORSMiddleware,diff --git a/deeptutor/api/run_server.py b/deeptutor/api/run_server.pyindex 17a40e02d..162226ec2 100644--- a/deeptutor/api/run_server.py+++ b/deeptutor/api/run_server.py@@ -64,6 +64,7 @@ def main() -> None:reload=True,reload_excludes=reload_excludes,log_level="info",+ access_log=False,)diff --git a/deeptutor/capabilities/request_contracts.py b/deeptutor/capabilities/request_contracts.pyindex bebd6bdad..5e95c3193 100644--- a/deeptutor/capabilities/request_contracts.py+++ b/deeptutor/capabilities/request_contracts.py@@ -41,6 +41,12 @@ class DeepQuestionRequestConfig(BaseModel):max_questions: int = Field(default=10, ge=1, le=100)+class VisualizeRequestConfig(BaseModel):+ model_config = ConfigDict(extra="forbid")++ render_mode: Literal["auto", "svg", "chartjs"] = "auto"++def _clean_public_config(raw_config: dict[str, Any] | None) -> dict[str, Any]:if raw_config is None:return {}@@ -85,6 +91,12 @@ def validate_deep_question_request_config(return _validate_model(DeepQuestionRequestConfig, raw_config, label="deep question")+def validate_visualize_request_config(+ raw_config: dict[str, Any] | None,+) -> VisualizeRequestConfig:+ return _validate_model(VisualizeRequestConfig, raw_config, label="visualize")++def build_request_schema(model_type: type[BaseModel]) -> dict[str, Any]:return model_type.model_json_schema(mode="validation")@@ -95,6 +107,7 @@ CAPABILITY_CONFIG_VALIDATORS: dict[str, Callable[[dict[str, Any] | None], Any]]"deep_question": validate_deep_question_request_config,"deep_research": validate_research_request_config,"math_animator": validate_math_animator_request_config,+ "visualize": validate_visualize_request_config,}CAPABILITY_REQUEST_SCHEMAS: dict[str, dict[str, Any]] = {@@ -103,6 +116,7 @@ CAPABILITY_REQUEST_SCHEMAS: dict[str, dict[str, Any]] = {"deep_question": build_request_schema(DeepQuestionRequestConfig),"deep_research": build_request_schema(DeepResearchRequestConfig),"math_animator": build_request_schema(MathAnimatorRequestConfig),+ "visualize": build_request_schema(VisualizeRequestConfig),}@@ -126,10 +140,12 @@ __all__ = ["ChatRequestConfig","DeepQuestionRequestConfig","DeepSolveRequestConfig",+ "VisualizeRequestConfig","build_request_schema","get_capability_request_schema","validate_capability_config","validate_chat_request_config","validate_deep_question_request_config","validate_deep_solve_request_config",+ "validate_visualize_request_config",]diff --git a/deeptutor/capabilities/visualize.py b/deeptutor/capabilities/visualize.pynew file mode 100644index 000000000..9835f33ac--- /dev/null+++ b/deeptutor/capabilities/visualize.py@@ -0,0 +1,209 @@+"""+Visualize Capability+====================++Three-stage visualization pipeline: Analyze -> Generate -> Review.+Produces SVG or Chart.js code from user requests and conversation context.+"""++from __future__ import annotations++from typing import Any++from deeptutor.capabilities.request_contracts import get_capability_request_schema+from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus+from deeptutor.core.trace import merge_trace_metadata+++class VisualizeCapability(BaseCapability):+ manifest = CapabilityManifest(+ name="visualize",+ description="Generate SVG or Chart.js visualizations.",+ stages=["analyzing", "generating", "reviewing"],+ tools_used=[],+ cli_aliases=["visualize", "viz"],+ request_schema=get_capability_request_schema("visualize"),+ )++ async def run(self, context: UnifiedContext, stream: StreamBus) -> None:+ from deeptutor.agents.visualize.pipeline import VisualizePipeline+ from deeptutor.services.llm.config import get_llm_config++ llm_config = get_llm_config()+ history_context = str(+ context.metadata.get("conversation_context_text", "") or ""+ ).strip()+ render_mode = str(+ context.config_overrides.get("render_mode", "auto") or "auto"+ ).strip().lower()++ pipeline = VisualizePipeline(+ api_key=llm_config.api_key,+ base_url=llm_config.base_url,+ api_version=llm_config.api_version,+ language=context.language,+ trace_callback=self._build_trace_bridge(stream),+ )++ # Stage 1: Analyze+ async with stream.stage("analyzing", source=self.name):+ await stream.thinking(+ "Analyzing visualization requirements...",+ source=self.name,+ stage="analyzing",+ )+ analysis = await pipeline.run_analysis(+ user_input=context.user_message,+ history_context=history_context,+ render_mode=render_mode,+ )+ await stream.progress(+ message=f"Render type: {analysis.render_type} — {analysis.description}",+ source=self.name,+ stage="analyzing",+ )++ # Stage 2: Generate code+ async with stream.stage("generating", source=self.name):+ await stream.thinking(+ "Generating visualization code...",+ source=self.name,+ stage="generating",+ )+ code = await pipeline.run_code_generation(+ user_input=context.user_message,+ history_context=history_context,+ analysis=analysis,+ )+ await stream.progress(+ message="Code generated.",+ source=self.name,+ stage="generating",+ )++ # Stage 3: Review & optimise+ async with stream.stage("reviewing", source=self.name):+ await stream.thinking(+ "Reviewing and optimizing code...",+ source=self.name,+ stage="reviewing",+ )+ review = await pipeline.run_review(+ user_input=context.user_message,+ analysis=analysis,+ code=code,+ )+ final_code = review.optimized_code+ if review.changed:+ await stream.progress(+ message=f"Code optimized: {review.review_notes}",+ source=self.name,+ stage="reviewing",+ )+ else:+ await stream.progress(+ message="Code looks good — no changes needed.",+ source=self.name,+ stage="reviewing",+ )++ # Emit final content as a fenced code block for the chat area+ lang_tag = "svg" if analysis.render_type == "svg" else "javascript"+ content_md = f"```{lang_tag}\n{final_code}\n```"+ await stream.content(content_md, source=self.name, stage="reviewing")++ # Structured result for the frontend viewer+ await stream.result(+ {+ "response": content_md,+ "render_type": analysis.render_type,+ "code": {+ "language": lang_tag,+ "content": final_code,+ },+ "analysis": analysis.model_dump(),+ "review": review.model_dump(),+ },+ source=self.name,+ )++ def _build_trace_bridge(self, stream: StreamBus):+ async def _trace_bridge(update: dict[str, Any]) -> None:+ event = str(update.get("event", "") or "")+ stage = str(update.get("phase") or update.get("stage") or "analyzing")+ base_metadata = {+ key: value+ for key, value in update.items()+ if key+ not in {"event", "state", "response", "chunk", "result", "tool_name", "tool_args"}+ }++ if event != "llm_call":+ return++ state = str(update.get("state", "running"))+ label = str(+ base_metadata.get("label", "") or stage.replace("_", " ").title()+ )+ if state == "running":+ await stream.progress(+ message=label,+ source=self.name,+ stage=stage,+ metadata=merge_trace_metadata(+ base_metadata,+ {"trace_kind": "call_status", "call_state": "running"},+ ),+ )+ return+ if state == "streaming":+ chunk = str(update.get("chunk", "") or "")+ if chunk:+ await stream.thinking(+ chunk,+ source=self.name,+ stage=stage,+ metadata=merge_trace_metadata(+ base_metadata,+ {"trace_kind": "llm_chunk"},+ ),+ )+ return+ if state == "complete":+ was_streaming = update.get("streaming", False)+ if not was_streaming:+ response = str(update.get("response", "") or "")+ if response:+ await stream.thinking(+ response,+ source=self.name,+ stage=stage,+ metadata=merge_trace_metadata(+ base_metadata,+ {"trace_kind": "llm_output"},+ ),+ )+ await stream.progress(+ message=label,+ source=self.name,+ stage=stage,+ metadata=merge_trace_metadata(+ base_metadata,+ {"trace_kind": "call_status", "call_state": "complete"},+ ),+ )+ return+ if state == "error":+ await stream.error(+ str(update.get("response", "") or "LLM call failed."),+ source=self.name,+ stage=stage,+ metadata=merge_trace_metadata(+ base_metadata,+ {"trace_kind": "call_status", "call_state": "error"},+ ),+ )++ return _trace_bridgediff --git a/deeptutor/runtime/bootstrap/builtin_capabilities.py b/deeptutor/runtime/bootstrap/builtin_capabilities.pyindex c7f5d3b0e..dac0174f6 100644--- a/deeptutor/runtime/bootstrap/builtin_capabilities.py+++ b/deeptutor/runtime/bootstrap/builtin_capabilities.py@@ -6,4 +6,5 @@ BUILTIN_CAPABILITY_CLASSES: dict[str, str] = {"deep_question": "deeptutor.capabilities.deep_question:DeepQuestionCapability","deep_research": "deeptutor.capabilities.deep_research:DeepResearchCapability","math_animator": "deeptutor.capabilities.math_animator:MathAnimatorCapability",+ "visualize": "deeptutor.capabilities.visualize:VisualizeCapability",}diff --git a/deeptutor/services/llm/capabilities.py b/deeptutor/services/llm/capabilities.pyindex f55bddb15..34e61d560 100644--- a/deeptutor/services/llm/capabilities.py+++ b/deeptutor/services/llm/capabilities.py@@ -165,6 +165,9 @@ MODEL_OVERRIDES: dict[str, dict[str, object]] = {"qwq": {"has_thinking_tags": True,},+ "minimax": {+ "supports_response_format": False,+ },# NOTE: supports_response_format and system_in_messages are binding-level# capabilities, NOT model-level. When using OpenRouter or other OpenAI-compatible# proxies (binding="openai"), they handle response_format translation and expectdiff --git a/web/app/(utility)/knowledge/page.tsx b/web/app/(utility)/knowledge/page.tsxindex b38e79833..3657eba1a 100644--- a/web/app/(utility)/knowledge/page.tsx+++ b/web/app/(utility)/knowledge/page.tsx@@ -298,9 +298,17 @@ export default function KnowledgePage() {for (const kb of kbs) {const status = kb.status ?? kb.statistics?.status;const progress = kb.progress ?? kb.statistics?.progress;- if (status && status !== "ready" && status !== "error") {+ const progressStage = (progress as ProgressInfo | undefined)?.stage;+ if (+ status &&+ status !== "ready" &&+ status !== "error" &&+ progressStage !== "completed" &&+ progressStage !== "error"+ ) {setProgressMap((prev) => ({ ...prev, [kb.name]: progress || prev[kb.name] || {} }));- subscribeProgress(kb.name);+ const taskId = (progress as ProgressInfo | undefined)?.task_id;+ subscribeProgress(kb.name, taskId || undefined);}}} catch (error) {@@ -343,7 +351,9 @@ export default function KnowledgePage() {const stage = progress.stage;if (stage === "completed" || stage === "error") {closeProgressSocket(kbName);- void loadAll();+ if (expectedTaskId) {+ void loadAll();+ }}} catch {// Ignore malformed progress events.diff --git a/web/app/(workspace)/page.tsx b/web/app/(workspace)/page.tsxindex fad70adcb..0dde74166 100644--- a/web/app/(workspace)/page.tsx+++ b/web/app/(workspace)/page.tsx@@ -4,6 +4,7 @@ import dynamic from "next/dynamic";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import {+ BarChart3,BrainCircuit,Clapperboard,Code2,@@ -43,6 +44,11 @@ import {buildMathAnimatorWSConfig,type MathAnimatorFormConfig,} from "@/lib/math-animator-types";+import {+ DEFAULT_VISUALIZE_CONFIG,+ buildVisualizeWSConfig,+ type VisualizeFormConfig,+} from "@/lib/visualize-types";import {buildResearchWSConfig,createEmptyResearchConfig,@@ -152,6 +158,14 @@ const CAPABILITIES: CapabilityDef[] = [allowedTools: [],defaultTools: [],},+ {+ value: "visualize",+ label: "Visualize",+ description: "Generate SVG or Chart.js visualizations",+ icon: BarChart3,+ allowedTools: [],+ defaultTools: [],+ },];interface KnowledgeBase {@@ -210,6 +224,9 @@ export default function HomePage() {const [mathAnimatorConfig, setMathAnimatorConfig] = useState<MathAnimatorFormConfig>({...DEFAULT_MATH_ANIMATOR_CONFIG,});+ const [visualizeConfig, setVisualizeConfig] = useState<VisualizeFormConfig>({+ ...DEFAULT_VISUALIZE_CONFIG,+ });const [researchConfig, setResearchConfig] = useState<DeepResearchFormConfig>(createEmptyResearchConfig());const [researchPanelCollapsed, setResearchPanelCollapsed] = useState(true);const [showSaveModal, setShowSaveModal] = useState(false);@@ -229,6 +246,7 @@ export default function HomePage() {const activeCap = useMemo(() => getCapability(state.activeCapability), [state.activeCapability]);const isQuizMode = activeCap.value === "deep_question";const isMathAnimatorMode = activeCap.value === "math_animator";+ const isVisualizeMode = activeCap.value === "visualize";const isResearchMode = activeCap.value === "deep_research";const selectedTools = useMemo(() => new Set(state.enabledTools), [state.enabledTools]);const ragActive = isResearchMode ? researchConfig.sources.includes("kb") : selectedTools.has("rag");@@ -631,6 +649,9 @@ export default function HomePage() {if (isMathAnimatorMode) {config = buildMathAnimatorWSConfig(mathAnimatorConfig);}+ if (isVisualizeMode) {+ config = buildVisualizeWSConfig(visualizeConfig);+ }if (isResearchMode) {config = buildResearchWSConfig(researchConfig);}@@ -774,9 +795,11 @@ export default function HomePage() {isResearchMode={isResearchMode}isQuizMode={isQuizMode}isMathAnimatorMode={isMathAnimatorMode}+ isVisualizeMode={isVisualizeMode}quizConfig={quizConfig}quizPdf={quizPdf}mathAnimatorConfig={mathAnimatorConfig}+ visualizeConfig={visualizeConfig}researchConfig={researchConfig}researchValidationErrors={researchValidation.errors}researchPanelCollapsed={researchPanelCollapsed}@@ -829,6 +852,7 @@ export default function HomePage() {onChangeQuizConfig={setQuizConfig}onUploadQuizPdf={setQuizPdf}onChangeMathAnimatorConfig={setMathAnimatorConfig}+ onChangeVisualizeConfig={setVisualizeConfig}onChangeResearchConfig={setResearchConfig}onToggleResearchCollapsed={() => setResearchPanelCollapsed((prev) => !prev)}/>diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsxindex bbc26c80c..04965b16b 100644--- a/web/components/chat/home/ChatComposer.tsx+++ b/web/components/chat/home/ChatComposer.tsx@@ -21,6 +21,7 @@ import AtMentionPopup from "@/components/chat/AtMentionPopup";import type { SelectedRecord } from "@/app/(workspace)/guide/types";import type { DeepQuestionFormConfig } from "@/lib/quiz-types";import type { MathAnimatorFormConfig } from "@/lib/math-animator-types";+import type { VisualizeFormConfig } from "@/lib/visualize-types";import type { DeepResearchFormConfig, ResearchSource } from "@/lib/research-types";import { ReferenceChips } from "./ChatMessages";@@ -35,6 +36,10 @@ const ResearchConfigPanel = dynamic(() => import("@/components/research/ResearchConfigPanel"),{ ssr: false },);+const VisualizeConfigPanel = dynamic(+ () => import("@/components/visualize/VisualizeConfigPanel"),+ { ssr: false },+);interface PendingAttachment {type: string;@@ -95,9 +100,11 @@ export default function ChatComposer({isResearchMode,isQuizMode,isMathAnimatorMode,+ isVisualizeMode,quizConfig,quizPdf,mathAnimatorConfig,+ visualizeConfig,researchConfig,researchValidationErrors,researchPanelCollapsed,@@ -127,6 +134,7 @@ export default function ChatComposer({onChangeQuizConfig,onUploadQuizPdf,onChangeMathAnimatorConfig,+ onChangeVisualizeConfig,onChangeResearchConfig,onToggleResearchCollapsed,}: {@@ -157,9 +165,11 @@ export default function ChatComposer({isResearchMode: boolean;isQuizMode: boolean;isMathAnimatorMode: boolean;+ isVisualizeMode: boolean;quizConfig: DeepQuestionFormConfig;quizPdf: File | null;mathAnimatorConfig: MathAnimatorFormConfig;+ visualizeConfig: VisualizeFormConfig;researchConfig: DeepResearchFormConfig;researchValidationErrors: Record<string, string>;researchPanelCollapsed: boolean;@@ -189,6 +199,7 @@ export default function ChatComposer({onChangeQuizConfig: (next: DeepQuestionFormConfig) => void;onUploadQuizPdf: (file: File | null) => void;onChangeMathAnimatorConfig: (next: MathAnimatorFormConfig) => void;+ onChangeVisualizeConfig: (next: VisualizeFormConfig) => void;onChangeResearchConfig: (next: DeepResearchFormConfig) => void;onToggleResearchCollapsed: () => void;}) {@@ -293,7 +304,9 @@ export default function ChatComposer({placeholder={isMathAnimatorMode? t("Describe the math animation or storyboard you want...")- : t("How can I help you today?")+ : isVisualizeMode+ ? t("Describe the chart or diagram you want to visualize...")+ : t("How can I help you today?")}className="w-full resize-none overflow-hidden bg-transparent text-[15px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"style={{ transition: "height 0.15s ease-out", minHeight: 28 }}@@ -464,7 +477,7 @@ export default function ChatComposer({</div></div>- {(isQuizMode || isMathAnimatorMode || isResearchMode) && (+ {(isQuizMode || isMathAnimatorMode || isVisualizeMode || isResearchMode) && (<div className="border-t border-[var(--border)]/15">{isQuizMode ? (<QuizConfigPanel@@ -478,6 +491,11 @@ export default function ChatComposer({value={mathAnimatorConfig}onChange={onChangeMathAnimatorConfig}/>+ ) : isVisualizeMode ? (+ <VisualizeConfigPanel+ value={visualizeConfig}+ onChange={onChangeVisualizeConfig}+ />) : (<ResearchConfigPanelvalue={researchConfig}diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsxindex 8cbb3b302..45701f0d9 100644--- a/web/components/chat/home/ChatMessages.tsx+++ b/web/components/chat/home/ChatMessages.tsx@@ -20,6 +20,7 @@ import AssistantResponse from "@/components/common/AssistantResponse";import type { MessageRequestSnapshot } from "@/context/UnifiedChatContext";import { extractMathAnimatorResult } from "@/lib/math-animator-types";import { extractQuizQuestions } from "@/lib/quiz-types";+import { extractVisualizeResult } from "@/lib/visualize-types";import type { StreamEvent } from "@/lib/unified-ws";import { hasVisibleMarkdownContent } from "@/lib/markdown-display";import { CallTracePanel } from "./TracePanels";@@ -33,6 +34,10 @@ const ResearchOutlineEditor = dynamic(() => import("@/components/research/ResearchOutlineEditor"),{ ssr: false },);+const VisualizationViewer = dynamic(+ () => import("@/components/visualize/VisualizationViewer"),+ { ssr: false },+);interface ChatMessageItem {role: "user" | "assistant" | "system";@@ -59,6 +64,7 @@ function getModeBadgeLabel(capability?: string | null) {if (capability === "deep_question") return "Quiz Generation";if (capability === "deep_research") return "Deep Research";if (capability === "math_animator") return "Math Animator";+ if (capability === "visualize") return "Visualize";return capability;}@@ -108,6 +114,11 @@ const AssistantMessage = memo(function AssistantMessage({return extractMathAnimatorResult(resultEvent.metadata);}, [msg.capability, resultEvent]);+ const visualizeResult = useMemo(() => {+ if (msg.capability !== "visualize" || !resultEvent) return null;+ return extractVisualizeResult(resultEvent.metadata);+ }, [msg.capability, resultEvent]);+return (<>{hasCallTrace ? (@@ -122,6 +133,8 @@ const AssistantMessage = memo(function AssistantMessage({/>) : mathAnimatorResult ? (<MathAnimatorViewer result={mathAnimatorResult} />+ ) : visualizeResult ? (+ <VisualizationViewer result={visualizeResult} />) : quizQuestions && quizQuestions.length > 0 ? (<QuizViewer questions={quizQuestions} sessionId={sessionId} language={language} />) : (diff --git a/web/components/visualize/VisualizationViewer.tsx b/web/components/visualize/VisualizationViewer.tsxnew file mode 100644index 000000000..987e68f5b--- /dev/null+++ b/web/components/visualize/VisualizationViewer.tsx@@ -0,0 +1,180 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import { Code2, Copy, Check } from "lucide-react";+import { useTranslation } from "react-i18next";+import type { VisualizeResult } from "@/lib/visualize-types";++function ChartJsRenderer({ config }: { config: string }) {+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const chartRef = useRef<unknown>(null);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;++ async function render() {+ if (!canvasRef.current) return;++ try {+ const ChartModule = await import("chart.js/auto");+ const Chart = ChartModule.default;++ if (chartRef.current) {+ (chartRef.current as InstanceType<typeof Chart>).destroy();+ chartRef.current = null;+ }++ // eslint-disable-next-line no-new-func+ const parsedConfig = new Function(`"use strict"; return (${config});`)();++ if (cancelled) return;++ chartRef.current = new Chart(canvasRef.current, parsedConfig);+ setError(null);+ } catch (err) {+ if (!cancelled) {+ setError(err instanceof Error ? err.message : "Failed to render chart");+ }+ }+ }++ void render();++ return () => {+ cancelled = true;+ if (chartRef.current) {+ (chartRef.current as { destroy: () => void }).destroy();+ chartRef.current = null;+ }+ };+ }, [config]);++ if (error) {+ return (+ <div className="rounded-lg border border-red-200 bg-red-50 p-4 dark:border-red-900/60 dark:bg-red-950/30">+ <p className="text-sm font-medium text-red-600 dark:text-red-400">+ Chart rendering error+ </p>+ <pre className="mt-2 whitespace-pre-wrap text-xs text-red-500">{error}</pre>+ </div>+ );+ }++ return (+ <div className="relative w-full" style={{ maxHeight: 480 }}>+ <canvas ref={canvasRef} />+ </div>+ );+}++function SvgRenderer({ svg }: { svg: string }) {+ const containerRef = useRef<HTMLDivElement>(null);+ const [error, setError] = useState<string | null>(null);++ const sanitizedSvg = useMemo(() => {+ const trimmed = svg.trim();+ if (!trimmed.startsWith("<svg")) {+ setError("Invalid SVG: does not start with <svg");+ return "";+ }+ setError(null);+ return trimmed;+ }, [svg]);++ if (error) {+ return (+ <div className="rounded-lg border border-red-200 bg-red-50 p-4 dark:border-red-900/60 dark:bg-red-950/30">+ <p className="text-sm font-medium text-red-600 dark:text-red-400">+ SVG rendering error+ </p>+ <pre className="mt-2 whitespace-pre-wrap text-xs text-red-500">{error}</pre>+ </div>+ );+ }++ return (+ <div+ ref={containerRef}+ className="flex justify-center overflow-x-auto"+ dangerouslySetInnerHTML={{ __html: sanitizedSvg }}+ />+ );+}++export default function VisualizationViewer({+ result,+}: {+ result: VisualizeResult;+}) {+ const { t } = useTranslation();+ const [showCode, setShowCode] = useState(false);+ const [copied, setCopied] = useState(false);++ const handleCopy = async () => {+ try {+ await navigator.clipboard.writeText(result.code.content);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ } catch {+ /* clipboard API may be unavailable */+ }+ };++ return (+ <div className="space-y-3">+ {/* Visualization area */}+ <div className="overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--background)] p-4">+ {result.render_type === "svg" ? (+ <SvgRenderer svg={result.code.content} />+ ) : (+ <ChartJsRenderer config={result.code.content} />+ )}+ </div>++ {/* Toolbar */}+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={() => setShowCode((prev) => !prev)}+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"+ >+ <Code2 size={12} strokeWidth={1.8} />+ {showCode ? t("Hide code") : t("Show code")}+ </button>++ <button+ type="button"+ onClick={handleCopy}+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"+ >+ {copied ? <Check size={12} strokeWidth={1.8} /> : <Copy size={12} strokeWidth={1.8} />}+ {copied ? t("Copied") : t("Copy code")}+ </button>++ <span className="ml-auto text-[10px] uppercase tracking-wider text-[var(--muted-foreground)]/50">+ {result.render_type === "svg" ? "SVG" : `Chart.js · ${result.analysis.chart_type || "chart"}`}+ </span>+ </div>++ {/* Code panel */}+ {showCode && (+ <div className="overflow-hidden rounded-xl border border-[var(--border)] bg-[#1f2937]">+ <div className="border-b border-white/10 px-3 py-2 text-[11px] font-medium uppercase tracking-wider text-[#9ca3af]">+ {result.code.language}+ </div>+ <pre className="max-h-80 overflow-auto p-4 text-[13px] leading-relaxed text-[#d1d5db]">+ <code>{result.code.content}</code>+ </pre>+ </div>+ )}++ {/* Review notes */}+ {result.review.changed && result.review.review_notes && (+ <p className="text-[11px] text-[var(--muted-foreground)]">+ {t("Review")}: {result.review.review_notes}+ </p>+ )}+ </div>+ );+}diff --git a/web/components/visualize/VisualizeConfigPanel.tsx b/web/components/visualize/VisualizeConfigPanel.tsxnew file mode 100644index 000000000..5de7baa10--- /dev/null+++ b/web/components/visualize/VisualizeConfigPanel.tsx@@ -0,0 +1,35 @@+"use client";++import { useTranslation } from "react-i18next";+import type { VisualizeFormConfig } from "@/lib/visualize-types";+import { Field, INPUT_CLS } from "@/components/chat/home/composer-field";++interface VisualizeConfigPanelProps {+ value: VisualizeFormConfig;+ onChange: (next: VisualizeFormConfig) => void;+}++export default function VisualizeConfigPanel({+ value,+ onChange,+}: VisualizeConfigPanelProps) {+ const { t } = useTranslation();++ return (+ <div className="flex flex-wrap items-end gap-x-3 gap-y-2 px-3.5 py-2.5">+ <Field label="Render Mode" width="w-[120px]">+ <select+ value={value.render_mode}+ onChange={(e) =>+ onChange({ ...value, render_mode: e.target.value as VisualizeFormConfig["render_mode"] })+ }+ className={`${INPUT_CLS} w-full`}+ >+ <option value="auto">{t("Auto")}</option>+ <option value="chartjs">{t("Chart.js")}</option>+ <option value="svg">{t("SVG")}</option>+ </select>+ </Field>+ </div>+ );+}diff --git a/web/lib/visualize-types.ts b/web/lib/visualize-types.tsnew file mode 100644index 000000000..ba6a3b411--- /dev/null+++ b/web/lib/visualize-types.ts@@ -0,0 +1,78 @@+export type VisualizeRenderType = "svg" | "chartjs";+export type VisualizeRenderMode = "auto" | "svg" | "chartjs";++export interface VisualizeFormConfig {+ render_mode: VisualizeRenderMode;+}++export const DEFAULT_VISUALIZE_CONFIG: VisualizeFormConfig = {+ render_mode: "auto",+};++export function buildVisualizeWSConfig(+ cfg: VisualizeFormConfig,+): Record<string, unknown> {+ return { render_mode: cfg.render_mode };+}++export interface VisualizeResult {+ response: string;+ render_type: VisualizeRenderType;+ code: {+ language: string;+ content: string;+ };+ analysis: {+ render_type: string;+ description: string;+ data_description: string;+ chart_type: string;+ visual_elements: string[];+ rationale: string;+ };+ review: {+ optimized_code: string;+ changed: boolean;+ review_notes: string;+ };+}++export function extractVisualizeResult(+ resultMetadata: Record<string, unknown> | undefined,+): VisualizeResult | null {+ if (!resultMetadata) return null;++ const renderType = resultMetadata.render_type;+ if (renderType !== "svg" && renderType !== "chartjs") return null;++ const codeRaw =+ resultMetadata.code && typeof resultMetadata.code === "object"+ ? (resultMetadata.code as Record<string, unknown>)+ : {};++ if (!codeRaw.content) return null;++ return {+ response: String(resultMetadata.response ?? ""),+ render_type: renderType,+ code: {+ language: String(codeRaw.language ?? ""),+ content: String(codeRaw.content ?? ""),+ },+ analysis:+ resultMetadata.analysis && typeof resultMetadata.analysis === "object"+ ? (resultMetadata.analysis as VisualizeResult["analysis"])+ : {+ render_type: renderType,+ description: "",+ data_description: "",+ chart_type: "",+ visual_elements: [],+ rationale: "",+ },+ review:+ resultMetadata.review && typeof resultMetadata.review === "object"+ ? (resultMetadata.review as VisualizeResult["review"])+ : { optimized_code: "", changed: false, review_notes: "" },+ };+}diff --git a/web/package-lock.json b/web/package-lock.jsonindex f13b21d55..6cbf89e4a 100644--- a/web/package-lock.json+++ b/web/package-lock.json@@ -8,6 +8,7 @@"name": "opentutor-web","version": "1.0.0","dependencies": {+ "chart.js": "^4.5.1","clsx": "^2.1.1","cytoscape": "^3.33.1","framer-motion": "^12.24.0",@@ -18,6 +19,7 @@"mermaid": "^11.12.2","next": "^16.1.1","react": "^19.0.0",+ "react-chartjs-2": "^5.3.1","react-dom": "^19.0.0","react-i18next": "^16.5.3","react-markdown": "^10.1.0",@@ -1136,6 +1138,12 @@"@jridgewell/sourcemap-codec": "^1.4.14"}},+ "node_modules/@kurkle/color": {+ "version": "0.3.4",+ "resolved": "https://registry.npmjs.org/@kurkle/color/-/color-0.3.4.tgz",+ "integrity": "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==",+ "license": "MIT"+ },"node_modules/@mermaid-js/parser": {"version": "0.6.3","resolved": "https://registry.npmjs.org/@mermaid-js/parser/-/parser-0.6.3.tgz",@@ -2968,6 +2976,18 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/chart.js": {+ "version": "4.5.1",+ "resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz",+ "integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==",+ "license": "MIT",+ "dependencies": {+ "@kurkle/color": "^0.3.0"+ },+ "engines": {+ "pnpm": ">=8"+ }+ },"node_modules/chevrotain": {"version": "11.0.3","resolved": "https://registry.npmjs.org/chevrotain/-/chevrotain-11.0.3.tgz",@@ -8168,6 +8188,16 @@"node": ">=0.10.0"}},+ "node_modules/react-chartjs-2": {+ "version": "5.3.1",+ "resolved": "https://registry.npmjs.org/react-chartjs-2/-/react-chartjs-2-5.3.1.tgz",+ "integrity": "sha512-h5IPXKg9EXpjoBzUfyWJvllMjG2mQ4EiuHQFhms/AjUm0XSZHhyRy2xVmLXHKrtcdrPO4mnGqRtYoD0vp95A0A==",+ "license": "MIT",+ "peerDependencies": {+ "chart.js": "^4.1.1",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },"node_modules/react-dom": {"version": "19.2.3","resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz",diff --git a/web/package.json b/web/package.jsonindex ac7e37740..3f149f78e 100644--- a/web/package.json+++ b/web/package.json@@ -19,6 +19,7 @@"audit:report": "playwright show-report"},"dependencies": {+ "chart.js": "^4.5.1","clsx": "^2.1.1","cytoscape": "^3.33.1","framer-motion": "^12.24.0",@@ -29,6 +30,7 @@"mermaid": "^11.12.2","next": "^16.1.1","react": "^19.0.0",+ "react-chartjs-2": "^5.3.1","react-dom": "^19.0.0","react-i18next": "^16.5.3","react-markdown": "^10.1.0",