diff --git a/deeptutor/agents/question/pipeline.py b/deeptutor/agents/question/pipeline.py index 2d4cf7c1d..b3fad995b 100644 --- a/deeptutor/agents/question/pipeline.py +++ b/deeptutor/agents/question/pipeline.py @@ -26,7 +26,7 @@ to :mod:`deeptutor.runtime.agentic` and the shared tool-composition policy. from __future__ import annotations from collections.abc import Awaitable -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from enum import StrEnum import json import logging @@ -307,6 +307,31 @@ def _format_per_type_counts(per_type_counts: dict[str, int]) -> str: return ", ".join(f"{t}={n}" for t, n in per_type_counts.items()) +def _apply_per_type_counts( + templates: list[QuizTemplate], per_type_counts: dict[str, int] +) -> list[QuizTemplate]: + """Retype planned templates so the quiz matches the requested type mix. + + The planner prompt asks for the exact per-type counts, but a model can + still return, say, five ``choice`` templates for ``choice=3, + fill_in_blank=2``. Templates keep their type while that type has quota + left; the rest are reassigned, in order, to the types still short. + Topics, order and difficulty are unchanged. + """ + remaining = dict(per_type_counts) + surplus: list[int] = [] + for index, template in enumerate(templates): + if remaining.get(template.question_type, 0) > 0: + remaining[template.question_type] -= 1 + else: + surplus.append(index) + missing = [qtype for qtype, count in remaining.items() for _ in range(count)] + adjusted = list(templates) + for index, qtype in zip(surplus, missing): + adjusted[index] = replace(adjusted[index], question_type=qtype) + return adjusted + + # --------------------------------------------------------------------------- # Data shapes # --------------------------------------------------------------------------- @@ -800,6 +825,7 @@ class QuestionPipeline: requested=num_questions, allowed_types=allowed_types, target_difficulty=difficulty, + per_type_counts=per_type_counts, ) if not plan.templates: # The retry above already gave a starved planner its second pass. @@ -830,6 +856,7 @@ class QuestionPipeline: requested: int, allowed_types: list[str], target_difficulty: str, + per_type_counts: dict[str, int] | None = None, ) -> QuizPlan: data = parse_json_response(raw, logger_instance=logger, fallback={}) if not isinstance(data, dict) or not data: @@ -886,6 +913,8 @@ class QuestionPipeline: ) if len(templates) >= requested: break + if per_type_counts: + templates = _apply_per_type_counts(templates, per_type_counts) return QuizPlan(analysis=analysis, templates=templates) # ------------------------------------------------------------------ diff --git a/tests/agents/question/test_pipeline.py b/tests/agents/question/test_pipeline.py index 2a2bcabae..d83df34ed 100644 --- a/tests/agents/question/test_pipeline.py +++ b/tests/agents/question/test_pipeline.py @@ -276,6 +276,56 @@ def test_parse_plan_truncates_to_requested() -> None: assert len(plan.templates) == 2 +def test_parse_plan_enforces_per_type_counts() -> None: + """A planner that ignores the per-type targets must not decide the quiz mix.""" + pipeline = _make_pipeline() + raw = json.dumps( + { + "templates": [ + {"topic": f"T{i}", "question_type": "choice", "difficulty": "easy"} + for i in range(5) + ] + } + ) + plan = pipeline._parse_plan( + raw, + requested=5, + allowed_types=["choice", "fill_in_blank"], + target_difficulty="", + per_type_counts={"choice": 3, "fill_in_blank": 2}, + ) + assert [t.question_type for t in plan.templates] == [ + "choice", + "choice", + "choice", + "fill_in_blank", + "fill_in_blank", + ] + assert [t.topic for t in plan.templates] == [f"T{i}" for i in range(5)] + assert all(t.difficulty == "easy" for t in plan.templates) + + +def test_parse_plan_keeps_types_that_already_match_counts() -> None: + pipeline = _make_pipeline() + raw = json.dumps( + { + "templates": [ + {"topic": "A", "question_type": "coding"}, + {"topic": "B", "question_type": "choice"}, + {"topic": "C", "question_type": "choice"}, + ] + } + ) + plan = pipeline._parse_plan( + raw, + requested=3, + allowed_types=["choice", "coding"], + target_difficulty="", + per_type_counts={"choice": 2, "coding": 1}, + ) + assert [t.question_type for t in plan.templates] == ["coding", "choice", "choice"] + + # --------------------------------------------------------------------------- # Payload normalization + issue collection # --------------------------------------------------------------------------- @@ -1362,6 +1412,35 @@ def test_plan_that_answers_first_time_is_not_asked_twice() -> None: assert len(calls) == 1 +def test_plan_holds_the_planner_to_the_requested_per_type_counts() -> None: + """The quiz panel's per-type counts reach ``_plan``; the plan must honour them.""" + pipeline = _make_pipeline() + raw = json.dumps( + {"templates": [{"topic": f"Topic {i}", "question_type": "choice"} for i in range(1, 6)]} + ) + + async def _fake_step(**_kwargs: Any) -> LabeledStepResult: + return LabeledStepResult(label="PLAN", text=raw) + + with patch.object(QuestionPipeline, "_run_labeled_step", side_effect=_fake_step): + plan = asyncio.run( + pipeline._plan( + user_message="quiz me", + exploration_trace="", + num_questions=5, + difficulty="", + allowed_types=["choice", "fill_in_blank"], + per_type_counts={"choice": 3, "fill_in_blank": 2}, + stream=_StubStreamBus(), + client=object(), + ) + ) + + types = [t.question_type for t in plan.templates] + assert types.count("choice") == 3 + assert types.count("fill_in_blank") == 2 + + def test_plan_still_empty_after_the_retry_fails_instead_of_returning_nothing() -> None: """Two starved rounds and no plan is the end of the road.