Fix Video Lesson ignoring image attachments (#3109)

This commit is contained in:
Bingxi Zhao (Frank)
2026-12-02 05:28:18 -05:00
4 changed files with 77 additions and 8 deletions

View File

@@ -53,7 +53,9 @@ class VideoLessonCapability(TurnCapability):
language=context.language,
)
writer.set_trace_callback(self._build_trace_bridge(stream, i18n))
writer.start(user_input=context.user_message, history=history)
writer.start(
user_input=context.user_message, history=history, attachments=context.attachments
)
# 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 = (

View File

@@ -8,7 +8,9 @@ import re
from typing import Any
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.multimodal import prepare_multimodal_messages
from .narration import NarrationLine
from .runtime import ASSETS_DIR
@@ -70,9 +72,12 @@ class LessonWriterAgent(BaseAgent):
api_version=api_version,
language=language,
)
self._messages: list[dict[str, str]] = []
self._messages: list[dict[str, Any]] = []
self._attachments: list[Attachment] = []
def start(self, *, user_input: str, history: str) -> None:
def start(
self, *, user_input: str, history: str, attachments: list[Attachment] | None = None
) -> None:
system = self.get_prompt("system")
template = self.get_prompt("user_template")
if not system or not template:
@@ -84,9 +89,12 @@ 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}]
self._attachments = list(attachments) if attachments else []
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
self._attachments = other._attachments
def add_feedback(self, *, previous: str, stage: str, errors: list[str]) -> None:
"""Keep the failed reply in the conversation and ask for a fix."""
@@ -98,11 +106,23 @@ class LessonWriterAgent(BaseAgent):
]
async def write(self, *, attempt: int) -> LessonDraft:
messages = self._messages
if self._attachments:
# Keep images on the original request when another provider handles a repair.
system, user, *feedback = messages
prepared = prepare_multimodal_messages(
[system, user.copy()],
self._attachments,
binding=self.binding,
model=self.get_model(),
)
messages = prepared.messages + feedback
chunks: list[str] = []
async for chunk in self.stream_llm(
user_prompt="",
system_prompt="",
messages=self._messages,
messages=messages,
stage="code_generation",
trace_meta=build_trace_metadata(
call_id=new_call_id("video-lesson"),

View File

@@ -8,7 +8,7 @@ import pytest
from deeptutor.agents.video_lesson import capability, lesson_writer, narration, runtime
from deeptutor.agents.video_lesson.lesson_writer import LessonDraft
from deeptutor.agents.video_lesson.narration import Clip
from deeptutor.core.context import UnifiedContext
from deeptutor.core.context import Attachment, UnifiedContext
from deeptutor.runtime.stream_bus import StreamBus
@@ -21,6 +21,8 @@ async def test_parse_failures_restore_previous_compiled_candidate(monkeypatch, t
good = LessonDraft("原始标题", "原始摘要", "原始源码", "原始回复")
broken = LessonDraft("错误标题", "错误摘要", "", "无代码")
image = Attachment(type="image", base64="aW1hZ2U=", mime_type="image/png")
class Writer:
def __init__(self, **kwargs):
pass
@@ -28,8 +30,8 @@ async def test_parse_failures_restore_previous_compiled_candidate(monkeypatch, t
def set_trace_callback(self, callback):
pass
def start(self, **kwargs):
pass
def start(self, *, user_input, history, attachments):
assert attachments == [image]
def add_feedback(self, **kwargs):
pass
@@ -73,7 +75,8 @@ async def test_parse_failures_restore_previous_compiled_candidate(monkeypatch, t
)
await capability.VideoLessonCapability().run(
UnifiedContext(session_id="turn", user_message="问题", language="zh"), StreamBus()
UnifiedContext(session_id="turn", user_message="问题", language="zh", attachments=[image]),
StreamBus(),
)
assert captured["title"] == "原始标题"

View File

@@ -5,6 +5,7 @@ from __future__ import annotations
import pytest
from deeptutor.agents.video_lesson.lesson_writer import LessonWriterAgent, parse_draft
from deeptutor.core.context import Attachment
REPLY = """```json
{"title": "Golden ratio", "summary": "Cobweb first, then the proof."}
@@ -69,3 +70,46 @@ def test_parse_draft_reads_the_narration() -> None:
)
draft = parse_draft(reply)
assert [(n.id, n.text) for n in draft.narration] == [("s1", "第一句。")]
@pytest.mark.asyncio
async def test_writer_keeps_images_on_the_original_message_during_repair(
monkeypatch: pytest.MonkeyPatch,
) -> None:
image_data = "aW1hZ2U="
attachment = Attachment(type="image", base64=image_data, mime_type="image/png")
requests = []
async def stream_reply(self, *, messages, **kwargs):
requests.append(messages)
yield REPLY
monkeypatch.setattr(
"deeptutor.agents.base_agent.get_agent_params",
lambda _: {"temperature": 0.7, "max_tokens": 16000},
)
monkeypatch.setattr(LessonWriterAgent, "stream_llm", stream_reply)
monkeypatch.setattr(LessonWriterAgent, "get_model", lambda self: "test-model")
writer = LessonWriterAgent(api_key="test", base_url="http://localhost", language="en")
writer.binding = "openai"
repair = LessonWriterAgent(api_key="test", base_url="http://localhost", language="en")
repair.binding = "anthropic"
writer.start(user_input="Explain the image", history="", attachments=[attachment])
repair.share_conversation(writer)
await writer.write(attempt=1)
writer.add_feedback(previous=REPLY, stage="layout", errors=["Overlap"])
await repair.write(attempt=2)
first_request, repair_request = requests
assert first_request[1]["content"][1] == {
"type": "image_url",
"image_url": {"url": f"data:image/png;base64,{image_data}"},
}
assert repair_request[1]["content"][1] == {
"type": "image",
"source": {"type": "base64", "media_type": "image/png", "data": image_data},
}
assert isinstance(repair_request[-1]["content"], str)
assert "Overlap" in repair_request[-1]["content"]
assert isinstance(writer._messages[1]["content"], str)