DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(reading): surface figure captions to the model
flower-moon8e19581d9357
diff --git a/deeptutor/capabilities/reading/capability.py b/deeptutor/capabilities/reading/capability.pyindex d8cd09a9c..249fc454b 100644--- a/deeptutor/capabilities/reading/capability.py+++ b/deeptutor/capabilities/reading/capability.py@@ -37,6 +37,7 @@ from typing import Anyimport yamlfrom deeptutor.capabilities.protocol import PromptBlock+from deeptutor.capabilities.reading.media_notes import CAPTION_CHAR_LIMITfrom deeptutor.capabilities.reading.tools import (BINDING_KWARG,MATERIAL_KWARG,@@ -61,6 +62,10 @@ MODE_KEY = "immersive_reading_mode"# part of a document, few enough that it cannot crowd out the conversation.LOCATE_HITS = 4LOCATE_SNIPPET_CHARS = 260+# The viewport caption line: at most a few figures, each caption clipped, and a+# hard ceiling on the whole line so one chatty figure cannot dominate the seed.+VIEWPORT_CAPTION_ITEMS = 3+VIEWPORT_CAPTION_CHARS = 600_PROMPT_CACHE: dict[str, dict[str, Any]] = {}@@ -252,6 +257,41 @@ class ReadingCapability:except Exception:return 0+ @staticmethod+ def _figure_caption_line(material_id: str, locator: int) -> str:+ """A compact caption line for the figures on the locator being viewed.++ A caption is written at ingestion by a vision model. This line is the+ only channel a text-only model has to know what a page's figures show+ when that page is not attached to the turn — the image parts ride the+ current message, nothing else carries their content. Best-effort: any+ failure (store unavailable, no captions) drops the line entirely rather+ than breaking the turn, and the seed is byte-for-byte unchanged without+ it.+ """+ try:+ from deeptutor.reading import ReadingStore++ rows = ReadingStore().media_items_at(material_id, locator)+ except Exception:+ return ""+ parts: list[str] = []+ for row in rows:+ if not isinstance(row, dict):+ continue+ name = str(row.get("name") or "")+ caption = str(row.get("caption") or "").strip()+ if name and caption:+ parts.append(f"{name} — {_clip(caption, CAPTION_CHAR_LIMIT)}")+ if len(parts) >= VIEWPORT_CAPTION_ITEMS:+ break+ if not parts:+ return ""+ return _clip(+ f"Locator {locator}'s figures: " + "; ".join(parts),+ VIEWPORT_CAPTION_CHARS,+ )+# -- tool kwargs ------------------------------------------------------def augment_kwargs(@@ -293,19 +333,23 @@ class ReadingCapability:"""if not resolve_material_id(context):return ""+ material_id = resolve_material_id(context)viewport = resolve_viewport(context)locator = _as_int(viewport.get("locator"))selection = str(viewport.get("selection") or "").strip()parts: list[str] = []if locator:parts.append(f"The reader is currently showing locator {locator}.")- embedded = self._embedded_image_count(resolve_material_id(context), locator)+ embedded = self._embedded_image_count(material_id, locator)if embedded:parts.append(f"Locator {locator} contains {embedded} embedded image(s) from the document; ""they are attached to this message, so read them directly when the question ""concerns a figure.")+ captions = self._figure_caption_line(material_id, locator)+ if captions:+ parts.append(captions)time_seconds = _as_float(viewport.get("time_seconds"))if time_seconds >= 0 and "time_seconds" in viewport:parts.append(f"Current media time: {_timestamp(time_seconds)} ({time_seconds:.1f}s).")diff --git a/deeptutor/capabilities/reading/media_notes.py b/deeptutor/capabilities/reading/media_notes.pynew file mode 100644index 000000000..5b55af621--- /dev/null+++ b/deeptutor/capabilities/reading/media_notes.py@@ -0,0 +1,94 @@+"""Render the embedded-image note that ``read_material`` appends to its result.++Kept beside :mod:`deeptutor.capabilities.reading.tools` rather than inside it+because the note grew its own formatting rules (per-caption truncation, a line+budget) and ``tools.py`` sits against its size ceiling. Nothing here imports the+tool classes, so the extraction is cycle-free.++A row in ``media.json`` is ``{"name", "locator", "mime", "bytes"}`` and may+carry an optional ``"caption"`` written at ingestion by a vision model. The+caption is the only way a text model learns what an embedded figure shows when+the image itself is not attached to the turn — a non-current page, a unit read+from another tab, or any turn without the viewport seed.+"""++from __future__ import annotations++from collections.abc import Sequence+from typing import Any++# One caption is a short English sentence; anything longer is runaway output, so+# it is clipped before it reaches the model's context.+CAPTION_CHAR_LIMIT = 300+# The note is supporting evidence, not the answer: a media-heavy material must+# not crowd out the text the model was actually asked to read.+MAX_NOTE_LINES = 20+++def _flatten(text: str) -> str:+ """Collapse whitespace so a caption cannot forge extra list lines."""+ return " ".join((text or "").split())+++def _render_image(name: str, caption: str) -> str:+ """One list entry: the file name, plus its caption when there is one."""+ if not caption:+ return name+ clipped = _flatten(caption)+ if len(clipped) > CAPTION_CHAR_LIMIT:+ clipped = clipped[: CAPTION_CHAR_LIMIT - 1] + "…"+ return f"{name} — {clipped}"+++def render_media_note(+ store: Any, material_id: str, unit: str, locators: Sequence[int]+) -> str:+ """List the embedded images that live in the units just read.++ The reader pane displays these images next to their unit, and the turn+ already carries the ones on the user's current page — so when the user+ asks about a figure, the model knows it exists, where it sits, and that+ the image parts attached to the message are those figures. Rows carrying a+ caption also hand the text model what the figure shows.+ """+ try:+ rows = store.media_items(material_id)+ except Exception:+ return ""+ wanted = set(locators)+ by_locator: dict[int, list[tuple[str, str]]] = {}+ for row in rows:+ try:+ locator = int(row.get("locator") or 0)+ except (TypeError, ValueError):+ continue+ name = str(row.get("name") or "")+ if locator in wanted and name:+ caption = str(row.get("caption") or "").strip()+ by_locator.setdefault(locator, []).append((name, caption))+ if not by_locator:+ return ""+ entries = sorted(by_locator.items())+ shown, omitted = entries[:MAX_NOTE_LINES], entries[MAX_NOTE_LINES:]+ lines = [+ f"- {unit} {locator}: "+ + ", ".join(_render_image(name, caption) for name, caption in images)+ for locator, images in shown+ ]+ if omitted:+ # Name the count so the model treats the list as incomplete rather than+ # assuming the units hold exactly these figures.+ dropped = sum(len(images) for _, images in omitted)+ lines.append(f"({dropped} more images omitted)")+ return (+ "\n\nEmbedded images in the units above (shown in the reader pane; "+ "image parts attached to this conversation's messages are these "+ "figures):\n" + "\n".join(lines)+ )+++__all__ = [+ "CAPTION_CHAR_LIMIT",+ "MAX_NOTE_LINES",+ "render_media_note",+]diff --git a/deeptutor/capabilities/reading/tools.py b/deeptutor/capabilities/reading/tools.pyindex 38567ba32..a35688c0f 100644--- a/deeptutor/capabilities/reading/tools.py+++ b/deeptutor/capabilities/reading/tools.py@@ -35,9 +35,9 @@ from __future__ import annotationsimport asyncioimport logging-from collections.abc import Sequencefrom typing import Any+from deeptutor.capabilities.reading.media_notes import render_media_note as _media_notefrom deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResultfrom deeptutor.tools.prompting import load_prompt_hints@@ -452,41 +452,6 @@ class ReadMaterialTool(_ReadingToolBase):)-def _media_note(store: Any, material_id: str, unit: str, locators: Sequence[int]) -> str:- """List the embedded images that live in the units just read.-- The reader pane displays these images next to their unit, and the turn- already carries the ones on the user's current page — so when the user- asks about a figure, the model knows it exists, where it sits, and that- the image parts attached to the message are those figures.- """- try:- rows = store.media_items(material_id)- except Exception:- return ""- wanted = set(locators)- by_locator: dict[int, list[str]] = {}- for row in rows:- try:- locator = int(row.get("locator") or 0)- except (TypeError, ValueError):- continue- name = str(row.get("name") or "")- if locator in wanted and name:- by_locator.setdefault(locator, []).append(name)- if not by_locator:- return ""- lines = [- f"- {unit} {locator}: " + ", ".join(names)- for locator, names in sorted(by_locator.items())- ]- return (- "\n\nEmbedded images in the units above (shown in the reader pane; "- "image parts attached to this conversation's messages are these "- "figures):\n" + "\n".join(lines)- )--class ReaderGotoTool(_ReadingToolBase):"""Move the user's viewport — refused unless the quote checks out."""diff --git a/tests/reading/test_reading_media_notes.py b/tests/reading/test_reading_media_notes.pynew file mode 100644index 000000000..56ca1e9d8--- /dev/null+++ b/tests/reading/test_reading_media_notes.py@@ -0,0 +1,200 @@+"""Media-note rendering: legacy output stays exact, captions are carried through.++Two render points are covered together because they share one idea — the text+model should learn what an embedded figure shows from the ``caption`` a vision+model wrote at ingestion, and nothing at all when there is no caption:++* ``read_material``'s per-unit image list (``_media_note``), and+* the viewport seed's compact figure caption line (``pre_loop_seed``).++The byte-for-byte guarantee for caption-less material is asserted explicitly on+both paths, so a future edit that merely "tidies" the wording fails here.+"""++from __future__ import annotations++import pytest++from deeptutor.capabilities.reading import ReadingCapability+from deeptutor.capabilities.reading.capability import (+ MATERIAL_ID_KEY,+ VIEWPORT_KEY,+)+from deeptutor.capabilities.reading.media_notes import (+ CAPTION_CHAR_LIMIT,+ MAX_NOTE_LINES,+)+from deeptutor.capabilities.reading.tools import _media_note+from deeptutor.core.context import UnifiedContext++import deeptutor.reading as reading_pkg+++class _FakeStore:+ """The slice of the reading store the two render points actually touch."""++ def __init__(self, rows: list[dict]) -> None:+ self._rows = rows++ def media_items(self, material_id: str) -> list[dict]:+ return list(self._rows)++ def media_items_at(self, material_id: str, locator: int) -> list[dict]:+ return [row for row in self._rows if row.get("locator") == locator]+++def _row(locator: int, name: str, caption: str = "") -> dict:+ row = {"name": name, "locator": locator, "mime": "image/png", "bytes": 10}+ if caption:+ row["caption"] = caption+ return row+++def _legacy_note(unit: str, rows: list[tuple[int, list[str]]]) -> str:+ lines = [f"- {unit} {locator}: " + ", ".join(names) for locator, names in rows]+ return (+ "\n\nEmbedded images in the units above (shown in the reader pane; "+ "image parts attached to this conversation's messages are these "+ "figures):\n" + "\n".join(lines)+ )+++# ---------------------------------------------------------------------------+# _media_note+# ---------------------------------------------------------------------------+++def test_media_note_without_captions_is_byte_for_byte_the_legacy_output() -> None:+ rows = [+ _row(3, "image-01.png"),+ _row(3, "image-02.png"),+ _row(5, "image-09.png"),+ ]++ note = _media_note(_FakeStore(rows), "material", "page", [3, 5])++ assert note == _legacy_note("page", [(3, ["image-01.png", "image-02.png"]), (5, ["image-09.png"])])+++def test_media_note_appends_each_caption_after_its_figure() -> None:+ rows = [+ _row(3, "image-01.png", "A red cube on a white table."),+ _row(3, "image-02.png", "A blue sphere beside it."),+ ]++ note = _media_note(_FakeStore(rows), "material", "page", [3])++ assert "image-01.png — A red cube on a white table." in note+ assert "image-02.png — A blue sphere beside it." in note+ # One caption-less row must not gain a stray separator.+ assert note.endswith("A blue sphere beside it.")+++def test_media_note_clips_a_runaway_caption() -> None:+ rows = [_row(1, "image-01.png", "x" * (CAPTION_CHAR_LIMIT + 200))]++ note = _media_note(_FakeStore(rows), "material", "page", [1])++ caption = note.rsplit(" — ", 1)[1]+ assert len(caption) == CAPTION_CHAR_LIMIT+ assert caption.endswith("…")+++def test_media_note_caps_the_number_of_lines() -> None:+ rows = [_row(locator, f"image-{locator:02d}.png") for locator in range(1, 26)]++ note = _media_note(_FakeStore(rows), "material", "page", list(range(1, 26)))++ lines = note.splitlines()+ image_lines = [line for line in lines if line.startswith("- page ")]+ assert len(image_lines) == MAX_NOTE_LINES+ # 25 locators, 20 shown, 5 dropped — and the model is told the list is short.+ assert lines[-1] == "(5 more images omitted)"+++def test_media_note_disappears_when_the_store_fails() -> None:+ class _Broken:+ def media_items(self, material_id: str) -> list[dict]:+ raise RuntimeError("media index unreadable")++ assert _media_note(_Broken(), "material", "page", [1]) == ""+++# ---------------------------------------------------------------------------+# pre_loop_seed+# ---------------------------------------------------------------------------+++def _viewport_context(locator: int, selection: str = "") -> UnifiedContext:+ viewport: dict = {"locator": locator}+ if selection:+ viewport["selection"] = selection+ return UnifiedContext(+ session_id="s1",+ user_message="what does the figure show?",+ metadata={MATERIAL_ID_KEY: "abc123ff", VIEWPORT_KEY: viewport},+ )+++def test_pre_loop_seed_adds_a_caption_line_for_the_current_locator(monkeypatch) -> None:+ rows = [+ _row(4, "image-01.png", "A red cube on a white table."),+ _row(4, "image-02.png", "A blue sphere beside it."),+ _row(9, "image-07.png", "A figure on another page."),+ ]+ monkeypatch.setattr(reading_pkg, "ReadingStore", lambda: _FakeStore(rows))++ seed = ReadingCapability().pre_loop_seed(_viewport_context(4))++ assert "Locator 4's figures: " in seed+ assert "image-01.png — A red cube on a white table." in seed+ assert "image-02.png — A blue sphere beside it." in seed+ # Only the current locator's figures are described.+ assert "image-07.png" not in seed+ # The attachment sentence keeps its old meaning alongside the caption line.+ assert "they are attached to this message" in seed+++def test_pre_loop_seed_omits_the_caption_line_without_captions(monkeypatch) -> None:+ rows = [_row(4, "image-01.png"), _row(4, "image-02.png")]+ monkeypatch.setattr(reading_pkg, "ReadingStore", lambda: _FakeStore(rows))++ seed = ReadingCapability().pre_loop_seed(_viewport_context(4))++ assert "figures:" not in seed+ assert "image-01.png" not in seed+ assert "Locator 4 contains 2 embedded image(s)" in seed+++def test_pre_loop_seed_is_unchanged_when_the_store_raises(monkeypatch) -> None:+ def _boom():+ raise RuntimeError("store unavailable")++ monkeypatch.setattr(reading_pkg, "ReadingStore", _boom)++ seed = ReadingCapability().pre_loop_seed(_viewport_context(4))++ # No material, no viewport seed breakage: exactly the legacy sentence.+ assert seed == "The reader is currently showing locator 4."+++def test_pre_loop_seed_caps_captions_at_three_figures(monkeypatch) -> None:+ rows = [_row(2, f"image-{index:02d}.png", f"Figure {index}.") for index in range(1, 6)]+ monkeypatch.setattr(reading_pkg, "ReadingStore", lambda: _FakeStore(rows))++ seed = ReadingCapability().pre_loop_seed(_viewport_context(2))++ assert seed.count(" — ") == 3+ assert "image-04.png" not in seed++[email protected]("locator", [0])+def test_pre_loop_seed_skips_media_work_without_a_locator(monkeypatch, locator) -> None:+ def _boom():+ raise AssertionError("no store call should happen without a locator")++ monkeypatch.setattr(reading_pkg, "ReadingStore", _boom)++ seed = ReadingCapability().pre_loop_seed(_viewport_context(locator))++ assert seed == ""