Skip to content

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

release(1.4.0-beta): docs, version bump, CLI init wizard, packaging

Bingxi Zhao (Frank)2c1b8e56b20c
diff --git a/README.md b/README.md
index fd59934b5..242d511ea 100644
--- a/README.md
+++ b/README.md
@@ -28,6 +28,8 @@
### 📦 Releases
+> **[2026.5.21]** [v1.4.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.4.0-beta) — Auto Mode agent-router; three-layer Memory v2 (L1/L2/L3) workbench; Deep Research / Deep Solve / Question rebuilt on the agentic engine; chat + LlamaIndex RAG refactor with session-cumulative source inventory; new tools (`ask_user`, `web_fetch`, `write_note`, `list_notebook`, `github_query`); delete-chat-turn, quiz follow-up chat, GeoGebra viewer; Visualize+Animator merge; unified capabilities infra & status i18n; settings split; env/launcher rewrite; multi-user isolation + Zulip fixes.
+
> **[2026.5.10]** [v1.3.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.10) — Remote Docker CORS recovery, `DISABLE_SSL_VERIFY` across SDK providers, safer code-block citations, and optional Matrix E2EE add-on.
> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — TutorBot Zulip and NVIDIA NIM support, safer thinking-model routing, `deeptutor start`, sidebar tooltips, and session-store parity.
@@ -48,11 +50,11 @@
> **[2026.4.28]** [v1.3.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.1) — Stability: safer RAG routing & embedding validation, Docker persistence, IME-safe input, Windows/GBK robustness.
-> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — Versioned KB indexes with re-index workflow, rebuilt Knowledge workspace, embedding auto-discovery with new adapters, Space hub.
-
<details>
<summary><b>Past releases (more than 2 weeks ago)</b></summary>
+> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — Versioned KB indexes with re-index workflow, rebuilt Knowledge workspace, embedding auto-discovery with new adapters, Space hub.
+
> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — Persistent chat attachments with file-preview drawer, attachment-aware capability pipelines, TutorBot Markdown export.
> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — Text/code/SVG attachments, one-command Setup Tour, Markdown chat export, compact KB management UI.
@@ -174,6 +176,7 @@ Notes:
### Option 2 — Install From Source
Use this when you are developing DeepTutor or want to run directly from a checkout.
+Use Python 3.11+ and Node.js 22 LTS for the closest match to CI and Docker.
**1. Clone the repository**
@@ -211,12 +214,16 @@ python -m pip install --upgrade pip
**3. Install the local package and frontend dependencies**
```bash
-pip install -e .
+python -m pip install -e .
cd web
-npm install
+npm ci --legacy-peer-deps
cd ..
```
+If you intentionally change frontend dependencies, use `npm install --legacy-peer-deps`
+to refresh `web/package-lock.json`, then commit both `web/package.json` and
+`web/package-lock.json`.
+
**4. Configure and start**
```bash
@@ -224,7 +231,19 @@ deeptutor init
deeptutor start
```
-Source installs use the local `web/` directory for the frontend. They are intentionally developer-friendly and do not write configuration to `.env`; edit `data/user/settings/*.json` or use the Web Settings page.
+Source installs use the local `web/` directory for the frontend and start it with
+Next.js dev mode. Keep the `deeptutor start` terminal open while using the app.
+They are intentionally developer-friendly and do not write configuration to
+`.env`; edit `data/user/settings/*.json` or use the Web Settings page.
+
+If `deeptutor start` reports an existing frontend that is not responding, stop
+the PID printed in the message. If no Next.js process is running, remove the
+stale lock files and start again:
+
+```bash
+rm -f web/.next/dev/lock web/.next/lock
+deeptutor start
+```
Useful developer extras:
@@ -245,7 +264,8 @@ Use this when you want the full Web app in one container. Images are published t
```bash
docker pull ghcr.io/hkuds/deeptutor:latest
-docker run -p 127.0.0.1:3782:3782 \
+docker run --rm --name deeptutor \
+ -p 127.0.0.1:3782:3782 \
-p 127.0.0.1:8001:8001 \
-v deeptutor-data:/app/data \
ghcr.io/hkuds/deeptutor:latest
@@ -264,7 +284,8 @@ Inside a Docker container, `localhost` refers to the container itself, not your
Option A — host gateway, recommended for normal Docker runs:
```bash
-docker run -p 127.0.0.1:3782:3782 \
+docker run --rm --name deeptutor \
+ -p 127.0.0.1:3782:3782 \
-p 127.0.0.1:8001:8001 \
--add-host=host.docker.internal:host-gateway \
-v deeptutor-data:/app/data \
@@ -290,14 +311,46 @@ docker run --network=host \
No `-p` mapping is needed in host-network mode. The container shares the host network directly, so open [http://127.0.0.1:3782](http://127.0.0.1:3782) by default, or the `frontend_port` configured in `/app/data/user/settings/system.json`. In this mode, host services can usually be reached with normal localhost URLs such as `http://127.0.0.1:11434/v1`. Host networking exposes container ports directly on the host and may conflict with existing services.
-To stop a foreground Docker run, press `Ctrl+C`. If you started it detached with `-d`, run `docker stop <container-name-or-id>`.
+To run in the background instead, add `-d` and follow logs by name:
+
+```bash
+docker run -d --name deeptutor \
+ -p 127.0.0.1:3782:3782 \
+ -p 127.0.0.1:8001:8001 \
+ -v deeptutor-data:/app/data \
+ ghcr.io/hkuds/deeptutor:latest
+docker logs -f deeptutor
+```
+
+To stop a foreground Docker run, press `Ctrl+C`. If you used the named detached
+container above, run `docker stop deeptutor`. Before starting another container
+with the same name, remove the stopped one with `docker rm deeptutor`; the
+`deeptutor-data` volume keeps your settings and workspace.
### Option 4 — CLI Only
-Use this when you do not need the Web UI.
+Use this when you do not need the Web UI. The CLI-only package is installed
+from a local source checkout instead of PyPI.
```bash
-pip install -U deeptutor-cli
+git clone https://github.com/HKUDS/DeepTutor.git
+cd DeepTutor
+
+python3 -m venv .venv-cli
+source .venv-cli/bin/activate
+python -m pip install --upgrade pip
+python -m pip install -e ./packaging/deeptutor-cli
+deeptutor init --cli
+deeptutor chat
+```
+
+Windows PowerShell:
+
+```powershell
+py -3.11 -m venv .venv-cli
+.\.venv-cli\Scripts\Activate.ps1
+python -m pip install --upgrade pip
+python -m pip install -e ./packaging/deeptutor-cli
deeptutor init --cli
deeptutor chat
```
@@ -319,9 +372,15 @@ deeptutor run deep_solve "Solve x^2 = 4" --tool rag --kb my-kb
deeptutor kb create my-kb --doc textbook.pdf
deeptutor kb list
deeptutor memory show
+deeptutor config show
```
-`deeptutor-cli` does not ship Web assets or server dependencies. If you later want the Web app, install the full package with `pip install -U deeptutor`, run `deeptutor init` if you want to add Web ports, and then run `deeptutor start` from the same workspace.
+The local `deeptutor-cli` install does not ship Web assets or server dependencies.
+Keep the source checkout around because the editable install points to it. If you
+later want the Web app, either follow Option 2 in the same checkout, or uninstall
+the local CLI package, install the full PyPI package with `pip install -U
+deeptutor`, run `deeptutor init` if you want to add Web ports, and then run
+`deeptutor start` from the same workspace.
### Configuration Reference
diff --git a/assets/releases/ver1-4-0-beta.md b/assets/releases/ver1-4-0-beta.md
new file mode 100644
index 000000000..745744021
--- /dev/null
+++ b/assets/releases/ver1-4-0-beta.md
@@ -0,0 +1,292 @@
+# DeepTutor v1.4.0-beta Release Notes
+
+**Release Date:** 2026.05.21
+
+v1.4.0-beta is the largest release since the agent-native rewrite. It folds an
+end-to-end **Auto Mode** on top of the existing capabilities, ships a
+**three-layer memory subsystem (L1/L2/L3)** with a dedicated workbench, rebuilds
+**Deep Research / Deep Solve / Question** on the same agentic engine as Chat,
+re-architects the **chat capability + LlamaIndex RAG pipeline** around a
+session-cumulative source inventory, unifies the **Capabilities infrastructure
+and i18n**, merges the Animator menu into **Visualize**, and reorganises
+**Settings, environment, and the local launcher**. Several new chat tools
+(`ask_user`, `web_fetch`, `write_note`, `list_notebook`, `github_query`) plus a
+delete-chat-turn flow, quiz follow-up chat, and a GeoGebra viewer round out the
+release.
+
+## Highlights
+
+### Auto Mode — Agentic Capability Router
+A new `auto` capability sits on top of the existing modes and chooses the right
+one for each request, instead of forcing the user to pick a mode up front.
+
+- **Three-stage agent loop** — `ANALYZING` (single LLM call, streamed as
+ thinking) → `DELEGATING` (up to `max_iterations` of router calls that emit
+ `delegate_to_<cap>` tool calls or atomic tool calls) → `SYNTHESIZING` (final
+ inline answer, either passed through from the loop or assembled by a closing
+ LLM call).
+- **Routes to real capabilities** — `deep_solve`, `deep_question`,
+ `deep_research`, `math_animator`, `visualize`, plus the chat-level atomic
+ tools (`web_search`, `web_fetch`, `rag`, …) live behind the same router so
+ the LLM can mix retrieval and full sub-capability runs in one turn.
+- **Bounded retries and quotas** — independent retry budgets for router-LLM
+ errors, per-delegation failures, and arg-validation feedback; a configurable
+ `max_same_capability_calls` quota keeps the loop from spinning on one mode.
+- **Clean conversation history** — sub-capability events flow through a
+ `forward_events` shim that tags every content event with a `call_id`, so the
+ conversation turn-runtime filter keeps only Auto's own final synthesis in
+ saved history. Sub-runs are still streamed live to the UI.
+- **`answer_now` fast-path** — when the user asks to "answer now" the pipeline
+ skips analysis + delegation and produces an immediate inline reply.
+
+### Three-Layer Memory Subsystem (Memory v2)
+The previous flat memory page is replaced by a structured three-layer store
+with an explicit consolidation pipeline and a dedicated workbench.
+
+- **L1 / L2 / L3 layout** — L1 captures raw run traces, L2 holds normalised
+ document records, L3 holds curated slots per surface (chat, notebook, book,
+ TutorBot). Per-user paths flow through `PathService` so multi-user
+ deployments stay isolated.
+- **Consolidator pipeline** — modular `consolidator/` modules (chunker, guards,
+ parse, references, runs, modes, line-doc, meta) turn run traces into
+ versioned line-oriented documents with stable ids, references between
+ layers, and a snapshot history.
+- **Memory Workbench UI** — new `/memory` routes (`graph`, `l1`, `l2`, `l3`,
+ `resolve`) ship as standalone pages with workbench, hub, graph viewer, run
+ panel, and an archived-state banner. A reusable `MemorySection` component is
+ embedded where the legacy memory panel used to live.
+- **First-class chat tools** — `read_memory` and `write_memory` are exposed
+ as agent tools (with i18n hints) so chat / Auto can recall and update memory
+ inside a turn instead of needing a separate save step.
+- **Settings integration** — Memory now has its own page under
+ `/settings/memory` with run controls, mode toggles, and storage status.
+
+### Deep Research, Deep Solve, and Question on the Agentic Engine
+The three multi-agent pipelines have been rewritten as orchestrators on top of
+the shared agentic-engine primitives, deleting hundreds of bespoke prompt
+files and per-agent classes.
+
+- **Deep Research → `agents/research/pipeline.py`** — four phases (`Rephrase`,
+ `Decompose`, `Research blocks`, `Reporting`) implemented as labeled steps
+ (`THINK` / `TOOL` / `APPEND` / `OUTLINE` / `SECTION` / `FINISH`). The dynamic
+ topic queue and `CitationManager` are preserved; the new `APPEND` label lets
+ research blocks add follow-up topics to the queue without leaving the loop.
+ `ask_user` v2 drives up to three rephrase rounds with multi-question cards.
+- **Deep Solve → `agents/solve/pipeline.py`** — `Pre-retrieve` (KB-only),
+ `Plan`, `Solve` (per-step `THINK` / `TOOL` / `FINISH` / `REPLAN` loop with a
+ back-edge from solve to plan), and a final `Synthesize` step. Each step's
+ `FINISH` flows into the next step's prompt context so the answer reads as
+ one continuous narrative.
+- **Question / Quiz** — coordinator + pipeline replace the old `generator` /
+ `idea_agent` / `models` modules; the old prompt directories have been
+ removed entirely.
+- **All three drop the legacy `agents/` and `prompts/` directories** for their
+ respective modes, leaving one pipeline file and shared labeled-step prompts.
+
+### Chat Capability & LlamaIndex RAG Refactor
+The agentic chat pipeline has been rebuilt around a session-cumulative
+"Attached Sources" manifest and a cleaner LlamaIndex pipeline.
+
+- **Branch-isolated source inventory** — `services/session/source_inventory.py`
+ materialises every source attached on the active branch's ancestor chain.
+ Fresh sources from the current turn show a full preview; historical sources
+ show a one-line row with id, name, kind, size, and the turn ordinal where
+ they first appeared. The LLM calls `read_source(id)` to expand the full
+ text on demand. Sibling branches never leak sources into each other.
+- **LlamaIndex pipeline split-out** — dedicated `config.py`, `ingestion.py`,
+ `retrievers.py`, and `document_loader.py` replace the previous monolithic
+ pipeline module. Storage stays backward-compatible with v1.3 versioned
+ indexes.
+- **Lean agentic chat prompt** — `agentic_chat.yaml` (EN/ZH) was rewritten to
+ match the new tool surface and the source-inventory contract; the old
+ parallel-tool prompt scaffolding is gone.
+- **Builtin tools registry** — `tools/builtin/__init__.py` is the single place
+ where chat-mounted tools, hint prompts, and arg-augmentation wrappers are
+ registered.
+
+### Capabilities Infrastructure Unification
+Every capability now goes through one shared envelope, one status-i18n loader,
+and one cost-tracking surface.
+
+- **`emit_capability_result` helper** — every capability emits its final
+ result through one helper that fills the result envelope (label, summary,
+ payload, render hints) and the trailing usage-tracker totals consistently.
+- **`StatusI18n`** — capability status copy lives in
+ `capabilities/prompts/{en,zh}/<name>.yaml` and is loaded via a shared
+ `StatusI18n` accessor. Hard-coded English status strings have been removed
+ from the pipelines.
+- **`UsageTracker` cost surface** — token usage and cost are tracked through
+ one tracker per capability run, exposed to the result envelope, and shown
+ on the new `/settings/capabilities` admin page (live list, defaults,
+ per-capability override toggles).
+- **Deprecated `main.yaml` keys removed** — the legacy `main.yaml` capability
+ copy has been deleted in favor of per-capability prompt files.
+
+### Visualize: Animator Folded Into One Capability
+The standalone Animator menu has been merged into Visualize so the user picks a
+visualization once and the system chooses the renderer.
+
+- **`render_type` discriminator** — `AnalysisAgent` picks one of six render
+ types — `svg`, `chartjs`, `mermaid`, `html` (text-emitting, three-stage
+ pipeline) or `manim_video` / `manim_image` (Manim subprocess pipeline). The
+ result envelope carries `render_type` so the frontend delegates to the
+ right viewer.
+- **Single sidebar entry** — the old `Animator` menu entry is gone; users now
+ go through `Visualize` for both static charts and Manim videos. The
+ fullscreen viewer / config panel handle all render types.
+
+### New Chat Tools
+- **`ask_user`** — packages 1–3 structured questions into a single payload that
+ pauses the same turn until the user answers. The frontend renders a card
+ letting the user navigate questions and submit answers in one batch; the
+ pipeline resumes the turn with the answers wired back as the tool result.
+ Used by Deep Research's Rephrase phase and available to chat / Auto.
+- **`web_fetch`** — URL fetch with readable-content extraction, strict scheme
+ / private-IP / size guards (applied both pre-flight and post-redirect),
+ and `…[truncated]` markers when output exceeds the cap.
+- **`write_note`** — replaces the old `save_to_notebook` tool. Two modes:
+ `append` creates a new record (default body is the rendered transcript,
+ optional agent-authored body) and `edit` updates an existing record by
+ `record_id`.
+- **`list_notebook`** — read-only index / drill-down listing of the active
+ user's notebooks and records. Only mounted when the user actually has
+ notebooks, so empty runs are impossible by construction.
+- **`github_query`** — read-only `gh` CLI wrapper covering `pr`, `issue`,
+ `run`, `repo`, and a GET-only `api` fallback. No mutation verbs are
+ reachable through the tool surface. Returns a clean "tool unavailable"
+ outcome when `gh` is not installed.
+
+### Chat Surface Features
+- **Delete chat turn** (#443) — message items now carry a stable `id`, the
+ session API exposes `deleteMessage`, the chat reducer adds a `DELETE_TURN`
+ action, and a 409 vs 404 check rejects deletion of a still-running turn.
+ Optimistic temp ids are resolved before deletion to avoid orphaned UI rows.
+- **Quiz follow-up chat composer** — `FollowupChatComposer` and
+ `QuizFollowupContext` let the user start a chat thread directly from a quiz
+ question. The composer reuses the main `ChatComposer` (look, @space
+ pickers, KB picker, attachments, LLM selector) but routes sends through a
+ dedicated follow-up controller. Companion `quiz-judge.ts` helper supports
+ judging follow-up answers inline.
+- **Quiz UI polish** — quiz answer textarea is vertically resizable (#478);
+ question content normalises single newlines to Markdown paragraphs (#441).
+- **GeoGebra viewer** — `Geogebra.tsx`, `GeogebraOpenCTA.tsx`, and
+ `GeogebraTabContext` add a GeoGebra applet renderer (loaded via the
+ official GGB applet script) so geometry / algebra snippets can be opened
+ inline alongside chat answers.
+
+### Multi-User Data Isolation
+Several regressions and gaps from the v1.3.x multi-user introduction were
+fixed in a focused pass (#474, #465).
+
+- **Auth decoupled from middleware** — multi-user identity resolution no
+ longer relies on global middleware state, fixing rebase regressions that
+ caused cross-user data bleed under specific routing orders.
+- **Legacy session manager path capture** — the older session manager
+ inherited the active user scope correctly, so its file paths land inside
+ the per-user workspace instead of the shared default.
+- **Frontend uses `apiFetch` everywhere** — every authenticated client call
+ now goes through `apiFetch()` so the auth header is attached consistently.
+- **SSL bypass sweep** — `DISABLE_SSL_VERIFY` now reaches the codex provider
+ and four embedding adapters that were still missing it after v1.3.10.
+
+### Environment Settings, Installer, and Local Launcher
+The install + launch story has been rewritten to remove the `.env` parsing
+maze and make `deeptutor start` / `deeptutor init` first-class.
+
+- **`runtime_settings.py`** — system / auth / launch settings now live in
+ one typed module with explicit defaults (`backend_port`, `frontend_port`,
+ `cors_origins`, `disable_ssl_verify`, `chat_attachment_dir`, …) and JSON
+ storage under `data/user/settings/`. The 280+ line legacy `env_store.py`
+ and the two `.env.example` files have been deleted.
+- **`runtime/launcher.py`** — single async launcher that owns the
+ backend + frontend lifecycle, port discovery, readiness probes, and
+ cleanup. Generates `web/.env.local` so the Next.js frontend always picks
+ up the resolved backend port.
+- **`deeptutor/runtime/banner.py`** — localized startup banner shared
+ between `deeptutor start` and `deeptutor init`; reads the language
+ preference from interface settings so the banner matches the UI locale.
+- **`init_wizard.py`** — interactive `deeptutor init` wizard with provider
+ menu, env-var auto-detect for API keys, live `GET {base_url}/models`
+ fetch, curated fallback list, and an optional connectivity probe before
+ save.
+- **`model_catalog.py` trimmed** — the catalog file shrank by ~400 lines as
+ per-provider boilerplate moved into `provider_registry` and adapter
+ modules.
+
+### Settings UI Reorganization
+The single `/settings` page has been split into focused tabs.
+
+- **New routes** — `/settings/appearance`, `/settings/capabilities`,
+ `/settings/embedding`, `/settings/llm`, `/settings/mcp`,
+ `/settings/memory`, `/settings/search`, `/settings/status`,
+ `/settings/tools`, with a shared layout and items index.
+- **Tools page** — lists every chat-mountable tool, surfaces availability
+ (e.g. `gh` for `github_query`), and exposes per-tool toggles.
+- **Capabilities page** — pairs the new `UsageTracker` cost surface with
+ per-capability defaults and override toggles described above.
+
+### Zulip Channel Integration
+The TutorBot Zulip channel (added in v1.3.9) gets a follow-up sweep of fixes
+and a self-subscribe feature (#480).
+
+- **Auto-subscribe channels for @mentions** — Bot can subscribe itself to
+ any channel where it gets @mentioned so it actually receives the message
+ in topics. Subscribed-channel warnings are downgraded to info-level so
+ startup logs stop misleadingly flagging the success path.
+- **All mention flag types supported** — `mentioned`, `wildcard_mentioned`,
+ `topic_wildcard_mentioned`, and `stream_wildcard_mentioned` all trigger
+ the bot, fixing channel-`@`-mention silence.
+- **Attachment send fixes** — re-sent attachments no longer treat the Zulip
+ upload path as a local file, the upload helper no longer crashes on
+ `'str' object has no attribute 'name'`, and missing routing metadata is
+ rebuilt from `_recipient_map` so `Message must have recipients` errors
+ are eliminated.
+- **Progress message dedup** — internal `_tool_hint` progress events are
+ filtered out of channel sends so the user no longer sees duplicate "tool
+ starting…" lines.
+- **Test coverage** — new unit tests for attachment upload + send recovery
+ and channel-subscription behavior.
+
+## Tests
+
+- New tests for the Auto pipeline, delegation, schemas, and the
+ `auto` capability surface — 1100+ lines of new coverage including
+ end-to-end agent-loop behavior.
+- Full test coverage for the new memory subsystem — chunker, consolidator,
+ document, ids, line-doc, merge, meta settings, modes, ops, references,
+ runs, store.
+- Per-tool unit tests for `ask_user`, `github_query`, `list_notebook`,
+ `web_fetch`, and `write_note`, plus ask-user UI state helpers.
+- Refit chat / research / solve / question pipeline tests against the
+ agentic-engine labels (`THINK` / `TOOL` / `APPEND` / `FINISH` / …).
+- New session / source-inventory tests covering branch isolation and
+ cumulative manifest behavior.
+- Frontend tests cover the message-branches helper, version surface, and
+ ask-user state machine.
+
+## Upgrade Notes
+
+- **Settings file relocation** — first launch will migrate any
+ `.env`-based settings into the new JSON files under
+ `data/user/settings/`. The legacy `env_store` shim is gone; if you
+ scripted `.env` writes externally, point them at
+ `runtime_settings.py` or the `/settings` API instead.
+- **`deeptutor start` is the recommended launcher** — `start_web.py` /
+ `start_tour.py` continue to work but are now thin wrappers around the
+ new `runtime/launcher.py`. Run `deeptutor init` once to seed providers
+ and credentials on a fresh machine.
+- **Animator menu users** — point at **Visualize** instead. The
+ capability now picks Manim automatically when the user asks for a
+ video / animation; existing Manim-rendered records are unaffected.
+- **Memory data migration** — the legacy single-blob memory format is
+ read by the consolidator on first access and written back as L2 / L3
+ records. No manual step is required; old snapshots remain on disk.
+- **Capability authors** — emit results via
+ `capabilities/_shared.emit_capability_result` and put status copy in
+ `capabilities/prompts/{en,zh}/<name>.yaml`. Hard-coded English status
+ strings will fail review.
+- **Beta scope** — this release ships substantial new surfaces (Auto,
+ Memory v2, settings split). Pin to `v1.4.0-beta` for production until
+ the GA cut; bug reports against any of the new modules are welcome.
+
+**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.3.10...v1.4.0-beta
diff --git a/deeptutor/__version__.py b/deeptutor/__version__.py
index c82d232df..aaab2524f 100644
--- a/deeptutor/__version__.py
+++ b/deeptutor/__version__.py
@@ -6,6 +6,6 @@ before publishing to PyPI; the web sidebar badge and CLI banner read from this
file directly.
"""
-__version__ = "1.4.0"
+__version__ = "1.4.0-beta"
__all__ = ("__version__",)
diff --git a/deeptutor_cli/README.md b/deeptutor_cli/README.md
index c666c7ec0..f3806475d 100644
--- a/deeptutor_cli/README.md
+++ b/deeptutor_cli/README.md
@@ -8,8 +8,13 @@ Agent-first 的命令行界面。两条核心路径:
## 安装
```bash
-# 仅 CLI(含 RAG / 文档解析 / 各家 LLM provider SDK)
-pip install deeptutor-cli
+# 仅 CLI(本地源码安装,含 RAG / 文档解析 / 各家 LLM provider SDK)
+git clone https://github.com/HKUDS/DeepTutor.git
+cd DeepTutor
+python3 -m venv .venv-cli
+source .venv-cli/bin/activate
+python -m pip install --upgrade pip
+python -m pip install -e ./packaging/deeptutor-cli
deeptutor init --cli
# CLI + Web/API 服务
@@ -28,6 +33,16 @@ pip install -e ".[all]" # 全部依赖(含开发工具)
`deeptutor init --cli` 和普通 `deeptutor init` 使用同一套 `data/user/settings/` 配置目录;区别是 `--cli` 不询问 Web 后端/前端端口,仍会创建 `system.json`、`auth.json`、`integrations.json`、`model_catalog.json`、`main.yaml` 和 `agents.yaml`,并继续询问 LLM 配置。Embedding 配置默认跳过;如果要使用 `deeptutor kb ...` 或 RAG,请在向导里选择配置 embedding,或稍后编辑 `data/user/settings/model_catalog.json`。
+Windows PowerShell 可使用:
+
+```powershell
+py -3.11 -m venv .venv-cli
+.\.venv-cli\Scripts\Activate.ps1
+python -m pip install --upgrade pip
+python -m pip install -e ./packaging/deeptutor-cli
+deeptutor init --cli
+```
+
---
## `run` — 执行 Capability
@@ -132,7 +147,7 @@ deeptutor chat [options]
deeptutor serve [--host 0.0.0.0] [--port 8001] [--reload]
```
-`deeptutor serve` 需要完整 Web/API 依赖;如果你是通过 `pip install deeptutor-cli` 安装的 CLI-only 包,请先切换到 `pip install -U deeptutor`。
+`deeptutor serve` 需要完整 Web/API 依赖;如果你是通过本地 `./packaging/deeptutor-cli` 安装的 CLI-only 包,请先卸载本地 CLI 包并切换到 `pip install -U deeptutor`。
---
diff --git a/deeptutor_cli/_tool_result.py b/deeptutor_cli/_tool_result.py
new file mode 100644
index 000000000..987169e4a
--- /dev/null
+++ b/deeptutor_cli/_tool_result.py
@@ -0,0 +1,166 @@
+"""Tool-result truncation and on-demand expansion buffer for the CLI.
+
+Tool outputs in agent loops (RAG hits, web search dumps, file reads, code
+execution stdout) can run to hundreds of lines. Streaming the full body into
+the terminal drowns the reasoning around it and forces the user to scroll
+past noise on every turn. We instead show a short head and stash the full
+body so the REPL can re-print it on request — mirroring the
+``… +N lines (ctrl+o to expand)`` UX users already know from other CLI
+agents.
+
+This module is pure logic so it can be unit-tested without a live REPL:
+
+* :func:`truncate_for_display` decides what to show now.
+* :class:`ToolResultBuffer` remembers the full bodies so the
+ ``/show`` REPL command (and any future Ctrl+O keybinding) can expand
+ them later.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+# Defaults tuned for "agent reasoning is the signal, tool dumps are the
+# noise". Ten lines is enough to recognise the result; long single lines
+# (a giant JSON blob, a binary blob) get a hard character cap so the head
+# never blows past one screen.
+DEFAULT_HEAD_LINES = 10
+DEFAULT_LINE_HARD_CAP = 240
+# Cap how many recent tool results we hold onto so a long REPL session
+# doesn't keep every tool dump in memory forever. The /show command only
+# needs the recent ones; older results stay in the session DB if anyone
+# wants the full archive.
+DEFAULT_RING_CAPACITY = 32
+
+
+def truncate_for_display(
+ body: str,
+ *,
+ head_lines: int = DEFAULT_HEAD_LINES,
+ line_hard_cap: int = DEFAULT_LINE_HARD_CAP,
+) -> tuple[str, int]:
+ """Return ``(visible_text, hidden_line_count)`` for an inline preview.
+
+ ``hidden_line_count == 0`` means the full body fits within the budget
+ and the caller should not append an expansion hint. The returned
+ ``visible_text`` already has overlong single lines clipped with an
+ ellipsis so the head can't blow past one screen on JSON-style output.
+ """
+
+ if head_lines <= 0:
+ return "", _line_count(body)
+
+ lines = body.split("\n")
+ if len(lines) <= head_lines:
+ head_slice = lines
+ hidden = 0
+ else:
+ head_slice = lines[:head_lines]
+ hidden = len(lines) - head_lines
+
+ clipped = [_clip_long_line(line, line_hard_cap) for line in head_slice]
+ return "\n".join(clipped), hidden
+
+
+def _line_count(body: str) -> int:
+ if not body:
+ return 0
+ return body.count("\n") + 1
+
+
+def _clip_long_line(line: str, line_hard_cap: int) -> str:
+ if line_hard_cap <= 0 or len(line) <= line_hard_cap:
+ return line
+ # Keep most of the line, append a marker so the reader knows the line
+ # itself was clipped (independent of the line-count hidden marker).
+ return line[: line_hard_cap - 1] + "…"
+
+
+@dataclass(slots=True)
+class ToolResultEntry:
+ """One captured tool result that can later be expanded by ``/show``."""
+
+ index: int # 1-based, monotonically increasing per REPL session
+ label: str # tool name as reported by the stream
+ body: str # untruncated text
+
+
+@dataclass(slots=True)
+class ToolResultBuffer:
+ """Bounded ring of recent tool results.
+
+ The buffer is intentionally tiny — its only purpose is to back the
+ ``/show`` REPL command, not to be a transcript store.
+ """
+
+ capacity: int = DEFAULT_RING_CAPACITY
+ head_lines: int = DEFAULT_HEAD_LINES
+ line_hard_cap: int = DEFAULT_LINE_HARD_CAP
+ _entries: list[ToolResultEntry] = field(default_factory=list)
+ _next_index: int = 1
+
+ def remember(self, label: str, body: str) -> ToolResultEntry:
+ entry = ToolResultEntry(index=self._next_index, label=label or "tool", body=body)
+ self._next_index += 1
+ self._entries.append(entry)
+ if len(self._entries) > self.capacity:
+ # Drop oldest; preserve indices so ``/show 7`` keeps meaning
+ # "the seventh tool result of this session" even after older
+ # entries fall out of the ring.
+ del self._entries[: len(self._entries) - self.capacity]
+ return entry
+
+ def truncate(self, body: str) -> tuple[str, int]:
+ """Front-door to :func:`truncate_for_display` using this buffer's policy."""
+
+ return truncate_for_display(
+ body,
+ head_lines=self.head_lines,
+ line_hard_cap=self.line_hard_cap,
+ )
+
+ def last(self) -> ToolResultEntry | None:
+ return self._entries[-1] if self._entries else None
+
+ def get(self, selector: str | int | None) -> ToolResultEntry | None:
+ """Resolve ``/show`` arguments: ``None``/``"last"`` → most recent;
+ a positive integer → entry with that 1-based index;
+ any other string → most recent entry whose label matches.
+ """
+
+ if selector is None or selector == "" or selector == "last":
+ return self.last()
+ if isinstance(selector, int):
+ return self._by_index(selector)
+ text = str(selector).strip()
+ if text.isdigit():
+ return self._by_index(int(text))
+ for entry in reversed(self._entries):
+ if entry.label == text:
+ return entry
+ return None
+
+ def entries(self) -> list[ToolResultEntry]:
+ """Snapshot of current contents (newest last). For inspection/tests."""
+
+ return list(self._entries)
+
+ def clear(self) -> None:
+ self._entries.clear()
+ self._next_index = 1
+
+ def _by_index(self, idx: int) -> ToolResultEntry | None:
+ for entry in self._entries:
+ if entry.index == idx:
+ return entry
+ return None
+
+
+__all__ = [
+ "DEFAULT_HEAD_LINES",
+ "DEFAULT_LINE_HARD_CAP",
+ "DEFAULT_RING_CAPACITY",
+ "ToolResultBuffer",
+ "ToolResultEntry",
+ "truncate_for_display",
+]
diff --git a/deeptutor_cli/chat.py b/deeptutor_cli/chat.py
index b8f9e22a6..e0f496765 100644
--- a/deeptutor_cli/chat.py
+++ b/deeptutor_cli/chat.py
@@ -11,7 +11,14 @@ import typer
from deeptutor.app import DeepTutorApp, TurnRequest
-from .common import console, maybe_run, regenerate_and_render, run_turn_and_render
+from .common import (
+ console,
+ maybe_run,
+ regenerate_and_render,
+ render_tool_result_entry,
+ run_turn_and_render,
+ tool_results,
+)
@dataclass
@@ -84,6 +91,7 @@ async def _chat_repl(state: ChatState) -> None:
" /kb <name>|none\n"
" /history add <id> | /history clear\n"
" /notebook add <ref> | /notebook clear\n"
+ " /show last|<n> — expand a truncated tool result\n"
" /refs /config show|set|clear",
title="deeptutor chat",
)
@@ -181,6 +189,20 @@ def _apply_command(raw: str, state: ChatState) -> bool:
state.notebook_references.extend(_parse_notebook_refs([parts[2]]))
_print_state(state)
return True
+ if command == "/show":
+ selector = parts[1] if len(parts) >= 2 else "last"
+ entry = tool_results.get(selector)
+ if entry is None:
+ if selector == "last":
+ console.print("[dim]No tool result captured yet in this session.[/]")
+ else:
+ console.print(
+ f"[dim]No tool result matches [bold]{selector}[/]. "
+ f"Available: {[e.index for e in tool_results.entries()] or 'none'}.[/]"
+ )
+ else:
+ render_tool_result_entry(entry)
+ return True
if command == "/config" and len(parts) >= 2:
subcommand = parts[1]
if subcommand == "show":
diff --git a/deeptutor_cli/common.py b/deeptutor_cli/common.py
index ec410ec41..27339ac71 100644
--- a/deeptutor_cli/common.py
+++ b/deeptutor_cli/common.py
@@ -13,8 +13,16 @@ from rich.table import Table
from deeptutor.app import DeepTutorApp, TurnRequest
+from ._tool_result import ToolResultBuffer, ToolResultEntry
+
console = Console()
+# Process-wide buffer that backs the ``/show`` REPL command. The buffer
+# lives at module scope so a single ``deeptutor chat`` session shares one
+# ring across turns; ``deeptutor run`` doesn't read it (single-shot mode),
+# but populating it is harmless.
+tool_results = ToolResultBuffer()
+
def parse_config_items(items: list[str]) -> dict[str, Any]:
config: dict[str, Any] = {}
@@ -132,13 +140,9 @@ async def render_turn_stream(*, app: DeepTutorApp, turn_id: str) -> None:
elif event_type == "content":
content_buf += str(item.get("content", "") or "")
elif event_type == "tool_call":
- metadata = item.get("metadata", {}) or {}
- console.print(
- f" [yellow]tool[/] {item.get('content', '')} {json.dumps(metadata, ensure_ascii=False)}",
- highlight=False,
- )
+ _render_tool_call(item)
elif event_type == "tool_result":
- console.print(f" [green]result[/] {item.get('content', '')}", highlight=False)
+ _render_tool_result(item)
elif event_type == "error":
console.print(f"[bold red]Error:[/] {item.get('content', '')}")
elif event_type == "done":
@@ -147,6 +151,106 @@ async def render_turn_stream(*, app: DeepTutorApp, turn_id: str) -> None:
content_buf = ""
+def _render_tool_call(item: dict[str, Any]) -> None:
+ """Print a one-line tool-call header. Long arg payloads are summarised
+ so the call stays scannable; the full body lands in tool_result if the
+ tool echoes it back, or in the stream metadata for debug tooling."""
+
+ tool_name = str(item.get("content", "") or "tool")
+ metadata = item.get("metadata", {}) or {}
+ args = metadata.get("args", {})
+ # Budget the args summary so the whole header — " ● <name>(<args>)" —
+ # fits the current terminal width on one line. We pick a soft floor so
+ # very narrow terminals still get something useful.
+ overhead = len(f" ● {tool_name}()")
+ budget = max(20, (console.width or 100) - overhead)
+ summary = _summarize_call_args(args, max_len=budget)
+ if summary:
+ console.print(f" [yellow]●[/] {tool_name}([dim]{summary}[/])", highlight=False)
+ else:
+ console.print(f" [yellow]●[/] {tool_name}", highlight=False)
+
+
+def _render_tool_result(item: dict[str, Any]) -> None:
+ """Print a truncated preview of a tool result, stashing the full text
+ in the shared :data:`tool_results` buffer so ``/show`` can expand it."""
+
+ body = str(item.get("content", "") or "")
+ metadata = item.get("metadata", {}) or {}
+ label = str(metadata.get("tool") or "tool")
+ entry = tool_results.remember(label, body)
+ head, hidden = tool_results.truncate(body)
+
+ # Empty result still gets a marker so the user can see the call closed.
+ if not head.strip() and not hidden:
+ console.print(
+ f" [green]└[/] [dim]#{entry.index} {label} → (empty result)[/]", highlight=False
+ )
+ return
+
+ if head:
+ for line in head.split("\n"):
+ console.print(f" [green]│[/] {line}", highlight=False)
+ if hidden:
+ console.print(
+ f" [green]└[/] [dim]#{entry.index} {label} — +{hidden} more line"
+ f"{'s' if hidden != 1 else ''}; "
+ f"run [bold]/show {entry.index}[/] (or [bold]/show last[/]) to expand[/]",
+ highlight=False,
+ )
+ else:
+ console.print(f" [green]└[/] [dim]#{entry.index} {label}[/]", highlight=False)
+
+
+def _summarize_call_args(args: Any, max_len: int = 120) -> str:
+ """Render call args as a short ``key=value, …`` string.
+
+ The full rendering is assembled first, then a single trailing-ellipsis
+ clip is applied so we never leave a dangling ``", "`` at the end when
+ the last key's value runs over the budget.
+ """
+
+ if isinstance(args, dict) and args:
+ rendered = ", ".join(f"{key}={_one_line(value)}" for key, value in args.items())
+ elif args:
+ rendered = _one_line(args)
+ else:
+ return ""
+ if len(rendered) > max_len:
+ return rendered[: max_len - 1].rstrip(", ") + "…"
+ return rendered
+
+
+def _one_line(value: Any) -> str:
+ """Compact one-line repr for a single arg value. No truncation here —
+ the caller's overall budget handles that uniformly so we don't double-
+ clip a dict and end up with a half-finished key=value pair."""
+
+ if isinstance(value, str):
+ text = value
+ else:
+ try:
+ text = json.dumps(value, ensure_ascii=False)
+ except (TypeError, ValueError):
+ text = repr(value)
+ return text.replace("\n", " ")
+
+
+def render_tool_result_entry(entry: ToolResultEntry) -> None:
+ """Fully print a stored tool result. Backs the ``/show`` REPL command."""
+
+ from rich.panel import Panel
+
+ console.print(
+ Panel(
+ entry.body or "[dim](empty result)[/]",
+ title=f"#{entry.index} {entry.label}",
+ border_style="green",
+ ),
+ highlight=False,
+ )
+
+
def build_turn_request(
*,
content: str,
diff --git a/deeptutor_cli/config_cmd.py b/deeptutor_cli/config_cmd.py
index 8b6903fd9..3ce29166b 100644
--- a/deeptutor_cli/config_cmd.py
+++ b/deeptutor_cli/config_cmd.py
@@ -29,7 +29,6 @@ def register(app: typer.Typer) -> None:
system_settings = load_system_settings()
llm_runtime = resolve_llm_runtime_config()
- embedding_runtime = resolve_embedding_runtime_config()
search_runtime = resolve_search_runtime_config()
llm_info = {
"binding_hint": llm_runtime.binding_hint,
@@ -41,6 +40,25 @@ def register(app: typer.Typer) -> None:
"extra_headers": llm_runtime.extra_headers,
"api_key": "***" if llm_runtime.api_key else "(not set)",
}
+ try:
+ embedding_runtime = resolve_embedding_runtime_config()
+ embedding_info = {
+ "status": "configured",
+ "binding_hint": embedding_runtime.binding_hint,
+ "provider": embedding_runtime.provider_name,
+ "provider_mode": embedding_runtime.provider_mode,
+ "model": embedding_runtime.model,
+ "base_url": embedding_runtime.effective_url,
+ "api_version": embedding_runtime.api_version,
+ "extra_headers": embedding_runtime.extra_headers,
+ "api_key": "***" if embedding_runtime.api_key else "(not set)",
+ "dimension": embedding_runtime.dimension,
+ }
+ except ValueError as exc:
+ embedding_info = {
+ "status": "not_configured",
+ "message": str(exc),
+ }
try:
main_cfg = load_config_with_main("main.yaml")
@@ -55,17 +73,7 @@ def register(app: typer.Typer) -> None:
"frontend": system_settings["frontend_port"],
},
"llm": llm_info,
- "embedding": {
- "binding_hint": embedding_runtime.binding_hint,
- "provider": embedding_runtime.provider_name,
- "provider_mode": embedding_runtime.provider_mode,
- "model": embedding_runtime.model,
- "base_url": embedding_runtime.effective_url,
- "api_version": embedding_runtime.api_version,
- "extra_headers": embedding_runtime.extra_headers,
- "api_key": "***" if embedding_runtime.api_key else "(not set)",
- "dimension": embedding_runtime.dimension,
- },
+ "embedding": embedding_info,
"search": {
"provider": search_runtime.provider or "(optional)",
"requested_provider": search_runtime.requested_provider or "(optional)",
diff --git a/deeptutor_cli/init_cmd.py b/deeptutor_cli/init_cmd.py
index 455deee89..d81cbcd51 100644
--- a/deeptutor_cli/init_cmd.py
+++ b/deeptutor_cli/init_cmd.py
@@ -1,15 +1,32 @@
-"""Interactive runtime settings initializer."""
+"""Interactive runtime settings initializer.
+
+``deeptutor init`` walks the user through a four-step wizard (ports → LLM →
+embedding → review) that writes the same files as the Web Settings page.
+
+Heavy lifting (provider menu, live ``/models`` fetch, connectivity probe,
+review panel) lives in :mod:`deeptutor_cli.init_wizard`. This module is
+intentionally thin so the order of steps is easy to read top-to-bottom.
+"""
from __future__ import annotations
from pathlib import Path
+from rich.console import Console
import typer
from deeptutor.runtime.home import DEEPTUTOR_HOME_ENV, get_runtime_home
+from . import init_wizard as wiz
+
def _reset_runtime_singletons() -> None:
+ """Drop cached service instances so the new DEEPTUTOR_HOME takes effect.
+
+ ``deeptutor init`` may pass ``--home`` to target a different workspace; the
+ singletons cache paths from the *previous* PathService and will silently
+ write to the wrong place if not cleared.
+ """
try:
from deeptutor.services.path_service import PathService
@@ -30,12 +47,8 @@ def _reset_runtime_singletons() -> None:
pass
-def _prompt(default: str, label: str, *, hide: bool = False) -> str:
- value = typer.prompt(label, default=default or "", hide_input=hide, show_default=bool(default))
- return str(value or "").strip()
-
-
def _ensure_model_service(catalog: dict, service_name: str, profile_id: str, model_id: str):
+ """Locate or create the default profile + model rows we'll mutate in place."""
services = catalog.setdefault("services", {})
service = services.setdefault(
service_name,
@@ -71,6 +84,299 @@ def _ensure_model_service(catalog: dict, service_name: str, profile_id: str, mod
return profile, model
+def _llm_step(
+ console: Console,
+ strings: dict,
+ current_profile: dict,
+ current_model: dict,
+) -> wiz.LLMChoice:
+ spec = wiz.select_llm_provider(
+ console,
+ strings,
+ current_binding=str(current_profile.get("binding") or "openai"),
+ )
+
+ if spec is not None:
+ binding = spec.name
+ default_base = spec.default_api_base or str(current_profile.get("base_url") or "")
+ display_provider = spec.label
+ env_key = spec.env_key
+ else:
+ binding = (
+ typer.prompt(
+ strings["init.binding"],
+ default=str(current_profile.get("binding") or "openai"),
+ ).strip()
+ or "openai"
+ )
+ default_base = str(current_profile.get("base_url") or "")
+ display_provider = "Custom"
+ env_key = ""
+
+ edit_base = typer.confirm(strings["init.edit_base_url"], default=not bool(default_base))
+ if edit_base:
+ base_url = typer.prompt(strings["init.new_base_url"], default=default_base or "")
+ else:
+ base_url = default_base
+ wiz.info(console, f"Base URL · {base_url or '(empty)'}")
+
+ api_key = wiz.capture_api_key(
+ console,
+ strings,
+ env_key=env_key,
+ current=str(current_profile.get("api_key") or ""),
+ )
+
+ models = wiz.fetch_models(
+ console,
+ strings,
+ base_url=base_url,
+ api_key=api_key,
+ binding=binding,
+ )
+ if not models:
+ models = list(wiz.LLM_FALLBACK_MODELS.get(binding, ()))
+
+ model = wiz.select_model(
+ console,
+ strings,
+ models=models,
+ current=str(current_model.get("model") or ""),
+ )
+
+ choice = wiz.LLMChoice(
+ binding=binding,
+ base_url=base_url,
+ api_key=api_key,
+ model=model,
+ display_provider=display_provider,
+ )
+
+ if typer.confirm(strings["init.probe_offer"], default=True):
+ _probe_llm_with_retry(console, strings, choice)
+
+ return choice
+
+
+def _probe_llm_with_retry(console: Console, strings: dict, choice: wiz.LLMChoice) -> None:
+ """Run the probe; on failure, offer a single retry with a fresh API key."""
+ while True:
+ wiz.info(console, strings["init.probe_running"].format(what=choice.display_provider))
+ ok_result, elapsed_ms, error = wiz.probe_llm(
+ base_url=choice.base_url,
+ api_key=choice.api_key,
+ binding=choice.binding,
+ model=choice.model,
+ )
+ choice.probed = True
+ choice.probe_ok = ok_result
+ choice.probe_ms = elapsed_ms
+ if ok_result:
+ wiz.ok(
+ console,
+ strings["init.probe_ok"].format(what=choice.display_provider, ms=elapsed_ms),
+ )
+ return
+ wiz.fail(
+ console, strings["init.probe_fail"].format(what=choice.display_provider, error=error)
+ )
+ if not typer.confirm(strings["init.probe_retry"], default=False):
+ return
+ choice.api_key = typer.prompt(
+ strings["init.api_key_prompt"], default="", hide_input=True, show_default=False
+ )
+
+
+def _embedding_step(
+ console: Console,
+ strings: dict,
+ catalog: dict,
+ llm_api_key: str,
+) -> wiz.EmbeddingChoice | None:
+ """Returns ``None`` when the user picks ``[s] Skip``."""
+
+ from deeptutor.services.config.embedding_endpoint import (
+ EMBEDDING_PROVIDER_LABELS,
+ normalize_embedding_endpoint_for_display,
+ )
+ from deeptutor.services.config.provider_runtime import EMBEDDING_PROVIDERS
+
+ current_profile = (catalog.get("services", {}).get("embedding", {}).get("profiles") or [{}])[
+ 0
+ ] or {}
+ current_binding = str(current_profile.get("binding") or "openai")
+
+ provider_pick = wiz.select_embedding_provider(console, strings, current=current_binding)
+ if provider_pick == wiz.SKIP_SENTINEL:
+ wiz.info(console, strings["init.skipped"])
+ return None
+ if provider_pick is None:
+ provider = typer.prompt(strings["init.binding"], default=current_binding or "openai")
+ else:
+ provider = provider_pick
+
+ spec = EMBEDDING_PROVIDERS.get(provider)
+ display_provider = (
+ spec.label if spec else EMBEDDING_PROVIDER_LABELS.get(provider, provider.title())
+ )
+ default_endpoint = spec.default_api_base if spec else str(current_profile.get("base_url") or "")
+
+ edit_endpoint = typer.confirm(strings["init.edit_base_url"], default=not bool(default_endpoint))
+ endpoint = (
+ typer.prompt(strings["init.embedding_endpoint"], default=default_endpoint)
+ if edit_endpoint
+ else default_endpoint
+ )
+ endpoint = normalize_embedding_endpoint_for_display(provider, endpoint)
+ if not edit_endpoint:
+ wiz.info(console, f"Endpoint · {endpoint or '(empty)'}")
+
+ # Reuse the LLM key by default — most users share creds across services.
+ masked = wiz._mask_secret(llm_api_key)
+ if llm_api_key and typer.confirm(
+ strings["init.api_key_reuse_llm"].format(masked=masked), default=True
+ ):
+ api_key = llm_api_key
+ else:
+ api_key = typer.prompt(
+ strings["init.embedding_api_key"], default="", hide_input=True, show_default=False
+ )
+
+ # Try live ``/models`` first; fall back to the curated list (spec default
+ # first, then EMBEDDING_FALLBACK_MODELS) when the fetch returns nothing.
+ models = wiz.fetch_embedding_models(
+ console, strings, endpoint=endpoint, api_key=api_key, provider=provider
+ )
+ if not models:
+ models = list(wiz.EMBEDDING_FALLBACK_MODELS.get(provider, ()))
+ if spec and spec.default_model and spec.default_model not in models:
+ models = [spec.default_model] + models
+ model = wiz.select_model(
+ console,
+ strings,
+ models=models,
+ current=str((current_profile.get("models") or [{}])[0].get("model") or ""),
+ custom_prompt_label=strings["init.embedding_model"],
+ )
+ dimension = typer.prompt(strings["init.embedding_dimension"], default="")
+
+ choice = wiz.EmbeddingChoice(
+ binding=provider,
+ base_url=endpoint,
+ api_key=api_key,
+ model=model,
+ dimension=str(dimension or "").strip(),
+ display_provider=display_provider,
+ )
+
+ if typer.confirm(strings["init.probe_offer"], default=True):
+ wiz.info(console, strings["init.probe_running"].format(what=display_provider))
+ ok_result, elapsed_ms, error = wiz.probe_embedding(
+ base_url=choice.base_url, api_key=choice.api_key, model=choice.model
+ )
+ choice.probed = True
+ choice.probe_ok = ok_result
+ choice.probe_ms = elapsed_ms
+ if ok_result:
+ wiz.ok(console, strings["init.probe_ok"].format(what=display_provider, ms=elapsed_ms))
+ else:
+ wiz.fail(console, strings["init.probe_fail"].format(what=display_provider, error=error))
+
+ return choice
+
+
+def _search_step(
+ console: Console,
+ strings: dict,
+ catalog: dict,
+) -> wiz.SearchChoice | None:
+ """Returns ``None`` when the user picks ``[s] Skip``.
+
+ A ``provider == "none"`` result is NOT skip — it's "explicitly disable
+ web search". We still write that into the catalog so agents stop trying.
+ """
+
+ current_profile = (catalog.get("services", {}).get("search", {}).get("profiles") or [{}])[
+ 0
+ ] or {}
+ current_provider = str(current_profile.get("provider") or "tavily")
+
+ spec = wiz.select_search_provider(console, strings, current=current_provider)
+ if spec is None:
+ wiz.info(console, strings["init.skipped"])
+ return None
+
+ if spec.name == "none":
+ wiz.info(console, strings["init.search_disabled_note"])
+ return wiz.SearchChoice(provider="none", label=spec.label)
+
+ api_key = ""
+ if spec.requires_api_key:
+ env_key, env_name = wiz.search_api_key_from_env(spec.env_keys)
+ if env_key:
+ masked = wiz._mask_secret(env_key)
+ offer = strings["init.api_key_env_detected"].format(env_var=env_name, masked=masked)
+ if typer.confirm(offer, default=True):
+ api_key = env_key
+ if not api_key:
+ current_key = str(current_profile.get("api_key") or "")
+ if current_key:
+ masked = wiz._mask_secret(current_key)
+ if typer.confirm(
+ strings["init.api_key_reuse_llm"].format(masked=masked), default=True
+ ):
+ api_key = current_key
+ if not api_key:
+ api_key = typer.prompt(
+ strings["init.search_api_key_prompt"],
+ default="",
+ hide_input=True,
+ show_default=False,
+ )
+ else:
+ wiz.info(console, strings["init.search_no_key_note"].format(label=spec.label))
+
+ base_url = ""
+ if spec.requires_base_url:
+ default_url = str(current_profile.get("base_url") or "") or spec.default_base_url
+ base_url = typer.prompt(strings["init.search_base_url_prompt"], default=default_url)
+
+ return wiz.SearchChoice(
+ provider=spec.name,
+ label=spec.label,
+ api_key=api_key,
+ base_url=base_url,
+ )
+
+
+def _ensure_search_service(catalog: dict, profile_id: str) -> dict:
+ """Locate or create the default search profile we'll mutate in place."""
+ services = catalog.setdefault("services", {})
+ service = services.setdefault(
+ "search",
+ {"active_profile_id": profile_id, "profiles": []},
+ )
+ profiles = service.setdefault("profiles", [])
+ profile = next(
+ (item for item in profiles if item.get("id") == service.get("active_profile_id")), None
+ )
+ if profile is None:
+ profile = {
+ "id": profile_id,
+ "name": "Default Search",
+ "provider": "brave",
+ "base_url": "",
+ "api_key": "",
+ "api_version": "",
+ "extra_headers": {},
+ "proxy": "",
+ "models": [],
+ }
+ profiles.append(profile)
+ service["active_profile_id"] = profile_id
+ return profile
+
+
def run_init(*, cli_only: bool = False, home: str | Path | None = None) -> None:
runtime_home = get_runtime_home(home)
runtime_home.mkdir(parents=True, exist_ok=True)
@@ -87,77 +393,117 @@ def run_init(*, cli_only: bool = False, home: str | Path | None = None) -> None:
language = resolve_language()
strings = labels_for(language)
+ console = Console()
+ # CLI-only: LLM, Embedding, Search, Review = 4 steps.
+ # Full: Ports, LLM, Embedding, Search, Review = 5 steps.
+ total_steps = 4 if cli_only else 5
- print_banner(language=language, mode_key="init.mode")
- typer.echo(f"{strings['init.workspace']}: {runtime_home}")
- typer.echo(strings["init.note_settings_dir"])
+ try:
+ print_banner(console, language=language, mode_key="init.mode")
+ console.print(f"{strings['init.workspace']}: [bold]{runtime_home}[/bold]")
+ console.print(f"[dim]{strings['init.note_settings_dir']}[/dim]")
- runtime = get_runtime_settings_service()
- system = runtime.load_system(include_process_overrides=False)
- if not cli_only:
- system["backend_port"] = int(
- _prompt(str(system.get("backend_port") or 8001), strings["init.backend_port"])
- )
- system["frontend_port"] = int(
- _prompt(str(system.get("frontend_port") or 3782), strings["init.frontend_port"])
- )
- runtime.save_system(system)
-
- catalog_service = get_model_catalog_service()
- catalog = catalog_service.load()
- llm_profile, llm_model = _ensure_model_service(
- catalog,
- "llm",
- "llm-profile-default",
- "llm-model-default",
- )
- typer.echo(f"\n{strings['init.llm_section']}")
- llm_profile["binding"] = _prompt(
- str(llm_profile.get("binding") or "openai"), strings["init.binding"]
- )
- llm_profile["base_url"] = _prompt(
- str(llm_profile.get("base_url") or "https://api.openai.com/v1"),
- strings["init.base_url"],
- )
- llm_profile["api_key"] = _prompt(
- str(llm_profile.get("api_key") or ""), strings["init.api_key"], hide=True
- )
- llm_model["model"] = _prompt(
- str(llm_model.get("model") or "gpt-4o-mini"), strings["init.model"]
- )
- llm_model["name"] = llm_model["model"] or "Default Model"
-
- if typer.confirm(strings["init.confirm_embedding"], default=not cli_only):
- emb_profile, emb_model = _ensure_model_service(
- catalog,
- "embedding",
- "embedding-profile-default",
- "embedding-model-default",
- )
- typer.echo(f"\n{strings['init.embedding_section']}")
- emb_profile["binding"] = _prompt(
- str(emb_profile.get("binding") or "openai"), strings["init.binding"]
- )
- emb_profile["base_url"] = _prompt(
- str(emb_profile.get("base_url") or "https://api.openai.com/v1/embeddings"),
- strings["init.embedding_endpoint"],
- )
- emb_profile["api_key"] = _prompt(
- str(emb_profile.get("api_key") or ""),
- strings["init.embedding_api_key"],
- hide=True,
+ runtime = get_runtime_settings_service()
+ system = runtime.load_system(include_process_overrides=False)
+
+ # --- Step 1 (CLI mode skips ports) ---
+ step_num = 0
+ if not cli_only:
+ step_num += 1
+ wiz.step_header(
+ console,
+ strings["init.step_ports"].format(n=step_num, total=total_steps),
+ )
+ system["backend_port"] = int(
+ typer.prompt(
+ strings["init.backend_port"],
+ default=str(system.get("backend_port") or 8001),
+ )
+ )
+ system["frontend_port"] = int(
+ typer.prompt(
+ strings["init.frontend_port"],
+ default=str(system.get("frontend_port") or 3782),
+ )
+ )
+
+ # --- Step 2: LLM ---
+ catalog_service = get_model_catalog_service()
+ catalog = catalog_service.load()
+ llm_profile, llm_model = _ensure_model_service(
+ catalog, "llm", "llm-profile-default", "llm-model-default"
)
- emb_model["model"] = _prompt(
- str(emb_model.get("model") or "text-embedding-3-large"),
- strings["init.embedding_model"],
+ step_num += 1
+ wiz.step_header(console, strings["init.step_llm"].format(n=step_num, total=total_steps))
+ llm_choice = _llm_step(console, strings, llm_profile, llm_model)
+
+ # Apply LLM choice back into the catalog draft.
+ llm_profile["binding"] = llm_choice.binding
+ llm_profile["base_url"] = llm_choice.base_url
+ llm_profile["api_key"] = llm_choice.api_key
+ llm_model["model"] = llm_choice.model
+ llm_model["name"] = llm_choice.model or "Default Model"
+
+ # --- Step 3: Embedding (skip via [s] inside the picker) ---
+ embedding_choice: wiz.EmbeddingChoice | None = None
+ step_num += 1
+ wiz.step_header(
+ console, strings["init.step_embedding"].format(n=step_num, total=total_steps)
)
- emb_model["name"] = emb_model["model"] or "Default Embedding Model"
- emb_model["dimension"] = _prompt(
- str(emb_model.get("dimension") or ""), strings["init.embedding_dimension"]
+ embedding_choice = _embedding_step(console, strings, catalog, llm_choice.api_key)
+ if embedding_choice is not None:
+ emb_profile, emb_model = _ensure_model_service(
+ catalog,
+ "embedding",
+ "embedding-profile-default",
+ "embedding-model-default",
+ )
+ emb_profile["binding"] = embedding_choice.binding
+ emb_profile["base_url"] = embedding_choice.base_url
+ emb_profile["api_key"] = embedding_choice.api_key
+ emb_model["model"] = embedding_choice.model
+ emb_model["name"] = embedding_choice.model or "Default Embedding Model"
+ if embedding_choice.dimension:
+ emb_model["dimension"] = embedding_choice.dimension
+
+ # --- Step 4: Search (skip via [s] inside the picker) ---
+ search_choice: wiz.SearchChoice | None = None
+ step_num += 1
+ wiz.step_header(console, strings["init.step_search"].format(n=step_num, total=total_steps))
+ search_choice = _search_step(console, strings, catalog)
+ if search_choice is not None:
+ search_profile = _ensure_search_service(catalog, "search-profile-default")
+ search_profile["provider"] = search_choice.provider
+ search_profile["api_key"] = search_choice.api_key
+ search_profile["base_url"] = search_choice.base_url
+
+ # --- Step 5: Review & save ---
+ step_num += 1
+ wiz.step_header(console, strings["init.step_review"].format(n=step_num, total=total_steps))
+ wiz.render_review_panel(
+ console,
+ strings,
+ llm=llm_choice,
+ embedding=embedding_choice,
+ search=search_choice,
+ backend_port=None if cli_only else system.get("backend_port"),
+ frontend_port=None if cli_only else system.get("frontend_port"),
)
+ if not typer.confirm(strings["init.confirm_save"], default=True):
+ wiz.warn(console, strings["init.cancelled"])
+ raise typer.Exit(code=1)
+
+ if not cli_only:
+ runtime.save_system(system)
+ catalog_service.save(catalog)
+ console.print()
+ wiz.ok(console, strings["init.saved"])
+ console.print(f"[dim]{strings['init.next_step']}[/dim]")
- catalog_service.save(catalog)
- typer.echo(f"\n{strings['init.saved']}")
+ except (KeyboardInterrupt, typer.Abort):
+ console.print()
+ wiz.warn(console, strings["init.cancelled"])
+ raise typer.Exit(code=130)
def register(app: typer.Typer) -> None:
diff --git a/deeptutor_cli/init_wizard.py b/deeptutor_cli/init_wizard.py
new file mode 100644
index 000000000..551edd752
--- /dev/null
+++ b/deeptutor_cli/init_wizard.py
@@ -0,0 +1,912 @@
+"""Interactive setup helpers used by ``deeptutor init``.
+
+Drives the multi-step wizard: provider menu, API-key capture (with env-var
+auto-detect), live model-list fetch from ``GET {base_url}/models`` with a
+curated fallback list, and an optional connectivity probe before save.
+
+Everything that touches I/O (HTTP, env, stdin) goes through small helpers so
+the orchestrator in ``init_cmd.py`` stays a thin sequence of steps.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import os
+import time
+from typing import Any
+
+import httpx
+from rich.console import Console
+from rich.markup import escape as rich_escape
+from rich.panel import Panel
+from rich.table import Table
+from rich.text import Text
+import typer
+
+from deeptutor.services.provider_registry import PROVIDERS, ProviderSpec, find_by_name
+
+
+# --- Featured selection ------------------------------------------------------
+# Hand-picked, in display order, for the LLM step. Everything else is reachable
+# via the "Show all" option. Names match ProviderSpec.name in provider_registry.
+
+FEATURED_LLM_PROVIDERS: tuple[str, ...] = (
+ "openai",
+ "anthropic",
+ "deepseek",
+ "dashscope",
+ "zhipu",
+ "moonshot",
+ "gemini",
+ "siliconflow",
+ "openrouter",
+ "ollama",
+)
+
+# Fallback model lists used only when ``GET {base_url}/models`` fails or the
+# provider is "custom". Live fetch is preferred — keep these short, just enough
+# to unblock common cases.
+LLM_FALLBACK_MODELS: dict[str, tuple[str, ...]] = {
+ "openai": ("gpt-4o-mini", "gpt-4o", "o4-mini", "gpt-4.1", "gpt-4.1-mini"),
+ "anthropic": (
+ "claude-sonnet-4-6",
+ "claude-opus-4-7",
+ "claude-haiku-4-5-20251001",
+ ),
+ "deepseek": ("deepseek-chat", "deepseek-reasoner"),
+ "dashscope": ("qwen-plus", "qwen-turbo", "qwen-max", "qwen3-coder-plus"),
+ "zhipu": ("glm-4.6", "glm-4.5", "glm-4-flash"),
+ "moonshot": ("kimi-k2.6", "kimi-k2.5", "kimi-latest"),
+ "gemini": ("gemini-2.5-pro", "gemini-2.5-flash", "gemini-2.5-flash-lite"),
+ "siliconflow": (
+ "Qwen/Qwen3-Coder-480B-A35B-Instruct",
+ "deepseek-ai/DeepSeek-V3",
+ ),
+ "openrouter": (
+ "openai/gpt-4o-mini",
+ "anthropic/claude-sonnet-4-6",
+ "deepseek/deepseek-chat",
+ ),
+ "ollama": ("llama3.2", "qwen2.5", "mistral"),
+}
+
+# Featured embedding providers — display order. Source of truth for label /
+# default URL / default model is ``EMBEDDING_PROVIDERS`` in
+# ``deeptutor.services.config.provider_runtime``. Adding a new featured entry
+# just means appending its key here.
+FEATURED_EMBEDDING_PROVIDERS: tuple[str, ...] = (
+ "openai",
+ "gemini",
+ "aliyun", # DashScope / Qwen multimodal embeddings
+ "siliconflow",
+ "jina",
+ "cohere",
+ "openrouter",
+ "azure_openai",
+ "vllm", # also covers LM Studio, llama.cpp via the same OpenAI-compatible adapter
+ "ollama",
+)
+
+# Fallback model lists used only when live ``/models`` fetch fails. For
+# providers where ``EmbeddingProviderSpec.default_model`` is set, that's
+# preferred and these are extras.
+EMBEDDING_FALLBACK_MODELS: dict[str, tuple[str, ...]] = {
+ "openai": ("text-embedding-3-large", "text-embedding-3-small"),
+ "gemini": ("gemini-embedding-001", "text-embedding-004"),
+ "aliyun": ("qwen3-vl-embedding", "text-embedding-v3", "text-embedding-v2"),
+ "siliconflow": (
+ "Qwen/Qwen3-Embedding-8B",
+ "BAAI/bge-m3",
+ "BAAI/bge-large-en-v1.5",
+ ),
+ "jina": ("jina-embeddings-v3", "jina-embeddings-v2-base-en"),
+ "cohere": ("embed-v4.0", "embed-multilingual-v3.0", "embed-english-v3.0"),
+ "openrouter": ("openai/text-embedding-3-large",),
+ "vllm": ("BAAI/bge-m3",),
+ "ollama": ("nomic-embed-text", "mxbai-embed-large", "snowflake-arctic-embed"),
+}
+
+
+# --- Search providers ----------------------------------------------------------
+# Source of truth: ``SUPPORTED_SEARCH_PROVIDERS`` in
+# ``deeptutor.services.config.provider_runtime``. Each entry below describes
+# how the wizard captures the credentials/config for that provider.
+
+@dataclass(frozen=True)
+class SearchProviderSpec:
+ """How the init wizard handles one search provider."""
+
+ name: str # canonical key written into catalog.services.search.profiles[].provider
+ label: str
+ requires_api_key: bool
+ env_keys: tuple[str, ...] = () # checked in order — first non-empty wins
+ requires_base_url: bool = False
+ default_base_url: str = ""
+ hint: str = ""
+
+
+SEARCH_PROVIDERS: tuple[SearchProviderSpec, ...] = (
+ SearchProviderSpec(
+ name="brave",
+ label="Brave Search",
+ requires_api_key=True,
+ env_keys=("BRAVE_API_KEY", "SEARCH_API_KEY"),
+ hint="independent index · paid tier",
+ ),
+ SearchProviderSpec(
+ name="tavily",
+ label="Tavily",
+ requires_api_key=True,
+ env_keys=("TAVILY_API_KEY", "SEARCH_API_KEY"),
+ hint="LLM-friendly · free tier",
+ ),
+ SearchProviderSpec(
+ name="jina",
+ label="Jina Reader Search",
+ requires_api_key=True,
+ env_keys=("JINA_API_KEY", "SEARCH_API_KEY"),
+ hint="returns full page content",
+ ),
+ SearchProviderSpec(
+ name="serper",
+ label="Serper",
+ requires_api_key=True,
+ env_keys=("SERPER_API_KEY", "SEARCH_API_KEY"),
+ hint="Google results · paid",
+ ),
+ SearchProviderSpec(
+ name="perplexity",
+ label="Perplexity",
+ requires_api_key=True,
+ env_keys=("PERPLEXITY_API_KEY", "SEARCH_API_KEY"),
+ hint="answer-style search",
+ ),
+ SearchProviderSpec(
+ name="duckduckgo",
+ label="DuckDuckGo",
+ requires_api_key=False,
+ hint="no API key needed",
+ ),
+ SearchProviderSpec(
+ name="searxng",
+ label="SearXNG",
+ requires_api_key=False,
+ requires_base_url=True,
+ default_base_url="http://localhost:8888",
+ hint="self-hosted · provide your instance URL",
+ ),
+ SearchProviderSpec(
+ name="none",
+ label="Disable web search",
+ requires_api_key=False,
+ hint="agents will skip all search tools",
+ ),
+)
+
+
+# --- Data ----------------------------------------------------------------------
+
+
+@dataclass
+class LLMChoice:
+ """User-confirmed LLM step result, ready to write into the catalog."""
+
+ binding: str
+ base_url: str
+ api_key: str
+ model: str
+ display_provider: str # human-friendly label for the review panel
+ probed: bool = False
+ probe_ok: bool = False
+ probe_ms: int = 0
+
+
+@dataclass
+class EmbeddingChoice:
+ binding: str
+ base_url: str # full /embeddings URL (already normalised)
+ api_key: str
+ model: str
+ dimension: str
+ display_provider: str
+ probed: bool = False
+ probe_ok: bool = False
+ probe_ms: int = 0
+
+
+@dataclass
+class SearchChoice:
+ """User-confirmed Search step result. ``provider == 'none'`` means
+ disable web search entirely."""
+
+ provider: str
+ label: str
+ api_key: str = ""
+ base_url: str = ""
+
+
+# --- Rendering helpers ---------------------------------------------------------
+
+
+def step_header(console: Console, label: str) -> None:
+ console.print()
+ bar = "─" * 8
+ console.print(f"[bright_cyan]{bar}[/bright_cyan] [bold]{label}[/bold] [bright_cyan]{bar}[/bright_cyan]")
+ console.print()
+
+
+def info(console: Console, message: str) -> None:
+ console.print(f"[dim]{message}[/dim]")
+
+
+def ok(console: Console, message: str) -> None:
+ console.print(f"[green]✓[/green] {message}")
+
+
+def warn(console: Console, message: str) -> None:
+ console.print(f"[yellow]![/yellow] {message}")
+
+
+def fail(console: Console, message: str) -> None:
+ console.print(f"[red]✗[/red] {message}")
+
+
+def _mask_secret(value: str) -> str:
+ """Show first 4 + last 4 chars of an API key. Empty / short → fully masked."""
+ if not value:
+ return "(empty)"
+ if len(value) <= 8:
+ return "*" * len(value)
+ return f"{value[:4]}...{value[-4:]}"
+
+
+# --- Numbered-list picker ------------------------------------------------------
+
+
+def select_from_options(
+ console: Console,
+ *,
+ title: str,
+ options: list[tuple[str, str, str]], # [(key, label, hint), ...]
+ default_key: str | None = None,
+ extra_keys: dict[str, str] | None = None,
+ prompt_label: str = "Choice",
+ invalid_label: str = "Invalid choice. Try again.",
+) -> str:
+ """Render a numbered/keyed menu, return the selected key.
+
+ ``options`` is the visible numbered list. ``extra_keys`` adds letter
+ shortcuts (e.g. ``{"s": "Show all providers", "c": "Custom"}``) — these
+ show up after the numbered rows and are accepted as input.
+ """
+
+ # Titles come from i18n and may contain `[c]`-style brackets that Rich
+ # would otherwise interpret as markup tags.
+ console.print(f"[bold]{rich_escape(title)}[/bold]")
+ console.print()
+ table = Table.grid(padding=(0, 1))
+ table.add_column(style="bright_cyan", justify="right")
+ table.add_column(style="bold")
+ table.add_column(style="dim")
+ # Rich Table cells parse markup, so e.g. `[s]` would be eaten as a
+ # nonexistent tag. Wrap markers in Text so they render verbatim.
+ def _marker(text: str) -> Text:
+ return Text(text, style="bright_cyan", justify="right")
+
+ for idx, (_key, label, hint) in enumerate(options, start=1):
+ table.add_row(_marker(f"[{idx}]"), label, hint or "")
+ if extra_keys:
+ for short, label in extra_keys.items():
+ table.add_row(_marker(f"[{short}]"), label, "")
+ console.print(table)
+ console.print()
+
+ valid_numbers = {str(i): options[i - 1][0] for i in range(1, len(options) + 1)}
+ valid_letters = {k.lower(): k.lower() for k in (extra_keys or {})}
+ default_input: str | None = None
+ if default_key is not None:
+ for idx, (key, _label, _hint) in enumerate(options, start=1):
+ if key == default_key:
+ default_input = str(idx)
+ break
+ if default_input is None and default_key.lower() in valid_letters:
+ default_input = default_key.lower()
+
+ while True:
+ raw = typer.prompt(prompt_label, default=default_input or "")
+ choice = str(raw).strip().lower()
+ if choice in valid_numbers:
+ return valid_numbers[choice]
+ if choice in valid_letters:
+ return valid_letters[choice]
+ fail(console, invalid_label)
+
+
+# --- Provider selection --------------------------------------------------------
+
+
+def _ordered_providers(featured: tuple[str, ...]) -> list[ProviderSpec]:
+ """Return featured provider specs in the given order, dropping unknowns."""
+ out: list[ProviderSpec] = []
+ seen: set[str] = set()
+ for name in featured:
+ spec = find_by_name(name)
+ if spec and spec.name not in seen:
+ out.append(spec)
+ seen.add(spec.name)
+ return out
+
+
+def _all_providers_except(featured: set[str]) -> list[ProviderSpec]:
+ """All providers from the registry that aren't already in the featured list."""
+ return [
+ spec
+ for spec in PROVIDERS
+ if spec.name not in featured and not spec.is_oauth # OAuth flows use `deeptutor login`
+ ]
+
+
+def select_llm_provider(
+ console: Console,
+ strings: dict[str, str],
+ *,
+ current_binding: str | None = None,
+) -> ProviderSpec | None:
+ """Walk the user through provider selection. ``None`` means custom/manual."""
+
+ featured = _ordered_providers(FEATURED_LLM_PROVIDERS)
+ featured_names = {spec.name for spec in featured}
+
+ options: list[tuple[str, str, str]] = []
+ for spec in featured:
+ hint = spec.default_api_base or ("local" if spec.is_local else "")
+ options.append((spec.name, spec.label, hint))
+
+ # ``[s]`` is reserved for the "Skip" shortcut in optional steps
+ # (embedding / search). LLM is mandatory, so we use ``[a]`` for "show all".
+ extra = {
+ "a": strings["init.show_all"],
+ "c": strings["init.custom_provider"],
+ }
+
+ default_key = current_binding if current_binding in featured_names else "openai"
+ pick = select_from_options(
+ console,
+ title=strings["init.pick_provider"],
+ options=options,
+ default_key=default_key,
+ extra_keys=extra,
+ prompt_label=strings["init.choice"],
+ invalid_label=strings["init.choice_invalid"],
+ )
+
+ if pick == "c":
+ return None
+ if pick == "a":
+ return _select_provider_full_list(console, strings, exclude=featured_names)
+ return find_by_name(pick)
+
+
+def _select_provider_full_list(
+ console: Console,
+ strings: dict[str, str],
+ *,
+ exclude: set[str],
+) -> ProviderSpec | None:
+ rest = _all_providers_except(exclude)
+ options: list[tuple[str, str, str]] = [
+ (spec.name, spec.label, spec.default_api_base or ("local" if spec.is_local else ""))
+ for spec in rest
+ ]
+ extra = {"b": strings["init.back"], "c": strings["init.custom_provider"]}
+ pick = select_from_options(
+ console,
+ title=strings["init.pick_provider"],
+ options=options,
+ extra_keys=extra,
+ prompt_label=strings["init.choice"],
+ invalid_label=strings["init.choice_invalid"],
+ )
+ if pick == "b":
+ return select_llm_provider(console, strings, current_binding=None)
+ if pick == "c":
+ return None
+ return find_by_name(pick)
+
+
+SKIP_SENTINEL = "__skip__"
+
+
+def select_embedding_provider(
+ console: Console,
+ strings: dict[str, str],
+ *,
+ current: str | None = None,
+) -> str | None:
+ """Pick an embedding provider key. Returns one of:
+
+ - canonical provider name (e.g. ``"openai"``, ``"aliyun"``)
+ - ``None`` → user wants to type their own (custom)
+ - :data:`SKIP_SENTINEL` → user wants to skip this step entirely
+
+ The featured list is driven by :data:`FEATURED_EMBEDDING_PROVIDERS`; labels
+ and default endpoints come from ``EMBEDDING_PROVIDERS`` in
+ ``provider_runtime`` so we don't duplicate the source of truth.
+ """
+
+ from deeptutor.services.config.provider_runtime import EMBEDDING_PROVIDERS
+
+ options: list[tuple[str, str, str]] = []
+ for name in FEATURED_EMBEDDING_PROVIDERS:
+ spec = EMBEDDING_PROVIDERS.get(name)
+ if not spec:
+ continue
+ hint = spec.default_api_base or ("local" if spec.is_local else "")
+ options.append((name, spec.label, hint))
+
+ extra = {
+ "s": strings["init.skip_step"],
+ "c": strings["init.custom_provider"],
+ }
+ default_key = current if current in {n for n, _, _ in options} else "openai"
+ pick = select_from_options(
+ console,
+ title=strings["init.pick_embedding_provider"],
+ options=options,
+ default_key=default_key,
+ extra_keys=extra,
+ prompt_label=strings["init.choice"],
+ invalid_label=strings["init.choice_invalid"],
+ )
+ if pick == "s":
+ return SKIP_SENTINEL
+ if pick == "c":
+ return None
+ return pick
+
+
+def select_search_provider(
+ console: Console,
+ strings: dict[str, str],
+ *,
+ current: str | None = None,
+) -> SearchProviderSpec | None:
+ """Pick a search provider. Returns the :class:`SearchProviderSpec` for the
+ chosen entry, or ``None`` when the user picks ``[s] Skip``."""
+
+ options = [(spec.name, spec.label, spec.hint) for spec in SEARCH_PROVIDERS]
+ extra = {"s": strings["init.skip_step"]}
+ default_key = current if current in {s.name for s in SEARCH_PROVIDERS} else "tavily"
+ pick = select_from_options(
+ console,
+ title=strings["init.pick_search_provider"],
+ options=options,
+ default_key=default_key,
+ extra_keys=extra,
+ prompt_label=strings["init.choice"],
+ invalid_label=strings["init.choice_invalid"],
+ )
+ if pick == "s":
+ return None
+ return next((spec for spec in SEARCH_PROVIDERS if spec.name == pick), None)
+
+
+def search_api_key_from_env(env_keys: tuple[str, ...]) -> tuple[str, str]:
+ """Return ``(key, env_name)`` of the first non-empty env var, else ``("", "")``."""
+ for env_name in env_keys:
+ value = os.environ.get(env_name, "")
+ if value:
+ return value, env_name
+ return "", ""
+
+
+# --- API key capture -----------------------------------------------------------
+
+
+def capture_api_key(
+ console: Console,
+ strings: dict[str, str],
+ *,
+ env_key: str,
+ current: str = "",
+) -> str:
+ """Prompt for an API key, with env-var auto-detect + saved-value fallback.
+
+ Preference order:
+ 1. Existing saved key — confirm with masked display.
+ 2. ``env_key`` environment variable — confirm with masked display.
+ 3. Plain hidden prompt.
+ """
+ if current:
+ masked = _mask_secret(current)
+ if typer.confirm(
+ strings["init.api_key_reuse_llm"].format(masked=masked),
+ default=True,
+ ):
+ return current
+
+ if env_key:
+ from_env = os.environ.get(env_key, "")
+ if from_env:
+ masked = _mask_secret(from_env)
+ offer = strings["init.api_key_env_detected"].format(env_var=env_key, masked=masked)
+ if typer.confirm(offer, default=True):
+ return from_env
+
+ return typer.prompt(strings["init.api_key_prompt"], default="", hide_input=True, show_default=False)
+
+
+# --- Live /models fetch --------------------------------------------------------
+
+
+def fetch_models(
+ console: Console,
+ strings: dict[str, str],
+ *,
+ base_url: str,
+ api_key: str,
+ binding: str,
+) -> list[str]:
+ """Query the provider for an available-model list.
+
+ Returns ``[]`` on any failure — callers should fall back to the curated
+ list in ``LLM_FALLBACK_MODELS`` / ``EMBEDDING_FALLBACK_MODELS``.
+ """
+ if not base_url:
+ return []
+
+ url = base_url.rstrip("/") + "/models"
+ headers: dict[str, str] = {}
+
+ if binding == "anthropic":
+ # Anthropic uses different auth headers.
+ if api_key:
+ headers["x-api-key"] = api_key
+ headers["anthropic-version"] = "2023-06-01"
+ else:
+ if api_key:
+ headers["Authorization"] = f"Bearer {api_key}"
+
+ info(console, strings["init.fetch_models"].format(url=url))
+ try:
+ with httpx.Client(timeout=5.0) as client:
+ response = client.get(url, headers=headers)
+ response.raise_for_status()
+ payload = response.json()
+ except Exception as exc:
+ warn(console, strings["init.fetch_models_fail"].format(error=str(exc)[:160]))
+ return []
+
+ raw_items: list[Any]
+ if isinstance(payload, dict) and isinstance(payload.get("data"), list):
+ raw_items = payload["data"]
+ elif isinstance(payload, dict) and isinstance(payload.get("models"), list):
+ # Ollama: GET /api/tags returns {"models": [{"name": "...", ...}]}
+ raw_items = payload["models"]
+ elif isinstance(payload, list):
+ raw_items = payload
+ else:
+ warn(console, strings["init.fetch_models_fail"].format(error="unexpected response shape"))
+ return []
+
+ names: list[str] = []
+ for item in raw_items:
+ if isinstance(item, str):
+ names.append(item)
+ elif isinstance(item, dict):
+ # OpenAI: {"id": "..."}. Ollama: {"name": "..."}. Anthropic: {"id": "..."}.
+ name = item.get("id") or item.get("name") or item.get("model")
+ if isinstance(name, str) and name:
+ names.append(name)
+ # Dedupe preserving order
+ seen: set[str] = set()
+ deduped = [n for n in names if not (n in seen or seen.add(n))]
+ if deduped:
+ ok(console, strings["init.fetch_models_ok"].format(count=len(deduped)))
+ return deduped
+
+
+def _derive_embedding_models_url(endpoint: str, provider: str) -> str:
+ """Convert a (full) embedding endpoint URL into its sibling ``/models`` URL.
+
+ Embedding endpoints are stored as the *exact* URL adapters POST to
+ (e.g. ``https://api.openai.com/v1/embeddings``), not a base. To list
+ available models we have to strip the embedding-specific path segment.
+
+ Ollama is special-cased: it exposes installed models at ``/api/tags``,
+ not ``/models``.
+ """
+ url = endpoint.rstrip("/")
+
+ if provider == "ollama" or url.endswith("/api/embed"):
+ base = url
+ for suffix in ("/api/embed", "/api/embeddings"):
+ if base.endswith(suffix):
+ base = base[: -len(suffix)]
+ break
+ return f"{base.rstrip('/')}/api/tags"
+
+ for suffix in ("/embeddings", "/embed"):
+ if url.endswith(suffix):
+ return f"{url[: -len(suffix)]}/models"
+
+ return f"{url}/models"
+
+
+# Strict "embed" substring match. Broader heuristics (``e5-``, ``nomic``,
+# ``voyage``...) drag too many LLMs in. Embedding models that don't follow
+# the naming convention (``bge-m3``, ``qwen3-embedding-8b``) are picked up
+# from the curated EMBEDDING_FALLBACK_MODELS list instead.
+def _looks_like_embedding_model(name: str) -> bool:
+ return "embed" in name.lower()
+
+
+def fetch_embedding_models(
+ console: Console,
+ strings: dict[str, str],
+ *,
+ endpoint: str,
+ api_key: str,
+ provider: str,
+) -> list[str]:
+ """Live-list embedding models from the provider's ``/models`` endpoint.
+
+ Returns ``[]`` on any failure so callers can fall back to the curated
+ list. When the provider's ``/models`` includes non-embedding models
+ (typical for OpenAI-compatible endpoints), the result is filtered down
+ to entries whose name looks like an embedding model. If filtering
+ leaves nothing, the unfiltered list is returned as a safety net.
+ """
+ if not endpoint:
+ return []
+
+ models_url = _derive_embedding_models_url(endpoint, provider)
+ headers: dict[str, str] = {}
+ if api_key:
+ headers["Authorization"] = f"Bearer {api_key}"
+
+ info(console, strings["init.fetch_models"].format(url=models_url))
+ try:
+ with httpx.Client(timeout=5.0) as client:
+ response = client.get(models_url, headers=headers)
+ response.raise_for_status()
+ payload = response.json()
+ except Exception as exc:
+ warn(console, strings["init.fetch_models_fail"].format(error=str(exc)[:160]))
+ return []
+
+ raw_items: list[Any] = []
+ if isinstance(payload, dict):
+ for key in ("data", "models"):
+ value = payload.get(key)
+ if isinstance(value, list):
+ raw_items = value
+ break
+ elif isinstance(payload, list):
+ raw_items = payload
+
+ names: list[str] = []
+ for item in raw_items:
+ if isinstance(item, str):
+ names.append(item)
+ elif isinstance(item, dict):
+ name = item.get("id") or item.get("name") or item.get("model")
+ if isinstance(name, str) and name:
+ names.append(name)
+ if not names:
+ warn(console, strings["init.fetch_models_fail"].format(error="empty model list"))
+ return []
+
+ # Mixed lists (OpenAI returns gpt-4o, dall-e, etc. alongside embeddings).
+ # Strict ``embed`` filter; if it matches nothing, return empty so the
+ # caller falls through to the curated EMBEDDING_FALLBACK_MODELS list.
+ filtered = [n for n in names if _looks_like_embedding_model(n)]
+ if not filtered:
+ return []
+
+ seen: set[str] = set()
+ deduped = [n for n in filtered if not (n in seen or seen.add(n))]
+ ok(console, strings["init.fetch_models_ok"].format(count=len(deduped)))
+ return deduped
+
+
+def select_model(
+ console: Console,
+ strings: dict[str, str],
+ *,
+ models: list[str],
+ current: str = "",
+ custom_prompt_label: str | None = None,
+) -> str:
+ """Numbered-list model picker with ``[c] Custom`` escape."""
+ if not models:
+ return typer.prompt(
+ custom_prompt_label or strings["init.custom_model"],
+ default=current or "",
+ )
+
+ options = [(m, m, "") for m in models]
+ extra = {"c": strings["init.custom_model"]}
+ default_key = current if current in models else models[0]
+ pick = select_from_options(
+ console,
+ title=strings["init.pick_model"].format(marker="[c]"),
+ options=options,
+ default_key=default_key,
+ extra_keys=extra,
+ prompt_label=strings["init.choice"],
+ invalid_label=strings["init.choice_invalid"],
+ )
+ if pick == "c":
+ return typer.prompt(
+ custom_prompt_label or strings["init.custom_model"],
+ default=current or "",
+ )
+ return pick
+
+
+# --- Connectivity probe --------------------------------------------------------
+
+
+def probe_llm(*, base_url: str, api_key: str, binding: str, model: str) -> tuple[bool, int, str]:
+ """Send a single-token completion to verify credentials.
+
+ Returns ``(ok, elapsed_ms, error_or_empty)``. Network failures, auth
+ failures, 4xx, 5xx all surface as ``ok=False`` with a short error string.
+ """
+ if not base_url or not model:
+ return False, 0, "missing base_url or model"
+
+ started = time.monotonic()
+ try:
+ if binding == "anthropic":
+ url = base_url.rstrip("/") + "/messages"
+ headers = {
+ "x-api-key": api_key or "",
+ "anthropic-version": "2023-06-01",
+ "Content-Type": "application/json",
+ }
+ body = {
+ "model": model,
+ "max_tokens": 1,
+ "messages": [{"role": "user", "content": "ping"}],
+ }
+ else:
+ url = base_url.rstrip("/") + "/chat/completions"
+ headers = {
+ "Authorization": f"Bearer {api_key or 'sk-no-key-required'}",
+ "Content-Type": "application/json",
+ }
+ body = {
+ "model": model,
+ "max_tokens": 1,
+ "messages": [{"role": "user", "content": "ping"}],
+ }
+
+ with httpx.Client(timeout=15.0) as client:
+ response = client.post(url, headers=headers, json=body)
+ elapsed = int((time.monotonic() - started) * 1000)
+ if response.status_code >= 400:
+ snippet = response.text[:200]
+ return False, elapsed, f"HTTP {response.status_code} · {snippet}"
+ return True, elapsed, ""
+ except Exception as exc:
+ elapsed = int((time.monotonic() - started) * 1000)
+ return False, elapsed, str(exc)[:200]
+
+
+def probe_embedding(*, base_url: str, api_key: str, model: str) -> tuple[bool, int, str]:
+ """POST a tiny embedding request. Returns ``(ok, elapsed_ms, error)``."""
+ if not base_url or not model:
+ return False, 0, "missing base_url or model"
+ started = time.monotonic()
+ try:
+ headers = {
+ "Authorization": f"Bearer {api_key or 'sk-no-key-required'}",
+ "Content-Type": "application/json",
+ }
+ body = {"model": model, "input": "ping"}
+ with httpx.Client(timeout=15.0) as client:
+ response = client.post(base_url, headers=headers, json=body)
+ elapsed = int((time.monotonic() - started) * 1000)
+ if response.status_code >= 400:
+ return False, elapsed, f"HTTP {response.status_code} · {response.text[:200]}"
+ return True, elapsed, ""
+ except Exception as exc:
+ elapsed = int((time.monotonic() - started) * 1000)
+ return False, elapsed, str(exc)[:200]
+
+
+# --- Review panel --------------------------------------------------------------
+
+
+def render_review_panel(
+ console: Console,
+ strings: dict[str, str],
+ *,
+ llm: LLMChoice | None,
+ embedding: EmbeddingChoice | None,
+ search: SearchChoice | None,
+ backend_port: int | None,
+ frontend_port: int | None,
+) -> None:
+ body = Text()
+
+ def _row(label: str, value: str, probe: tuple[bool, bool] | None = None) -> None:
+ body.append(f"{label:>12} ", style="bold")
+ body.append(value)
+ if probe is not None:
+ probed, ok_flag = probe
+ if probed:
+ if ok_flag:
+ body.append(" ✓ probed", style="green")
+ else:
+ body.append(" ! probe failed", style="yellow")
+ body.append("\n")
+
+ if llm:
+ _row(
+ strings["init.review_llm"],
+ f"{llm.display_provider} · {llm.model} · {llm.base_url}",
+ probe=(llm.probed, llm.probe_ok),
+ )
+ if embedding:
+ _row(
+ strings["init.review_embedding"],
+ f"{embedding.display_provider} · {embedding.model} · {embedding.base_url}",
+ probe=(embedding.probed, embedding.probe_ok),
+ )
+ if search:
+ if search.provider == "none":
+ value = strings["init.review_search_disabled"]
+ elif search.base_url:
+ value = f"{search.label} · {search.base_url}"
+ else:
+ value = search.label
+ _row(strings["init.review_search"], value)
+ if backend_port is not None and frontend_port is not None:
+ _row(
+ strings["init.review_ports"],
+ strings["init.review_ports_value"].format(
+ backend=backend_port, frontend=frontend_port
+ ),
+ )
+ console.print(
+ Panel(
+ body,
+ title=f"[bold]{rich_escape(strings['init.review_title'])}[/]",
+ border_style="bright_cyan",
+ padding=(1, 2),
+ )
+ )
+
+
+__all__ = [
+ "EMBEDDING_FALLBACK_MODELS",
+ "EmbeddingChoice",
+ "FEATURED_EMBEDDING_PROVIDERS",
+ "FEATURED_LLM_PROVIDERS",
+ "LLMChoice",
+ "LLM_FALLBACK_MODELS",
+ "SEARCH_PROVIDERS",
+ "SKIP_SENTINEL",
+ "SearchChoice",
+ "SearchProviderSpec",
+ "capture_api_key",
+ "fail",
+ "fetch_embedding_models",
+ "fetch_models",
+ "info",
+ "ok",
+ "probe_embedding",
+ "probe_llm",
+ "render_review_panel",
+ "search_api_key_from_env",
+ "select_embedding_provider",
+ "select_from_options",
+ "select_llm_provider",
+ "select_model",
+ "select_search_provider",
+ "step_header",
+ "warn",
+]
diff --git a/deeptutor_cli/provider_cmd.py b/deeptutor_cli/provider_cmd.py
index e77e9c6cd..e7ec91000 100644
--- a/deeptutor_cli/provider_cmd.py
+++ b/deeptutor_cli/provider_cmd.py
@@ -32,7 +32,10 @@ def _login_openai_codex() -> None:
try:
from oauth_cli_kit import get_token, login_oauth_interactive
except ImportError:
- typer.echo("oauth_cli_kit is not installed. Install CLI deps: pip install -U deeptutor-cli")
+ typer.echo(
+ "oauth_cli_kit is not installed. Install CLI deps from a local checkout: "
+ "python -m pip install -e ./packaging/deeptutor-cli"
+ )
raise typer.Exit(code=1)
token = None
@@ -56,7 +59,10 @@ async def _login_github_copilot() -> None:
try:
from openai import AsyncOpenAI
except ImportError:
- typer.echo("openai is not installed. Install CLI deps: pip install -U deeptutor-cli")
+ typer.echo(
+ "openai is not installed. Install CLI deps from a local checkout: "
+ "python -m pip install -e ./packaging/deeptutor-cli"
+ )
raise typer.Exit(code=1)
try:
client = AsyncOpenAI(
diff --git a/packaging/deeptutor-cli/README.md b/packaging/deeptutor-cli/README.md
index 976fc6846..68062a25a 100644
--- a/packaging/deeptutor-cli/README.md
+++ b/packaging/deeptutor-cli/README.md
@@ -5,5 +5,14 @@ Python modules required for terminal workflows, RAG, document parsing, and model
provider integrations, but it does not ship the packaged Next.js Web assets or
FastAPI/Uvicorn server dependencies used by `deeptutor start`.
-Build from this repository root with a release workflow that uses this directory
-as the package project.
+Install from the repository root when you want a local CLI-only environment:
+
+```bash
+python3 -m venv .venv-cli
+source .venv-cli/bin/activate
+python -m pip install --upgrade pip
+python -m pip install -e ./packaging/deeptutor-cli
+```
+
+Keep the checkout in place after installation because editable installs point
+the `deeptutor` command at these source files.
diff --git a/pyproject.toml b/pyproject.toml
index afb79fda8..fbb0c7803 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -61,8 +61,8 @@ deeptutor = "deeptutor_cli.main:main"
[project.optional-dependencies]
# Compatibility extra for source installs and older docs. These packages are
-# already included in the public `deeptutor` wheel; the separate public
-# `deeptutor-cli` distribution uses the same list without Web assets/server deps.
+# already included in the public `deeptutor` wheel; the local CLI-only project
+# under `packaging/deeptutor-cli` uses the same list without Web assets/server deps.
cli = [
# LLM provider SDKs
"anthropic>=0.30.0",
@@ -174,6 +174,21 @@ where = ["."]
include = ["deeptutor*", "deeptutor_cli*"]
[tool.setuptools.package-data]
+# Runtime data shipped inside the deeptutor package: prompt YAMLs (loaded by
+# PromptManager from PACKAGE_ROOT/deeptutor/.../prompts/*.yaml), markdown
+# templates (tutorbot SKILL.md, vision_solver prompts), and helper shell
+# scripts (tutorbot tmux skill). Without these, ``pip install deeptutor`` ships
+# a wheel missing every agent prompt and capability fails at first use.
+deeptutor = [
+ "**/*.yaml",
+ "**/*.yml",
+ "**/*.md",
+ "**/*.json",
+ "**/*.sh",
+ "**/*.j2",
+ "**/*.jinja",
+]
+deeptutor_cli = ["**/*.md"]
deeptutor_web = ["**/*", ".next/**/*"]
# ============================================
diff --git a/scripts/_cli_kit.py b/scripts/_cli_kit.py
deleted file mode 100644
index 0c4a7dc2d..000000000
--- a/scripts/_cli_kit.py
+++ /dev/null
@@ -1,382 +0,0 @@
-"""Pure-ANSI terminal UI toolkit — zero external dependencies.
-
-Provides banner, inline arrow-key selector, confirm, text input, step
-headers, coloured log helpers, spinner, and countdown. Designed for a
-minimal / industrial aesthetic inspired by Claude Code.
-"""
-
-from __future__ import annotations
-
-from contextlib import contextmanager
-import getpass
-import os
-import shutil
-import sys
-import textwrap
-import time
-from typing import Generator
-
-
-def _configure_text_stream(stream: object) -> None:
- """Avoid UnicodeEncodeError on legacy Windows code pages."""
- reconfigure = getattr(stream, "reconfigure", None)
- if reconfigure is None:
- return
- try:
- reconfigure(errors="replace")
- except (TypeError, ValueError, OSError):
- return
-
-
-def configure_text_streams() -> None:
- _configure_text_stream(sys.stdout)
- _configure_text_stream(sys.stderr)
-
-
-configure_text_streams()
-
-# ---------------------------------------------------------------------------
-# Colour helpers
-# ---------------------------------------------------------------------------
-
-
-def _is_color() -> bool:
- return sys.stdout.isatty() and os.environ.get("TERM", "dumb") != "dumb"
-
-
-def _wrap(text: str, code: str) -> str:
- if not _is_color():
- return text
- return f"\033[{code}m{text}\033[0m"
-
-
-def accent(text: str) -> str:
- return _wrap(text, "38;5;111")
-
-
-def success(text: str) -> str:
- return _wrap(text, "38;5;78")
-
-
-def warn(text: str) -> str:
- return _wrap(text, "38;5;214")
-
-
-def error(text: str) -> str:
- return _wrap(text, "38;5;203")
-
-
-def dim(text: str) -> str:
- return _wrap(text, "2")
-
-
-def bold(text: str) -> str:
- return _wrap(text, "1")
-
-
-# ---------------------------------------------------------------------------
-# Terminal geometry
-# ---------------------------------------------------------------------------
-
-
-def term_width() -> int:
- return min(max(shutil.get_terminal_size((80, 24)).columns, 60), 100)
-
-
-# ---------------------------------------------------------------------------
-# Low-level key reading (Unix / Windows)
-# ---------------------------------------------------------------------------
-
-
-def _read_key() -> str:
- """Read a single keypress. Returns 'up', 'down', 'enter', or char."""
- try:
- import termios
- import tty
-
- fd = sys.stdin.fileno()
- old = termios.tcgetattr(fd)
- try:
- tty.setraw(fd)
- ch = sys.stdin.read(1)
- if ch == "\x1b":
- seq = sys.stdin.read(2)
- if seq == "[A":
- return "up"
- if seq == "[B":
- return "down"
- return "esc"
- if ch in ("\r", "\n"):
- return "enter"
- if ch == "\x03":
- raise KeyboardInterrupt
- return ch
- finally:
- termios.tcsetattr(fd, termios.TCSADRAIN, old)
- except ImportError:
- # Windows fallback
- import msvcrt # type: ignore[import-untyped]
-
- ch = msvcrt.getwch()
- if ch == "\xe0":
- code = msvcrt.getwch()
- if code == "H":
- return "up"
- if code == "P":
- return "down"
- return "esc"
- if ch in ("\r", "\n"):
- return "enter"
- if ch == "\x03":
- raise KeyboardInterrupt
- return ch
-
-
-# ---------------------------------------------------------------------------
-# Banner
-# ---------------------------------------------------------------------------
-
-
-def banner(title: str, lines: list[str] | None = None) -> None:
- w = term_width()
- inner = w - 4 # usable chars between "│ " and " │"
-
- print()
- dashes = max(w - 4 - len(title), 0)
- print(f"┌ {accent(title)} " + "─" * dashes + "┐")
-
- if lines:
- print(f"│{' ' * (w - 2)}│")
- for line in lines:
- for wrapped in textwrap.wrap(line, width=inner) or [""]:
- print(f"│ {dim(wrapped.ljust(inner))} │")
- print(f"│{' ' * (w - 2)}│")
-
- print("└" + "─" * (w - 2) + "┘")
- print()
-
-
-# ---------------------------------------------------------------------------
-# Inline arrow-key selector
-# ---------------------------------------------------------------------------
-
-
-def select(prompt: str, options: list[tuple[str, str, str]]) -> str:
- """Arrow-key selector. *options* is a list of ``(value, label, desc)``.
-
- Returns the *value* of the chosen option. Falls back to numbered
- input when stdin is not a tty.
-
- Long lists are rendered as a scrolling window so they always fit on
- screen without leaving stale rows behind when redrawing.
- """
- if not sys.stdin.isatty():
- return _select_fallback(prompt, options)
-
- idx = 0
- total = len(options)
-
- # Reserve rows for: prompt + blank + (optional ↑) + (optional ↓) + blank + safety
- term_rows = max(shutil.get_terminal_size((80, 24)).lines, 10)
- max_window = max(5, min(total, term_rows - 6))
- use_window = total > max_window
- window_size = max_window if use_window else total
-
- print(dim(f" {prompt}"))
- if use_window:
- print(dim(f" ({total} options — use ↑/↓, Enter to confirm)"))
- print()
-
- rendered_lines = 0 # how many lines the last _render() emitted
-
- def _render() -> int:
- nonlocal rendered_lines
- if use_window:
- half = window_size // 2
- start = max(0, min(idx - half, total - window_size))
- end = start + window_size
- else:
- start, end = 0, total
-
- lines = 0
- if use_window and start > 0:
- print(f" {dim(' ↑ ' + str(start) + ' more above')}")
- lines += 1
-
- for i in range(start, end):
- _, label, desc = options[i]
- if i == idx:
- marker = accent("> ")
- text = f"{bold(label)} {dim(desc)}" if desc else bold(label)
- else:
- marker = " "
- text = dim(f"{label} {desc}") if desc else dim(label)
- print(f" {marker}{text}")
- lines += 1
-
- if use_window and end < total:
- print(f" {dim(' ↓ ' + str(total - end) + ' more below')}")
- lines += 1
-
- rendered_lines = lines
- return lines
-
- _render()
-
- while True:
- key = _read_key()
- if key == "up":
- idx = (idx - 1) % total
- elif key == "down":
- idx = (idx + 1) % total
- elif key == "enter":
- sys.stdout.write(f"\033[{rendered_lines}A")
- sys.stdout.write("\033[J")
- chosen_label = options[idx][1]
- chosen_desc = options[idx][2]
- print(f" {accent('>')} {bold(chosen_label)} {dim(chosen_desc)}")
- print()
- return options[idx][0]
- elif key == "esc":
- continue
- else:
- continue
-
- sys.stdout.write(f"\033[{rendered_lines}A")
- sys.stdout.write("\033[J")
- _render()
-
-
-def _select_fallback(prompt: str, options: list[tuple[str, str, str]]) -> str:
- print(f" {prompt}")
- for i, (_, label, desc) in enumerate(options, 1):
- print(f" {i}. {label} {desc}")
- while True:
- answer = input(" > ").strip()
- if answer.isdigit() and 1 <= int(answer) <= len(options):
- return options[int(answer) - 1][0]
- for value, label, _ in options:
- if answer in (value, label):
- return value
- print(warn(" Please choose a valid option."))
-
-
-# ---------------------------------------------------------------------------
-# Confirm (Y/n)
-# ---------------------------------------------------------------------------
-
-
-def confirm(prompt: str, default: bool = True) -> bool:
- hint = "[Y/n]" if default else "[y/N]"
- while True:
- answer = input(f" {prompt} {dim(hint)} ").strip().lower()
- if not answer:
- return default
- if answer in ("y", "yes"):
- return True
- if answer in ("n", "no"):
- return False
- print(warn(" Please answer y or n."))
-
-
-# ---------------------------------------------------------------------------
-# Text input
-# ---------------------------------------------------------------------------
-
-
-def text_input(prompt: str, default: str = "", secret: bool = False) -> str:
- display = f" {prompt}"
- if default and not secret:
- display += f" {dim(f'[{default}]')}"
- display += dim(": ")
-
- if secret:
- value = getpass.getpass(display)
- else:
- value = input(display).strip()
- return value or default
-
-
-# ---------------------------------------------------------------------------
-# Step header
-# ---------------------------------------------------------------------------
-
-
-def step(current: int, total: int | str, title: str) -> None:
- print()
- w = term_width()
- label = f" {current}/{total} "
- left = (w - len(label)) // 2
- right = w - left - len(label)
- print(dim("─" * left + label + "─" * right))
- print(f" {bold(title)}")
- print()
-
-
-# ---------------------------------------------------------------------------
-# Log helpers
-# ---------------------------------------------------------------------------
-
-
-def log_info(msg: str) -> None:
- print(f" {accent('·')} {msg}")
-
-
-def log_success(msg: str) -> None:
- print(f" {success('✓')} {msg}")
-
-
-def log_warn(msg: str) -> None:
- print(f" {warn('!')} {msg}")
-
-
-def log_error(msg: str) -> None:
- print(f" {error('✗')} {msg}")
-
-
-# ---------------------------------------------------------------------------
-# Spinner (context manager)
-# ---------------------------------------------------------------------------
-
-_SPINNER_FRAMES = ("⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏")
-
-
-@contextmanager
-def spinner(label: str) -> Generator[None, None, None]:
- """Simple braille-dot spinner shown while the body executes."""
- import threading
-
- stop = threading.Event()
-
- def _spin() -> None:
- i = 0
- while not stop.is_set():
- frame = _SPINNER_FRAMES[i % len(_SPINNER_FRAMES)]
- sys.stdout.write(f"\r {accent(frame)} {label}")
- sys.stdout.flush()
- i += 1
- stop.wait(0.08)
- sys.stdout.write("\r" + " " * (len(label) + 6) + "\r")
- sys.stdout.flush()
-
- t = threading.Thread(target=_spin, daemon=True)
- t.start()
- try:
- yield
- finally:
- stop.set()
- t.join()
-
-
-# ---------------------------------------------------------------------------
-# Countdown
-# ---------------------------------------------------------------------------
-
-
-def countdown(seconds: int, label: str = "Starting in") -> None:
- for remaining in range(seconds, 0, -1):
- sys.stdout.write(f"\r {dim(label)} {accent(str(remaining))}s ")
- sys.stdout.flush()
- time.sleep(1)
- sys.stdout.write("\r" + " " * (len(label) + 12) + "\r")
- sys.stdout.flush()
diff --git a/scripts/audit_prompts.py b/scripts/audit_prompts.py
deleted file mode 100644
index 28362ae41..000000000
--- a/scripts/audit_prompts.py
+++ /dev/null
@@ -1,178 +0,0 @@
-#!/usr/bin/env python
-
-"""
-Audit prompt parity between prompts/en and prompts/zh|prompts/cn.
-
-Checks:
-- Missing/extra keys (recursive)
-- Placeholder drift in string templates (e.g. {question}, {context})
-
-Usage:
- python scripts/audit_prompts.py
- python scripts/audit_prompts.py --fail
-"""
-
-from __future__ import annotations
-
-import argparse
-from dataclasses import dataclass
-from pathlib import Path
-import re
-import sys
-from typing import Any, Iterable
-
-import yaml
-
-PROJECT_ROOT = Path(__file__).resolve().parents[1]
-AGENTS_DIR = PROJECT_ROOT / "deeptutor" / "agents"
-
-# Template placeholders are expected to be like {topic}, {knowledge_title}, etc.
-# Avoid false positives from LaTeX (\frac{1}{3}) and Mermaid (B{{Processing}}).
-PLACEHOLDER_RE = re.compile(r"(?<!\{)\{[A-Za-z_][A-Za-z0-9_]*\}(?!\})")
-
-
-def _load_yaml(path: Path) -> Any:
- with open(path, encoding="utf-8") as f:
- return yaml.safe_load(f) or {}
-
-
-def _iter_yaml_files(root: Path) -> Iterable[Path]:
- if not root.exists():
- return []
- return sorted([p for p in root.rglob("*.yaml") if p.is_file()])
-
-
-def _get_placeholders(value: Any) -> set[str]:
- found: set[str] = set()
- if isinstance(value, str):
- found |= set(PLACEHOLDER_RE.findall(value))
- elif isinstance(value, dict):
- for v in value.values():
- found |= _get_placeholders(v)
- elif isinstance(value, list):
- for v in value:
- found |= _get_placeholders(v)
- return found
-
-
-def _collect_keys(value: Any, prefix: str = "") -> set[str]:
- """
- Collect dotted key paths for all dict nodes.
- Leaves (non-dict) are also included as paths.
- """
- keys: set[str] = set()
- if isinstance(value, dict):
- for k, v in value.items():
- path = f"{prefix}.{k}" if prefix else str(k)
- keys.add(path)
- keys |= _collect_keys(v, path)
- elif isinstance(value, list):
- # Lists: we don't expand indices; still consider it a leaf container.
- if prefix:
- keys.add(prefix)
- else:
- if prefix:
- keys.add(prefix)
- return keys
-
-
-@dataclass
-class Diff:
- missing_zh: list[str]
- extra_zh: list[str]
- placeholder_missing_zh: list[str]
- placeholder_extra_zh: list[str]
-
-
-def _diff(en_obj: Any, zh_obj: Any) -> Diff:
- en_keys = _collect_keys(en_obj)
- zh_keys = _collect_keys(zh_obj)
-
- en_ph = _get_placeholders(en_obj)
- zh_ph = _get_placeholders(zh_obj)
-
- return Diff(
- missing_zh=sorted(en_keys - zh_keys),
- extra_zh=sorted(zh_keys - en_keys),
- placeholder_missing_zh=sorted(en_ph - zh_ph),
- placeholder_extra_zh=sorted(zh_ph - en_ph),
- )
-
-
-def main() -> int:
- parser = argparse.ArgumentParser()
- parser.add_argument("--fail", action="store_true", help="exit non-zero on any issue")
- args = parser.parse_args()
-
- if not AGENTS_DIR.exists():
- print(f"Agents directory not found: {AGENTS_DIR}", file=sys.stderr)
- return 2
-
- issues = 0
-
- for module_dir in sorted([p for p in AGENTS_DIR.iterdir() if p.is_dir()]):
- prompts_dir = module_dir / "prompts"
- en_dir = prompts_dir / "en"
- if not en_dir.exists():
- continue
-
- # Prefer zh if exists, else cn if exists (but we also compare against cn if present)
- zh_dir = prompts_dir / "zh"
- cn_dir = prompts_dir / "cn"
-
- for en_file in _iter_yaml_files(en_dir):
- rel = en_file.relative_to(en_dir)
- candidates = []
- if zh_dir.exists():
- candidates.append(("zh", zh_dir / rel))
- if cn_dir.exists():
- candidates.append(("cn", cn_dir / rel))
-
- if not candidates:
- continue
-
- en_obj = _load_yaml(en_file)
-
- for lang_name, zh_file in candidates:
- if not zh_file.exists():
- issues += 1
- print(f"[MISSING {lang_name}] {module_dir.name}: {rel.as_posix()}")
- continue
-
- zh_obj = _load_yaml(zh_file)
- d = _diff(en_obj, zh_obj)
-
- if d.missing_zh or d.extra_zh or d.placeholder_missing_zh or d.placeholder_extra_zh:
- issues += 1
- print(f"[DIFF {lang_name}] {module_dir.name}: {rel.as_posix()}")
- if d.missing_zh:
- print(" - missing keys:")
- for k in d.missing_zh[:50]:
- print(f" - {k}")
- if len(d.missing_zh) > 50:
- print(f" ... ({len(d.missing_zh) - 50} more)")
- if d.extra_zh:
- print(" - extra keys:")
- for k in d.extra_zh[:50]:
- print(f" - {k}")
- if len(d.extra_zh) > 50:
- print(f" ... ({len(d.extra_zh) - 50} more)")
- if d.placeholder_missing_zh:
- print(" - missing placeholders:")
- for p in d.placeholder_missing_zh:
- print(f" - {p}")
- if d.placeholder_extra_zh:
- print(" - extra placeholders:")
- for p in d.placeholder_extra_zh:
- print(f" - {p}")
-
- if issues == 0:
- print("OK: prompts are structurally aligned (keys/placeholders).")
- return 0
-
- print(f"Found {issues} prompt parity issue(s).")
- return 1 if args.fail else 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/scripts/check_install.py b/scripts/check_install.py
deleted file mode 100644
index 5ead6f0af..000000000
--- a/scripts/check_install.py
+++ /dev/null
@@ -1,439 +0,0 @@
-#!/usr/bin/env python
-"""
-DeepTutor Installation Checker
-
-Verifies that all required dependencies are correctly installed.
-Run this script to diagnose installation issues.
-"""
-
-import importlib.metadata
-import os
-from pathlib import Path
-import shutil
-import subprocess
-import sys
-
-# Set Windows console UTF-8 encoding
-if sys.platform == "win32":
- import io
-
- sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
- sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
-
-
-# Color codes for terminal output
-class Colors:
- RED = "\033[0;31m"
- GREEN = "\033[0;32m"
- YELLOW = "\033[1;33m"
- BLUE = "\033[0;34m"
- CYAN = "\033[0;36m"
- NC = "\033[0m" # No Color
-
- @classmethod
- def disable(cls):
- """Disable colors for non-TTY output"""
- cls.RED = cls.GREEN = cls.YELLOW = cls.BLUE = cls.CYAN = cls.NC = ""
-
-
-# Disable colors if not a TTY
-if not sys.stdout.isatty():
- Colors.disable()
-
-
-def print_header(message: str):
- """Print section header"""
- print(f"\n{'=' * 60}")
- print(f"📋 {message}")
- print("=" * 60)
-
-
-def print_success(message: str):
- """Print success message"""
- print(f"{Colors.GREEN}✅ {message}{Colors.NC}")
-
-
-def print_error(message: str):
- """Print error message"""
- print(f"{Colors.RED}❌ {message}{Colors.NC}")
-
-
-def print_warning(message: str):
- """Print warning message"""
- print(f"{Colors.YELLOW}⚠️ {message}{Colors.NC}")
-
-
-def print_info(message: str):
- """Print info message"""
- print(f"{Colors.CYAN}ℹ️ {message}{Colors.NC}")
-
-
-def get_package_version(package_name: str) -> str | None:
- """Get installed package version"""
- try:
- return importlib.metadata.version(package_name)
- except importlib.metadata.PackageNotFoundError:
- return None
-
-
-def check_python_environment() -> bool:
- """Check Python environment"""
- print_header("Python Environment")
-
- all_ok = True
-
- # Python version
- py_version = sys.version_info
- print_info(f"Python version: {py_version.major}.{py_version.minor}.{py_version.micro}")
-
- if py_version >= (3, 11):
- print_success(f"Python {py_version.major}.{py_version.minor} meets requirement (>=3.11)")
- else:
- print_error(f"Python {py_version.major}.{py_version.minor} is below requirement (>=3.11)")
- all_ok = False
-
- # Python executable
- print_info(f"Python executable: {sys.executable}")
-
- # Virtual environment
- in_venv = hasattr(sys, "real_prefix") or (
- hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix
- )
- conda_env = os.environ.get("CONDA_DEFAULT_ENV")
-
- if conda_env:
- print_success(f"Conda environment: {conda_env}")
- elif in_venv:
- print_success(f"Virtual environment: {sys.prefix}")
- else:
- print_warning("No isolated environment detected (recommended: use conda or venv)")
-
- return all_ok
-
-
-def check_backend_packages() -> tuple[bool, int, int]:
- """Check backend Python packages"""
- print_header("Backend Dependencies")
-
- # Required packages: (pip_name, import_name, min_version, is_optional)
- packages = [
- # Core
- ("PyYAML", "yaml", "6.0", False),
- ("tiktoken", "tiktoken", "0.5.0", False),
- ("jinja2", "jinja2", "3.1.0", False),
- # HTTP & API
- ("requests", "requests", "2.32.0", False),
- ("openai", "openai", "1.30.0", False),
- ("anthropic", "anthropic", "0.30.0", True),
- ("aiohttp", "aiohttp", "3.9.0", False),
- ("httpx", "httpx", "0.27.0", False),
- # Async
- ("nest-asyncio", "nest_asyncio", "1.5.8", False),
- ("tenacity", "tenacity", "8.0.0", False),
- # Web framework
- ("fastapi", "fastapi", "0.100.0", False),
- ("uvicorn", "uvicorn", "0.24.0", False),
- ("websockets", "websockets", "12.0", False),
- ("pydantic", "pydantic", "2.0.0", False),
- # RAG
- ("llama-index", "llama_index", "0.14.0", False),
- ("PyMuPDF", "fitz", "1.26.0", False),
- # Academic
- ("arxiv", "arxiv", "2.0.0", False),
- # Optional API clients
- ("perplexityai", "perplexity", "0.1.0", True),
- ("dashscope", "dashscope", "1.14.0", True),
- ]
-
- installed = 0
- missing = 0
- all_ok = True
-
- for pip_name, import_name, min_version, is_optional in packages:
- try:
- __import__(import_name)
- version = get_package_version(pip_name)
- version_str = f" (v{version})" if version else ""
- print_success(f" ✓ {pip_name}{version_str}")
- installed += 1
- except ImportError:
- if is_optional:
- print_warning(f" ⚠ {pip_name} not installed (optional)")
- else:
- print_error(f" ✗ {pip_name} not installed")
- all_ok = False
- missing += 1
-
- return all_ok, installed, missing
-
-
-def check_frontend_packages(project_root: Path) -> tuple[bool, int, int]:
- """Check frontend Node.js packages"""
- print_header("Frontend Dependencies")
-
- web_dir = project_root / "web"
- node_modules = web_dir / "node_modules"
- package_json = web_dir / "package.json"
-
- installed = 0
- missing = 0
- all_ok = True
-
- # Check npm
- npm_path = shutil.which("npm")
- if npm_path:
- try:
- result = subprocess.run(
- ["npm", "--version"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- npm_version = result.stdout.strip()
- print_success(f"npm available (v{npm_version})")
- except Exception:
- print_warning("npm found but version check failed")
- else:
- print_error("npm not found - Node.js is required for frontend")
- all_ok = False
-
- # Check node
- node_path = shutil.which("node")
- if node_path:
- try:
- result = subprocess.run(
- ["node", "--version"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- node_version = result.stdout.strip()
- print_success(f"Node.js available ({node_version})")
- except Exception:
- print_warning("Node.js found but version check failed")
- else:
- print_error("Node.js not found")
- all_ok = False
-
- # Check package.json exists
- if not package_json.exists():
- print_error(f"package.json not found: {package_json}")
- return False, 0, 0
-
- # Check node_modules
- if not node_modules.exists():
- print_error("node_modules directory does not exist")
- print_info("Run 'npm install' in web/ directory to install dependencies")
- return False, 0, 0
-
- # Check key packages
- key_packages = [
- "next",
- "react",
- "react-dom",
- "typescript",
- "tailwindcss",
- "@radix-ui/react-dialog",
- "lucide-react",
- ]
-
- print_info("Checking key frontend packages...")
-
- for pkg in key_packages:
- pkg_dir = node_modules / pkg
- if pkg_dir.exists():
- # Try to get version from package.json
- pkg_json = pkg_dir / "package.json"
- version = ""
- if pkg_json.exists():
- try:
- import json
-
- with open(pkg_json) as f:
- data = json.load(f)
- version = f" (v{data.get('version', '?')})"
- except Exception:
- pass
- print_success(f" ✓ {pkg}{version}")
- installed += 1
- else:
- print_error(f" ✗ {pkg} not installed")
- missing += 1
- all_ok = False
-
- return all_ok, installed, missing
-
-
-def check_system_tools() -> bool:
- """Check system tools and utilities"""
- print_header("System Tools")
-
- all_ok = True
-
- # Git
- git_path = shutil.which("git")
- if git_path:
- try:
- result = subprocess.run(
- ["git", "--version"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- git_version = result.stdout.strip()
- print_success(f"{git_version}")
- except Exception:
- print_warning("git found but version check failed")
- else:
- print_warning("git not found (optional but recommended)")
-
- # uv (fast Python package manager)
- uv_path = shutil.which("uv")
- if uv_path:
- try:
- result = subprocess.run(
- ["uv", "--version"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- uv_version = result.stdout.strip()
- print_success(f"uv available ({uv_version})")
- except Exception:
- print_warning("uv found but version check failed")
- else:
- print_info("uv not found (optional, for faster package installation)")
-
- return all_ok
-
-
-def check_runtime_settings(project_root: Path) -> bool:
- """Check data/user/settings runtime configuration."""
- print_header("Runtime Settings")
-
- settings_dir = project_root / "data" / "user" / "settings"
- required_files = ["system.json", "auth.json", "integrations.json", "model_catalog.json"]
- ok = True
- for name in required_files:
- path = settings_dir / name
- if path.exists():
- print_success(f"{name} exists")
- else:
- print_warning(f"{name} is missing")
- ok = False
-
- if not ok:
- print_info("Run `deeptutor init` or start the app once to create defaults.")
- return False
-
- try:
- import json
-
- catalog = json.loads((settings_dir / "model_catalog.json").read_text(encoding="utf-8"))
- services = catalog.get("services", {})
- for service_name in ("llm", "embedding", "search"):
- service = services.get(service_name, {})
- profiles = service.get("profiles") or []
- if profiles:
- print_success(f" ✓ {service_name} profile configured")
- else:
- level = print_info if service_name == "search" else print_warning
- level(f" ○ {service_name} profile not configured")
- if service_name != "search":
- ok = False
- except Exception as e:
- print_warning(f"Could not inspect model_catalog.json: {e}")
- ok = False
-
- return ok
-
-
-def main():
- """Main function"""
- print("\n" + "=" * 60)
- print("🔍 DeepTutor Installation Checker")
- print("=" * 60)
- print("Checking all dependencies and configurations...")
-
- # Get project root
- script_dir = Path(__file__).parent
- project_root = script_dir.parent
-
- print_info(f"Project root: {project_root}")
-
- # Track overall status
- all_checks_passed = True
- summary = []
-
- # 1. Python environment
- if check_python_environment():
- summary.append(("Python Environment", "✅ OK"))
- else:
- summary.append(("Python Environment", "❌ Issues found"))
- all_checks_passed = False
-
- # 2. Backend packages
- backend_ok, backend_installed, backend_missing = check_backend_packages()
- if backend_ok:
- summary.append(("Backend Dependencies", f"✅ OK ({backend_installed} packages)"))
- else:
- summary.append(
- ("Backend Dependencies", f"❌ {backend_missing} missing, {backend_installed} installed")
- )
- all_checks_passed = False
-
- # 3. Frontend packages
- frontend_ok, frontend_installed, frontend_missing = check_frontend_packages(project_root)
- if frontend_ok:
- summary.append(("Frontend Dependencies", f"✅ OK ({frontend_installed} packages)"))
- else:
- summary.append(
- (
- "Frontend Dependencies",
- f"❌ {frontend_missing} missing, {frontend_installed} installed",
- )
- )
- all_checks_passed = False
-
- # 4. System tools
- check_system_tools()
- summary.append(("System Tools", "✅ Checked"))
-
- # 5. Runtime settings
- if check_runtime_settings(project_root):
- summary.append(("Runtime Settings", "✅ configured"))
- else:
- summary.append(("Runtime Settings", "⚠️ incomplete"))
-
- # Print summary
- print_header("Summary")
-
- for item, status in summary:
- print(f" {item}: {status}")
-
- print("")
- if all_checks_passed:
- print_success("All required dependencies are installed!")
- print_info("You can start DeepTutor with: deeptutor start")
- else:
- print_error("Some dependencies are missing!")
- print_info("Run: deeptutor init")
- print_info("Or manually install missing packages")
-
- print("=" * 60 + "\n")
-
- return 0 if all_checks_passed else 1
-
-
-if __name__ == "__main__":
- try:
- sys.exit(main())
- except KeyboardInterrupt:
- print("\n\n⚠️ Check interrupted by user")
- sys.exit(1)
- except Exception as e:
- print_error(f"\n❌ Unexpected error: {e}")
- import traceback
-
- traceback.print_exc()
- sys.exit(1)
diff --git a/scripts/generate_roster.py b/scripts/generate_roster.py
deleted file mode 100644
index f76769421..000000000
--- a/scripts/generate_roster.py
+++ /dev/null
@@ -1,327 +0,0 @@
-#!/usr/bin/env python3
-"""
-Generate Stargazers and Forkers roster SVG images for GitHub README.
-Modern, minimal style - shows latest users with "and X others" text.
-
-Usage:
- python generate_roster.py --repo HKUDS/DeepTutor --output assets/roster
-"""
-
-import argparse
-import base64
-from concurrent.futures import ThreadPoolExecutor, as_completed
-import json
-import os
-import ssl
-import urllib.request
-
-# Create SSL context that doesn't verify certificates (for macOS compatibility)
-ssl_context = ssl.create_default_context()
-ssl_context.check_hostname = False
-ssl_context.verify_mode = ssl.CERT_NONE
-
-
-def fetch_repo_stats(owner: str, repo: str, token: str = None) -> dict:
- """Fetch repository statistics (accurate counts) from GitHub API."""
- headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": "Repo-Roster-Generator"}
- if token:
- headers["Authorization"] = f"token {token}"
-
- url = f"https://api.github.com/repos/{owner}/{repo}"
- req = urllib.request.Request(url, headers=headers)
-
- try:
- with urllib.request.urlopen(req, timeout=30, context=ssl_context) as response:
- data = json.loads(response.read().decode())
- return {
- "stargazers_count": data.get("stargazers_count", 0),
- "forks_count": data.get("forks_count", 0),
- }
- except Exception as e:
- print(f"Error fetching repo stats: {e}")
- return {"stargazers_count": 0, "forks_count": 0}
-
-
-def fetch_github_api(url: str, token: str = None, count_only: bool = False) -> tuple:
- """Fetch data from GitHub API with pagination. Returns (users, total_count)."""
- headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": "Repo-Roster-Generator"}
- if token:
- headers["Authorization"] = f"token {token}"
-
- all_data = []
- page = 1
- per_page = 100
- total_count = 0
-
- while True:
- paginated_url = f"{url}?per_page={per_page}&page={page}"
- req = urllib.request.Request(paginated_url, headers=headers)
-
- try:
- with urllib.request.urlopen(req, timeout=30, context=ssl_context) as response:
- data = json.loads(response.read().decode())
- if not data:
- break
- all_data.extend(data)
- total_count += len(data)
- if len(data) < per_page:
- break
- page += 1
- # Keep counting but limit data collection
- if len(all_data) >= 500:
- # Continue counting total
- while True:
- page += 1
- paginated_url = f"{url}?per_page={per_page}&page={page}"
- req = urllib.request.Request(paginated_url, headers=headers)
- try:
- with urllib.request.urlopen(
- req, timeout=30, context=ssl_context
- ) as resp:
- more_data = json.loads(resp.read().decode())
- if not more_data:
- break
- total_count += len(more_data)
- if len(more_data) < per_page:
- break
- except:
- break
- break
- except Exception as e:
- print(f"Error fetching {paginated_url}: {e}")
- break
-
- return all_data, total_count
-
-
-def fetch_avatar_as_base64(avatar_url: str, size: int = 48) -> str:
- """Fetch avatar image and convert to base64 data URI."""
- try:
- if "?" in avatar_url:
- avatar_url += f"&s={size}"
- else:
- avatar_url += f"?s={size}"
-
- req = urllib.request.Request(avatar_url, headers={"User-Agent": "Repo-Roster-Generator"})
- with urllib.request.urlopen(req, timeout=10, context=ssl_context) as response:
- data = response.read()
- content_type = response.headers.get("Content-Type", "image/png")
- base64_data = base64.b64encode(data).decode("utf-8")
- return f"data:{content_type};base64,{base64_data}"
- except Exception as e:
- print(f"Error fetching avatar {avatar_url}: {e}")
- return None
-
-
-def generate_modern_roster_svg(
- users: list,
- total_count: int,
- title: str,
- theme: str = "dark",
- display_count: int = 6,
- avatar_size: int = 36,
-) -> str:
- """Generate modern minimal SVG with overlapping avatars."""
-
- # Get latest users (reverse to show newest first)
- display_users = (
- list(reversed(users[-display_count:]))
- if len(users) >= display_count
- else list(reversed(users))
- )
- others_count = total_count - len(display_users)
-
- if not display_users:
- return generate_empty_svg(title, theme)
-
- # Theme colors
- if theme == "dark":
- bg_color = "#0d1117"
- text_color = "#e6edf3"
- muted_color = "#8b949e"
- border_color = "#30363d"
- accent_color = "#58a6ff"
- else:
- bg_color = "#ffffff"
- text_color = "#1f2328"
- muted_color = "#656d76"
- border_color = "#d0d7de"
- accent_color = "#0969da"
-
- # Calculate dimensions
- overlap = 12 # How much avatars overlap
- avatar_spacing = avatar_size - overlap
- avatars_width = avatar_size + (len(display_users) - 1) * avatar_spacing
-
- padding_x = 24
- padding_y = 16
-
- # Text measurements (approximate)
- title_width = len(title) * 9
- others_text = f"and {others_count:,} others" if others_count > 0 else ""
- others_width = len(others_text) * 7 if others_text else 0
-
- total_content_width = avatars_width + 16 + others_width
- width = max(total_content_width + padding_x * 2, 280)
- height = avatar_size + padding_y * 2 + 28 # Extra space for title
-
- # Fetch avatars
- print(f"Fetching {len(display_users)} avatars for {title}...")
- avatar_cache = {}
-
- with ThreadPoolExecutor(max_workers=10) as executor:
- future_to_user = {
- executor.submit(fetch_avatar_as_base64, user["avatar_url"], avatar_size * 2): user[
- "login"
- ]
- for user in display_users
- }
- for future in as_completed(future_to_user):
- login = future_to_user[future]
- try:
- avatar_cache[login] = future.result()
- except Exception as e:
- print(f"Error processing {login}: {e}")
-
- # Build SVG
- svg_parts = [
- f'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="{width}" height="{height}" viewBox="0 0 {width} {height}">',
- "<defs>",
- "<style>",
- '@import url("https://fonts.googleapis.com/css2?family=Inter:wght@500;600&amp;display=swap");',
- '.title { font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; font-weight: 600; }',
- '.others { font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; font-weight: 500; }',
- "</style>",
- "</defs>",
- f'<rect width="100%" height="100%" fill="{bg_color}" rx="12"/>',
- ]
-
- # Title
- svg_parts.append(
- f'<text x="{padding_x}" y="{padding_y + 14}" class="title" fill="{text_color}" font-size="14">{title}</text>'
- )
-
- # Avatars row
- avatar_y = padding_y + 28
-
- for i, user in enumerate(display_users):
- x = padding_x + i * avatar_spacing
- avatar_data = avatar_cache.get(user["login"])
-
- clip_id = f"clip-{i}"
- svg_parts.append(
- f'<clipPath id="{clip_id}"><circle cx="{x + avatar_size / 2}" cy="{avatar_y + avatar_size / 2}" r="{avatar_size / 2}"/></clipPath>'
- )
-
- # White/dark border ring for depth
- svg_parts.append(
- f'<circle cx="{x + avatar_size / 2}" cy="{avatar_y + avatar_size / 2}" r="{avatar_size / 2 + 2}" fill="{bg_color}"/>'
- )
-
- if avatar_data:
- svg_parts.append(
- f'<image x="{x}" y="{avatar_y}" width="{avatar_size}" height="{avatar_size}" '
- f'clip-path="url(#{clip_id})" xlink:href="{avatar_data}" preserveAspectRatio="xMidYMid slice"/>'
- )
- else:
- svg_parts.append(
- f'<circle cx="{x + avatar_size / 2}" cy="{avatar_y + avatar_size / 2}" r="{avatar_size / 2}" fill="{border_color}"/>'
- )
- svg_parts.append(
- f'<text x="{x + avatar_size / 2}" y="{avatar_y + avatar_size / 2 + 5}" text-anchor="middle" '
- f'fill="{text_color}" font-size="14" font-weight="600">{user["login"][0].upper()}</text>'
- )
-
- # "and X others" text
- if others_count > 0:
- text_x = padding_x + avatars_width + 12
- text_y = avatar_y + avatar_size / 2 + 5
- svg_parts.append(
- f'<text x="{text_x}" y="{text_y}" class="others" fill="{muted_color}" font-size="13">and {others_count:,} others</text>'
- )
-
- svg_parts.append("</svg>")
-
- return "\n".join(svg_parts)
-
-
-def generate_empty_svg(title: str, theme: str) -> str:
- """Generate empty state SVG."""
- if theme == "dark":
- bg_color = "#0d1117"
- text_color = "#8b949e"
- else:
- bg_color = "#ffffff"
- text_color = "#656d76"
-
- return f'''<svg xmlns="http://www.w3.org/2000/svg" width="200" height="60">
-<rect width="100%" height="100%" fill="{bg_color}" rx="12"/>
-<text x="100" y="35" text-anchor="middle" fill="{text_color}"
-font-family="Inter, -apple-system, sans-serif" font-size="13" font-weight="500">
-No {title.lower()} yet
-</text>
-</svg>'''
-
-
-def main():
- parser = argparse.ArgumentParser(description="Generate GitHub roster SVG images")
- parser.add_argument("--repo", required=True, help="GitHub repo in format owner/repo")
- parser.add_argument("--output", default="assets/roster", help="Output directory")
- parser.add_argument("--theme", default="dark", choices=["dark", "light"], help="Color theme")
- parser.add_argument("--display", type=int, default=6, help="Number of avatars to display")
- parser.add_argument("--token", default=os.environ.get("GITHUB_TOKEN"), help="GitHub token")
-
- args = parser.parse_args()
-
- owner, repo = args.repo.split("/")
-
- # Create output directory
- os.makedirs(args.output, exist_ok=True)
-
- # Fetch accurate counts from repo API
- print(f"Fetching repo stats for {args.repo}...")
- repo_stats = fetch_repo_stats(owner, repo, args.token)
- stargazers_total = repo_stats["stargazers_count"]
- forks_total = repo_stats["forks_count"]
- print(f"Repo stats: {stargazers_total:,} stars, {forks_total:,} forks")
-
- # Fetch stargazers (only need latest ones for avatars)
- print(f"Fetching stargazers for {args.repo}...")
- stargazers_url = f"https://api.github.com/repos/{owner}/{repo}/stargazers"
- stargazers, _ = fetch_github_api(stargazers_url, args.token)
- print(f"Fetched {len(stargazers)} stargazer records for avatars")
-
- # Fetch forkers (only need latest ones for avatars)
- print(f"Fetching forkers for {args.repo}...")
- forks_url = f"https://api.github.com/repos/{owner}/{repo}/forks"
- forks, _ = fetch_github_api(forks_url, args.token)
- forkers = [
- {"login": f["owner"]["login"], "avatar_url": f["owner"]["avatar_url"]} for f in forks
- ]
- print(f"Fetched {len(forkers)} forker records for avatars")
-
- # Generate stargazers SVG
- print("Generating stargazers SVG...")
- stargazers_svg = generate_modern_roster_svg(
- stargazers, stargazers_total, "Stargazers", theme=args.theme, display_count=args.display
- )
- stargazers_path = os.path.join(args.output, "stargazers.svg")
- with open(stargazers_path, "w", encoding="utf-8") as f:
- f.write(stargazers_svg)
- print(f"Saved: {stargazers_path}")
-
- # Generate forkers SVG
- print("Generating forkers SVG...")
- forkers_svg = generate_modern_roster_svg(
- forkers, forks_total, "Forkers", theme=args.theme, display_count=args.display
- )
- forkers_path = os.path.join(args.output, "forkers.svg")
- with open(forkers_path, "w", encoding="utf-8") as f:
- f.write(forkers_svg)
- print(f"Saved: {forkers_path}")
-
- print("Done!")
-
-
-if __name__ == "__main__":
- main()
diff --git a/scripts/migrate_kb.py b/scripts/migrate_kb.py
deleted file mode 100644
index 514d17c11..000000000
--- a/scripts/migrate_kb.py
+++ /dev/null
@@ -1,566 +0,0 @@
-#!/usr/bin/env python
-"""
-Knowledge Base Migration Script
-===============================
-
-Migrate existing knowledge bases into DeepTutor's knowledge base system.
-
-Features:
-- Auto-detect index format (llamaindex or legacy rag_storage)
-- Validate required index files
-- Copy/migrate KB to target directory
-- Register in kb_config.json
-- Run test query to verify migration
-
-Usage:
- python scripts/migrate_kb.py /path/to/kb --name my_kb --test
- python scripts/migrate_kb.py /path/to/kb --validate-only
-"""
-
-import argparse
-import asyncio
-from datetime import datetime
-import json
-from pathlib import Path
-import shutil
-import sys
-
-# Add project root to path
-PROJECT_ROOT = Path(__file__).resolve().parent.parent
-sys.path.insert(0, str(PROJECT_ROOT))
-
-
-# =============================================================================
-# Constants: Required files for index formats
-# =============================================================================
-
-LLAMAINDEX_REQUIRED_FILES = [
- "docstore.json",
- "index_store.json",
- "default__vector_store.json",
-]
-
-LEGACY_RAG_REQUIRED_FILES = [
- "kv_store_text_chunks.json",
- "kv_store_full_entities.json",
- "kv_store_full_relations.json",
-]
-
-# Optional but recommended for better performance
-LEGACY_RAG_OPTIONAL_FILES = [
- "vdb_chunks.json",
- "vdb_entities.json",
- "vdb_relationships.json",
- "graph_chunk_entity_relation.graphml",
-]
-
-# Default target directory
-DEFAULT_KB_BASE_DIR = PROJECT_ROOT / "data" / "knowledge_bases"
-
-
-# =============================================================================
-# Validation Functions
-# =============================================================================
-
-
-def detect_provider(kb_path: Path) -> str | None:
- """
- Detect the RAG provider type based on directory structure and valid files.
-
- Args:
- kb_path: Path to the knowledge base directory
-
- Returns:
- Provider marker: "llamaindex", "legacy_rag", or None if not detected
- """
- llamaindex_dir = kb_path / "llamaindex_storage"
- legacy_rag_dir = kb_path / "rag_storage"
-
- has_llamaindex = llamaindex_dir.exists() and llamaindex_dir.is_dir()
- has_legacy_rag = legacy_rag_dir.exists() and legacy_rag_dir.is_dir()
-
- # Check which one has valid index files
- llamaindex_valid = False
- legacy_rag_valid = False
-
- if has_llamaindex:
- # Check if LlamaIndex has required files
- llamaindex_valid = all((llamaindex_dir / f).exists() for f in LLAMAINDEX_REQUIRED_FILES)
-
- if has_legacy_rag:
- # Check if legacy rag_storage has expected files
- legacy_rag_valid = all((legacy_rag_dir / f).exists() for f in LEGACY_RAG_REQUIRED_FILES)
-
- if llamaindex_valid:
- return "llamaindex"
- elif has_llamaindex:
- # Directory exists but incomplete
- return "llamaindex"
- elif legacy_rag_valid:
- return "legacy_rag"
- elif has_legacy_rag:
- # Directory exists but incomplete
- return "legacy_rag"
- else:
- return None
-
-
-def validate_llamaindex_files(storage_dir: Path) -> tuple[bool, list[str], list[str]]:
- """
- Validate LlamaIndex storage has required files.
-
- Args:
- storage_dir: Path to llamaindex_storage directory
-
- Returns:
- Tuple of (is_valid, missing_files, found_files)
- """
- missing = []
- found = []
-
- for filename in LLAMAINDEX_REQUIRED_FILES:
- filepath = storage_dir / filename
- if filepath.exists():
- found.append(filename)
- else:
- missing.append(filename)
-
- return len(missing) == 0, missing, found
-
-
-def validate_legacy_rag_files(storage_dir: Path) -> tuple[bool, list[str], list[str]]:
- """
- Validate legacy rag_storage has expected files.
-
- Args:
- storage_dir: Path to rag_storage directory
-
- Returns:
- Tuple of (is_valid, missing_files, found_files)
- """
- missing = []
- found = []
-
- for filename in LEGACY_RAG_REQUIRED_FILES:
- filepath = storage_dir / filename
- if filepath.exists():
- found.append(filename)
- else:
- missing.append(filename)
-
- # Also check optional files
- optional_found = []
- for filename in LEGACY_RAG_OPTIONAL_FILES:
- if (storage_dir / filename).exists():
- optional_found.append(filename)
-
- return len(missing) == 0, missing, found + optional_found
-
-
-def validate_kb(kb_path: Path) -> dict:
- """
- Validate a knowledge base directory.
-
- Args:
- kb_path: Path to the knowledge base directory
-
- Returns:
- Validation result dictionary
- """
- result = {
- "path": str(kb_path),
- "exists": kb_path.exists(),
- "is_valid": False,
- "provider": None,
- "needs_reindex": False,
- "missing_files": [],
- "found_files": [],
- "has_raw_docs": False,
- "has_images": False,
- "has_metadata": False,
- }
-
- if not kb_path.exists():
- return result
-
- # Detect provider
- provider = detect_provider(kb_path)
- result["provider"] = provider
-
- if provider is None:
- result["error"] = (
- "No valid RAG storage found (neither llamaindex_storage/ nor rag_storage/)"
- )
- return result
-
- # Validate based on provider
- if provider == "llamaindex":
- storage_dir = kb_path / "llamaindex_storage"
- is_valid, missing, found = validate_llamaindex_files(storage_dir)
- result["provider"] = "llamaindex"
- result["needs_reindex"] = False
- else: # legacy_rag
- storage_dir = kb_path / "rag_storage"
- is_valid, missing, found = validate_legacy_rag_files(storage_dir)
- # Legacy index is still migratable, but must be reindexed in llamaindex.
- result["provider"] = "llamaindex"
- result["needs_reindex"] = True
- if storage_dir.exists():
- is_valid = True
-
- result["is_valid"] = is_valid
- result["missing_files"] = missing
- result["found_files"] = found
-
- # Check optional directories
- raw_dir = kb_path / "raw"
- result["has_raw_docs"] = raw_dir.exists() and any(raw_dir.iterdir())
-
- images_dir = kb_path / "images"
- result["has_images"] = images_dir.exists() and any(images_dir.iterdir())
-
- result["has_metadata"] = (kb_path / "metadata.json").exists()
- return result
-
-
-# =============================================================================
-# Migration Functions
-# =============================================================================
-
-
-def copy_kb_directory(source_path: Path, target_path: Path, verbose: bool = True) -> bool:
- """
- Copy knowledge base directory to target location.
-
- Args:
- source_path: Source KB directory
- target_path: Target KB directory
- verbose: Print progress messages
-
- Returns:
- True if successful
- """
- if target_path.exists():
- if verbose:
- print(f" ⚠️ Target directory already exists: {target_path}")
- return False
-
- if verbose:
- print(f" Copying {source_path} -> {target_path}")
-
- shutil.copytree(source_path, target_path)
-
- if verbose:
- print(" ✓ Copied successfully")
-
- return True
-
-
-def register_kb(
- kb_name: str,
- kb_base_dir: Path,
- description: str = "",
- provider: str | None = None,
- needs_reindex: bool = False,
-) -> bool:
- """
- Register knowledge base in kb_config.json.
-
- Args:
- kb_name: Knowledge base name
- kb_base_dir: Base directory containing kb_config.json
- description: Optional description
- provider: RAG provider name
-
- Returns:
- True if successful
- """
- config_file = kb_base_dir / "kb_config.json"
-
- # Load existing config
- if config_file.exists():
- with open(config_file, encoding="utf-8") as f:
- config = json.load(f)
- else:
- config = {"knowledge_bases": {}}
-
- if "knowledge_bases" not in config:
- config["knowledge_bases"] = {}
-
- # Check if already registered
- if kb_name in config["knowledge_bases"]:
- print(f" ⚠️ KB '{kb_name}' is already registered in kb_config.json")
- return True
-
- # Add to config
- config["knowledge_bases"][kb_name] = {
- "path": kb_name,
- "description": description or f"Knowledge base: {kb_name}",
- "rag_provider": provider or "llamaindex",
- "needs_reindex": bool(needs_reindex),
- "status": "needs_reindex" if needs_reindex else "ready",
- }
-
- # Save config
- with open(config_file, "w", encoding="utf-8") as f:
- json.dump(config, f, indent=2, ensure_ascii=False)
-
- print(f" ✓ Registered '{kb_name}' in kb_config.json")
-
- # Also create/update metadata.json if needed
- kb_dir = kb_base_dir / kb_name
- metadata_file = kb_dir / "metadata.json"
-
- if not metadata_file.exists():
- metadata = {
- "name": kb_name,
- "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
- "description": description or f"Knowledge base: {kb_name}",
- "version": "1.0",
- "rag_provider": provider or "llamaindex",
- "needs_reindex": bool(needs_reindex),
- "migrated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
- }
- with open(metadata_file, "w", encoding="utf-8") as f:
- json.dump(metadata, f, indent=2, ensure_ascii=False)
- print(" ✓ Created metadata.json")
- else:
- # Update existing metadata with migration info
- with open(metadata_file, encoding="utf-8") as f:
- metadata = json.load(f)
-
- if provider:
- metadata["rag_provider"] = provider
- metadata["needs_reindex"] = bool(needs_reindex)
- metadata["migrated_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
-
- with open(metadata_file, "w", encoding="utf-8") as f:
- json.dump(metadata, f, indent=2, ensure_ascii=False)
- print(" ✓ Updated metadata.json")
-
- return True
-
-
-
-async def test_kb_search(kb_name: str, query: str = "What is this knowledge base about?") -> bool:
- """
- Test knowledge base with a simple search query.
-
- Args:
- kb_name: Knowledge base name
- query: Test query
-
- Returns:
- True if search succeeded
- """
- try:
- from deeptutor.tools.rag_tool import rag_search
- except ImportError as e:
- print(f" ⚠️ Could not import rag_tool: {e}")
- return False
-
- print(f" Running test query: '{query[:50]}...'")
-
- try:
- result = await rag_search(
- query=query,
- kb_name=kb_name,
- mode="naive", # Use simplest mode for testing
- )
-
- if result and result.get("answer"):
- answer_preview = result["answer"][:200]
- print(" ✓ Search successful!")
- print(f" Provider: {result.get('provider', 'unknown')}")
- print(f" Answer preview: {answer_preview}...")
- return True
- else:
- print(" ⚠️ Search returned empty result")
- return False
-
- except Exception as e:
- print(f" ✗ Search failed: {e}")
- return False
-
-
-async def migrate_kb(
- source_path: str,
- target_base_dir: str | None = None,
- kb_name: str | None = None,
- run_test: bool = False,
- validate_only: bool = False,
- force: bool = False,
-) -> bool:
- """
- Migrate a knowledge base to DeepTutor.
-
- Args:
- source_path: Path to source knowledge base
- target_base_dir: Target base directory (default: data/knowledge_bases)
- kb_name: Name for the migrated KB (default: source directory name)
- run_test: Run a test query after migration
- validate_only: Only validate, don't migrate
- force: Overwrite existing KB if exists
-
- Returns:
- True if successful
- """
- source = Path(source_path).resolve()
- target_base = Path(target_base_dir) if target_base_dir else DEFAULT_KB_BASE_DIR
- target_base = target_base.resolve()
-
- # Determine KB name
- if kb_name is None:
- kb_name = source.name
-
- print("=" * 60)
- print("Knowledge Base Migration")
- print("=" * 60)
- print(f"Source: {source}")
- print(f"Target: {target_base / kb_name}")
- print()
-
- # Step 1: Validate source KB
- print("Step 1: Validating source knowledge base...")
- validation = validate_kb(source)
-
- if not validation["exists"]:
- print(f" ✗ Source directory does not exist: {source}")
- return False
-
- if not validation["is_valid"]:
- print(" ✗ Validation failed!")
- if validation.get("error"):
- print(f" Error: {validation['error']}")
- if validation["missing_files"]:
- print(f" Missing files: {', '.join(validation['missing_files'])}")
- return False
-
- print(" ✓ Validation passed")
- print(f" Provider: {validation['provider']}")
- print(f" Needs reindex: {'Yes' if validation['needs_reindex'] else 'No'}")
- print(f" Found files: {', '.join(validation['found_files'][:5])}...")
- print(f" Has raw docs: {'Yes' if validation['has_raw_docs'] else 'No'}")
- print(f" Has images: {'Yes' if validation['has_images'] else 'No'}")
- print()
-
- if validate_only:
- print("Validation-only mode. Exiting.")
- return True
-
- # Step 2: Copy to target
- print("Step 2: Copying knowledge base...")
- target_path = target_base / kb_name
-
- if target_path.exists():
- if force:
- print(" Removing existing directory (--force)...")
- shutil.rmtree(target_path)
- elif source.resolve() == target_path.resolve():
- print(" Source and target are the same. Skipping copy.")
- else:
- print(f" ✗ Target directory already exists: {target_path}")
- print(" Use --force to overwrite or --name to specify a different name")
- return False
-
- if source.resolve() != target_path.resolve():
- success = copy_kb_directory(source, target_path)
- if not success:
- return False
- print()
-
- # Step 3: Register in kb_config.json
- print("Step 3: Registering knowledge base...")
- register_kb(
- kb_name=kb_name,
- kb_base_dir=target_base,
- description=f"Migrated from: {source}",
- provider=validation["provider"],
- needs_reindex=bool(validation.get("needs_reindex")),
- )
- print()
-
- # Step 4: Test search (optional)
- if run_test:
- print("Step 4: Testing knowledge base...")
- await test_kb_search(kb_name)
- print()
-
- print("=" * 60)
- print("✓ Migration complete!")
- print(f" Knowledge base '{kb_name}' is now available in DeepTutor.")
- print("=" * 60)
-
- return True
-
-
-# =============================================================================
-# CLI Entry Point
-# =============================================================================
-
-
-def main():
- parser = argparse.ArgumentParser(
- description="Migrate knowledge bases into DeepTutor",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog="""
-Examples:
- # Migrate a knowledge base
- python scripts/migrate_kb.py /path/to/my_kb
-
- # Migrate with custom name
- python scripts/migrate_kb.py /path/to/kb --name my_textbook
-
- # Migrate and run test query
- python scripts/migrate_kb.py /path/to/kb --test
-
-
- # Validate only (don't migrate)
- python scripts/migrate_kb.py /path/to/kb --validate-only
-
- # Force overwrite existing KB
- python scripts/migrate_kb.py /path/to/kb --force
-""",
- )
-
- parser.add_argument("source", help="Path to source knowledge base directory")
-
- parser.add_argument(
- "--name", help="Name for the migrated knowledge base (default: source directory name)"
- )
-
- parser.add_argument(
- "--target-dir", help=f"Target base directory (default: {DEFAULT_KB_BASE_DIR})"
- )
-
- parser.add_argument("--test", action="store_true", help="Run a test query after migration")
-
- parser.add_argument(
- "--validate-only",
- action="store_true",
- help="Only validate the knowledge base, don't migrate",
- )
-
- parser.add_argument(
- "--force", action="store_true", help="Overwrite existing knowledge base if exists"
- )
-
- args = parser.parse_args()
-
- # Run migration
- success = asyncio.run(
- migrate_kb(
- source_path=args.source,
- target_base_dir=args.target_dir,
- kb_name=args.name,
- run_test=args.test,
- validate_only=args.validate_only,
- force=args.force,
- )
- )
-
- sys.exit(0 if success else 1)
-
-
-if __name__ == "__main__":
- main()
diff --git a/scripts/migrate_user_data.py b/scripts/migrate_user_data.py
deleted file mode 100644
index b5fb0f15c..000000000
--- a/scripts/migrate_user_data.py
+++ /dev/null
@@ -1,262 +0,0 @@
-#!/usr/bin/env python
-"""Migrate legacy runtime data into the new ``data/user`` layout."""
-
-from __future__ import annotations
-
-import os
-from pathlib import Path
-import shutil
-import sys
-
-project_root = Path(__file__).parent.parent
-sys.path.insert(0, str(project_root))
-
-
-def print_banner(title: str):
- print("\n" + "=" * 70)
- print(f" {title}")
- print("=" * 70)
-
-
-def print_step(message: str, status: str = ""):
- if status:
- print(f" [OK] {message} - {status}")
- else:
- print(f" ... {message}")
-
-
-def move_directory(src: Path, dst: Path) -> bool:
- if not src.exists():
- return False
-
- dst.parent.mkdir(parents=True, exist_ok=True)
- if dst.exists():
- for item in src.iterdir():
- dst_item = dst / item.name
- if item.is_dir():
- move_directory(item, dst_item)
- elif not dst_item.exists():
- shutil.move(str(item), str(dst_item))
- if src.exists() and not any(src.iterdir()):
- src.rmdir()
- else:
- shutil.move(str(src), str(dst))
- return True
-
-
-def move_file(src: Path, dst: Path) -> bool:
- if not src.exists():
- return False
- dst.parent.mkdir(parents=True, exist_ok=True)
- if dst.exists():
- dst.unlink()
- shutil.move(str(src), str(dst))
- return True
-
-
-def delete_file(path: Path) -> bool:
- if path.exists():
- path.unlink()
- return True
- return False
-
-
-def create_structure(user_dir: Path) -> None:
- required_dirs = [
- user_dir / "settings",
- user_dir / "logs",
- user_dir / "workspace" / "memory",
- user_dir / "workspace" / "notebook",
- user_dir / "workspace" / "co-writer" / "audio",
- user_dir / "workspace" / "co-writer" / "tool_calls",
- user_dir / "workspace" / "chat" / "chat",
- user_dir / "workspace" / "chat" / "deep_solve",
- user_dir / "workspace" / "chat" / "deep_question",
- user_dir / "workspace" / "chat" / "deep_research" / "reports",
- user_dir / "workspace" / "chat" / "math_animator",
- user_dir / "workspace" / "chat" / "_detached_code_execution",
- ]
- for directory in required_dirs:
- directory.mkdir(parents=True, exist_ok=True)
- print_step(f"Created {directory.relative_to(user_dir)}/")
-
-
-def migrate() -> None:
- user_dir = project_root / "data" / "user"
- data_dir = project_root / "data"
- if not user_dir.exists():
- print("No user data directory found. Nothing to migrate.")
- return
-
- print_banner("User Data Migration")
- print(f"Source directory: {user_dir}")
-
- print_banner("Step 1: Creating New Directory Structure")
- create_structure(user_dir)
-
- print_banner("Step 2: Moving Chat History Database")
- legacy_chat_db = data_dir / "chat_history.db"
- new_chat_db = user_dir / "chat_history.db"
- if legacy_chat_db.exists() and not new_chat_db.exists():
- os.replace(legacy_chat_db, new_chat_db)
- print_step("Moved chat_history.db", "-> data/user/chat_history.db")
- else:
- print_step("chat_history.db", "not found or already migrated")
-
- print_banner("Step 3: Moving Session Files")
- session_moves = [
- (
- user_dir / "solver_sessions.json",
- user_dir / "workspace" / "chat" / "deep_solve" / "sessions.json",
- ),
- (
- user_dir / "chat_sessions.json",
- user_dir / "workspace" / "chat" / "chat" / "sessions.json",
- ),
- ]
- for src, dst in session_moves:
- if move_file(src, dst):
- print_step(f"Moved {src.name}", f"-> {dst.relative_to(user_dir)}")
- else:
- print_step(src.name, "not found, skipped")
-
- print_banner("Step 4: Moving Legacy Runtime Directories")
- moves = [
- (user_dir / "solve", user_dir / "workspace" / "chat" / "deep_solve"),
- (user_dir / "agent" / "solve", user_dir / "workspace" / "chat" / "deep_solve"),
- (user_dir / "chat", user_dir / "workspace" / "chat" / "chat"),
- (user_dir / "agent" / "chat", user_dir / "workspace" / "chat" / "chat"),
- (user_dir / "question", user_dir / "workspace" / "chat" / "deep_question"),
- (user_dir / "agent" / "question", user_dir / "workspace" / "chat" / "deep_question"),
- (user_dir / "research", user_dir / "workspace" / "chat" / "deep_research"),
- (user_dir / "agent" / "research", user_dir / "workspace" / "chat" / "deep_research"),
- (user_dir / "co-writer", user_dir / "workspace" / "co-writer"),
- (user_dir / "agent" / "co-writer", user_dir / "workspace" / "co-writer"),
- (user_dir / "workspace" / "logs", user_dir / "logs"),
- (user_dir / "logs", user_dir / "logs"),
- (user_dir / "agent" / "logs", user_dir / "logs"),
- (user_dir / "notebook", user_dir / "workspace" / "notebook"),
- (user_dir / "workspace" / "notebook", user_dir / "workspace" / "notebook"),
- (
- user_dir / "run_code_workspace",
- user_dir / "workspace" / "chat" / "_detached_code_execution",
- ),
- (
- user_dir / "agent" / "run_code_workspace",
- user_dir / "workspace" / "chat" / "_detached_code_execution",
- ),
- (user_dir / "agent" / "math_animator", user_dir / "workspace" / "chat" / "math_animator"),
- ]
- for src, dst in moves:
- if src == dst:
- continue
- if move_directory(src, dst):
- print_step(f"Moved {src.relative_to(user_dir)}/", f"-> {dst.relative_to(user_dir)}/")
- else:
- print_step(str(src.relative_to(user_dir)), "not found, skipped")
-
- print_banner("Step 5: Deleting Deprecated Files")
- deprecated_files = [
- "user_history.json",
- "settings.json",
- "llm_providers.json",
- "embedding_providers.json",
- ]
- for filename in deprecated_files:
- path = user_dir / filename
- if delete_file(path):
- print_step(f"Deleted {filename}")
- else:
- print_step(filename, "not found, skipped")
-
- print_banner("Migration Complete")
- print(
- """
-New structure:
-data/user/
-├── chat_history.db
- ├── logs/
- ├── settings/
-└── workspace/
- ├── memory/
- ├── notebook/
- ├── co-writer/
- ├── logs/
- └── chat/
- ├── chat/
- ├── deep_solve/
- ├── deep_question/
- ├── deep_research/
- ├── math_animator/
- └── _detached_code_execution/
-"""
- )
-
-
-def verify_migration() -> bool:
- print_banner("Verification")
- user_dir = project_root / "data" / "user"
- required = [
- "chat_history.db",
- "logs",
- "settings",
- "workspace/memory",
- "workspace/notebook",
- "workspace/co-writer/audio",
- "workspace/co-writer/tool_calls",
- "workspace/chat/chat",
- "workspace/chat/deep_solve",
- "workspace/chat/deep_question",
- "workspace/chat/deep_research/reports",
- "workspace/chat/math_animator",
- "workspace/chat/_detached_code_execution",
- ]
-
- all_ok = True
- for path in required:
- full_path = user_dir / path
- if full_path.exists():
- print_step(f"{path}/", "OK")
- else:
- print_step(f"{path}/", "MISSING!")
- all_ok = False
-
- deprecated = [
- "user_history.json",
- "settings.json",
- "llm_providers.json",
- "embedding_providers.json",
- ]
- for filename in deprecated:
- path = user_dir / filename
- if path.exists():
- print_step(filename, "STILL EXISTS (should be deleted)")
- all_ok = False
-
- if all_ok:
- print("\n [OK] All verifications passed!")
- else:
- print("\n [FAIL] Some issues found. Please check above.")
- return all_ok
-
-
-if __name__ == "__main__":
- import argparse
-
- parser = argparse.ArgumentParser(description="Migrate runtime data into data/user/")
- parser.add_argument("--verify", action="store_true", help="Only verify migration status")
- parser.add_argument(
- "--dry-run", action="store_true", help="Show what would be done without making changes"
- )
- args = parser.parse_args()
-
- if args.verify:
- verify_migration()
- elif args.dry_run:
- print("DRY RUN - No changes will be made")
- print_banner(
- "Would create settings/ + workspace/ structure and move legacy runtime files under data/user/"
- )
- else:
- migrate()
- verify_migration()
diff --git a/scripts/sync_prompts_from_en.py b/scripts/sync_prompts_from_en.py
deleted file mode 100644
index 331f98222..000000000
--- a/scripts/sync_prompts_from_en.py
+++ /dev/null
@@ -1,146 +0,0 @@
-#!/usr/bin/env python
-
-"""
-Semi-automatic sync of prompt structure from prompts/en to prompts/zh|prompts/cn.
-
-Behavior (safe by default):
-- Dry-run: prints what would be added
-- With --write: adds missing keys to zh/cn files without overwriting existing values
-- With --create-missing-files: creates missing zh/cn files using the en structure
-
-NOTE: This tool does NOT translate. It inserts TODO markers to be manually rewritten in Chinese.
-"""
-
-from __future__ import annotations
-
-import argparse
-from pathlib import Path
-import sys
-from typing import Any
-
-import yaml
-
-PROJECT_ROOT = Path(__file__).resolve().parents[1]
-AGENTS_DIR = PROJECT_ROOT / "deeptutor" / "agents"
-
-
-def _load_yaml(path: Path) -> Any:
- with open(path, encoding="utf-8") as f:
- return yaml.safe_load(f) or {}
-
-
-def _dump_yaml(path: Path, obj: Any) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- with open(path, "w", encoding="utf-8") as f:
- yaml.safe_dump(obj, f, allow_unicode=True, sort_keys=False)
-
-
-def _merge_missing(en_obj: Any, zh_obj: Any) -> tuple[Any, int]:
- """
- Add missing keys from en_obj into zh_obj without overwriting existing zh content.
- Returns (new_obj, added_count).
- """
- added = 0
-
- if isinstance(en_obj, dict):
- if not isinstance(zh_obj, dict):
- zh_obj = {}
- for k, v in en_obj.items():
- if k not in zh_obj:
- added += 1
- if isinstance(v, str):
- zh_obj[k] = f"<<TODO_TRANSLATE>> {v}"
- else:
- # For non-string nodes, insert scaffold recursively
- zh_obj[k], inc = _merge_missing(
- v, {} if isinstance(v, dict) else [] if isinstance(v, list) else None
- )
- added += inc
- else:
- zh_obj[k], inc = _merge_missing(v, zh_obj[k])
- added += inc
- return zh_obj, added
-
- if isinstance(en_obj, list):
- # Do not attempt to merge list structures; keep existing zh list.
- return zh_obj, 0
-
- # Primitive leaf: nothing to do
- return zh_obj, 0
-
-
-def main() -> int:
- parser = argparse.ArgumentParser()
- parser.add_argument("--write", action="store_true", help="write changes to disk")
- parser.add_argument(
- "--create-missing-files",
- action="store_true",
- help="create missing zh/cn files from en structure with TODO markers",
- )
- parser.add_argument(
- "--target",
- choices=["zh", "cn", "both"],
- default="both",
- help="which target language directory to sync",
- )
- args = parser.parse_args()
-
- if not AGENTS_DIR.exists():
- print(f"Agents directory not found: {AGENTS_DIR}", file=sys.stderr)
- return 2
-
- total_added = 0
- total_files = 0
-
- for module_dir in sorted([p for p in AGENTS_DIR.iterdir() if p.is_dir()]):
- prompts_dir = module_dir / "prompts"
- en_dir = prompts_dir / "en"
- if not en_dir.exists():
- continue
-
- targets: list[tuple[str, Path]] = []
- if args.target in ("zh", "both"):
- targets.append(("zh", prompts_dir / "zh"))
- if args.target in ("cn", "both"):
- targets.append(("cn", prompts_dir / "cn"))
-
- en_files = [p for p in en_dir.rglob("*.yaml") if p.is_file()]
- for en_file in sorted(en_files):
- rel = en_file.relative_to(en_dir)
- en_obj = _load_yaml(en_file)
- for lang_name, lang_dir in targets:
- zh_file = lang_dir / rel
- if not zh_file.exists():
- if not args.create_missing_files:
- print(f"[MISSING {lang_name}] {module_dir.name}: {rel.as_posix()}")
- continue
- zh_obj = {}
- else:
- zh_obj = _load_yaml(zh_file)
-
- new_obj, added = _merge_missing(en_obj, zh_obj)
- if added == 0:
- continue
-
- total_added += added
- total_files += 1
- print(f"[SYNC {lang_name}] {module_dir.name}: {rel.as_posix()} (+{added} keys)")
-
- if args.write:
- _dump_yaml(zh_file, new_obj)
-
- if total_files == 0:
- print("No changes needed.")
- return 0
-
- if args.write:
- print(f"Updated {total_files} file(s), added {total_added} key(s).")
- else:
- print(
- f"Dry-run: would update {total_files} file(s), add {total_added} key(s). Use --write to apply."
- )
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/scripts/test_embedding.py b/scripts/test_embedding.py
deleted file mode 100644
index e3aee3ab9..000000000
--- a/scripts/test_embedding.py
+++ /dev/null
@@ -1,126 +0,0 @@
-#!/usr/bin/env python3
-"""
-Quick embedding smoke test.
-
-Usage examples:
- python3 scripts/test_embedding.py --text "hello world"
- python3 scripts/test_embedding.py --text "test" --repeat 3 --show-config
- python3 scripts/test_embedding.py --direct
-"""
-
-from __future__ import annotations
-
-import argparse
-import asyncio
-import json
-from pathlib import Path
-import sys
-
-import httpx
-
-PROJECT_ROOT = Path(__file__).resolve().parent.parent
-if str(PROJECT_ROOT) not in sys.path:
- sys.path.insert(0, str(PROJECT_ROOT))
-
-
-def _load_embedding_services():
- from deeptutor.services.embedding.client import get_embedding_client, reset_embedding_client
- from deeptutor.services.embedding.config import get_embedding_config
-
- return get_embedding_client, reset_embedding_client, get_embedding_config
-
-
-get_embedding_client, reset_embedding_client, get_embedding_config = _load_embedding_services()
-
-
-def _mask_key(key: str) -> str:
- if not key:
- return "(empty)"
- if len(key) <= 10:
- return "*" * len(key)
- return f"{key[:6]}...{key[-4:]}"
-
-
-async def run_client_test(text: str, repeat: int) -> None:
- reset_embedding_client()
- client = get_embedding_client()
- cfg = get_embedding_config()
-
- inputs = [f"{text} #{i + 1}" if repeat > 1 else text for i in range(repeat)]
- print("[ClientTest] Calling EmbeddingClient.embed(...)")
- vectors = await client.embed(inputs)
-
- dim = len(vectors[0]) if vectors else 0
- print(f"[ClientTest] OK: vectors={len(vectors)}, dim={dim}, model={cfg.model}")
- if vectors:
- print(f"[ClientTest] First vector preview (8 dims): {vectors[0][:8]}")
-
-
-async def run_direct_test(text: str) -> None:
- cfg = get_embedding_config()
- url = f"{(cfg.base_url or '').rstrip('/')}/embeddings"
- headers = {
- "Content-Type": "application/json",
- "Authorization": f"Bearer {cfg.api_key}",
- }
- payload = {
- "input": [text],
- "model": cfg.model,
- "encoding_format": "float",
- }
- if cfg.dim:
- payload["dimensions"] = cfg.dim
-
- print(f"[DirectTest] POST {url}")
- async with httpx.AsyncClient(timeout=cfg.request_timeout) as client:
- resp = await client.post(url, headers=headers, json=payload)
- print(f"[DirectTest] status={resp.status_code}")
-
- try:
- body_json = resp.json()
- print("[DirectTest] JSON response:")
- print(json.dumps(body_json, ensure_ascii=False, indent=2)[:4000])
- except Exception:
- print("[DirectTest] Non-JSON response:")
- print(resp.text.strip()[:2000])
-
-
-async def main() -> None:
- parser = argparse.ArgumentParser(description="Quick embedding smoke test")
- parser.add_argument("--text", default="hello world", help="Input text for embedding")
- parser.add_argument("--repeat", type=int, default=1, help="How many inputs to send")
- parser.add_argument(
- "--show-config", action="store_true", help="Print effective embedding config before testing"
- )
- parser.add_argument(
- "--direct",
- action="store_true",
- help="Also directly call /embeddings endpoint and print raw response",
- )
- args = parser.parse_args()
-
- cfg = get_embedding_config()
- if args.show_config:
- print("[Config]")
- print(f" binding={cfg.binding}")
- print(f" host={cfg.base_url}")
- print(f" model={cfg.model}")
- print(f" dim={cfg.dim}")
- print(f" timeout={cfg.request_timeout}")
- print(f" batch_size={cfg.batch_size}")
- print(f" api_key={_mask_key(cfg.api_key)}")
-
- try:
- await run_client_test(args.text, max(1, args.repeat))
- except Exception as exc:
- print(f"[ClientTest] FAILED: {type(exc).__name__}: {exc}")
-
- if args.direct:
- try:
- await run_direct_test(args.text)
- except Exception as exc:
- print(f"[DirectTest] FAILED: {type(exc).__name__}: {exc}")
-
-
-if __name__ == "__main__":
- asyncio.run(main())
diff --git a/scripts/test_llm_api.py b/scripts/test_llm_api.py
deleted file mode 100644
index 33abc97dc..000000000
--- a/scripts/test_llm_api.py
+++ /dev/null
@@ -1,134 +0,0 @@
-#!/usr/bin/env python3
-"""
-Quick LLM API smoke test.
-
-Usage:
- python3 scripts/test_llm_api.py --prompt "Say hello"
- python3 scripts/test_llm_api.py --show-config
- python3 scripts/test_llm_api.py --direct --show-config
-"""
-
-from __future__ import annotations
-
-import argparse
-import asyncio
-import json
-from pathlib import Path
-import sys
-
-import httpx
-
-PROJECT_ROOT = Path(__file__).resolve().parent.parent
-if str(PROJECT_ROOT) not in sys.path:
- sys.path.insert(0, str(PROJECT_ROOT))
-
-
-def _load_llm_services():
- from deeptutor.services.llm import factory
- from deeptutor.services.llm.config import clear_llm_config_cache, get_llm_config
-
- return factory, clear_llm_config_cache, get_llm_config
-
-
-factory, clear_llm_config_cache, get_llm_config = _load_llm_services()
-
-
-def _mask_key(key: str) -> str:
- if not key:
- return "(empty)"
- if len(key) <= 10:
- return "*" * len(key)
- return f"{key[:6]}...{key[-4:]}"
-
-
-async def run_factory_test(
- prompt: str, system_prompt: str, max_tokens: int, temperature: float
-) -> None:
- cfg = get_llm_config()
- print(f"[FactoryTest] model={cfg.model}")
- print("[FactoryTest] Calling factory.complete(...)")
- answer = await factory.complete(
- prompt=prompt,
- system_prompt=system_prompt,
- max_tokens=max_tokens,
- temperature=temperature,
- )
- text = (answer or "").strip()
- print(f"[FactoryTest] OK (model={cfg.model})")
- print("[FactoryTest] Response preview:")
- print(text[:1000] if text else "(empty)")
-
-
-async def run_direct_test(
- prompt: str, system_prompt: str, max_tokens: int, temperature: float
-) -> None:
- cfg = get_llm_config()
- url = f"{(cfg.base_url or '').rstrip('/')}/chat/completions"
- headers = {
- "Content-Type": "application/json",
- "Authorization": f"Bearer {cfg.api_key}",
- }
- payload = {
- "model": cfg.model,
- "messages": [
- {"role": "system", "content": system_prompt},
- {"role": "user", "content": prompt},
- ],
- "max_tokens": max_tokens,
- "temperature": temperature,
- }
-
- print(f"[DirectTest] POST {url}")
- async with httpx.AsyncClient(timeout=120) as client:
- resp = await client.post(url, headers=headers, json=payload)
- print(f"[DirectTest] status={resp.status_code}")
-
- try:
- body = resp.json()
- print("[DirectTest] JSON response:")
- print(json.dumps(body, ensure_ascii=False, indent=2)[:4000])
- except Exception:
- print("[DirectTest] Non-JSON response:")
- print(resp.text[:2000])
-
-
-async def main() -> None:
- parser = argparse.ArgumentParser(description="Quick LLM API smoke test")
- parser.add_argument("--prompt", default="Briefly explain what a derivative is.")
- parser.add_argument("--system", default="You are a concise helpful assistant.")
- parser.add_argument("--max-tokens", type=int, default=256)
- parser.add_argument("--temperature", type=float, default=0.2)
- parser.add_argument("--show-config", action="store_true")
- parser.add_argument(
- "--direct",
- action="store_true",
- help="Also call /chat/completions endpoint directly and print raw response.",
- )
- args = parser.parse_args()
-
- clear_llm_config_cache()
- cfg = get_llm_config()
-
- if args.show_config:
- print("[Config]")
- print(f" binding={cfg.binding}")
- print(f" host={cfg.base_url}")
- print(f" model={cfg.model}")
- print(f" max_concurrency={cfg.max_concurrency}")
- print(f" requests_per_minute={cfg.requests_per_minute}")
- print(f" api_key={_mask_key(cfg.api_key)}")
-
- try:
- await run_factory_test(args.prompt, args.system, args.max_tokens, args.temperature)
- except Exception as exc:
- print(f"[FactoryTest] FAILED: {type(exc).__name__}: {exc}")
-
- if args.direct:
- try:
- await run_direct_test(args.prompt, args.system, args.max_tokens, args.temperature)
- except Exception as exc:
- print(f"[DirectTest] FAILED: {type(exc).__name__}: {exc}")
-
-
-if __name__ == "__main__":
- asyncio.run(main())
diff --git a/tests/cli/test_chat_cli.py b/tests/cli/test_chat_cli.py
index 369ced570..b8d46bd9f 100644
--- a/tests/cli/test_chat_cli.py
+++ b/tests/cli/test_chat_cli.py
@@ -94,7 +94,7 @@ def test_run_command_with_config(monkeypatch) -> None:
"deep_research",
"compare retrieval stacks",
"--config-json",
- '{"mode":"report","depth":"deep","sources":["web","papers"]}',
+ '{"mode":"report","depth":"deep"}',
],
)
@@ -104,7 +104,6 @@ def test_run_command_with_config(monkeypatch) -> None:
assert request.config == {
"mode": "report",
"depth": "deep",
- "sources": ["web", "papers"],
}
diff --git a/tests/cli/test_config_cli.py b/tests/cli/test_config_cli.py
new file mode 100644
index 000000000..9e15b9186
--- /dev/null
+++ b/tests/cli/test_config_cli.py
@@ -0,0 +1,65 @@
+"""CLI config command tests."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from typer.testing import CliRunner
+
+from deeptutor_cli.main import app
+
+runner = CliRunner()
+
+
+def test_config_show_handles_missing_embedding(monkeypatch) -> None:
+ """CLI-only defaults skip embedding setup, so config show must not traceback."""
+ import deeptutor.services.config as config
+
+ monkeypatch.setattr(
+ config,
+ "load_system_settings",
+ lambda: {"backend_port": 8001, "frontend_port": 3782},
+ )
+ monkeypatch.setattr(
+ config,
+ "resolve_llm_runtime_config",
+ lambda: SimpleNamespace(
+ binding_hint="openai",
+ provider_name="openai",
+ provider_mode="standard",
+ model="gpt-4o-mini",
+ effective_url="https://api.openai.com/v1",
+ api_version=None,
+ extra_headers={},
+ api_key="",
+ ),
+ )
+
+ def _missing_embedding() -> None:
+ raise ValueError("No active embedding model is configured.")
+
+ monkeypatch.setattr(config, "resolve_embedding_runtime_config", _missing_embedding)
+ monkeypatch.setattr(
+ config,
+ "resolve_search_runtime_config",
+ lambda: SimpleNamespace(
+ provider="duckduckgo",
+ requested_provider="duckduckgo",
+ status="ok",
+ fallback_reason=None,
+ base_url="",
+ proxy=None,
+ api_key="",
+ ),
+ )
+ monkeypatch.setattr(
+ config,
+ "load_config_with_main",
+ lambda _name: {"system": {"language": "en"}, "tools": {}},
+ )
+
+ result = runner.invoke(app, ["config", "show"])
+
+ assert result.exit_code == 0, result.output
+ assert '"status": "not_configured"' in result.output
+ assert "No active embedding model is configured." in result.output