Files
DeepTutor/deeptutor/book/blocks/figure.py
Bingxi Zhao (Frank) bd80a4d28a release: v1.5.17
Partners stop being a deployment-wide admin resource and become
per-user: three nested rights (manage / use / neither) replace the
blanket admin gate on the router, each member can build and own their
own, and every person's conversations with a partner stay private to
their account. Grants keep working and now offer only admin-managed
partners. Channel runtime state moves from one directory per channel to
one per partner — copied, not moved, and only when its owner is
unambiguous — so two partners can finally run the same channel.

Around that: a knowledge base can track GitHub repositories and re-sync
their Markdown (#903); Antigravity CLI joins My Agents now that Gemini
CLI is retired (#828); personal WeChat signs in from a QR code drawn in
the browser instead of the server log (#951); a chat account can be
linked to a DeepTutor account with /link; containers re-apply the extras
they declare instead of losing them at compose down (#762); and
`deeptutor doctor` answers whether a workspace is ready to run (#959).

Reliability, largely from community PRs: embeddings survive a
rate-limited provider through key rotation, a retry budget and a global
throttle (#962); MinerU parsing and code execution work on Windows
(#844, #964); indexing fails bounded instead of hanging (#946); MinerU
page-layout blocks stop being indexed as content (#949); voice uploads
carry a MIME the transcription API accepts (#945); and reasoning effort
can be overridden per conversation (#641).

Release plumbing: notes in assets/releases/ver1-5-17.md, v1.5.13
archived, __version__ 1.5.17, README Releases row and all eleven
translations synced.

Two defects found by the release gate and fixed here:

- Six partner routes — the four channel-onboarding endpoints and both
  WeChat QR endpoints — kept the _auth-only mount they had inherited
  from the blanket admin gate, so any signed-in account could start a
  QR login for someone else's partner and write a bot token into its
  channel config. All six now declare _MANAGEABLE, and a sweep test
  asserts no {partner_id} route is left ungated.
- A configured api_key became `str | list[str]` when key rotation
  landed, but ten call sites pass it somewhere that takes one key; a
  list would have rendered into an Authorization header verbatim.
  keypool.primary_api_key reduces at each boundary.

Gates: pre-commit (all 15 hooks), ruff check + format, pytest
5276 passed, web 605 node tests, docs build.
2026-08-25 02:24:35 +08:00

136 lines
5.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Figure block – static visual figure (svg / chartjs / mermaid).
Wraps :class:`deeptutor.agents.visualize.pipeline.VisualizePipeline` with
``render_mode="figure"`` so the LLM picks the best static rendering for the
chapter, but never falls back to interactive HTML (handled by the
``interactive`` block type).
Like the chat capability, the draft is checked by the deterministic local
``validate_visualization``; only on failure do we spend one targeted repair
call. If the code still fails after repair we raise ``GenerationFailure`` so
the book engine can retry, instead of baking a broken figure into the book.
"""
from __future__ import annotations
import logging
from typing import Any
from deeptutor.services.keypool import primary_api_key
from ..models import BlockType, SourceAnchor
from ._prompts import get_book_prompt, load_book_prompts
from .base import BlockContext, BlockGenerator, GenerationFailure
logger = logging.getLogger(__name__)
class FigureGenerator(BlockGenerator):
block_type = BlockType.FIGURE
async def _generate(
self, ctx: BlockContext
) -> tuple[dict[str, Any], list[SourceAnchor], dict[str, Any]]:
params = ctx.block.params
chapter_title = params.get("chapter_title", ctx.chapter.title)
chapter_summary = params.get("chapter_summary", ctx.chapter.summary)
objectives = params.get("objectives") or ctx.chapter.learning_objectives
variant = str(params.get("variant") or "diagram")
focus = str(params.get("focus") or "")
prompts = load_book_prompts("figure", ctx.language)
history_lines: list[str] = []
if chapter_summary:
history_lines.append(
get_book_prompt(prompts, "context_summary")
.strip()
.format(chapter_summary=chapter_summary)
)
if objectives:
history_lines.append(get_book_prompt(prompts, "context_objectives").strip())
for obj in objectives:
history_lines.append(f"- {obj}")
history_context = "\n".join(history_lines)
focus_clause = (
get_book_prompt(prompts, "focus_clause").rstrip().format(focus=focus) if focus else ""
)
user_input = (
get_book_prompt(prompts, "brief")
.strip()
.format(
variant=variant,
chapter_title=chapter_title,
focus_clause=focus_clause,
)
)
try:
from deeptutor.agents.visualize.models import ReviewResult
from deeptutor.agents.visualize.pipeline import VisualizePipeline
from deeptutor.agents.visualize.utils import validate_visualization
from deeptutor.services.llm.config import get_llm_config
llm_config = get_llm_config()
pipeline = VisualizePipeline(
api_key=primary_api_key(llm_config.api_key),
base_url=llm_config.base_url,
api_version=llm_config.api_version,
language=ctx.language,
)
analysis = await pipeline.run_analysis(
user_input=user_input,
history_context=history_context,
render_mode="figure",
)
code = await pipeline.run_code_generation(
user_input=user_input,
history_context=history_context,
analysis=analysis,
)
ok, validation_error = validate_visualization(code, analysis.render_type)
if ok:
review = ReviewResult(
optimized_code=code,
changed=False,
review_notes="Passed local validation.",
)
else:
review = await pipeline.run_repair(
user_input=user_input,
analysis=analysis,
code=code,
error=validation_error,
)
except Exception as exc:
logger.warning(f"FigureGenerator failed: {exc}", exc_info=True)
raise GenerationFailure(f"figure generation failed: {exc}") from exc
final_code = review.optimized_code or code
render_type = analysis.render_type
final_ok, residual_error = validate_visualization(final_code, render_type)
if not final_ok:
raise GenerationFailure(f"figure failed validation after repair: {residual_error}")
lang_tag = {
"svg": "svg",
"mermaid": "mermaid",
"chartjs": "javascript",
}.get(render_type, "svg")
return (
{
"render_type": render_type,
"code": {"language": lang_tag, "content": final_code},
"description": analysis.description,
"chart_type": analysis.chart_type,
},
[],
{
"review_changed": review.changed,
"review_notes": review.review_notes,
},
)
__all__ = ["FigureGenerator"]