DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(visualize): stop an invented enum value from aborting generation (#748)
王子天75c8ea9270c1
diff --git a/deeptutor/agents/visualize/models.py b/deeptutor/agents/visualize/models.pyindex 99112447d..8afb3bd40 100644--- a/deeptutor/agents/visualize/models.py+++ b/deeptutor/agents/visualize/models.py@@ -2,22 +2,39 @@from __future__ import annotations-from typing import Literal+import logging+from typing import Any, Literal, get_args-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, model_validator++logger = logging.getLogger(__name__)++RenderType = Literal[+ "svg",+ "chartjs",+ "mermaid",+ "html",+ "manim_video",+ "manim_image",+]++VisualGenre = Literal[+ "",+ "flowchart",+ "structural",+ "illustrative",+ "chart",+ "stepper",+ "interactive",+ "mockup",+ "art",+]class VisualizationAnalysis(BaseModel):"""Output of the analysis stage."""- render_type: Literal[- "svg",- "chartjs",- "mermaid",- "html",- "manim_video",- "manim_image",- ] = Field(+ render_type: RenderType = Field(description=("Render output: raw SVG, a Chart.js configuration, a Mermaid ""diagram, a self-contained interactive HTML page, or a Manim "@@ -49,17 +66,7 @@ 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(+ visual_genre: VisualGenre = Field(default="",description=("Teaching-oriented sub-type that drives the code-generation style, "@@ -72,6 +79,29 @@ class VisualizationAnalysis(BaseModel):),)+ @model_validator(mode="before")+ @classmethod+ def _drop_off_enum_values(cls, data: Any) -> Any:+ """Degrade an invented enum value instead of failing the whole render.++ Models regularly answer with a genre or render type that is not in the+ prompt's list ("simulation", "diagram"). Both fields are enums, so+ validation used to abort generation over a label that no downstream+ stage strictly needs — the genre only selects a code-generation style,+ and svg is the universal fallback render.+ """+ if not isinstance(data, dict):+ return data+ genre = data.get("visual_genre")+ if genre is not None and genre not in get_args(VisualGenre):+ logger.warning("Discarding unknown visual_genre %r", genre)+ data = {**data, "visual_genre": ""}+ render_type = data.get("render_type")+ if render_type is not None and render_type not in get_args(RenderType):+ logger.warning("Falling back to svg for unknown render_type %r", render_type)+ data = {**data, "render_type": "svg"}+ return data+class ReviewResult(BaseModel):"""Output of the review / optimization stage."""diff --git a/deeptutor/agents/visualize/prompts/en/analysis_agent.yaml b/deeptutor/agents/visualize/prompts/en/analysis_agent.yamlindex 9ccdfa8fa..0f17ca8d9 100644--- a/deeptutor/agents/visualize/prompts/en/analysis_agent.yaml+++ b/deeptutor/agents/visualize/prompts/en/analysis_agent.yaml@@ -87,7 +87,7 @@ 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",+ "visual_genre": "the genre that best fits this {render_type} and the user's intent. Must be one of: flowchart | structural | illustrative | chart | stepper | interactive | mockup | art, or empty string if none fit","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 (interactive / animation / walkthrough / quiz) if html; otherwise empty string",diff --git a/deeptutor/agents/visualize/prompts/zh/analysis_agent.yaml b/deeptutor/agents/visualize/prompts/zh/analysis_agent.yamlindex 11e2cecb6..c9356d6b9 100644--- a/deeptutor/agents/visualize/prompts/zh/analysis_agent.yaml+++ b/deeptutor/agents/visualize/prompts/zh/analysis_agent.yaml@@ -78,7 +78,7 @@ user_template_fixed: |返回 JSON:{{"render_type": "{render_type}",- "visual_genre": "最贴合这个 {render_type} 和用户意图的 genre,或空字符串",+ "visual_genre": "最贴合这个 {render_type} 和用户意图的 genre。必须是以下之一:flowchart / structural / illustrative / chart / stepper / interactive / mockup / art,没有合适的就留空","description": "可视化应展示的内容的高层描述","data_description": "要可视化的数据或元素的描述","chart_type": "如果是 chartjs 填 Chart.js 图表类型;如果是 mermaid 填 Mermaid 图表类型;如果是 html 填交互形式(interactive / animation / walkthrough / quiz);否则为空字符串",diff --git a/tests/agents/visualize/test_analysis_fallback.py b/tests/agents/visualize/test_analysis_fallback.pynew file mode 100644index 000000000..5f97cf74e--- /dev/null+++ b/tests/agents/visualize/test_analysis_fallback.py@@ -0,0 +1,177 @@+"""The analysis stage must not crash when the LLM invents an enum value —+an unknown visual_genre degrades to "" and an unknown render_type to svg."""++from __future__ import annotations++import json+from typing import Any++import pytest++from deeptutor.agents.base_agent import BaseAgent+from deeptutor.agents.visualize.agents.analysis_agent import AnalysisAgent+from deeptutor.agents.visualize.models import VisualizationAnalysis+++def _llm_reply(visual_genre: str, render_type: str = "svg") -> str:+ """A well-formed analysis JSON with caller-controlled enum fields."""+ return json.dumps(+ {+ "render_type": render_type,+ "description": "a diagram",+ "data_description": "",+ "chart_type": "",+ "visual_elements": ["box"],+ "rationale": "test",+ "visual_genre": visual_genre,+ }+ )+++# Config-free prompt stubs — just enough for get_prompt() to return truthy values.+_FIXED_PROMPTS = {+ "system_fixed": "You are a visualization analyst.",+ "user_template_fixed": "Return JSON: {user_input} {history_context} {render_type}",+}++_AUTO_PROMPTS = {+ "system": "You are a visualization analyst.",+ "user_template": "Return JSON: {user_input} {history_context}",+}+++def _install_agent_stubs(+ monkeypatch: pytest.MonkeyPatch,+ prompts: dict[str, str],+ llm_reply: str,+) -> None:+ """Mock the three things ``AnalysisAgent`` needs for a local test run:++ 1. ``get_agent_params`` — returns a dummy dict (avoids agents.yaml).+ 2. ``self.prompts`` — pre-populated after ``__init__`` finishes.+ 3. ``BaseAgent.call_llm`` — returns *llm_reply*.+ """+ # (1) Avoid FileNotFoundError in BaseAgent.__init__+ monkeypatch.setattr(+ "deeptutor.agents.base_agent.get_agent_params",+ lambda _module_name: {},+ )++ # (2) After real __init__ runs, overwrite prompts with our stubs.+ real_init = AnalysisAgent.__init__++ def _patched_init(self: AnalysisAgent, **kwargs: Any) -> None:+ real_init(self, **kwargs)+ self.prompts = dict(prompts)++ monkeypatch.setattr(AnalysisAgent, "__init__", _patched_init)++ # (3) Replace the LLM call.+ async def _fake_call(self: BaseAgent, **_kwargs: Any) -> str:+ return llm_reply++ monkeypatch.setattr(BaseAgent, "call_llm", _fake_call)+++# ── tests ───────────────────────────────────────────────────────────────────+++async def test_invalid_visual_genre_falls_back_to_empty(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The agent should return visual_genre="" instead of crashing."""+ _install_agent_stubs(monkeypatch, _FIXED_PROMPTS, _llm_reply("simulation"))++ result = await AnalysisAgent().process(+ user_input="explain how a CPU works",+ history_context="",+ render_mode="svg",+ )++ assert isinstance(result, VisualizationAnalysis)+ assert result.visual_genre == ""+++async def test_valid_visual_genre_passes_through(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Valid values should not be touched by the fallback."""+ _install_agent_stubs(monkeypatch, _FIXED_PROMPTS, _llm_reply("interactive"))++ result = await AnalysisAgent().process(+ user_input="interactive demo of a pendulum",+ history_context="",+ render_mode="html",+ )++ assert result.visual_genre == "interactive"+++async def test_fixed_render_mode_preserves_render_type(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """When visual_genre is illegal, fixed render_type is not affected."""+ _install_agent_stubs(monkeypatch, _FIXED_PROMPTS, _llm_reply("simulation"))++ result = await AnalysisAgent().process(+ user_input="draw a flowchart",+ history_context="",+ render_mode="svg",+ )++ assert result.render_type == "svg"+++async def test_auto_mode_survives_bad_genre(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The fallback works in auto mode (the default) too."""+ _install_agent_stubs(monkeypatch, _AUTO_PROMPTS, _llm_reply("simulation"))++ result = await AnalysisAgent().process(+ user_input="help me understand neural networks",+ history_context="",+ )++ assert isinstance(result, VisualizationAnalysis)+ assert result.visual_genre == ""+++async def test_auto_mode_survives_bad_render_type(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """An invented render_type is the same failure — it has no default, so in+ auto mode a value like "diagram" used to abort the whole render."""+ _install_agent_stubs(monkeypatch, _AUTO_PROMPTS, _llm_reply("flowchart", render_type="diagram"))++ result = await AnalysisAgent().process(+ user_input="show me the request lifecycle",+ history_context="",+ )++ assert result.render_type == "svg"+ assert result.visual_genre == "flowchart"+++def test_off_enum_values_are_coerced_on_the_model() -> None:+ """The coercion lives on the model, so every parse site inherits it."""+ result = VisualizationAnalysis.model_validate(+ {"render_type": "diagram", "visual_genre": "simulation"}+ )++ assert result.render_type == "svg"+ assert result.visual_genre == ""+++def test_known_enum_values_are_left_alone() -> None:+ result = VisualizationAnalysis.model_validate(+ {"render_type": "mermaid", "visual_genre": "structural"}+ )++ assert result.render_type == "mermaid"+ assert result.visual_genre == "structural"