Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix: Qwen model JSON stripping, force-recompile overview pages, health false positives

Name Card Scanner Dev34b46d672b15
diff --git a/deeptutor/book/blocks/_llm_writer.py b/deeptutor/book/blocks/_llm_writer.py
index 034a47d3f..d1a8c3a9e 100644
--- a/deeptutor/book/blocks/_llm_writer.py
+++ b/deeptutor/book/blocks/_llm_writer.py
@@ -89,6 +89,42 @@ def _json_has_expected(data: dict[str, Any], expected_key: str | None) -> bool:
return bool(value)
+def _strip_thinking_preamble(text: str) -> str:
+ """Strip model thinking/reasoning preamble before JSON output.
+
+ Some local/Qwen models output reasoning text (e.g. "Here's a thinking
+ process:...") even when ``response_format`` is ``json_object``. The
+ reasoning text often contains backtick-quoted JSON templates with `{`
+ characters, so finding the *first* ``{`` is wrong. Instead we find the
+ **last** ``{`` in the response — the actual JSON output comes after the
+ thinking text, and a top-level JSON object starts with its opening brace.
+ """
+ if not text:
+ return text
+ # Find the last '{' — that's where the actual JSON object starts
+ brace = text.rindex("{")
+ if brace > 0:
+ candidate = text[brace:]
+ # Quick check: can json.loads parse it?
+ import json
+ try:
+ json.loads(candidate)
+ return candidate # Valid JSON -> use it
+ except (json.JSONDecodeError, ValueError):
+ pass # Not valid JSON, fall through to original approach
+ # Fallback: try the first '{' with the thinking-heuristic check
+ if "{" not in text:
+ return text
+ brace = text.index("{")
+ if brace > 0:
+ before = text[:brace].strip()
+ if not before or before.lower().startswith(
+ ("here", "think", "let me", "ok", "okay", "i will", "first", "note", "so")
+ ) or before.rstrip(".").isdigit():
+ return text[brace:]
+ return text
+
+
async def llm_json(
*,
user_prompt: str,
@@ -104,28 +140,39 @@ async def llm_json(
tokens and leave the visible JSON object empty. For structured book blocks
we first honor the configured reasoning mode, then retry once with minimal
reasoning if parsing fails or the expected top-level key is missing.
+
+ Also strips thinking/reasoning preamble text (common with local models)
+ before JSON parsing.
"""
async def _once(reasoning_effort: str | None) -> dict[str, Any]:
raw = await llm_text(
user_prompt=user_prompt,
system_prompt=system_prompt,
- max_tokens=max_tokens,
+ max_tokens=2600, # generous budget: thinking + actual JSON
temperature=temperature,
- response_format={"type": "json_object"},
language=language,
reasoning_effort=reasoning_effort,
)
- parsed = parse_json_response(raw, fallback={})
- return _normalize_json_payload(parsed, expected_key=expected_key)
+ # First pass: strip thinking preamble (Qwen outputs thinking text
+ # even with json_object format), then let parse_json_response handle
+ # what remains via its json-repair fallback.
+ cleaned = _strip_thinking_preamble(raw)
+ parsed = parse_json_response(cleaned, fallback={})
+ if parsed:
+ return _normalize_json_payload(parsed, expected_key=expected_key)
+ # Second pass: if stripping failed, feed the raw response to
+ # parse_json_response — json-repair may extract JSON from mixed text.
+ recovered = parse_json_response(raw, fallback={})
+ return _normalize_json_payload(recovered, expected_key=expected_key)
data = await _once(None)
if _json_has_expected(data, expected_key):
return data
- retry_data = await _once("minimal")
+ retry_data = await _once("low")
if _json_has_expected(retry_data, expected_key):
- retry_data.setdefault("_metadata", {})["reasoning_retry"] = "minimal"
+ retry_data.setdefault("_metadata", {})["reasoning_retry"] = "low"
return retry_data
return data or retry_data
diff --git a/deeptutor/book/engine.py b/deeptutor/book/engine.py
index 18d631178..696a2673a 100644
--- a/deeptutor/book/engine.py
+++ b/deeptutor/book/engine.py
@@ -712,7 +712,7 @@ class BookEngine:
raise ValueError(f"Cannot compile page – missing book/spine/page ({book_id}/{page_id})")
if page.status == PageStatus.READY and not force:
return page
- if force and page.content_type != ContentType.OVERVIEW:
+ if force:
self._reset_page_for_force_compile(page)
self.storage.save_page(page)
@@ -919,6 +919,7 @@ class BookEngine:
self.storage.save_page(page)
self.compiler._finalize_page_status(page)
self.storage.save_page(page)
+ await self._maybe_finalize_book(book_id)
return block
# ── Maintenance / health (Phase 4) ─────────────────────────────────
diff --git a/deeptutor/book/kb_health.py b/deeptutor/book/kb_health.py
index d6aac1e37..561adb2dc 100644
--- a/deeptutor/book/kb_health.py
+++ b/deeptutor/book/kb_health.py
@@ -283,8 +283,11 @@ def scan_log_health(book_id: str, storage: BookStorage | None = None) -> LogHeal
logger.warning(f"Could not read log {log_path}: {exc}")
return report
+ # Only report repeated entries that are actual errors/failures.
repeated: list[dict[str, str | int]] = [
- {"signature": k, "count": v} for k, v in counter.items() if v >= 3
+ {"signature": k, "count": v}
+ for k, v in counter.items()
+ if v >= 3 and ("error" in k.lower() or "fail" in k.lower())
]
repeated.sort(key=lambda r: r["count"] if isinstance(r["count"], int) else 0, reverse=True)
report.repeated_failures = repeated[:10]
diff --git a/web/app/(workspace)/book/components/PageReader.tsx b/web/app/(workspace)/book/components/PageReader.tsx
index e52816e87..f77d04d47 100644
--- a/web/app/(workspace)/book/components/PageReader.tsx
+++ b/web/app/(workspace)/book/components/PageReader.tsx
@@ -157,9 +157,15 @@ export default function PageReader({
{!headerCollapsed && onRecompile && (
<button
onClick={onRecompile}
- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--card)] px-2.5 py-1 text-xs font-medium text-[var(--muted-foreground)] hover:border-[var(--primary)]/40 hover:text-[var(--primary)]"
+ disabled={loading}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--card)] px-2.5 py-1 text-xs font-medium text-[var(--muted-foreground)] hover:border-[var(--primary)]/40 hover:text-[var(--primary)] disabled:cursor-not-allowed disabled:opacity-50"
>
- <RefreshCcw className="h-3.5 w-3.5" /> {t("Force regenerate")}
+ {loading ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <RefreshCcw className="h-3.5 w-3.5" />
+ )}
+ {loading ? "Regenerating…" : "Force regenerate"}
</button>
)}
<button
@@ -208,10 +214,15 @@ export default function PageReader({
{onRecompile && (
<button
onClick={onRecompile}
- className="inline-flex items-center gap-1 rounded-md border border-current px-2 py-1 text-xs font-medium hover:bg-white/40 dark:hover:bg-white/10"
+ disabled={loading}
+ className="inline-flex items-center gap-1 rounded-md border border-current px-2 py-1 text-xs font-medium hover:bg-white/40 dark:hover:bg-white/10 disabled:cursor-not-allowed disabled:opacity-50"
>
- <RefreshCcw className="h-3.5 w-3.5" />
- {t("Regenerate page")}
+ {loading ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <RefreshCcw className="h-3.5 w-3.5" />
+ )}
+ {loading ? "Regenerating…" : "Regenerate page"}
</button>
)}
</div>
diff --git a/web/app/(workspace)/book/page.tsx b/web/app/(workspace)/book/page.tsx
index e37caf1ce..ad5483848 100644
--- a/web/app/(workspace)/book/page.tsx
+++ b/web/app/(workspace)/book/page.tsx
@@ -11,6 +11,7 @@ import {
} from "react";
import { useSearchParams } from "next/navigation";
import { Loader2, MessageSquare } from "lucide-react";
+import { notify } from "@/lib/notifications";
import { useTranslation } from "react-i18next";
import { bookApi, openBookSocket } from "@/lib/book-api";
@@ -314,6 +315,10 @@ function BookPageInner() {
setCompilingPageId(pageId);
try {
await bookApi.compilePage(selectedBookId, pageId, force);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ notify(`Compile failed: ${msg}`, { tone: "error", durationMs: 8000 });
+ console.error("compilePage failed:", err);
} finally {
setCompilingPageId((current) => (current === pageId ? null : current));
await loadBookDetail(selectedBookId);
@@ -333,8 +338,15 @@ function BookPageInner() {
const handleRegenerateBlock = async (block: Block) => {
if (!detail || !selectedPage) return;
- await bookApi.regenerateBlock(detail.book.id, selectedPage.id, block.id);
- await loadBookDetail(detail.book.id);
+ try {
+ await bookApi.regenerateBlock(detail.book.id, selectedPage.id, block.id);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ notify(`Regenerate block failed: ${msg}`, { tone: "error", durationMs: 8000 });
+ console.error("regenerateBlock failed:", err);
+ } finally {
+ await loadBookDetail(detail.book.id);
+ }
};
const handleDeleteBlock = async (block: Block) => {
diff --git a/web/app/layout.tsx b/web/app/layout.tsx
index 216b65db6..61f2df22b 100644
--- a/web/app/layout.tsx
+++ b/web/app/layout.tsx
@@ -45,7 +45,7 @@ export default function RootLayout({
<head>
<ThemeScript />
</head>
- <body className="font-sans bg-[var(--background)] text-[var(--foreground)]">
+ <body className="font-sans bg-[var(--background)] text-[var(--foreground)]" suppressHydrationWarning>
<AppShellProvider>
<I18nClientBridge>{children}</I18nClientBridge>
<ToastViewport />