diff --git a/deeptutor/agents/math_animator/pipeline.py b/deeptutor/agents/math_animator/pipeline.py index c3263cf1c..a2007e539 100644 --- a/deeptutor/agents/math_animator/pipeline.py +++ b/deeptutor/agents/math_animator/pipeline.py @@ -7,6 +7,7 @@ import time from typing import Any, Callable from deeptutor.core.context import Attachment +from deeptutor.services.model_selection.task_agent import task_model_agent from .agents import ( CodeGeneratorAgent, @@ -61,6 +62,12 @@ class MathAnimatorPipeline: api_version=api_version, language=language, ) + # Repairs are targeted edits to a working script; the task model does them in + # seconds where a reasoning chat model can take several minutes. + self.repair_agent = ( + task_model_agent(lambda **kw: CodeGeneratorAgent(language=language, **kw)) + or self.code_agent + ) self.summary_agent = SummaryAgent( api_key=api_key, base_url=base_url, @@ -84,6 +91,7 @@ class MathAnimatorPipeline: self.analysis_agent, self.design_agent, self.code_agent, + self.repair_agent, self.summary_agent, self.visual_review_agent, ): @@ -195,7 +203,7 @@ class MathAnimatorPipeline: on_retry=on_retry, on_status=on_retry_status, review_callback=review_callback, - repair_callback=lambda current_code, error_message, attempt: self.code_agent.repair( + repair_callback=lambda current_code, error_message, attempt: self.repair_agent.repair( user_input=user_input, output_mode=request_config.output_mode, current_code=current_code, diff --git a/deeptutor/agents/video_lesson/capability.py b/deeptutor/agents/video_lesson/capability.py index 9215cb229..6e293e6e5 100644 --- a/deeptutor/agents/video_lesson/capability.py +++ b/deeptutor/agents/video_lesson/capability.py @@ -31,6 +31,7 @@ class VideoLessonCapability(TurnCapability): write_page, ) from deeptutor.services.llm.config import get_llm_config + from deeptutor.services.model_selection.task_agent import task_model_agent from deeptutor.services.path_service import get_path_service llm_config = get_llm_config() @@ -49,6 +50,15 @@ class VideoLessonCapability(TurnCapability): ) writer.set_trace_callback(self._build_trace_bridge(stream, i18n)) writer.start(user_input=context.user_message, history=history) + # Fixes edit a lesson that already exists; the fast task model does them in a + # fraction of the main model's time. Without one, the main writer fixes too. + fixer = ( + task_model_agent(lambda **kw: LessonWriterAgent(language=context.language, **kw)) + or writer + ) + if fixer is not writer: + fixer.set_trace_callback(self._build_trace_bridge(stream, i18n)) + fixer.share_conversation(writer) # npm install (first use only) overlaps the first, much longer, LLM call. runtime_ready = asyncio.create_task(ensure_runtime()) @@ -67,7 +77,7 @@ class VideoLessonCapability(TurnCapability): source=self.name, stage="code_generation", ) - draft = await writer.write(attempt=attempt) + draft = await (writer if attempt == 1 else fixer).write(attempt=attempt) timings["code_generation"] += round(time.perf_counter() - started, 3) if not draft.code: attempts.append( diff --git a/deeptutor/agents/video_lesson/lesson_writer.py b/deeptutor/agents/video_lesson/lesson_writer.py index 79cae6250..83c781e8a 100644 --- a/deeptutor/agents/video_lesson/lesson_writer.py +++ b/deeptutor/agents/video_lesson/lesson_writer.py @@ -84,6 +84,10 @@ class LessonWriterAgent(BaseAgent): user = template.format(user_input=user_input.strip(), history=history.strip() or "-") self._messages = [{"role": "system", "content": system}, {"role": "user", "content": user}] + def share_conversation(self, other: "LessonWriterAgent") -> None: + """Use ``other``'s conversation (same list), so either agent can write the next draft.""" + self._messages = other._messages + def add_feedback(self, *, previous: str, stage: str, errors: list[str]) -> None: """Keep the failed reply in the conversation and ask for a fix.""" template = self.get_prompt("retry_template") or "{stage}\n{errors}" diff --git a/deeptutor/services/model_selection/task_agent.py b/deeptutor/services/model_selection/task_agent.py new file mode 100644 index 000000000..544692279 --- /dev/null +++ b/deeptutor/services/model_selection/task_agent.py @@ -0,0 +1,52 @@ +"""Build an agent bound to the Settings task model (the fast model for small, targeted calls).""" + +from __future__ import annotations + +from typing import Any, Callable, TypeVar + +A = TypeVar("A") + + +def task_model_agent(factory: Callable[..., A]) -> A | None: + """``factory(api_key=, base_url=, api_version=)`` on the task model, at its reasoning level. + + Returns None when no task model is configured or it cannot be resolved, so callers can + fall back to their main-model agent. + """ + try: + from deeptutor.services.config.model_catalog import get_model_catalog_service + from deeptutor.services.config.provider_runtime import resolve_llm_runtime_config + from deeptutor.services.model_selection.runtime import llm_config_from_resolved + from deeptutor.services.model_selection.tasks import ( + TASK_SERVICE, + catalog_for_task, + task_service_configured, + ) + + catalog = catalog_for_task(get_model_catalog_service().load(), None) + if not task_service_configured(catalog): + return None + config = llm_config_from_resolved( + resolve_llm_runtime_config(catalog, service_name=TASK_SERVICE) + ) + except Exception: + return None + agent: Any = factory( + api_key=config.api_key, + base_url=config.base_url, + api_version=getattr(config, "api_version", None), + ) + agent.model = config.model + agent.binding = getattr(config, "binding", None) or agent.binding + effort = getattr(config, "reasoning_effort", None) + if effort: + stream = agent.stream_llm + + def _stream_llm(*args: Any, reasoning_effort: str | None = None, **kwargs: Any): + return stream(*args, reasoning_effort=reasoning_effort or effort, **kwargs) + + agent.stream_llm = _stream_llm + return agent + + +__all__ = ["task_model_agent"] diff --git a/tests/services/model_selection/test_task_agent.py b/tests/services/model_selection/test_task_agent.py new file mode 100644 index 000000000..feada0e44 --- /dev/null +++ b/tests/services/model_selection/test_task_agent.py @@ -0,0 +1,76 @@ +"""task_model_agent binds an agent to the Settings task model, or returns None.""" + +from __future__ import annotations + +from types import SimpleNamespace + +from deeptutor.services.config import model_catalog, provider_runtime +from deeptutor.services.model_selection import runtime, tasks +from deeptutor.services.model_selection.task_agent import task_model_agent + + +class _Agent: + def __init__(self, *, api_key, base_url, api_version) -> None: + self.api_key, self.base_url, self.api_version = api_key, base_url, api_version + self.model, self.binding = "main-model", "openai" + self.calls: list[dict] = [] + + def stream_llm(self, *args, reasoning_effort=None, **kwargs): + self.calls.append({"reasoning_effort": reasoning_effort, **kwargs}) + return "stream" + + +def _patch(monkeypatch, *, configured: bool, effort: str | None = None) -> None: + monkeypatch.setattr( + model_catalog, "get_model_catalog_service", lambda: SimpleNamespace(load=lambda: {}) + ) + monkeypatch.setattr(tasks, "catalog_for_task", lambda catalog, kind: catalog) + monkeypatch.setattr(tasks, "task_service_configured", lambda catalog: configured) + monkeypatch.setattr(provider_runtime, "resolve_llm_runtime_config", lambda c, service_name: c) + monkeypatch.setattr( + runtime, + "llm_config_from_resolved", + lambda resolved: SimpleNamespace( + api_key="k", + base_url="https://task.example/v1", + api_version=None, + model="fast-model", + binding="zhipu", + reasoning_effort=effort, + ), + ) + + +def test_returns_none_without_a_task_model(monkeypatch) -> None: + _patch(monkeypatch, configured=False) + assert task_model_agent(_Agent) is None + + +def test_binds_the_task_model(monkeypatch) -> None: + _patch(monkeypatch, configured=True) + agent = task_model_agent(_Agent) + assert agent is not None + assert (agent.model, agent.binding, agent.base_url) == ( + "fast-model", + "zhipu", + "https://task.example/v1", + ) + agent.stream_llm(user_prompt="x") + assert agent.calls[-1]["reasoning_effort"] is None + + +def test_applies_the_task_models_reasoning_effort(monkeypatch) -> None: + _patch(monkeypatch, configured=True, effort="none") + agent = task_model_agent(_Agent) + agent.stream_llm(user_prompt="x") + assert agent.calls[-1]["reasoning_effort"] == "none" + agent.stream_llm(user_prompt="x", reasoning_effort="high") + assert agent.calls[-1]["reasoning_effort"] == "high" + + +def test_resolution_errors_fall_back(monkeypatch) -> None: + def boom(): + raise RuntimeError("catalog unreadable") + + monkeypatch.setattr(model_catalog, "get_model_catalog_service", boom) + assert task_model_agent(_Agent) is None