diff --git a/deeptutor/agents/math_animator/agents/visual_review_agent.py b/deeptutor/agents/math_animator/agents/visual_review_agent.py index f459df7ec..5762d9609 100644 --- a/deeptutor/agents/math_animator/agents/visual_review_agent.py +++ b/deeptutor/agents/math_animator/agents/visual_review_agent.py @@ -8,9 +8,9 @@ from deeptutor.agents.base_agent import BaseAgent from deeptutor.core.context import Attachment from deeptutor.core.trace import build_trace_metadata, new_call_id from deeptutor.services.llm import supports_vision +from deeptutor.services.llm.structured_retry import json_with_reasoning_retry from ..models import RenderResult, VisualReviewResult -from ..utils import extract_json_object class VisualReviewAgent(BaseAgent): @@ -72,27 +72,43 @@ class VisualReviewAgent(BaseAgent): {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}, ] - _chunks: list[str] = [] - async for _c in self.stream_llm( - user_prompt=user_prompt, - system_prompt=system_prompt, - messages=messages, - attachments=attachments, - response_format={"type": "json_object"}, - model=model, - stage="render_output", - trace_meta=build_trace_metadata( - call_id=new_call_id("math-visual-review"), - phase="render_output", - label="Visual quality review", - call_kind="math_visual_review", - trace_role="review", - trace_kind="llm_output", - ), - ): - _chunks.append(_c) - response = "".join(_chunks) - payload = extract_json_object(response) + + async def _run(reasoning_effort: str | None) -> str: + chunks: list[str] = [] + async for chunk in self.stream_llm( + user_prompt=user_prompt, + system_prompt=system_prompt, + messages=messages, + attachments=attachments, + response_format={"type": "json_object"}, + reasoning_effort=reasoning_effort, + model=model, + stage="render_output", + trace_meta=build_trace_metadata( + call_id=new_call_id("math-visual-review"), + phase="render_output", + label="Visual quality review", + call_kind="math_visual_review", + trace_role="review", + trace_kind="llm_output", + ), + ): + chunks.append(chunk) + return "".join(chunks) + + payload = await json_with_reasoning_retry(_run, logger_instance=self.logger) + if not payload: + # The reviewer never gave a verdict, on either attempt. Rendering + # already succeeded, and reporting ``passed=False`` here would send a + # silent model into up to four repair-and-re-render cycles, so keep + # the video and say that no review took place. Falling through to + # ``VisualReviewResult``'s defaults would claim the opposite: + # ``passed=True`` over ``reviewed_frames`` that were never looked at. + return VisualReviewResult( + passed=True, + summary="Visual review was skipped because the reviewer returned no verdict.", + reviewed_frames=0, + ) payload.setdefault("reviewed_frames", len(attachments)) return VisualReviewResult.model_validate(payload) diff --git a/tests/agents/math_animator/test_visual_review_verdict.py b/tests/agents/math_animator/test_visual_review_verdict.py new file mode 100644 index 000000000..1c0590f18 --- /dev/null +++ b/tests/agents/math_animator/test_visual_review_verdict.py @@ -0,0 +1,113 @@ +"""A visual review that never produced a verdict must not read as a passed review.""" + +from __future__ import annotations + +from collections.abc import AsyncIterator + +import pytest + +from deeptutor.agents.math_animator.agents import visual_review_agent as module +from deeptutor.agents.math_animator.agents.visual_review_agent import VisualReviewAgent +from deeptutor.agents.math_animator.models import RenderResult +from deeptutor.core.context import Attachment +from deeptutor.services.llm.reasoning_params import RETRY_REASONING_EFFORT + +_VERDICT = '{"passed": true, "summary": "Visuals are clear.", "issues": []}' +_FRAMES = 3 + + +def _agent() -> VisualReviewAgent: + agent = VisualReviewAgent() + agent.prompts = { + "system": "Review the rendered frames.", + "user_template": "{user_input} {output_mode} {reviewed_frames} {render_json} {current_code}", + } + return agent + + +async def _review( + agent: VisualReviewAgent, + replies: list[str], + monkeypatch: pytest.MonkeyPatch, +) -> tuple[object, list[dict[str, object]]]: + monkeypatch.setattr(module, "supports_vision", lambda *_args: True) + monkeypatch.setattr(agent, "get_model", lambda: "vision-model") + calls: list[dict[str, object]] = [] + + async def fake_provider(**kwargs) -> AsyncIterator[str]: + calls.append(kwargs) + yield replies[min(len(calls) - 1, len(replies) - 1)] + + monkeypatch.setattr(agent, "stream_llm", fake_provider) + result = await agent.process( + user_input="Animate a circle", + output_mode="video", + current_code="from manim import *", + render_result=RenderResult(output_mode="video"), + attachments=[ + Attachment(type="image", url=f"/frame_{index}.png") for index in range(_FRAMES) + ], + ) + return result, calls + + +@pytest.mark.asyncio +async def test_visual_review_reports_no_verdict_instead_of_a_pass( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An empty reply after the retry keeps the render but admits it went unviewed.""" + result, calls = await _review(_agent(), ["", ""], monkeypatch) + + assert [entry["reasoning_effort"] for entry in calls] == [None, RETRY_REASONING_EFFORT] + assert result.reviewed_frames == 0, "the record must not claim frames it never reviewed" + assert "skipped" in result.summary, "the report has to say why there is no verdict" + # Rendering already succeeded, so an unanswered review must not discard it. + assert result.passed is True + + +@pytest.mark.asyncio +async def test_visual_review_survives_a_reply_that_is_not_json( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Prose instead of JSON used to raise out of the render loop after a success.""" + result, calls = await _review( + _agent(), + ["The animation looks great, nothing to fix.", "The animation looks great."], + monkeypatch, + ) + + assert len(calls) == 2 + assert result.reviewed_frames == 0 + assert "skipped" in result.summary + + +@pytest.mark.asyncio +async def test_visual_review_retries_a_reasoning_only_reply( + monkeypatch: pytest.MonkeyPatch, +) -> None: + result, calls = await _review( + _agent(), + ["Let me look at each frame first.", _VERDICT], + monkeypatch, + ) + + assert [entry["reasoning_effort"] for entry in calls] == [None, RETRY_REASONING_EFFORT] + assert result.summary == "Visuals are clear." + assert result.reviewed_frames == _FRAMES + + +@pytest.mark.asyncio +async def test_failed_verdict_on_the_first_reply_is_used_without_a_retry( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """ "The reviewer found a problem" is an answer, not a missing one.""" + result, calls = await _review( + _agent(), + ['{"passed": false, "summary": "Labels overlap.", "suggested_fix": "Move them out"}'], + monkeypatch, + ) + + assert len(calls) == 1 + assert result.passed is False + assert result.suggested_fix == "Move them out" + assert result.reviewed_frames == _FRAMES