20 Commits

Author SHA1 Message Date
wojiecihuo
651a616b02 fix(visualize): raise the budget to 32k, cap it to the model, and retry without thinking (#3019)
* fix(book): retry an interactive page with thinking off when it runs out of room

deepseek-flash thinks by default and can spend the whole 16000-token
visualize budget on reasoning, so a book interactive block came back with
no code. When the page is empty or cut off before </html>, ask once more
with thinking turned off (thinking_off_effort_for) before failing. If that
still runs out of room, the error names the budget sent to the model and
the settings that change it.

The shipped default stays at 16000: the budget is shared by every visualize
caller, and 32768 breaks models with a lower output cap (#3018).

Refs #3011

* fix(llm): raise the visualize budget to 32k and cap each request to the model

A thinking model can spend 16k tokens before it writes any code, so the
visualize default is now 32768. Sent unchanged that would be rejected by
models whose output stops lower (gpt-4o and gpt-4o-mini at 16384) and could
overflow a small local context window, so every request now carries
min(budget, the model's known output limit, half the configured context
window). The cap lives in get_token_limit_kwargs, so it applies to every
caller; BaseAgent and the agentic loop pass the configured window.
2026-11-27 22:26:59 +08:00
stefanielizeth73-art
3f943e14c8 feat(agent-loop): configure bounded reasoning-budget recovery 2026-11-03 00:12:00 +08:00
SeleiXi
6b7897a32f feat(video_lesson): register the video lesson capability
`video_lesson` (CLI alias `lesson`) turns a question into a playable
Remotion explainer:

1. code_generation: the lesson writer drafts Lesson.tsx
2. render_check: compile and frame-check it, feeding failures back,
   up to three attempts
3. render_output: write the player page and emit it as an html artifact,
   along with the lesson's summary and source

npm packages are installed on first use while the first LLM call is
still running. The capability reports itself unavailable when node or
npm is missing. Its LLM budget lives under plugins.video_lesson in
agents.yaml (48k tokens by default: a whole lesson comes back in one
reply).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 23:58:03 +08:00
Frank_zhu
6fbed6c28e fix(research): recover report labels on finished reply (#1514)
Keep the streaming 64-char probe strict, then re-read a finished report
reply so an unclosed/over-wide fence or a matching ## n. heading no
longer kills the turn. Raise report_section max_tokens to 12000 and
turn reasoning off for report prose so first attempts stop starving.
2026-09-21 10:27:09 +08:00
Bingxi Zhao (Frank)
ed85fe9bc2 refactor(config): put every LLM budget in agents.yaml, one entry per stage
A capability that makes several different LLM calls cannot be described
by one max_tokens: the step emitting a whole JSON plan and the step
writing one paragraph need different room. `chat` has said so since it
grew `exploring`/`responding`. `question` and `research` said the same
thing in module constants instead, where no user could reach them.

The cost of that was not theoretical. `capabilities.question.max_tokens`
governed exactly one of question's six LLM calls — the follow-up agent —
while the pipeline's five steps used constants that ignored it. The plan
step's constant sat below the capability's own ceiling, which is how
#1318 shipped a step that could spend its whole allowance thinking and
emit zero templates without an error. `EXPLORE_FINISH_MAX_TOKENS` had
been dead since it was written.

Generalises the seam that already worked rather than adding a parallel
one: `get_chat_params` becomes `get_capability_params(capability)` over a
table of per-stage defaults, and `question`, `research` and
`explore_context` get tables of their own holding the numbers they
already ran on. The pipelines resolve once in `__init__` beside the
budget they already cached. Unknown keys are dropped, so a misspelled
stage cannot become a silent no-op that reads like a setting.

The rule this establishes, stated in the tables: **agents.yaml owns every
LLM budget** (temperature, max_tokens, per stage); **main.yaml owns
runtime behaviour** (iteration caps, timeouts, retry policy, modes). A
budget in main.yaml is a bug. `tool_summarizer.max_tokens` still reads
its main.yaml value first so nobody's existing configuration moves; new
installs reach the same number through agents.yaml like everything else.
GraphRAG's reachability probe is the one documented exemption — tuning it
could only make a health check lie.

Seeds are derived from the same tables the pipelines read, because two
lists of the same numbers is how a default and its seed drift apart —
the shape of #1316. Tests pin both halves: the shipped values, and that
every stage in code is present in the seeded file.

No behaviour change: every default is the constant it replaced.
6902 passed, 24 skipped.
2026-09-11 12:43:41 +08:00
Bingxi Zhao (Frank)
5ac8e2c9d3 fix(book): give Book a reachable token budget, and retry a starved plan
A book built with a reasoning model arrives as a single "Overview"
chapter, or with the right chapter count and every learning objective
and summary empty (#1316). Two independent faults compose into that.

`get_agent_params` maps a module name to a section of agents.yaml, and
`book` was not in the map — so the function returned the source-level
`global_defaults` of 4096 *before* ever opening the file. That budget
was therefore not the shipped default and not overridable: adding a
`capabilities.book` block did nothing, and only editing the source could
change it. It is now mapped, seeded at 12000 in DEFAULT_AGENTS_SETTINGS
(so a stale agents.yaml still gets it), and honoured from the yaml.
12000 rather than a larger figure matches `research`, the closest
analogue, and keeps the request under the output cap of providers that
enforce one.

The budget is the trigger, not the fault. A reasoning model pays for its
hidden tokens out of the same `max_tokens` as its answer, so on a large
prompt asking for a whole JSON object it can spend the lot and emit
nothing. The provider does not raise — it returns a truncated body, or
none — and `parse_json_response` hands back the caller's fallback, which
in `SpineSynthesizer._materialise` is one placeholder chapter. Where the
budget ran out *mid*-object, json-repair closes the fragment and the
caller gets chapters whose objectives never arrived: the same failure
wearing a different face.

`blocks/_llm_writer.llm_json` already knew the escape hatch — ask again
with thinking turned down — but only block generators went through it.
The four pipeline agents each parsed their own response and had no retry
at all. `book/json_retry.py` is now the one place that rule lives, and
ideation, both source-explorer calls, all three spine rounds and the
page planner go through it; `llm_json` shares its predicate so the two
cannot drift. Each caller names the key that proves the payload arrived,
which is what lets a repaired-but-gutted object trigger the retry rather
than settle the stage.

`BaseAgent.call_llm` / `stream_llm` gained the `reasoning_effort`
parameter this needs; it was already the shape `llm_text` used.
2026-09-10 22:50:45 +08:00
Bingxi Zhao (Frank)
04040a2c06 release: v1.6.5
Ship a content workspace you choose, one exec tool for every language,
Mastery Path modes that gate its tools, and Settings that grades
readiness instead of listing faults.

Release notes: assets/releases/ver1-6-5.md
2026-09-06 13:46:29 +08:00
Bingxi Zhao (Frank)
591329322d fix(i18n): stop collapsing every non-English language to Chinese (#712)
`parse_language()` ended in a bare `return "zh"`, so ja/ko/fr/de/ru/ar
all resolved to Chinese. Book prose normalized its code correctly while
quiz, Deep Research and Mastery Path went through this parser — which is
why a Japanese book came back with Chinese quizzes.

Delegate to the existing `normalize_language()` instead of keeping a
second, weaker implementation, and pass unknown codes through. What makes
the model answer in a language is the directive built from the code, not
the prompt file, so no new locale resources are needed.

Two fallback chains assumed the result was zh or en and had to follow:

* `PromptManager` now tries `[code, base locale, "en"]`, so "zh-tw" reuses
  the Chinese files and "ja" lands on English rather than Chinese. The
  chains for zh and en are unchanged.
* Mastery Path's `[lang, "zh" if lang != "zh" else "en"]` gets the same
  treatment, and its notebook prompts now append the shared language
  directive — without it a Japanese learner would only have traded
  Chinese output for English.

An unconfigured language still defaults to "zh", so deployments that
never set one keep the behaviour they shipped with.

Reported with an exact root-cause analysis by @takeshi-o.
2026-07-27 21:24:00 +08:00
Bingxi Zhao (Frank)
46093e5e2b update msg 2026-06-11 20:03:34 +08:00
Bingxi Zhao (Frank)
db41c574a1 refactor: centralize Gemini default-off reasoning in reasoning_params
Follow-up to #490. The PR inlined the "disable thinking for Gemini 2.5/3"
gate in 5 places across 3 files. This commit collapses them to one
registry and three thin call sites.

Changes:

* `services/llm/reasoning_params.py`: new `_PROVIDER_DEFAULT_OFF_PATTERNS`
  registry + `default_reasoning_effort_for(provider, model)` public helper.
  `build_openai_compatible_reasoning_kwargs` now consults the registry, so
  the openai-compat path (which lost its inline gate during the #490 merge
  conflict resolution) is restored via the helper.

* `services/llm/executors.py` (sdk_complete + sdk_stream) and
  `services/llm/cloud_provider.py` (_openai_complete + _openai_stream) now
  call `default_reasoning_effort_for(...)` instead of inlining the
  ('gemini-2.5', 'gemini-3') startswith check.

* Use substring (not startswith) match so `models/gemini-2.5-flash` is
  also covered — some OpenAI-compat clients prefix model ids with `models/`.

* `services/config/loader.py:get_agent_params`: when a module's section is
  missing from the user's stale `agents.yaml`, fall back through
  `DEFAULT_AGENTS_SETTINGS` before the global `(0.5, 4096)` default. This
  lets the `capabilities.visualize` default (`max_tokens=16384` from #490)
  reach existing installs, not just fresh ones.

* `capabilities/visualize.py`: hoist the duplicated lazy
  `from deeptutor.agents.visualize.models import ReviewResult` import
  from two branches into the top of `run()`.

Tests:

* `tests/services/llm/test_reasoning_params.py` — 17 new cases covering
  Gemini 2.5/3 + `models/` prefix + case-insensitivity + the legacy
  Gemini 1.5/2.0 / other-provider untouched paths + the explicit-override
  takes-precedence rule.
* All 107 tests in `tests/services/llm/` still pass; 5 pre-existing
  `test_chat_params_config` failures (8192 vs 8000 drift) are unrelated.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 18:00:08 +08:00
Bingxi Zhao (Frank)
44564b077b Merge pull request #490: fix(visualize): unblock Gemini 2.5+ and harden Visualize pipeline
Squash-merge of #490 (skinred78) with two non-trivial conflict resolutions:

* `openai_compat_provider.py`: PR inlined reasoning_effort logic that has since
  been refactored into `build_openai_compatible_reasoning_kwargs`. Keep the
  helper call; the Gemini default-down will be folded into the helper in a
  follow-up commit instead of duplicating it inline.

* `capabilities/visualize.py`: i18n was applied to the review-stage messages
  after the PR forked. Kept the new try/except review-fallback structure but
  routed all three messages through `i18n.t(...)`; added `review_skipped_error`
  key to en/zh visualize.yaml.

Other PR changes applied as-is:
* `executors.py` / `cloud_provider.py`: inline Gemini 2.5/3.x default-down
* `loader.py`: section_map entry for `visualize`
* `init.py`: `capabilities.visualize` default with max_tokens=16384
* `code_generator_agent.py`: defensive root-tag trim for svg/html

Closes #489.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 17:50:56 +08:00
Bingxi Zhao (Frank)
90a2c14c81 chore: backend + frontend follow-ons for v1.4.0-beta
Wires the new memory / capability / settings / quiz subsystems into
existing surfaces and finishes the chat-pipeline follow-on work.

Backend:
- Session services pick up the cumulative source inventory + new tool
  tags (turn_runtime, sqlite_store, pocketbase_store, protocol,
  base_session_manager).
- LlamaIndex RAG pipeline config / document_loader / retrievers
  tightened; rag/service.py routed to match.
- Sessions / unified_ws / settings / notebook routers updated for
  delete-chat-turn, multi-user, and the new tool surface.
- TutorBot manager + Zulip channel + openai_compat_provider follow-on
  fixes layered on top of the v1.3.10 SSL/Zulip sweeps.
- runtime/{banner, launcher, orchestrator}, services/setup/init,
  prompt/manager, json_parser refined for the runtime-settings
  rewrite.

Frontend:
- Co-Learn pages and session-surfaces removed (folded into chat).
- Chat composer / messages / trace / session panels, sidebars,
  common modals, markdown renderers, and i18n updated for the new
  ask_user / write_note / source-inventory flow.
- Admin, agents, co-writer, playground, book pages picked up the
  shared updates.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 18:08:22 +08:00
Sam
6c2615df39 fix(visualize): unblock Gemini 2.5+, harden Visualize pipeline
Six bugs that combined to break the Visualize capability on Gemini 2.5
Flash (and similar thinking-by-default models). Each is independently
useful, but the user-visible symptom — Visualize "kind of works but
output is randomly truncated at ~370 chars" — needs all of them.

1. Gemini 2.5/3.x reasoning-tokens default (root cause)

   Gemini 2.5+ models burn most of `max_tokens` on internal "thinking"
   tokens by default. With `max_tokens=4096`, ~3900 went to reasoning
   and only ~160 came out as actual content, causing finish_reason=length
   on every multi-step pipeline (Visualize codegen + review, Deep Solve,
   anything that asks for a structured output beyond a sentence).

   Default `reasoning_effort="none"` for Gemini 2.5/3.x models when the
   caller doesn't specify, in all three execution paths:
   - provider_core/openai_compat_provider.py:_build_kwargs (live path)
   - executors.py:sdk_complete / sdk_stream (legacy SDK path)
   - cloud_provider.py:_openai_complete / _openai_stream (aiohttp fallback)

2. visualize capability had no agents.yaml entry

   `get_agent_params("visualize")` silently fell through to the 4096
   default because there was no section_map entry and no
   DEFAULT_AGENTS_SETTINGS entry. Added both, with a 16384-token budget
   appropriate for full HTML pages.

3. Review stage crashed hard on JSON parse failure

   `ReviewAgent.process` does `ReviewResult.model_validate(extract_json_object(response))`.
   When the model returned prose instead of JSON (common with large SVGs
   that the model can't escape into a JSON string), the parse raised and
   killed the entire turn. Wrapped pipeline.run_review() in try/except
   so review failure falls back to the unreviewed draft and the user
   still gets a rendered result.

4. Codegen output not trimmed to the root tag

   Models often wrap SVG/HTML in prose ("Here you go: <svg>…</svg>
   Enjoy!") or emit a closing code fence on the same line as `</html>`,
   which `extract_code_block`'s regex (requiring a leading \n before
   the fence) doesn't strip. Added defensive root-tag trimming for
   render_type=="svg" and render_type=="html".

Verified end-to-end on Gemini 2.5 Flash via the CLI and headless
Playwright: full 22 KB long-division HTML page, no truncation, all
interactive elements present, multi-step walkthrough completes
correctly (7852 ÷ 6 → 1308 R 4).
2026-05-17 16:36:05 +09:00
Bingxi Zhao (Frank)
85779c846b refactor env settings and installation 2026-05-11 12:59:56 +08:00
Bingxi Zhao (Frank)
2c4769a96f prepare v1.3.8 release
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 02:36:24 +08:00
Roman Barlos
444b12a6d9 feat(chat): make per-stage token limits and temperature configurable via agents.yaml (#348)
Rebased onto latest dev (post-#352) to pull in the lazy loguru import in `deeptutor/tutorbot/channels/manager.py`, which was the root cause of the smoke-test failures (unrelated to this PR's own diff).

Merging: adds per-stage `max_tokens` and `temperature` knobs under `capabilities.chat` in `agents.yaml`, bumps the `responding`/`answer_now` defaults from 1800 → 8000 to fix mid-sentence truncation on long answers, and keeps safe fallbacks in `_ChatLimits.from_config` for legacy configs. 10 new unit tests covering loader resolution and dataclass coercion.
2026-04-21 00:13:07 +08:00
Bingxi Zhao (Frank)
2745e8bde9 feat(book): introduce book capability and restructure guide/co_writer modules
- Add new `deeptutor/book/` module with multi-agent pipeline
  (ideation, spine, page planner, source explorer, synthesizer)
  and rich block system (text, code, figure, quiz, flash cards,
  callout, deep dive, timeline, animation, concept graph, etc.)
- Add `/api/routers/book.py` and `deeptutor_cli/book.py` entry points
- Add web UI under `web/app/(workspace)/book/` with sidebar,
  chat panel, page reader, spine editor, progress timeline, and
  block renderers
- Move `deeptutor/agents/co_writer` -> `deeptutor/co_writer` and
  `deeptutor/agents/guide` -> `deeptutor/guide` (then remove guide
  entirely now superseded by book)
- Remove legacy guide UI, hooks, types, and API router
- Update visualize agents/prompts, notebook service, prompt manager,
  session turn runtime, and shared services to support new flows
- Refresh chat composer, sidebar, notebook selector, and locales

Made-with: Cursor
2026-04-20 00:33:33 +08:00
Bingxi Zhao (Frank)
727d49cf8b release: v1.1.0 — LaTeX parsing overhaul, LLM probe config, extra_headers fix, notebook UUID fix
- Rewrite LaTeX block math normalization with heuristic-based $→$$ promotion
- Move LLM diagnostic probe max_tokens from env var to agents.yaml
- Fix extra_headers merge in LLM factory complete/stream (prevents TypeError)
- Fix SaveToNotebookModal to use notebook UUIDs instead of category IDs (#301)
- Add Docker + local LLM (host.docker.internal) guidance in env/compose files
- Add tests: LaTeX, notebook router, summarize agent, LLM probe, extra_headers
- Add v1.1.0 release notes and update README

Made-with: Cursor
2026-04-15 02:15:19 +08:00
Bingxi Zhao (Frank)
f3779138ae fix: remove lightrag and unify llm & search config 2026-03-13 23:48:49 +08:00
Bingxi Zhao (Frank)
9c18bf0705 codebase cleanup and decoupled, introduce cli operation 2026-03-13 20:42:16 +08:00