DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(geogebra): repair image analysis that crashed before any model call (#1362)
Albertanda08963e29ab0b
diff --git a/deeptutor/agents/vision_solver/vision_solver_agent.py b/deeptutor/agents/vision_solver/vision_solver_agent.pyindex c34e39c51..1da491711 100644--- a/deeptutor/agents/vision_solver/vision_solver_agent.py+++ b/deeptutor/agents/vision_solver/vision_solver_agent.py@@ -136,18 +136,34 @@ class VisionSolverAgent(BaseAgent):messages=messages,temperature=temperature,model=self.vision_model or self.get_model(),- verbose=False,):chunks.append(chunk)return "".join(chunks)@staticmethoddef _extract_json(response: str) -> dict[str, Any]:- """Pull the JSON object out of an LLM response (markdown-fenced or raw)."""- matches = re.findall(r"```(?:json)?\s*([\s\S]*?)\s*```", response)- json_str = matches[0] if matches else response+ """Pull the JSON object out of an LLM response.++ Handles the shapes real models produce:+ * a ```json fenced block (possibly after a ``<think>`` preamble);+ * bare JSON in the tail of a reasoning-model answer (``<think>``+ blocks are stripped first — e.g. Qwen3-VL-*-Thinking emits a long+ thinking preamble before the final JSON object);+ * prose appended after the object (start at the first object brace+ and drop everything after the final closing brace);+ * inline comments and trailing commas, common model slips.+ """+ text = re.sub(r"<think>[\s\S]*?</think>", "", response)+ matches = re.findall(r"```(?:json)?\s*([\s\S]*?)\s*```", text)+ json_str = matches[-1] if matches else textjson_str = re.sub(r"//.*?$", "", json_str, flags=re.MULTILINE)json_str = re.sub(r"/\*.*?\*/", "", json_str, flags=re.DOTALL)+ start = json_str.find("{")+ if start > 0:+ json_str = json_str[start:]+ end = json_str.rfind("}")+ if end >= 0 and end < len(json_str) - 1:+ json_str = json_str[: end + 1]try:return json.loads(json_str)except json.JSONDecodeError:diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.pyindex 984a042c1..cee030edd 100644--- a/deeptutor/tools/builtin/__init__.py+++ b/deeptutor/tools/builtin/__init__.py@@ -382,6 +382,11 @@ class PaperSearchToolWrapper(_PromptHintsMixin, BaseTool):class GeoGebraAnalysisTool(_PromptHintsMixin, BaseTool):"""Analyze a math-problem image and generate GeoGebra visualization commands."""+ # Ceiling on a single vision analysis call (see the timeout branch in+ # ``execute``). Reasoning VL models legitimately take minutes on hard+ # figures; this only guards against provider stalls.+ _VISION_ANALYSIS_TIMEOUT_S = 240+def get_definition(self) -> ToolDefinition:return ToolDefinition(name="geogebra_analysis",@@ -437,9 +442,29 @@ class GeoGebraAnalysisTool(_PromptHintsMixin, BaseTool):)try:- result = await agent.process(- question_text=question,- image_base64=image_base64,+ # Bound the vision call: reasoning models (e.g. Qwen3-VL-*-Thinking)+ # can take minutes on hard figures, but an unbounded await would+ # hang the whole turn if the provider stalls. 240s covers long+ # thinking while still failing loudly instead of silently.+ result = await asyncio.wait_for(+ agent.process(+ question_text=question,+ image_base64=image_base64,+ ),+ timeout=self._VISION_ANALYSIS_TIMEOUT_S,+ )+ except asyncio.TimeoutError:+ logger.warning(+ "geogebra analysis timed out after %ss",+ self._VISION_ANALYSIS_TIMEOUT_S,+ )+ return ToolResult(+ content=(+ f"Vision analysis timed out after {self._VISION_ANALYSIS_TIMEOUT_S}s "+ "(the multimodal model is slow or unresponsive). "+ "Tell the user to retry, or describe the figure in text."+ ),+ success=False,)except Exception as exc:logger.exception("GeoGebra analysis pipeline failed")diff --git a/tests/agents/vision_solver/__init__.py b/tests/agents/vision_solver/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/agents/vision_solver/test_vision_solver_agent.py b/tests/agents/vision_solver/test_vision_solver_agent.pynew file mode 100644index 000000000..84ebb272f--- /dev/null+++ b/tests/agents/vision_solver/test_vision_solver_agent.py@@ -0,0 +1,101 @@+"""Regression tests for the geogebra image-analysis agent.++Covers the two defects fixed together:++* ``_call_vision_llm`` passed a nonexistent ``verbose=`` kwarg to+ ``stream_llm``, so *every* image analysis raised ``TypeError`` before any+ model call — the tool was completely broken.+* ``_extract_json`` could not handle the output shapes reasoning VL models+ actually produce (``<think>`` preambles, prose appended after the object),+ so even a successful model call frequently ended in a parse failure.+"""++from __future__ import annotations++import asyncio+import json+from typing import Any++import pytest++from deeptutor.agents.vision_solver.vision_solver_agent import VisionSolverAgent+++class TestExtractJson:+ @pytest.mark.parametrize(+ "response",+ [+ # Plain object.+ '{"commands": [{"command": "A = (1, 2)"}]}',+ # Markdown-fenced block with prose around it.+ "Here is the analysis:\n```json\n"+ '{"commands": [{"command": "Polygon(A,B,C)"}]}\n```\nThat is all.',+ # Reasoning-model preamble followed by a fenced block.+ "<thinking>Let me look at the figure.</thinking>\n<response>\n```json\n"+ '{"commands": [{"command": "A=(0,0)"}, {"command": "B=(4,0)"}]}\n```\n'+ "</response>",+ # Reasoning-model preamble followed by bare tail JSON.+ "<thinking>This is a parabola.</thinking>\n<response>\n"+ '{"commands": [{"command": "f(x)=x^2"}]}\n</response>',+ # Prose appended after the JSON object.+ 'I analyzed it:\n{"commands": [{"command": "Circle((0,0),3)"}]} '+ "and that is the answer.",+ # Inline comments (the original parser tolerated them).+ '{\n// highlight the vertex\n"commands": [{"command": "A = (-3, 0)"}]\n}',+ # Block comments.+ '{\n/* highlight */\n"commands": [{"command": "A = (-3, 0)"}]\n}',+ # Trailing commas — the last-resort path.+ '```json\n{"commands": [{"command": "Line(A,B)",},]}\n```',+ ],+ )+ def test_extracts_commands(self, response: str) -> None:+ data = VisionSolverAgent._extract_json(response)+ assert isinstance(data, dict)+ assert data["commands"]++ def test_prefers_last_fenced_block(self) -> None:+ response = (+ '```json\n{"commands": [{"command": "A = (1, 1)"}]}\n```\n'+ "Wait, the correct figure is:\n```json\n"+ '{"commands": [{"command": "B = (2, 2)"}]}\n```'+ )+ data = VisionSolverAgent._extract_json(response)+ assert data["commands"][0]["command"] == "B = (2, 2)"++ def test_rejects_output_without_json_object(self) -> None:+ with pytest.raises(json.JSONDecodeError):+ VisionSolverAgent._extract_json("I cannot see any figure in this image.")+++class TestCallVisionLlmKwargs:+ """Regression: ``_call_vision_llm`` must not pass ``verbose=`` to stream_llm."""++ def test_stream_llm_receives_no_verbose_kwarg(self) -> None:+ agent = VisionSolverAgent.__new__(VisionSolverAgent)+ agent.vision_model = None+ agent.get_model = lambda: "main-model" # type: ignore[method-assign]++ captured: dict[str, Any] = {}++ async def fake_stream_llm(**kwargs: Any):+ captured.update(kwargs)+ if False: # pragma: no cover — makes this an async generator+ yield ""++ agent.stream_llm = fake_stream_llm # type: ignore[method-assign]++ async def run() -> None:+ await agent._call_vision_llm(+ "analyze",+ "data:image/png;base64,AAAA",+ )++ asyncio.run(run())++ # The crash: stream_llm() has no ``verbose`` parameter, so passing it+ # raised TypeError before any model call. Guard against regression.+ assert "verbose" not in captured+ # The multimodal message shape must still be built and routed.+ assert captured["model"] == "main-model"+ content = captured["messages"][0]["content"]+ assert any(part.get("type") == "image_url" for part in content)