Skip to content

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

release: v1.2.3 — document attachments, thinking blocks, provider core refactor

Bingxi Zhao (Frank)4b7d24d33efe
diff --git a/README.md b/README.md
index bef0c3ddc..e5e36db63 100644
--- a/README.md
+++ b/README.md
@@ -28,6 +28,8 @@
### 📦 Releases
+> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — Document attachments in chat (PDF/DOCX/XLSX/PPTX), reasoning model thinking-block display, tri-state embedding `send_dimensions` toggle, LLM provider core refactor, Soul template editor, Co-Writer save-to-notebook, Knowledge Base drag-and-drop upload & delete resilience, and question generation language fidelity.
+
> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — User-authored Skills system (CRUD + chat integration), chat input performance overhaul with state colocation, `response_format` auto-fallback for incompatible providers, LAN remote access fix, sidebar version badge, Deep Solve image attachments, TutorBot WebSocket auto-start, Book Library UI, and visualization fullscreen mode.
> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — Per-stage chat token limits in `agents.yaml` (8000-token responses), Regenerate last response across CLI / WebSocket / Web UI, RAG `None`-embedding crash fix, Gemma `json_object` compatibility, and dark code-block readability.
@@ -115,7 +117,7 @@ You'll also need an **API key** from at least one LLM provider (e.g. [OpenAI](ht
### Option A — Setup Tour (Recommended)
-A **single interactive script** that walks you through everything: dependency installation, environment configuration, live connection testing, and launch. No manual `.env` editing needed.
+A **single interactive CLI script** that walks you through local configuration: language selection, ports, LLM, embedding, and optional search. The wizard writes everything directly into `.env`, so no manual env editing is needed.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
@@ -130,12 +132,18 @@ python -m venv .venv && .venv\Scripts\activate # otherwise
python scripts/start_tour.py
```
-The tour asks how you'd like to use DeepTutor:
+The setup tour:
+
+- automatically creates `.env` from `.env.example` if needed
+- lets you choose the UI language first
+- walks through backend/frontend ports plus LLM, embedding, and search settings
+- writes the final values directly into `.env`
-- **Web mode** (recommended) — Installs all dependencies (pip + npm), spins up a temporary server, and opens the **Settings** page in your browser. A four-step guided tour walks you through LLM, Embedding, and Search provider setup with live connection testing. Once complete, DeepTutor restarts automatically with your configuration.
-- **CLI mode** — A fully interactive terminal flow: choose a dependency profile, install dependencies, configure providers, verify connections, and apply — all without leaving the shell.
+Once the wizard finishes, start DeepTutor with:
-Either way, you end up with a running DeepTutor at [http://localhost:3782](http://localhost:3782).
+```bash
+python scripts/start_web.py
+```
> **Daily launch** — The tour is only needed once. From now on, start DeepTutor with:
>
@@ -143,7 +151,7 @@ Either way, you end up with a running DeepTutor at [http://localhost:3782](http:
> python scripts/start_web.py
> ```
>
-> This boots both the backend and frontend in one command and opens the browser automatically. Re-run `start_tour.py` only if you need to reconfigure providers or reinstall dependencies.
+> This boots both the backend and frontend in one command and prints the frontend URL in the terminal. Re-run `start_tour.py` only if you need to reconfigure providers. Inside the web Settings page, you can also click **Run Tour** to replay the highlight-based UI walkthrough.
### Option B — Manual Local Install
@@ -198,30 +206,32 @@ EMBEDDING_DIMENSION=3072
| Azure OpenAI | `azure_openai` | — |
| BytePlus | `byteplus` | `https://ark.ap-southeast.bytepluses.com/api/v3` |
| BytePlus Coding Plan | `byteplus_coding_plan` | `https://ark.ap-southeast.bytepluses.com/api/coding/v3` |
-| Custom (OpenAI-compat) | `custom` | — |
-| DashScope (Qwen) | `dashscope` | `https://dashscope.aliyuncs.com/compatible-mode/v1` |
+| Custom | `custom` | — |
+| Custom (Anthropic API) | `custom_anthropic` | — |
+| DashScope | `dashscope` | `https://dashscope.aliyuncs.com/compatible-mode/v1` |
| DeepSeek | `deepseek` | `https://api.deepseek.com` |
| Gemini | `gemini` | `https://generativelanguage.googleapis.com/v1beta/openai/` |
| GitHub Copilot | `github_copilot` | `https://api.githubcopilot.com` |
| Groq | `groq` | `https://api.groq.com/openai/v1` |
| llama.cpp | `llama_cpp` | `http://localhost:8080/v1` |
| LM Studio | `lm_studio` | `http://localhost:1234/v1` |
-| MiniMax | `minimax` | `https://api.minimax.io/v1` |
+| MiniMax | `minimax` | `https://api.minimaxi.com/v1` |
+| MiniMax (Anthropic) | `minimax_anthropic` | `https://api.minimaxi.com/anthropic` |
| Mistral | `mistral` | `https://api.mistral.ai/v1` |
-| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.ai/v1` |
+| Moonshot | `moonshot` | `https://api.moonshot.cn/v1` |
| Ollama | `ollama` | `http://localhost:11434/v1` |
| OpenAI | `openai` | `https://api.openai.com/v1` |
| OpenAI Codex | `openai_codex` | `https://chatgpt.com/backend-api` |
| OpenRouter | `openrouter` | `https://openrouter.ai/api/v1` |
| OpenVINO Model Server | `ovms` | `http://localhost:8000/v3` |
-| Qianfan (Ernie) | `qianfan` | `https://qianfan.baidubce.com/v2` |
+| Qianfan | `qianfan` | `https://qianfan.baidubce.com/v2` |
| SiliconFlow | `siliconflow` | `https://api.siliconflow.cn/v1` |
| Step Fun | `stepfun` | `https://api.stepfun.com/v1` |
-| vLLM | `vllm` | `http://localhost:8000/v1` |
+| vLLM/Local | `vllm` | — |
| VolcEngine | `volcengine` | `https://ark.cn-beijing.volces.com/api/v3` |
| VolcEngine Coding Plan | `volcengine_coding_plan` | `https://ark.cn-beijing.volces.com/api/coding/v3` |
| Xiaomi MIMO | `xiaomi_mimo` | `https://api.xiaomimimo.com/v1` |
-| Zhipu AI (GLM) | `zhipu` | `https://open.bigmodel.cn/api/paas/v4` |
+| Zhipu AI | `zhipu` | `https://open.bigmodel.cn/api/paas/v4` |
</details>
diff --git a/assets/README/README_AR.md b/assets/README/README_AR.md
index 000a5ecaa..56823d178 100644
--- a/assets/README/README_AR.md
+++ b/assets/README/README_AR.md
@@ -202,7 +202,7 @@ EMBEDDING_DIMENSION=3072
| LM Studio | `lm_studio` | `http://localhost:1234/v1` |
| MiniMax | `minimax` | `https://api.minimax.io/v1` |
| Mistral | `mistral` | `https://api.mistral.ai/v1` |
-| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.ai/v1` |
+| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.cn/v1` |
| Ollama | `ollama` | `http://localhost:11434/v1` |
| OpenAI | `openai` | `https://api.openai.com/v1` |
| OpenAI Codex | `openai_codex` | `https://chatgpt.com/backend-api` |
diff --git a/assets/README/README_CN.md b/assets/README/README_CN.md
index 724e16279..3a937f654 100644
--- a/assets/README/README_CN.md
+++ b/assets/README/README_CN.md
@@ -203,7 +203,7 @@ EMBEDDING_DIMENSION=3072
| LM Studio | `lm_studio` | `http://localhost:1234/v1` |
| MiniMax | `minimax` | `https://api.minimax.io/v1` |
| Mistral | `mistral` | `https://api.mistral.ai/v1` |
-| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.ai/v1` |
+| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.cn/v1` |
| Ollama | `ollama` | `http://localhost:11434/v1` |
| OpenAI | `openai` | `https://api.openai.com/v1` |
| OpenAI Codex | `openai_codex` | `https://chatgpt.com/backend-api` |
diff --git a/assets/README/README_ES.md b/assets/README/README_ES.md
index 0ce48f17d..4373576f7 100644
--- a/assets/README/README_ES.md
+++ b/assets/README/README_ES.md
@@ -202,7 +202,7 @@ EMBEDDING_DIMENSION=3072
| LM Studio | `lm_studio` | `http://localhost:1234/v1` |
| MiniMax | `minimax` | `https://api.minimax.io/v1` |
| Mistral | `mistral` | `https://api.mistral.ai/v1` |
-| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.ai/v1` |
+| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.cn/v1` |
| Ollama | `ollama` | `http://localhost:11434/v1` |
| OpenAI | `openai` | `https://api.openai.com/v1` |
| OpenAI Codex | `openai_codex` | `https://chatgpt.com/backend-api` |
diff --git a/assets/README/README_FR.md b/assets/README/README_FR.md
index 605ac3f4c..abe4aa9a3 100644
--- a/assets/README/README_FR.md
+++ b/assets/README/README_FR.md
@@ -202,7 +202,7 @@ EMBEDDING_DIMENSION=3072
| LM Studio | `lm_studio` | `http://localhost:1234/v1` |
| MiniMax | `minimax` | `https://api.minimax.io/v1` |
| Mistral | `mistral` | `https://api.mistral.ai/v1` |
-| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.ai/v1` |
+| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.cn/v1` |
| Ollama | `ollama` | `http://localhost:11434/v1` |
| OpenAI | `openai` | `https://api.openai.com/v1` |
| OpenAI Codex | `openai_codex` | `https://chatgpt.com/backend-api` |
diff --git a/assets/README/README_HI.md b/assets/README/README_HI.md
index 12951bf83..7ac5acfb7 100644
--- a/assets/README/README_HI.md
+++ b/assets/README/README_HI.md
@@ -201,7 +201,7 @@ EMBEDDING_DIMENSION=3072
| LM Studio | `lm_studio` | `http://localhost:1234/v1` |
| MiniMax | `minimax` | `https://api.minimax.io/v1` |
| Mistral | `mistral` | `https://api.mistral.ai/v1` |
-| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.ai/v1` |
+| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.cn/v1` |
| Ollama | `ollama` | `http://localhost:11434/v1` |
| OpenAI | `openai` | `https://api.openai.com/v1` |
| OpenAI Codex | `openai_codex` | `https://chatgpt.com/backend-api` |
diff --git a/assets/README/README_JA.md b/assets/README/README_JA.md
index 42e5580a9..0d52646f1 100644
--- a/assets/README/README_JA.md
+++ b/assets/README/README_JA.md
@@ -200,7 +200,7 @@ EMBEDDING_DIMENSION=3072
| LM Studio | `lm_studio` | `http://localhost:1234/v1` |
| MiniMax | `minimax` | `https://api.minimax.io/v1` |
| Mistral | `mistral` | `https://api.mistral.ai/v1` |
-| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.ai/v1` |
+| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.cn/v1` |
| Ollama | `ollama` | `http://localhost:11434/v1` |
| OpenAI | `openai` | `https://api.openai.com/v1` |
| OpenAI Codex | `openai_codex` | `https://chatgpt.com/backend-api` |
diff --git a/assets/README/README_PT.md b/assets/README/README_PT.md
index b37427ad4..973f9cdec 100644
--- a/assets/README/README_PT.md
+++ b/assets/README/README_PT.md
@@ -202,7 +202,7 @@ EMBEDDING_DIMENSION=3072
| LM Studio | `lm_studio` | `http://localhost:1234/v1` |
| MiniMax | `minimax` | `https://api.minimax.io/v1` |
| Mistral | `mistral` | `https://api.mistral.ai/v1` |
-| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.ai/v1` |
+| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.cn/v1` |
| Ollama | `ollama` | `http://localhost:11434/v1` |
| OpenAI | `openai` | `https://api.openai.com/v1` |
| OpenAI Codex | `openai_codex` | `https://chatgpt.com/backend-api` |
diff --git a/assets/README/README_RU.md b/assets/README/README_RU.md
index 803df3beb..e30d2c27b 100644
--- a/assets/README/README_RU.md
+++ b/assets/README/README_RU.md
@@ -202,7 +202,7 @@ EMBEDDING_DIMENSION=3072
| LM Studio | `lm_studio` | `http://localhost:1234/v1` |
| MiniMax | `minimax` | `https://api.minimax.io/v1` |
| Mistral | `mistral` | `https://api.mistral.ai/v1` |
-| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.ai/v1` |
+| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.cn/v1` |
| Ollama | `ollama` | `http://localhost:11434/v1` |
| OpenAI | `openai` | `https://api.openai.com/v1` |
| OpenAI Codex | `openai_codex` | `https://chatgpt.com/backend-api` |
diff --git a/assets/README/README_TH.md b/assets/README/README_TH.md
index 52e0c9ea0..94bc3a17c 100644
--- a/assets/README/README_TH.md
+++ b/assets/README/README_TH.md
@@ -199,7 +199,7 @@ EMBEDDING_DIMENSION=3072
| LM Studio | `lm_studio` | `http://localhost:1234/v1` |
| MiniMax | `minimax` | `https://api.minimax.io/v1` |
| Mistral | `mistral` | `https://api.mistral.ai/v1` |
-| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.ai/v1` |
+| Moonshot (Kimi) | `moonshot` | `https://api.moonshot.cn/v1` |
| Ollama | `ollama` | `http://localhost:11434/v1` |
| OpenAI | `openai` | `https://api.openai.com/v1` |
| OpenAI Codex | `openai_codex` | `https://chatgpt.com/backend-api` |
diff --git a/assets/releases/ver1-2-3.md b/assets/releases/ver1-2-3.md
new file mode 100644
index 000000000..a2508e0bd
--- /dev/null
+++ b/assets/releases/ver1-2-3.md
@@ -0,0 +1,61 @@
+# DeepTutor v1.2.3 Release Notes
+
+**Release Date:** 2026.04.24
+
+## Highlights
+
+### Document Attachments in Chat
+Chat now accepts non-image file attachments (PDF, DOCX, XLSX, PPTX) alongside images. A new paperclip button in the composer opens a system file picker, and drag-and-drop / paste have been extended from images-only to all supported document types. Attached documents are rendered as typed preview cards (colour-coded icon + filename + size label) in both the pending-attachment bar and the message history. On the backend, a new `document_extractor` module extracts plain text from the uploaded bytes using PyMuPDF / pypdf / python-docx / openpyxl / python-pptx (all optional, graceful fallback) and injects the content into the `[Attached Documents]` section of the effective user message, so the LLM can read the file without a separate RAG call. File-type classification, per-file and total size limits, and duplicate-name detection are handled by `web/lib/doc-attachments.ts` on the frontend and `DocumentValidator` on the backend.
+
+### Model Thinking Block Display
+Responses from reasoning models (DeepSeek-R1, Claude with extended thinking, QwQ, etc.) often contain `<think>` / `<|thinking|>` scratchpad blocks that were previously rendered as raw text. A new `parseModelThinkingSegments` parser (`web/lib/think-segments.ts`) splits assistant content into alternating text and thinking segments, and `AssistantResponse` now renders each thinking segment as a collapsible `ModelThinkingCard` — collapsed by default — so users can peek at the model's chain-of-thought without the scratchpad overwhelming the conversation. Incomplete (still-streaming) thinking blocks show a pulsing indicator and expand automatically.
+
+### Tri-State `send_dimensions` for Embeddings (#368)
+Some OpenAI-compatible embedding providers reject the `dimensions` parameter that OpenAI's `text-embedding-3-*` models require. A two-part fix: first, the adapter now only sends `dimensions` when the model name matches `text-embedding-3*` (PR #368 by **@jefflv**). Second, a new **Send Dimensions** tri-state toggle (Auto / On / Off) was added to the Settings page, the `.env` store (`EMBEDDING_SEND_DIMENSIONS`), and the model catalog, giving operators explicit control. `Auto` (the default) preserves the #368 heuristic; `On` forces the parameter for providers that accept it on custom models; `Off` suppresses it unconditionally. The toggle is reflected end-to-end: catalog → `provider_runtime.ResolvedEmbeddingConfig.send_dimensions` → `OpenAICompatibleEmbeddingAdapter`.
+
+### LLM Provider Core Refactor
+The monolithic `factory.py` has been rewritten around a new `provider_core/` package (~3 000 lines) that gives each provider family its own module: `openai_compat_provider`, `anthropic_provider`, `azure_openai_provider`, `github_copilot_provider`, and `openai_codex_provider`, all inheriting from a shared `BaseProvider`. A `provider_factory.py` resolves the correct runtime provider from config, and `factory.py` itself shrank from ~600 to ~490 lines by deriving presets dynamically from the `PROVIDERS` registry instead of maintaining hard-coded dictionaries. A new `context_window.py` module exposes `resolve_effective_context_window()`, used by `ContextBuilder` to base the history-budget calculation on the model's true context window rather than the `max_tokens` output cap — improving long-conversation history recall for models with large windows.
+
+### Soul Template Editor (PR #373)
+TutorBot's "Soul" (system personality) can now be authored directly inside the Agents page. The new inline editor lets users create, preview, and save `SOUL.md` templates with YAML frontmatter, replacing the previous workflow of hand-editing files on disk. Contributed by **@srinivasrk**.
+
+### Co-Writer Save to Notebook
+The Co-Writer toolbar gains a **Save to Notebook** button (📓 icon). Clicking it opens the existing `SaveToNotebookModal` with a new `co_writer` record type, so Co-Writer drafts appear alongside chat and quiz entries in the Knowledge page's Notebooks tab. Backend: `co_writer` was added to the notebook record type enum, the summarize agent prompts, and the API Literal type.
+
+### Knowledge Base Management Improvements
+- **Drag-and-drop upload** — the Knowledge page now accepts file drops directly onto KB cards (or the creation form) with real-time extension/size validation, duplicate-name detection, and a typed file-selection list before upload starts.
+- **`/supported-file-types` endpoint** — a new REST endpoint returns the server's current upload policy (accepted extensions, per-file and per-PDF size caps) so the web client stays in sync without hard-coding.
+- **Richer KB cards** — each card now displays creation / last-updated timestamps, embedding model name, dimension, reindex-needed badge, and live progress bars with percent readout during indexing.
+- **Delete resilience (#370)** — `shutil.rmtree` now uses an `onerror` handler that clears the read-only bit and retries, preventing Docker bind-mount and Windows permission errors from leaving a KB stuck in the list.
+- **Progress persistence** — `ProgressTracker` now writes a snapshot file alongside the `kb_config.json` entry and emits task-stream events, so WebSocket subscribers and page reloads can recover live indexing state without relying on in-memory callbacks. When a KB reaches `ready`, the progress blob is removed from config to keep the card looking like a stable resource.
+
+### Question Generation Language Fidelity
+Extracted the language-directive system from the Book engine's `_language.py` into a shared `services/prompt/language.py` module. The Deep Question agents — `Generator`, `IdeaAgent`, and `FollowupAgent` — now call `append_language_directive()` on their system prompts, ensuring that quiz questions, answer choices, and follow-up answers respect the user's configured language instead of occasionally drifting to English.
+
+### Settings Page Tour Redesign
+The **Run Tour** button moved from the page bottom to the top toolbar, sitting alongside **Save Draft** and **Apply**. The guided tour itself was expanded to walk through the full save-and-test cycle (Save → Diagnostics → Apply). The former bottom area was replaced with a concise configuration note explaining the runtime priority of `model_catalog.json` over `.env`.
+
+### CLI: Notebook `add-md` and `replace-md`
+Two new `deeptutor notebook` sub-commands let users add or replace Markdown content in a notebook record directly from the terminal, useful for scripted workflows and CI pipelines.
+
+### Bug Fixes
+- **TutorBot pure-CJK bot name crash** — creating a bot whose name contains only non-ASCII characters produced an empty slug, breaking the API route. A stable ASCII fallback (`bot-<hash>`) is now generated, and the frontend surfaces a creation error toast instead of silently failing.
+- **React 19 I18nProvider render-time `setState` warning** — `i18n.init()` was being called synchronously during the first render of `I18nProvider`, triggering a React 19 warning about state updates in the render phase. Initialization is now performed at module-load time; the provider body only syncs `document.documentElement.lang` via `useEffect`.
+- **Skills default to off** — `skillsAutoMode` now defaults to `false` so new users aren't surprised by automatic skill injection until they intentionally enable it.
+- **Moonshot default Base URL** — changed from `https://api.moonshot.ai/v1` to `https://api.moonshot.cn/v1` to match the provider's current canonical endpoint, with all multilingual README files updated.
+- **Version badge display** — fixed a minor rendering issue in the sidebar version badge introduced during the v1.2.2 merge.
+
+### Provider Registry Enhancements
+- **`custom_anthropic`** — a new provider spec for Anthropic-API-compatible endpoints (e.g. AWS Bedrock proxies) that routes through the Anthropic backend instead of OpenAI-compat.
+- **`thinking_style`** — new `ProviderSpec` field allowing providers like Volcengine to advertise how they signal extended-thinking mode.
+- **Alias expansion** — `lm-studio`, `anthropic-compatible`, `openai-compatible` (hyphenated) are now recognized; `canonical_provider_name()` uses `to_snake()` for more robust normalization.
+
+### Test Suite Expansion
+Net **+1 900** test lines across 15 new or expanded files: `test_document_extractor.py` (245), `test_language_prompts.py` (156), `think-segments.test.ts` (122), `test_provider_runtime.py` (103), `test_llm_probe_config.py` (116), `test_manager_delete.py` (79), `doc-attachments.test.ts` (75), `test_context_window_detection.py` (60), `test_progress_tracker.py` (58), `quiz-question-type.test.ts` (58), plus expansions to `test_factory_provider_exec.py`, `test_context_builder.py`, `test_chat_params_config.py`, `test_config_module.py`, `test_knowledge_router.py`, and `test_start_tour.py`.
+
+## Community Contributions
+
+- **@jefflv** — Gate embedding `dimensions` parameter to `text-embedding-3-*` models (#368)
+- **@srinivasrk** — Revamp soul template creation and usage in the Agents page (#373)
+
+**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.2.2...v1.2.3
diff --git a/deeptutor/agents/notebook/prompts/en/summarize_agent.yaml b/deeptutor/agents/notebook/prompts/en/summarize_agent.yaml
index 157dee1aa..99085bae5 100644
--- a/deeptutor/agents/notebook/prompts/en/summarize_agent.yaml
+++ b/deeptutor/agents/notebook/prompts/en/summarize_agent.yaml
@@ -23,4 +23,5 @@ user_template: |
record_hints:
chat: "A full chat transcript; focus on the question, conclusion, and next actions."
guided_learning: "A guided learning record; focus on topic, knowledge structure, and partial/final output."
+ co_writer: "A Co-Writer markdown draft authored by the user; focus on the document's topic, structure, current completion state, and what makes it worth revisiting."
default: "Summarize the most reusable information in this record."
diff --git a/deeptutor/agents/notebook/prompts/zh/summarize_agent.yaml b/deeptutor/agents/notebook/prompts/zh/summarize_agent.yaml
index 976d6b6b8..4d9ca87db 100644
--- a/deeptutor/agents/notebook/prompts/zh/summarize_agent.yaml
+++ b/deeptutor/agents/notebook/prompts/zh/summarize_agent.yaml
@@ -24,4 +24,5 @@ user_template: |
record_hints:
chat: "一段完整聊天历史,重点提炼问题、结论与后续行动。"
guided_learning: "一段引导式学习记录,重点提炼学习主题、知识点结构与阶段性产出。"
+ co_writer: "一份用户在 Co-Writer 中撰写的 Markdown 草稿,重点提炼文档主题、结构骨架、当前完成度,以及后续值得回顾的部分。"
default: "请总结此记录中最值得复用的信息。"
diff --git a/deeptutor/agents/question/agents/followup_agent.py b/deeptutor/agents/question/agents/followup_agent.py
index 42a2a0051..b6c50665a 100644
--- a/deeptutor/agents/question/agents/followup_agent.py
+++ b/deeptutor/agents/question/agents/followup_agent.py
@@ -9,6 +9,7 @@ from typing import Any
from deeptutor.agents.base_agent import BaseAgent
from deeptutor.core.trace import build_trace_metadata, new_call_id
+from deeptutor.services.prompt.language import append_language_directive
class FollowupAgent(BaseAgent):
@@ -29,7 +30,10 @@ class FollowupAgent(BaseAgent):
question_context: dict[str, Any],
history_context: str = "",
) -> str:
- system_prompt = self.get_prompt("system", "")
+ system_prompt = append_language_directive(
+ self.get_prompt("system", ""),
+ self.language,
+ )
user_prompt_template = self.get_prompt("answer_followup", "")
if not user_prompt_template:
user_prompt_template = (
@@ -47,7 +51,7 @@ class FollowupAgent(BaseAgent):
_chunks: list[str] = []
async for _c in self.stream_llm(
user_prompt=user_prompt,
- system_prompt=system_prompt or "",
+ system_prompt=system_prompt,
stage="followup_answer",
trace_meta=build_trace_metadata(
call_id=new_call_id(
diff --git a/deeptutor/agents/question/agents/generator.py b/deeptutor/agents/question/agents/generator.py
index 6e2b1c4f9..061d941d0 100644
--- a/deeptutor/agents/question/agents/generator.py
+++ b/deeptutor/agents/question/agents/generator.py
@@ -13,6 +13,7 @@ from deeptutor.agents.base_agent import BaseAgent
from deeptutor.agents.question.models import QAPair, QuestionTemplate
from deeptutor.core.trace import build_trace_metadata, new_call_id
from deeptutor.runtime.registry.tool_registry import get_tool_registry
+from deeptutor.services.prompt.language import append_language_directive
class Generator(BaseAgent):
@@ -116,7 +117,10 @@ class Generator(BaseAgent):
available_tools: str,
previous_questions: str = "",
) -> dict[str, Any]:
- system_prompt = self.get_prompt("system", "")
+ system_prompt = append_language_directive(
+ self.get_prompt("system", ""),
+ self.language,
+ )
user_prompt_template = self.get_prompt("generate", "")
if not user_prompt_template:
user_prompt_template = (
@@ -145,7 +149,7 @@ class Generator(BaseAgent):
_chunks: list[str] = []
async for _c in self.stream_llm(
user_prompt=user_prompt,
- system_prompt=system_prompt or "",
+ system_prompt=system_prompt,
response_format={"type": "json_object"},
stage="generator_build_qa",
trace_meta=build_trace_metadata(
@@ -258,7 +262,10 @@ class Generator(BaseAgent):
_chunks: list[str] = []
async for _c in self.stream_llm(
user_prompt=repair_prompt,
- system_prompt="You fix malformed quiz payloads and return valid JSON only.",
+ system_prompt=append_language_directive(
+ "You fix malformed quiz payloads and return valid JSON only.",
+ self.language,
+ ),
response_format={"type": "json_object"},
stage="generator_repair_qa",
trace_meta=build_trace_metadata(
diff --git a/deeptutor/agents/question/agents/idea_agent.py b/deeptutor/agents/question/agents/idea_agent.py
index 3bd7b04e6..df9e680d3 100644
--- a/deeptutor/agents/question/agents/idea_agent.py
+++ b/deeptutor/agents/question/agents/idea_agent.py
@@ -11,6 +11,7 @@ from typing import Any
from deeptutor.agents.base_agent import BaseAgent
from deeptutor.agents.question.models import QuestionTemplate
from deeptutor.core.trace import build_trace_metadata, new_call_id
+from deeptutor.services.prompt.language import append_language_directive
from deeptutor.tools.rag_tool import rag_search
from deeptutor.utils.json_parser import parse_json_response
@@ -177,7 +178,10 @@ class IdeaAgent(BaseAgent):
trace_id: str = "ideation",
batch_number: int | None = None,
) -> list[QuestionTemplate]:
- system_prompt = self.get_prompt("system", "")
+ system_prompt = append_language_directive(
+ self.get_prompt("system", ""),
+ self.language,
+ )
idea_prompt = self.get_prompt("generate_ideas", "")
if not idea_prompt:
idea_prompt = (
@@ -211,7 +215,7 @@ class IdeaAgent(BaseAgent):
_chunks: list[str] = []
async for _c in self.stream_llm(
user_prompt=user_prompt,
- system_prompt=system_prompt or "",
+ system_prompt=system_prompt,
response_format={"type": "json_object"},
stage="idea_generate_templates",
trace_meta=build_trace_metadata(
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py
index cb6239676..533187536 100644
--- a/deeptutor/api/routers/knowledge.py
+++ b/deeptutor/api/routers/knowledge.py
@@ -79,6 +79,8 @@ class KnowledgeBaseInfo(BaseModel):
name: str
is_default: bool
statistics: dict
+ metadata: dict | None = None
+ path: str | None = None
status: str | None = None
progress: dict | None = None
@@ -98,6 +100,15 @@ class LinkedFolderInfo(BaseModel):
file_count: int
+class SupportedFileTypesInfo(BaseModel):
+ """Upload constraints exposed to the web client."""
+
+ extensions: list[str]
+ accept: str
+ max_file_size_bytes: int
+ max_pdf_size_bytes: int
+
+
def _build_unique_task_id(task_type: str, task_key_prefix: str) -> str:
task_manager = TaskIDManager.get_instance()
task_key = f"{task_key_prefix}_{datetime.now().isoformat()}_{uuid4().hex[:8]}"
@@ -111,50 +122,123 @@ def _save_uploaded_files(
) -> tuple[list[str], list[str]]:
uploaded_files: list[str] = []
uploaded_file_paths: list[str] = []
+ written_file_paths: list[Path] = []
+
+ try:
+ for file in files:
+ file_path = None
+ original_filename = file.filename or "upload"
+ try:
+ sanitized_filename = DocumentValidator.validate_upload_safety(
+ original_filename,
+ _get_upload_file_size(file),
+ allowed_extensions=allowed_extensions,
+ )
+ file.filename = sanitized_filename
+
+ file_path = target_dir / sanitized_filename
+ max_size = DocumentValidator.MAX_FILE_SIZE
+ written_bytes = 0
+
+ file.file.seek(0)
+ with open(file_path, "wb") as buffer:
+ for chunk in iter(lambda: file.file.read(8192), b""):
+ written_bytes += len(chunk)
+ if written_bytes > max_size:
+ size_str = format_bytes_human_readable(max_size)
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"File '{sanitized_filename}' exceeds maximum size "
+ f"limit of {size_str}"
+ ),
+ )
+ buffer.write(chunk)
+
+ DocumentValidator.validate_upload_safety(
+ sanitized_filename, written_bytes, allowed_extensions=allowed_extensions
+ )
+ written_file_paths.append(file_path)
+ uploaded_files.append(sanitized_filename)
+ uploaded_file_paths.append(str(file_path))
+ except Exception as e:
+ if file_path and file_path.exists():
+ try:
+ os.unlink(file_path)
+ except OSError:
+ pass
+
+ error_message = (
+ f"Validation failed for file '{original_filename}': {format_exception_message(e)}"
+ )
+ logger.error(error_message, exc_info=True)
+ raise HTTPException(status_code=400, detail=error_message) from e
+ except Exception:
+ for written_path in written_file_paths:
+ if written_path.exists():
+ try:
+ os.unlink(written_path)
+ except OSError:
+ pass
+ raise
+
+ return uploaded_files, uploaded_file_paths
+
+
+def _get_upload_file_size(file: UploadFile) -> int | None:
+ """Best-effort byte size detection without consuming the uploaded stream."""
+ try:
+ current_position = file.file.tell()
+ file.file.seek(0, os.SEEK_END)
+ size = file.file.tell()
+ file.file.seek(current_position)
+ return size
+ except Exception:
+ return None
+
+
+def _validate_upload_batch(
+ files: list[UploadFile],
+ allowed_extensions: set[str] | None = None,
+) -> list[dict[str, int | str | None]]:
+ """Validate upload metadata before mutating KB state or writing any files."""
+ validated: list[dict[str, int | str | None]] = []
+ seen_names: set[str] = set()
for file in files:
- file_path = None
original_filename = file.filename or "upload"
+ size_bytes = _get_upload_file_size(file)
try:
sanitized_filename = DocumentValidator.validate_upload_safety(
- original_filename, None, allowed_extensions=allowed_extensions
- )
- file.filename = sanitized_filename
-
- file_path = target_dir / sanitized_filename
- max_size = DocumentValidator.MAX_FILE_SIZE
- written_bytes = 0
-
- with open(file_path, "wb") as buffer:
- for chunk in iter(lambda: file.file.read(8192), b""):
- written_bytes += len(chunk)
- if written_bytes > max_size:
- size_str = format_bytes_human_readable(max_size)
- raise HTTPException(
- status_code=400,
- detail=f"File '{sanitized_filename}' exceeds maximum size limit of {size_str}",
- )
- buffer.write(chunk)
-
- DocumentValidator.validate_upload_safety(
- sanitized_filename, written_bytes, allowed_extensions=allowed_extensions
+ original_filename,
+ size_bytes,
+ allowed_extensions=allowed_extensions,
)
- uploaded_files.append(sanitized_filename)
- uploaded_file_paths.append(str(file_path))
except Exception as e:
- if file_path and file_path.exists():
- try:
- os.unlink(file_path)
- except OSError:
- pass
-
error_message = (
f"Validation failed for file '{original_filename}': {format_exception_message(e)}"
)
- logger.error(error_message, exc_info=True)
raise HTTPException(status_code=400, detail=error_message) from e
- return uploaded_files, uploaded_file_paths
+ if sanitized_filename in seen_names:
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"Duplicate filename after sanitization: '{sanitized_filename}'. "
+ "Rename one of the files and try again."
+ ),
+ )
+
+ seen_names.add(sanitized_filename)
+ validated.append(
+ {
+ "original_filename": original_filename,
+ "sanitized_filename": sanitized_filename,
+ "size_bytes": size_bytes,
+ }
+ )
+
+ return validated
def _task_log(task_id: str, message: str, level: str = "info") -> None:
@@ -415,6 +499,18 @@ async def get_rag_providers():
raise HTTPException(status_code=500, detail=str(e))
[email protected]("/supported-file-types", response_model=SupportedFileTypesInfo)
+async def get_supported_file_types():
+ """Return the current upload policy so the web client stays in sync."""
+ extensions = sorted(FileTypeRouter.get_supported_extensions())
+ return SupportedFileTypesInfo(
+ extensions=extensions,
+ accept=",".join(extensions),
+ max_file_size_bytes=DocumentValidator.MAX_FILE_SIZE,
+ max_pdf_size_bytes=DocumentValidator.MAX_PDF_SIZE,
+ )
+
+
@router.get("/configs")
async def get_all_kb_configs():
"""Get all knowledge base configurations from centralized config file."""
@@ -531,6 +627,8 @@ async def list_knowledge_bases():
name=info["name"],
is_default=info["is_default"],
statistics=info.get("statistics", {}),
+ metadata=info.get("metadata"),
+ path=info.get("path"),
status=info.get("status"),
progress=info.get("progress"),
)
@@ -553,6 +651,8 @@ async def list_knowledge_bases():
"content_lists": 0,
"rag_initialized": False,
},
+ metadata=None,
+ path=str(kb_dir),
status="unknown",
progress=None,
)
@@ -652,6 +752,7 @@ async def upload_files(
),
)
allowed_extensions = FileTypeRouter.get_supported_extensions()
+ _validate_upload_batch(files, allowed_extensions=allowed_extensions)
uploaded_files, uploaded_file_paths = _save_uploaded_files(
files, raw_dir, allowed_extensions=allowed_extensions
)
@@ -698,6 +799,8 @@ async def create_knowledge_base(
raise HTTPException(status_code=400, detail=f"Knowledge base '{name}' already exists")
rag_provider = _validate_registered_provider(rag_provider)
+ allowed_extensions = FileTypeRouter.get_supported_extensions()
+ _validate_upload_batch(files, allowed_extensions=allowed_extensions)
logger.info(f"Creating KB: {name}")
task_id = _build_unique_task_id("kb_init", name)
@@ -741,7 +844,6 @@ async def create_knowledge_base(
logger.warning(f"KB {name} not found in config, registering manually")
initializer._register_to_config()
- allowed_extensions = FileTypeRouter.get_supported_extensions()
uploaded_files, _ = _save_uploaded_files(
files, initializer.raw_dir, allowed_extensions=allowed_extensions
)
diff --git a/deeptutor/api/routers/notebook.py b/deeptutor/api/routers/notebook.py
index 751aab369..91e842d9d 100644
--- a/deeptutor/api/routers/notebook.py
+++ b/deeptutor/api/routers/notebook.py
@@ -41,7 +41,7 @@ class AddRecordRequest(BaseModel):
"""Add record request"""
notebook_ids: list[str]
- record_type: Literal["solve", "question", "research", "chat"]
+ record_type: Literal["solve", "question", "research", "chat", "co_writer"]
title: str
summary: str = ""
user_query: str
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.py
index fdc0a01f4..8774f6a0d 100644
--- a/deeptutor/api/routers/settings.py
+++ b/deeptutor/api/routers/settings.py
@@ -102,7 +102,20 @@ def _provider_choices() -> dict[str, list[dict[str, str]]]:
from deeptutor.services.provider_registry import PROVIDERS
llm = sorted(
- [{"value": s.name, "label": s.label, "base_url": s.default_api_base} for s in PROVIDERS],
+ [
+ {
+ "value": s.name,
+ "label": (
+ "Custom (OpenAI API)"
+ if s.name == "custom"
+ else "Custom (Anthropic API)"
+ if s.name == "custom_anthropic"
+ else s.label
+ ),
+ "base_url": s.default_api_base,
+ }
+ for s in PROVIDERS
+ ],
key=lambda p: p["label"].lower(),
)
embedding = sorted(
diff --git a/deeptutor/book/blocks/_language.py b/deeptutor/book/blocks/_language.py
index a4d00b823..52673c8d0 100644
--- a/deeptutor/book/blocks/_language.py
+++ b/deeptutor/book/blocks/_language.py
@@ -1,73 +1,15 @@
-"""Shared language directive for BookEngine LLM prompts.
-
-Every block generator and agent that writes user-facing prose should append
-``language_directive(language)`` to its **system prompt**. This guarantees the
-output stays in the book's chosen language even when the rest of the prompt
-contains English token names (block types, role hints, JSON keys, etc.) or
-when the underlying source material is in a different language.
-"""
-
-from __future__ import annotations
-
-_LANGUAGE_LABELS: dict[str, str] = {
- "zh": "中文(简体)",
- "zh-cn": "中文(简体)",
- "zh-tw": "繁體中文",
- "en": "English",
- "ja": "日本語",
- "ko": "한국어",
- "es": "Español",
- "fr": "Français",
- "de": "Deutsch",
- "ru": "Русский",
- "pt": "Português",
- "it": "Italiano",
-}
-
-
-def normalize_language(language: str | None) -> str:
- return (language or "en").strip().lower() or "en"
-
-
-def language_label(language: str | None) -> str:
- code = normalize_language(language)
- if code in _LANGUAGE_LABELS:
- return _LANGUAGE_LABELS[code]
- base = code.split("-", 1)[0]
- return _LANGUAGE_LABELS.get(base, language or "English")
-
-
-def language_directive(language: str | None) -> str:
- """Strict instruction that forces the LLM to respond in *language*.
-
- The directive is intentionally repetitive — empirically that's what gets
- LLMs to stop drifting back to English when the prompt mixes languages.
- """
- code = normalize_language(language)
- label = language_label(code)
- if code.startswith("zh"):
- return (
- "\n\n[语言要求 / Language] "
- f"请严格使用{label}撰写所有面向读者的文本(标题、正文、解释、提示、过渡句、"
- "题干、选项等),即使参考资料、JSON 字段名或英文术语出现在 prompt 中也"
- "不得切换语言;保留必要的专有名词原文(如人名、产品名、公式中的变量符号"
- f"等)即可,其余一律使用{label}。"
- )
- if code == "en":
- return (
- "\n\n[Language] Write ALL reader-facing text (titles, prose, "
- "explanations, hints, transitions, quiz stems, options, etc.) in "
- "English. Do NOT switch languages even if the source material, "
- "JSON keys, or examples in this prompt are in another language. "
- "Keep proper nouns (people, products, formula symbols) in their "
- "original form."
- )
- return (
- f"\n\n[Language] Write ALL reader-facing text strictly in {label}. "
- "Do NOT switch languages even if the source material, JSON keys, or "
- "examples in this prompt are in a different language. Keep proper "
- "nouns (people, products, formula symbols) in their original form."
- )
-
-
-__all__ = ["language_directive", "language_label", "normalize_language"]
+"""Backward-compatible re-export of shared prompt language helpers."""
+
+from deeptutor.services.prompt.language import (
+ append_language_directive,
+ language_directive,
+ language_label,
+ normalize_language,
+)
+
+__all__ = [
+ "append_language_directive",
+ "language_directive",
+ "language_label",
+ "normalize_language",
+]
diff --git a/deeptutor/book/blocks/_llm_writer.py b/deeptutor/book/blocks/_llm_writer.py
index 6e0e4a459..0fc8ad582 100644
--- a/deeptutor/book/blocks/_llm_writer.py
+++ b/deeptutor/book/blocks/_llm_writer.py
@@ -17,8 +17,7 @@ from deeptutor.services.llm import (
from deeptutor.services.llm import (
complete as llm_complete,
)
-
-from ._language import language_directive
+from deeptutor.services.prompt.language import append_language_directive
async def llm_text(
@@ -39,7 +38,7 @@ async def llm_text(
JSON keys, or non-matching source material.
"""
if language:
- system_prompt = system_prompt.rstrip() + language_directive(language)
+ system_prompt = append_language_directive(system_prompt, language)
config = get_llm_config()
model = config.model
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py
index 60766facc..8a5c55c6b 100644
--- a/deeptutor/knowledge/manager.py
+++ b/deeptutor/knowledge/manager.py
@@ -12,6 +12,7 @@ import json
import os
from pathlib import Path
import shutil
+import stat
import sys
from typing import Any
@@ -247,15 +248,14 @@ class KnowledgeBaseManager:
kb_config["status"] = status
kb_config["updated_at"] = datetime.now().isoformat()
- if progress is not None:
+ if status == "ready":
+ # Ready KBs should look like stable resources in the UI instead of
+ # permanently carrying a "completed" progress banner.
+ kb_config.pop("progress", None)
+ if progress is not None:
+ kb_config["last_completed_at"] = progress.get("timestamp") or datetime.now().isoformat()
+ elif progress is not None:
kb_config["progress"] = progress
- elif status == "ready":
- # Clear progress when ready
- kb_config["progress"] = {
- "stage": "completed",
- "message": "Ready",
- "percent": 100,
- }
if status == "ready":
fp = _get_embedding_fingerprint()
@@ -673,14 +673,28 @@ class KnowledgeBaseManager:
return False
if dir_exists:
- try:
- shutil.rmtree(kb_dir)
- except FileNotFoundError:
- # Race: someone else deleted it between exists() and rmtree.
- pass
- except OSError as e:
- logger.error(f"Failed to remove KB directory '{kb_dir}': {e}")
- raise
+
+ def _on_rmtree_error(func, path, exc_info):
+ exc = exc_info[1]
+ if isinstance(exc, FileNotFoundError):
+ # Race: something else removed the entry between walk and unlink.
+ return
+ # On Windows (and some bind-mounted filesystems) a read-only bit
+ # or a stale handle from a failed RAG init can block removal.
+ # Clear the read-only bit and retry once; if it still fails, log
+ # and continue so the config entry gets cleaned up regardless —
+ # leaving the KB stuck in the list is worse than orphan files on
+ # disk (issue #370).
+ try:
+ os.chmod(path, stat.S_IWRITE)
+ func(path)
+ except Exception as retry_exc:
+ logger.warning(
+ f"Could not remove '{path}' while deleting KB '{name}': "
+ f"{retry_exc}. Continuing; orphan files may remain on disk."
+ )
+
+ shutil.rmtree(kb_dir, onerror=_on_rmtree_error)
else:
logger.warning(
f"KB directory '{kb_dir}' missing on disk; cleaning up orphaned config entry."
diff --git a/deeptutor/knowledge/progress_tracker.py b/deeptutor/knowledge/progress_tracker.py
index 4ada8b8e5..ee710f878 100644
--- a/deeptutor/knowledge/progress_tracker.py
+++ b/deeptutor/knowledge/progress_tracker.py
@@ -124,6 +124,18 @@ class ProgressTracker:
except Exception as e:
_get_logger().warning("Failed to save progress to kb_config.json: %s", e)
+ # Persist the last seen progress snapshot so websocket subscribers and
+ # page reloads can recover the live state without relying on in-memory callbacks.
+ try:
+ self.kb_dir.mkdir(parents=True, exist_ok=True)
+ temp_progress_file = self.progress_file.parent / f"{self.progress_file.name}.tmp"
+ with open(temp_progress_file, "w", encoding="utf-8") as f:
+ json.dump(progress, f, indent=2, ensure_ascii=False)
+ f.flush()
+ temp_progress_file.replace(self.progress_file)
+ except Exception as e:
+ _get_logger().warning("Failed to persist progress snapshot for '%s': %s", self.kb_name, e)
+
def update(
self,
stage: ProgressStage,
@@ -184,19 +196,41 @@ class ProgressTracker:
fallback_logger.error("%s [ProgressTracker] Error: %s", prefix, error)
self._save_progress(progress)
+
+ if self.task_id:
+ try:
+ from deeptutor.api.utils.task_log_stream import get_task_stream_manager
+
+ get_task_stream_manager().emit(self.task_id, "progress", progress)
+ except Exception as e:
+ _get_logger().debug("Failed to emit task progress event: %s", e)
+
self._notify(progress)
def get_progress(self) -> dict | None:
"""Get current progress"""
- if not self.progress_file.exists():
- return None
+ if self.progress_file.exists():
+ try:
+ with open(self.progress_file, encoding="utf-8") as f:
+ return json.load(f)
+ except Exception as e:
+ _get_logger().debug(f"Failed to read progress file for '{self.kb_name}': {e}")
try:
- with open(self.progress_file, encoding="utf-8") as f:
- return json.load(f)
+ from deeptutor.knowledge.manager import KnowledgeBaseManager
+
+ manager = KnowledgeBaseManager(base_dir=str(self.base_dir))
+ status = manager.get_kb_status(self.kb_name)
+ if status and status.get("progress"):
+ return status.get("progress")
except Exception as e:
- _get_logger().debug(f"Failed to read progress file for '{self.kb_name}': {e}")
- return None
+ _get_logger().debug(
+ "Failed to recover progress snapshot from kb_config for '%s': %s",
+ self.kb_name,
+ e,
+ )
+
+ return None
def clear(self):
"""Clear progress file"""
diff --git a/deeptutor/services/config/__init__.py b/deeptutor/services/config/__init__.py
index 4fa61ebb6..e6d99c1d6 100644
--- a/deeptutor/services/config/__init__.py
+++ b/deeptutor/services/config/__init__.py
@@ -1,5 +1,7 @@
"""Configuration helpers backed by runtime YAML and the project `.env` file."""
+import importlib
+
from .env_store import ConfigSummary, EnvStore, get_env_store
from .knowledge_base_config import (
KnowledgeBaseConfigService,
@@ -18,6 +20,10 @@ from .loader import (
)
from .model_catalog import ModelCatalogService, get_model_catalog_service
+# Re-export the loader module itself for code paths that monkeypatch via the
+# package namespace, e.g. ``deeptutor.services.config.loader.PROJECT_ROOT``.
+loader = importlib.import_module(f"{__name__}.loader")
+
__all__ = [
"ConfigSummary",
"EnvStore",
@@ -67,14 +73,10 @@ def __getattr__(name: str):
"resolve_search_runtime_config",
"search_provider_state",
}:
- import importlib
-
provider_runtime = importlib.import_module(f"{__name__}.provider_runtime")
return getattr(provider_runtime, name)
if name in {"ConfigTestRunner", "TestRun", "get_config_test_runner"}:
- import importlib
-
test_runner = importlib.import_module(f"{__name__}.test_runner")
return getattr(test_runner, name)
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/deeptutor/services/config/context_window_detection.py b/deeptutor/services/config/context_window_detection.py
new file mode 100644
index 000000000..dff255efc
--- /dev/null
+++ b/deeptutor/services/config/context_window_detection.py
@@ -0,0 +1,188 @@
+"""Detect or suggest a model context window during settings diagnostics."""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Iterable, Mapping
+from dataclasses import dataclass
+from datetime import datetime, timezone
+import logging
+from typing import Any
+
+import aiohttp
+
+from deeptutor.services.llm.config import LLMConfig
+from deeptutor.services.llm.context_window import (
+ coerce_positive_int,
+ default_context_window_for_model,
+)
+from deeptutor.services.llm.utils import build_auth_headers
+
+logger = logging.getLogger(__name__)
+
+_CONTEXT_WINDOW_KEYS = (
+ "context_window",
+ "context_window_tokens",
+ "context_length",
+ "max_context_tokens",
+ "max_input_tokens",
+ "input_token_limit",
+ "max_prompt_tokens",
+ "max_model_len",
+ "max_sequence_length",
+)
+
+
+@dataclass(frozen=True)
+class ContextWindowDetectionResult:
+ """Structured context-window detection output."""
+
+ context_window: int
+ source: str
+ detail: str
+ detected_at: str
+
+
+def _model_aliases(model: str) -> set[str]:
+ value = (model or "").strip().lower()
+ if not value:
+ return set()
+ aliases = {value}
+ if "/" in value:
+ aliases.add(value.split("/", 1)[1])
+ if ":" in value:
+ aliases.add(value.split(":", 1)[1])
+ return {item for item in aliases if item}
+
+
+def _record_identities(item: Mapping[str, Any]) -> set[str]:
+ aliases: set[str] = set()
+ for key in ("id", "model", "name"):
+ aliases.update(_model_aliases(str(item.get(key, "") or "")))
+ return aliases
+
+
+def _recursive_context_window(value: Any) -> int | None:
+ if isinstance(value, Mapping):
+ for key in _CONTEXT_WINDOW_KEYS:
+ parsed = coerce_positive_int(value.get(key))
+ if parsed is not None:
+ return parsed
+ for nested in value.values():
+ parsed = _recursive_context_window(nested)
+ if parsed is not None:
+ return parsed
+ elif isinstance(value, list):
+ for nested in value:
+ parsed = _recursive_context_window(nested)
+ if parsed is not None:
+ return parsed
+ return None
+
+
+def _iter_model_records(payload: Any) -> Iterable[Mapping[str, Any]]:
+ if isinstance(payload, list):
+ for item in payload:
+ if isinstance(item, Mapping):
+ yield item
+ return
+ if not isinstance(payload, Mapping):
+ return
+ for key in ("data", "models", "result", "items"):
+ items = payload.get(key)
+ if isinstance(items, list):
+ for item in items:
+ if isinstance(item, Mapping):
+ yield item
+
+
+def _extract_context_window_from_payload(payload: Any, model: str) -> int | None:
+ target_aliases = _model_aliases(model)
+ if not target_aliases:
+ return None
+
+ exact_matches: list[Mapping[str, Any]] = []
+ partial_matches: list[Mapping[str, Any]] = []
+ for item in _iter_model_records(payload):
+ identities = _record_identities(item)
+ if not identities:
+ continue
+ if identities & target_aliases:
+ exact_matches.append(item)
+ continue
+ if any(
+ item_identity.endswith(f"/{alias}") or alias.endswith(f"/{item_identity}")
+ for item_identity in identities
+ for alias in target_aliases
+ ):
+ partial_matches.append(item)
+
+ for item in [*exact_matches, *partial_matches]:
+ parsed = _recursive_context_window(item)
+ if parsed is not None:
+ return parsed
+ return None
+
+
+async def _detect_from_models_endpoint(
+ llm_config: LLMConfig,
+ *,
+ on_log: Callable[[str], None] | None = None,
+) -> int | None:
+ base_url = str(llm_config.base_url or llm_config.effective_url or "").strip()
+ if not base_url:
+ return None
+
+ url = f"{base_url.rstrip('/')}/models"
+ headers = build_auth_headers(llm_config.api_key, llm_config.binding)
+ headers.pop("Content-Type", None)
+
+ timeout = aiohttp.ClientTimeout(total=12)
+ try:
+ async with aiohttp.ClientSession(
+ timeout=timeout,
+ trust_env=True,
+ ) as session:
+ async with session.get(url, headers=headers) as response:
+ if response.status != 200:
+ if on_log is not None:
+ on_log(f"`GET {url}` returned HTTP {response.status}; skipping metadata detection.")
+ return None
+ payload = await response.json()
+ except Exception as exc:
+ logger.debug("Context-window metadata request failed for %s: %s", url, exc)
+ if on_log is not None:
+ on_log(f"Could not read `{url}` for context-window metadata: {exc}")
+ return None
+
+ return _extract_context_window_from_payload(payload, llm_config.model)
+
+
+async def detect_context_window(
+ llm_config: LLMConfig,
+ *,
+ on_log: Callable[[str], None] | None = None,
+) -> ContextWindowDetectionResult:
+ """Detect the current model's context window or fall back to the runtime default."""
+ detected_at = datetime.now(timezone.utc).isoformat()
+ metadata_window = await _detect_from_models_endpoint(llm_config, on_log=on_log)
+ if metadata_window is not None:
+ return ContextWindowDetectionResult(
+ context_window=metadata_window,
+ source="metadata",
+ detail="Detected from provider `/models` metadata.",
+ detected_at=detected_at,
+ )
+
+ fallback = default_context_window_for_model(
+ model=llm_config.model,
+ max_tokens=llm_config.max_tokens,
+ )
+ return ContextWindowDetectionResult(
+ context_window=fallback,
+ source="default",
+ detail="Provider metadata did not expose a window; using the runtime fallback.",
+ detected_at=detected_at,
+ )
+
+
+__all__ = ["ContextWindowDetectionResult", "detect_context_window"]
diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.py
index 1f862c76b..4df3a397c 100644
--- a/deeptutor/services/config/provider_runtime.py
+++ b/deeptutor/services/config/provider_runtime.py
@@ -161,6 +161,7 @@ class ResolvedLLMConfig:
api_version: str | None = None
extra_headers: dict[str, str] = field(default_factory=dict)
reasoning_effort: str | None = None
+ context_window: int | None = None
@dataclass(slots=True)
@@ -354,6 +355,9 @@ def resolve_llm_runtime_config(
)
active_extra_headers = _to_headers((profile or {}).get("extra_headers"))
reasoning_effort = _as_str((model or {}).get("reasoning_effort")) or None
+ context_window = _coerce_optional_int((model or {}).get("context_window"))
+ if context_window is None:
+ context_window = _coerce_optional_int((model or {}).get("context_window_tokens"))
provider_pool = _collect_provider_pool(loaded)
spec = _choose_resolved_provider(
@@ -386,6 +390,7 @@ def resolve_llm_runtime_config(
api_version=api_version or None,
extra_headers=extra_headers,
reasoning_effort=reasoning_effort,
+ context_window=context_window,
)
@@ -450,6 +455,17 @@ def _coerce_optional_bool(value: Any) -> bool | None:
return None
+def _coerce_optional_int(value: Any) -> int | None:
+ """Parse a positive int from catalog values, returning ``None`` when unset."""
+ if value is None:
+ return None
+ try:
+ parsed = int(str(value).strip())
+ except (TypeError, ValueError):
+ return None
+ return parsed if parsed > 0 else None
+
+
def _resolve_embedding_provider(
*,
hint: str | None,
diff --git a/deeptutor/services/config/test_runner.py b/deeptutor/services/config/test_runner.py
index 25e5bba52..322de5dcc 100644
--- a/deeptutor/services/config/test_runner.py
+++ b/deeptutor/services/config/test_runner.py
@@ -11,6 +11,10 @@ import time
from typing import Any
from uuid import uuid4
+from deeptutor.services.llm.client import reset_llm_client
+from deeptutor.services.llm.config import clear_llm_config_cache
+
+from .context_window_detection import detect_context_window
from .env_store import get_env_store
from .model_catalog import get_model_catalog_service
from .provider_runtime import (
@@ -133,6 +137,26 @@ class ConfigTestRunner:
run.status = "failed"
run.emit("failed", str(exc))
+ def _persist_llm_context_window(
+ self,
+ *,
+ catalog: dict[str, Any],
+ context_window: int,
+ source: str,
+ detected_at: str,
+ ) -> dict[str, Any]:
+ service = get_model_catalog_service()
+ llm_model = service.get_active_model(catalog, "llm")
+ if llm_model is None:
+ return catalog
+ llm_model["context_window"] = str(context_window)
+ llm_model["context_window_source"] = source
+ llm_model["context_window_detected_at"] = detected_at
+ saved = service.save(catalog)
+ clear_llm_config_cache()
+ reset_llm_client()
+ return saved
+
async def _test_llm(self, run: TestRun, catalog: dict[str, Any]) -> None:
from deeptutor.services.llm import clear_llm_config_cache, get_token_limit_kwargs
from deeptutor.services.llm import complete as llm_complete
@@ -184,6 +208,34 @@ class ConfigTestRunner:
if not snippet:
raise ValueError("LLM returned an empty response.")
+ run.emit("info", "Detecting model context window.")
+ detection = await detect_context_window(
+ llm_config,
+ on_log=lambda message: run.emit("info", message),
+ )
+ run.emit(
+ "context_window",
+ (
+ f"Context window set to {detection.context_window} tokens "
+ f"({detection.source})."
+ ),
+ context_window=detection.context_window,
+ source=detection.source,
+ detail=detection.detail,
+ detected_at=detection.detected_at,
+ )
+ saved_catalog = self._persist_llm_context_window(
+ catalog=catalog,
+ context_window=detection.context_window,
+ source=detection.source,
+ detected_at=detection.detected_at,
+ )
+ run.emit(
+ "catalog",
+ "Saved updated model metadata to model_catalog.json.",
+ catalog=saved_catalog,
+ )
+
async def _test_embedding(
self, run: TestRun, model: dict[str, Any], catalog: dict[str, Any]
) -> None:
diff --git a/deeptutor/services/llm/config.py b/deeptutor/services/llm/config.py
index bc85e97bd..386d5afff 100644
--- a/deeptutor/services/llm/config.py
+++ b/deeptutor/services/llm/config.py
@@ -36,6 +36,7 @@ class LLMConfigUpdate(TypedDict, total=False):
api_version: str | None
extra_headers: dict[str, str]
reasoning_effort: str | None
+ context_window: int | None
max_tokens: int
temperature: float
max_concurrency: int
@@ -50,10 +51,10 @@ PROJECT_ROOT = get_env_store().path.parent
def _is_openai_compatible_binding(binding: str | None) -> bool:
canonical = canonical_provider_name(binding) or (binding or "").strip().lower()
- if canonical in {"custom", "azure_openai"}:
- return True
spec = find_by_name(canonical)
- return bool(spec and not spec.is_oauth)
+ if not spec or spec.is_oauth:
+ return False
+ return spec.backend in {"openai_compat", "azure_openai"}
def _set_openai_env_vars(api_key: str | None, base_url: str | None, *, source: str) -> None:
@@ -104,6 +105,7 @@ class LLMConfig:
api_version: str | None = None
extra_headers: dict[str, str] | None = None
reasoning_effort: str | None = None
+ context_window: int | None = None
max_tokens: int = 4096
temperature: float = 0.7
max_concurrency: int = 20
@@ -205,6 +207,7 @@ def _get_llm_config_from_resolver() -> LLMConfig:
api_version=resolved.api_version,
extra_headers=resolved.extra_headers,
reasoning_effort=resolved.reasoning_effort,
+ context_window=resolved.context_window,
)
diff --git a/deeptutor/services/llm/context_window.py b/deeptutor/services/llm/context_window.py
new file mode 100644
index 000000000..fb8a64133
--- /dev/null
+++ b/deeptutor/services/llm/context_window.py
@@ -0,0 +1,76 @@
+"""Helpers for reasoning about model context-window budgets."""
+
+from __future__ import annotations
+
+from typing import Any
+
+DEFAULT_CONTEXT_WINDOW_FALLBACK = 16_384
+MAX_EFFECTIVE_CONTEXT_WINDOW = 65_536
+KNOWN_LARGE_CONTEXT_MARKERS = (
+ "gpt-4.1",
+ "gpt-4o",
+ "gpt-5",
+ "o1",
+ "o3",
+ "o4",
+ "claude",
+ "gemini",
+ "qwen",
+ "deepseek",
+ "moonshot",
+ "kimi",
+)
+
+
+def coerce_positive_int(value: Any) -> int | None:
+ """Parse a positive integer from arbitrary input."""
+ try:
+ parsed = int(str(value).strip())
+ except (TypeError, ValueError):
+ return None
+ return parsed if parsed > 0 else None
+
+
+def looks_like_large_context_model(model: str) -> bool:
+ """Return True when a model family is typically backed by a large window."""
+ normalized = (model or "").strip().lower()
+ return any(marker in normalized for marker in KNOWN_LARGE_CONTEXT_MARKERS)
+
+
+def default_context_window_for_model(
+ *,
+ model: str,
+ max_tokens: Any = None,
+) -> int:
+ """Return the fallback window used when no explicit model metadata exists."""
+ if looks_like_large_context_model(model):
+ return MAX_EFFECTIVE_CONTEXT_WINDOW
+ output_limit = coerce_positive_int(max_tokens) or 4096
+ return max(DEFAULT_CONTEXT_WINDOW_FALLBACK, output_limit * 4)
+
+
+def resolve_effective_context_window(
+ *,
+ context_window: Any = None,
+ model: str,
+ max_tokens: Any = None,
+) -> int:
+ """Resolve the bounded history-planning window for the current model."""
+ configured = coerce_positive_int(context_window)
+ if configured is not None:
+ return min(configured, MAX_EFFECTIVE_CONTEXT_WINDOW)
+ return min(
+ default_context_window_for_model(model=model, max_tokens=max_tokens),
+ MAX_EFFECTIVE_CONTEXT_WINDOW,
+ )
+
+
+__all__ = [
+ "DEFAULT_CONTEXT_WINDOW_FALLBACK",
+ "MAX_EFFECTIVE_CONTEXT_WINDOW",
+ "KNOWN_LARGE_CONTEXT_MARKERS",
+ "coerce_positive_int",
+ "default_context_window_for_model",
+ "looks_like_large_context_model",
+ "resolve_effective_context_window",
+]
diff --git a/deeptutor/services/llm/factory.py b/deeptutor/services/llm/factory.py
index ae78b71ce..4fe8a97d1 100644
--- a/deeptutor/services/llm/factory.py
+++ b/deeptutor/services/llm/factory.py
@@ -1,72 +1,29 @@
-"""
-LLM Factory - Central Hub for LLM Calls
-=======================================
-This module serves as the central hub for all LLM calls in DeepTutor.
-It provides a unified interface for agents to call LLMs, routing requests
-to the appropriate provider (cloud or local) based on URL detection.
-
-Compatibility:
- This factory preserves legacy behaviors from the pre-provider refactor,
- including BaseAgent.call_llm()/stream_llm() signatures and retry semantics.
- The adapter layer remains until all legacy entry points migrate to direct
- provider calls. Once all agents and tools depend on provider modules
- directly, this wrapper can be removed.
-
-Architecture:
- Agents (ChatAgent, SolveAgent, etc.)
- ↓
- BaseAgent.call_llm() / stream_llm()
- ↓
- LLM Factory (this module)
- ↓
- ┌─────────┴─────────┐
- ↓ ↓
-CloudProvider LocalProvider
-(cloud_provider) (local_provider)
- ↓ ↓
-OpenAI/DeepSeek/etc LM Studio/Ollama/etc
-
-Routing:
-- Automatically routes to local_provider for local URLs (localhost, 127.0.0.1, etc.)
-- Routes to cloud_provider for all other URLs
-
-Retry Mechanism:
-- Automatic retry with exponential backoff for transient errors
-- Configurable max_retries, retry_delay, and exponential_backoff
-- Only retries on retriable errors (timeout, rate limit, server errors)
-"""
+"""Unified services-layer LLM factory."""
+
+from __future__ import annotations
import asyncio
+import contextlib
from collections.abc import AsyncGenerator, Mapping
-from typing import TYPE_CHECKING, Any, TypedDict
-
-import tenacity
+from types import SimpleNamespace
+from typing import Any, TypedDict
from deeptutor.config.settings import settings
-from deeptutor.logging.logger import Logger, get_logger
+from deeptutor.services.provider_registry import (
+ PROVIDERS,
+ canonical_provider_name,
+ find_by_model,
+ find_by_name,
+ find_gateway,
+)
-from . import local_provider
+from .capabilities import supports_response_format
from .config import LLMConfig, get_llm_config
-from .exceptions import (
- LLMAPIError,
- LLMAuthenticationError,
- LLMConfigError,
- LLMRateLimitError,
- LLMTimeoutError,
-)
-from .executors import (
- sdk_complete,
- sdk_stream,
-)
+from .error_mapping import map_error
+from .multimodal import prepare_multimodal_messages
+from .provider_factory import get_runtime_provider
from .utils import is_local_llm_server
-if TYPE_CHECKING:
- from .providers.base_provider import BaseLLMProvider
-
-# Initialize logger
-logger: Logger = get_logger("LLMFactory")
-
-# Default retry configuration (bound to settings)
DEFAULT_MAX_RETRIES = settings.retry.max_retries
DEFAULT_RETRY_DELAY = settings.retry.base_delay
DEFAULT_EXPONENTIAL_BACKOFF = settings.retry.exponential_backoff
@@ -74,67 +31,248 @@ DEFAULT_EXPONENTIAL_BACKOFF = settings.retry.exponential_backoff
CallKwargs = dict[str, Any]
-def _is_retriable_error(error: BaseException) -> bool:
- """
- Check if an error is retriable.
-
- Retriable errors:
- - Timeout errors
- - Rate limit errors (429)
- - Server errors (5xx)
- - Network/connection errors
-
- Non-retriable errors:
- - CancelledError / KeyboardInterrupt (must propagate immediately)
- - Authentication errors (401)
- - Bad request (400)
- - Not found (404)
- - Client errors (4xx except 429)
- """
- if isinstance(error, (asyncio.CancelledError, KeyboardInterrupt, GeneratorExit)):
- return False
-
- from aiohttp import ClientError
-
- if isinstance(error, (asyncio.TimeoutError, ClientError)):
- return True
- if isinstance(error, LLMTimeoutError):
- return True
- if isinstance(error, LLMRateLimitError):
- return True
- if isinstance(error, LLMAuthenticationError):
- return False # Don't retry auth errors
- if isinstance(error, LLMConfigError):
- return False
-
- if isinstance(error, LLMAPIError):
- status_code = error.status_code
- if status_code:
- # Retry on server errors (5xx) and rate limits (429)
- if status_code >= 500 or status_code == 429:
- return True
- # Don't retry on client errors (4xx except 429)
- if 400 <= status_code < 500:
- return False
-
- # When status_code is None (e.g. connection drop), retry.
- return True
-
- # For other exceptions (network errors, etc.), retry
- return True
-
-
-def _should_use_local(base_url: str | None) -> bool:
- """
- Determine if we should use the local provider based on URL.
-
- Args:
- base_url: The base URL to check
-
- Returns:
- True if local provider should be used (localhost, 127.0.0.1, etc.)
- """
- return is_local_llm_server(base_url) if base_url else False
+class ApiProviderPreset(TypedDict, total=False):
+ """Typed representation of API provider presets."""
+
+ name: str
+ base_url: str
+ requires_key: bool
+ models: list[str]
+ binding: str
+
+
+class LocalProviderPreset(TypedDict, total=False):
+ """Typed representation of local provider presets."""
+
+ name: str
+ base_url: str
+ requires_key: bool
+ default_key: str
+ binding: str
+
+
+ProviderPreset = ApiProviderPreset | LocalProviderPreset
+ProviderPresetMap = Mapping[str, ProviderPreset]
+ProviderPresetBundle = Mapping[str, ProviderPresetMap]
+
+
+def _build_retry_delays(
+ max_retries: int,
+ retry_delay: float,
+ exponential_backoff: bool,
+) -> tuple[float, ...]:
+ if max_retries <= 0:
+ return ()
+ delays: list[float] = []
+ base = max(float(retry_delay), 0.0)
+ for attempt in range(max_retries):
+ delay = base * (2**attempt) if exponential_backoff else base
+ delays.append(min(delay, 120.0))
+ return tuple(delays)
+
+
+def _resolve_provider_spec(
+ *,
+ binding: str | None,
+ model: str,
+ api_key: str,
+ base_url: str | None,
+ fallback: str | None,
+):
+ explicit = find_by_name(binding)
+ gateway = find_gateway(
+ provider_name=explicit.name if explicit else None,
+ api_key=api_key or None,
+ api_base=base_url or None,
+ )
+ if explicit and gateway and explicit.name == "openai":
+ return gateway
+ if explicit:
+ return explicit
+ if gateway:
+ return gateway
+
+ model_spec = find_by_model(model)
+ if model_spec:
+ return model_spec
+
+ if is_local_llm_server(base_url):
+ if base_url and "11434" in base_url:
+ return find_by_name("ollama") or find_by_name("vllm")
+ return find_by_name("vllm") or find_by_name("ollama")
+
+ return find_by_name(fallback) or find_by_name("openai")
+
+
+def _resolve_call_config(
+ *,
+ model: str | None,
+ api_key: str | None,
+ base_url: str | None,
+ api_version: str | None,
+ binding: str | None,
+ extra_headers: dict[str, str] | None,
+ reasoning_effort: str | None,
+) -> tuple[LLMConfig, Any]:
+ if model and api_key is not None and (base_url is not None or binding is not None):
+ provider_spec = _resolve_provider_spec(
+ binding=binding,
+ model=model,
+ api_key=api_key,
+ base_url=base_url,
+ fallback=binding or "openai",
+ )
+ provider_name = (
+ provider_spec.name
+ if provider_spec is not None
+ else canonical_provider_name(binding) or binding or "openai"
+ )
+ provider_mode = provider_spec.mode if provider_spec is not None else "standard"
+ config = LLMConfig(
+ model=model,
+ api_key=api_key,
+ base_url=base_url,
+ effective_url=base_url,
+ binding=provider_name,
+ provider_name=provider_name,
+ provider_mode=provider_mode,
+ api_version=api_version,
+ extra_headers=extra_headers or {},
+ reasoning_effort=reasoning_effort,
+ )
+ return config, provider_spec
+
+ current = get_llm_config()
+ merged_headers = dict(current.extra_headers or {})
+ if extra_headers:
+ merged_headers.update(extra_headers)
+
+ resolved_model = model or current.model
+ resolved_api_key = current.api_key if api_key is None else api_key
+ resolved_base_url = base_url if base_url is not None else current.base_url
+ resolved_effective_url = base_url if base_url is not None else current.effective_url
+ resolved_api_version = api_version if api_version is not None else current.api_version
+ binding_hint = binding or current.provider_name or current.binding
+ provider_spec = _resolve_provider_spec(
+ binding=binding_hint,
+ model=resolved_model,
+ api_key=resolved_api_key,
+ base_url=resolved_effective_url,
+ fallback=current.provider_name or current.binding,
+ )
+ provider_name = provider_spec.name if provider_spec is not None else current.provider_name
+ provider_mode = provider_spec.mode if provider_spec is not None else current.provider_mode
+ resolved_binding = provider_name or binding_hint or current.binding or "openai"
+
+ config = current.model_copy(
+ update={
+ "model": resolved_model,
+ "api_key": resolved_api_key,
+ "base_url": resolved_base_url,
+ "effective_url": resolved_effective_url,
+ "binding": resolved_binding,
+ "provider_name": provider_name or resolved_binding,
+ "provider_mode": provider_mode,
+ "api_version": resolved_api_version,
+ "extra_headers": merged_headers,
+ "reasoning_effort": (
+ reasoning_effort if reasoning_effort is not None else current.reasoning_effort
+ ),
+ }
+ )
+ return config, provider_spec
+
+
+def _capability_binding(config: LLMConfig, provider_spec: Any) -> str:
+ backend = getattr(provider_spec, "backend", "openai_compat") if provider_spec else "openai_compat"
+ if backend == "anthropic":
+ return "anthropic"
+ if backend == "azure_openai":
+ return "azure_openai"
+ return getattr(provider_spec, "name", None) or config.provider_name or config.binding or "openai"
+
+
+def _build_messages(
+ prompt: str,
+ system_prompt: str,
+ messages: list[dict[str, Any]] | None,
+) -> list[dict[str, Any]]:
+ if messages is not None:
+ return messages
+ return [
+ {"role": "system", "content": system_prompt},
+ {"role": "user", "content": prompt},
+ ]
+
+
+def _find_last_user_message(messages: list[dict[str, Any]]) -> dict[str, Any] | None:
+ for message in reversed(messages):
+ if message.get("role") == "user":
+ return message
+ return None
+
+
+def _append_image_placeholder(messages: list[dict[str, Any]]) -> None:
+ target = _find_last_user_message(messages)
+ placeholder = "[image omitted]"
+ if target is None:
+ messages.append({"role": "user", "content": placeholder})
+ return
+
+ content = target.get("content")
+ if isinstance(content, str):
+ target["content"] = f"{content}\n\n{placeholder}" if content else placeholder
+ return
+ if isinstance(content, list):
+ content.append({"type": "text", "text": placeholder})
+ return
+ target["content"] = placeholder
+
+
+def _apply_inline_image_data(
+ messages: list[dict[str, Any]],
+ *,
+ binding: str,
+ model: str,
+ image_data: str | None,
+) -> list[dict[str, Any]]:
+ if not image_data:
+ return messages
+
+ attachment = SimpleNamespace(
+ type="image",
+ base64=image_data,
+ filename="image.png",
+ mime_type="image/png",
+ )
+ result = prepare_multimodal_messages(messages, [attachment], binding=binding, model=model)
+ if result.images_stripped:
+ _append_image_placeholder(messages)
+ return result.messages
+
+
+def _sanitize_call_kwargs(
+ *,
+ binding: str,
+ model: str,
+ kwargs: dict[str, Any],
+) -> CallKwargs:
+ extra_kwargs = dict(kwargs)
+ for key in (
+ "messages",
+ "image_data",
+ "api_key",
+ "base_url",
+ "api_version",
+ "binding",
+ "extra_headers",
+ "reasoning_effort",
+ ):
+ extra_kwargs.pop(key, None)
+
+ if not supports_response_format(binding, model):
+ extra_kwargs.pop("response_format", None)
+ return extra_kwargs
async def complete(
@@ -151,194 +289,44 @@ async def complete(
exponential_backoff: bool = DEFAULT_EXPONENTIAL_BACKOFF,
**kwargs: Any,
) -> str:
- """
- Unified LLM completion function with automatic retry.
-
- Routes to cloud_provider or local_provider based on configuration.
- Includes automatic retry with exponential backoff for transient errors.
-
- Args:
- prompt: The user prompt
- system_prompt: System prompt for context
- model: Model name (optional, uses effective config if not provided)
- api_key: API key (optional)
- base_url: Base URL for the API (optional)
- api_version: API version for Azure OpenAI (optional)
- binding: Provider binding type (optional)
- messages: Pre-built messages array (optional)
- max_retries: Maximum number of retry attempts (default: 5)
- retry_delay: Initial delay between retries in seconds (default: 2.0)
- exponential_backoff: Whether to use exponential backoff (default: True)
- **kwargs: Additional parameters (temperature, max_tokens, etc.)
-
- Returns:
- str: The LLM response
- """
- provider_name = binding or "openai"
- provider_mode = "standard"
- extra_headers: dict[str, str] = {}
caller_extra_headers = kwargs.pop("extra_headers", None) or {}
reasoning_effort = kwargs.pop("reasoning_effort", None)
-
- if not model or not base_url or api_key is None or not binding:
- config = get_llm_config()
- model = model or config.model
- api_key = api_key if api_key is not None else config.api_key
- base_url = base_url or config.base_url
- api_version = api_version or config.api_version
- binding = binding or config.binding or "openai"
- provider_name = getattr(config, "provider_name", binding or "openai")
- provider_mode = getattr(config, "provider_mode", "standard")
- extra_headers = getattr(config, "extra_headers", {}) or {}
- if reasoning_effort is None:
- reasoning_effort = getattr(config, "reasoning_effort", None)
- else:
- from .provider_registry import find_by_name
-
- provider_name = binding or "openai"
- spec = find_by_name(provider_name)
- if spec is not None:
- provider_mode = spec.mode
-
- if caller_extra_headers:
- extra_headers.update(caller_extra_headers)
-
- use_local_fallback = _should_use_local(base_url)
-
- def _is_retriable_llm_api_error(exc: BaseException) -> bool:
- """Delegate retriable checks to shared helper."""
- return _is_retriable_error(exc)
-
- def _log_retry_warning(retry_state: tenacity.RetryCallState) -> None:
- """Log retry warnings with safe handling for missing exceptions."""
- outcome = retry_state.outcome
- exception = outcome.exception() if outcome else None
- error_message = str(exception) if exception else "unknown error"
- if not error_message.strip():
- error_message = f"{type(exception).__name__} (no message)"
- logger.warning(
- "LLM call failed (attempt %s/%s), retrying in %.1fs... Error: %s"
- % (
- retry_state.attempt_number,
- max_retries + 1,
- retry_state.upcoming_sleep,
- error_message,
- )
- )
-
- wait_strategy = (
- tenacity.wait_exponential(
- multiplier=retry_delay,
- min=retry_delay,
- max=120,
- )
- if exponential_backoff
- else tenacity.wait_fixed(retry_delay)
+ image_data = kwargs.pop("image_data", None)
+
+ config, provider_spec = _resolve_call_config(
+ model=model,
+ api_key=api_key,
+ base_url=base_url,
+ api_version=api_version,
+ binding=binding,
+ extra_headers=caller_extra_headers,
+ reasoning_effort=reasoning_effort,
)
-
- total_attempts = max_retries + 1
-
- @tenacity.retry(
- retry=(
- tenacity.retry_if_exception_type(LLMRateLimitError)
- | tenacity.retry_if_exception_type(LLMTimeoutError)
- | tenacity.retry_if_exception(_is_retriable_llm_api_error)
- ),
- wait=wait_strategy,
- stop=tenacity.stop_after_attempt(total_attempts),
- before_sleep=_log_retry_warning,
+ provider = get_runtime_provider(config)
+ capability_binding = _capability_binding(config, provider_spec)
+ request_messages = _build_messages(prompt, system_prompt, messages)
+ request_messages = _apply_inline_image_data(
+ request_messages,
+ binding=capability_binding,
+ model=config.model,
+ image_data=image_data,
)
- async def _do_complete(
- *,
- prompt_value: str,
- system_prompt_value: str,
- model_value: str,
- api_key_value: str | None,
- base_url_value: str | None,
- api_version_value: str | None,
- binding_value: str | None,
- extra_kwargs: CallKwargs,
- messages_value: list[dict[str, Any]] | None,
- ) -> str:
- try:
- if provider_mode == "oauth" and provider_name == "openai_codex":
- raise LLMConfigError(
- "openai_codex requires OAuth login in CLI. "
- "Run `deeptutor provider login openai-codex` first."
- )
- if provider_mode == "oauth":
- raise LLMConfigError(
- f"{provider_name} requires OAuth session. "
- "Run `deeptutor provider login ...` first."
- )
- if provider_mode != "direct":
- return await sdk_complete(
- prompt=prompt_value,
- system_prompt=system_prompt_value,
- provider_name=provider_name,
- model=model_value,
- api_key=api_key_value,
- base_url=base_url_value,
- api_version=api_version_value,
- messages=messages_value,
- extra_headers=extra_headers or None,
- reasoning_effort=reasoning_effort,
- **extra_kwargs,
- )
+ retry_delays = _build_retry_delays(max_retries, retry_delay, exponential_backoff)
+ extra_kwargs = _sanitize_call_kwargs(binding=capability_binding, model=config.model, kwargs=kwargs)
+
+ try:
+ response = await provider.chat_with_retry(
+ messages=request_messages,
+ model=config.model,
+ retry_delays=retry_delays,
+ **extra_kwargs,
+ )
+ except Exception as exc:
+ raise map_error(exc, provider=config.provider_name) from exc
- if use_local_fallback:
- return await local_provider.complete(
- prompt=prompt_value,
- system_prompt=system_prompt_value,
- model=model_value,
- api_key=api_key_value,
- base_url=base_url_value,
- messages=messages_value,
- **extra_kwargs,
- )
- from . import cloud_provider
-
- direct_binding = "azure_openai" if provider_name == "azure_openai" else "openai"
- return await cloud_provider.complete(
- prompt=prompt_value,
- system_prompt=system_prompt_value,
- model=model_value,
- api_key=api_key_value,
- base_url=base_url_value,
- api_version=api_version_value,
- binding=direct_binding
- if provider_mode == "direct"
- else (binding_value or "openai"),
- messages=messages_value,
- extra_headers=extra_headers or None,
- **extra_kwargs,
- )
- except Exception as exc:
- if isinstance(exc, LLMConfigError):
- raise
- from .error_mapping import map_error
-
- provider_for_error = provider_name
- if use_local_fallback and provider_mode != "direct":
- provider_for_error = "local"
- mapped_error = map_error(exc, provider=provider_for_error)
- raise mapped_error from exc
-
- extra_kwargs: CallKwargs = dict(kwargs)
- extra_kwargs.pop("messages", None)
- extra_kwargs.pop("extra_headers", None)
-
- return await _do_complete(
- prompt_value=prompt,
- system_prompt_value=system_prompt,
- model_value=model,
- api_key_value=api_key,
- base_url_value=base_url,
- api_version_value=api_version,
- binding_value=binding or "openai",
- extra_kwargs=extra_kwargs,
- messages_value=messages,
- )
+ if response.finish_reason == "error":
+ raise map_error(RuntimeError(response.content or "LLM request failed"), provider=config.provider_name)
+ return response.content or ""
async def stream(
@@ -355,130 +343,75 @@ async def stream(
exponential_backoff: bool = DEFAULT_EXPONENTIAL_BACKOFF,
**kwargs: Any,
) -> AsyncGenerator[str, None]:
- """Stream LLM responses with retry handling."""
- provider_name = binding or "openai"
- provider_mode = "standard"
- extra_headers: dict[str, str] = {}
caller_extra_headers = kwargs.pop("extra_headers", None) or {}
reasoning_effort = kwargs.pop("reasoning_effort", None)
+ image_data = kwargs.pop("image_data", None)
+
+ config, provider_spec = _resolve_call_config(
+ model=model,
+ api_key=api_key,
+ base_url=base_url,
+ api_version=api_version,
+ binding=binding,
+ extra_headers=caller_extra_headers,
+ reasoning_effort=reasoning_effort,
+ )
+ provider = get_runtime_provider(config)
+ capability_binding = _capability_binding(config, provider_spec)
+ request_messages = _build_messages(prompt, system_prompt, messages)
+ request_messages = _apply_inline_image_data(
+ request_messages,
+ binding=capability_binding,
+ model=config.model,
+ image_data=image_data,
+ )
+ retry_delays = _build_retry_delays(max_retries, retry_delay, exponential_backoff)
+ extra_kwargs = _sanitize_call_kwargs(binding=capability_binding, model=config.model, kwargs=kwargs)
+
+ queue: asyncio.Queue[str | BaseException | None] = asyncio.Queue()
+ saw_output = False
- if not model or not base_url or api_key is None or not binding:
- config = get_llm_config()
- model = model or config.model
- api_key = api_key if api_key is not None else config.api_key
- base_url = base_url or config.base_url
- api_version = api_version or config.api_version
- binding = binding or config.binding or "openai"
- provider_name = getattr(config, "provider_name", binding or "openai")
- provider_mode = getattr(config, "provider_mode", "standard")
- extra_headers = getattr(config, "extra_headers", {}) or {}
- if reasoning_effort is None:
- reasoning_effort = getattr(config, "reasoning_effort", None)
- else:
- from .provider_registry import find_by_name
-
- provider_name = binding or "openai"
- spec = find_by_name(provider_name)
- if spec is not None:
- provider_mode = spec.mode
-
- if caller_extra_headers:
- extra_headers.update(caller_extra_headers)
-
- use_local_fallback = _should_use_local(base_url)
- extra_kwargs: CallKwargs = dict(kwargs)
- extra_kwargs.pop("messages", None)
- extra_kwargs.pop("extra_headers", None)
-
- total_attempts = max_retries + 1
- last_exception: Exception | None = None
- delay = retry_delay
- has_yielded = False
- max_delay = 120
-
- for attempt in range(total_attempts):
+ async def _on_content_delta(chunk: str) -> None:
+ nonlocal saw_output
+ saw_output = True
+ await queue.put(chunk)
+
+ async def _runner() -> None:
try:
- if provider_mode == "oauth" and provider_name == "openai_codex":
- raise LLMConfigError(
- "openai_codex requires OAuth login in CLI. "
- "Run `deeptutor provider login openai-codex` first."
- )
- if provider_mode == "oauth":
- raise LLMConfigError(
- f"{provider_name} requires OAuth session. "
- "Run `deeptutor provider login ...` first."
+ response = await provider.chat_stream_with_retry(
+ messages=request_messages,
+ model=config.model,
+ on_content_delta=_on_content_delta,
+ retry_delays=retry_delays,
+ **extra_kwargs,
+ )
+ if response.finish_reason == "error" and not saw_output:
+ await queue.put(
+ map_error(
+ RuntimeError(response.content or "LLM request failed"),
+ provider=config.provider_name,
+ )
)
-
- if provider_mode != "direct":
- async for chunk in sdk_stream(
- prompt=prompt,
- system_prompt=system_prompt,
- provider_name=provider_name,
- model=model,
- api_key=api_key,
- base_url=base_url,
- api_version=api_version,
- messages=messages,
- extra_headers=extra_headers or None,
- reasoning_effort=reasoning_effort,
- **extra_kwargs,
- ):
- has_yielded = True
- yield chunk
- elif use_local_fallback:
- async for chunk in local_provider.stream(
- prompt=prompt,
- system_prompt=system_prompt,
- model=model,
- api_key=api_key,
- base_url=base_url,
- messages=messages,
- **extra_kwargs,
- ):
- has_yielded = True
- yield chunk
- else:
- from . import cloud_provider
-
- direct_binding = "azure_openai" if provider_name == "azure_openai" else "openai"
- async for chunk in cloud_provider.stream(
- prompt=prompt,
- system_prompt=system_prompt,
- model=model,
- api_key=api_key,
- base_url=base_url,
- api_version=api_version,
- binding=direct_binding if provider_mode == "direct" else (binding or "openai"),
- messages=messages,
- extra_headers=extra_headers or None,
- **extra_kwargs,
- ):
- has_yielded = True
- yield chunk
- return
except Exception as exc:
- last_exception = exc
- if has_yielded:
- raise
- if attempt >= max_retries or not _is_retriable_error(exc):
- raise
-
- if exponential_backoff:
- current_delay = min(delay * (2**attempt), max_delay)
- else:
- current_delay = delay
-
- if isinstance(exc, LLMRateLimitError) and exc.retry_after:
- current_delay = max(current_delay, exc.retry_after)
-
- logger.warning(
- "LLM streaming failed (attempt %s/%s), retrying in %.1fs... Error: %s"
- % (attempt + 1, total_attempts, current_delay, exc)
- )
- await asyncio.sleep(current_delay)
-
- if last_exception:
- raise last_exception
+ await queue.put(map_error(exc, provider=config.provider_name))
+ finally:
+ await queue.put(None)
+
+ task = asyncio.create_task(_runner())
+ try:
+ while True:
+ item = await queue.get()
+ if item is None:
+ break
+ if isinstance(item, BaseException):
+ raise item
+ yield item
+ await task
+ finally:
+ if not task.done():
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
async def fetch_models(
@@ -486,113 +419,51 @@ async def fetch_models(
base_url: str,
api_key: str | None = None,
) -> list[str]:
- """
- Fetch available models from the provider.
-
- Routes to cloud_provider or local_provider based on URL.
-
- Args:
- binding: Provider type (openai, ollama, etc.)
- base_url: API endpoint URL
- api_key: API key (optional for local providers)
-
- Returns:
- List of available model names
- """
if is_local_llm_server(base_url):
+ from . import local_provider
+
return await local_provider.fetch_models(base_url, api_key)
- else:
- from . import cloud_provider
- return await cloud_provider.fetch_models(base_url, api_key, binding)
+ from . import cloud_provider
+ return await cloud_provider.fetch_models(base_url, api_key, binding)
-class ApiProviderPreset(TypedDict, total=False):
- """Typed representation of API provider presets."""
- name: str
- base_url: str
- requires_key: bool
- models: list[str]
- binding: str
+def _build_api_provider_presets() -> dict[str, ApiProviderPreset]:
+ presets: dict[str, ApiProviderPreset] = {}
+ for spec in PROVIDERS:
+ if spec.is_local:
+ continue
+ presets[spec.name] = {
+ "name": spec.label,
+ "base_url": spec.default_api_base,
+ "requires_key": not spec.is_oauth,
+ "models": [],
+ "binding": spec.name,
+ }
+ return presets
-class LocalProviderPreset(TypedDict, total=False):
- """Typed representation of local provider presets."""
-
- name: str
- base_url: str
- requires_key: bool
- default_key: str
+def _build_local_provider_presets() -> dict[str, LocalProviderPreset]:
+ presets: dict[str, LocalProviderPreset] = {}
+ for spec in PROVIDERS:
+ if not spec.is_local:
+ continue
+ presets[spec.name] = {
+ "name": spec.label,
+ "base_url": spec.default_api_base,
+ "requires_key": False,
+ "default_key": "sk-no-key-required",
+ "binding": spec.name,
+ }
+ return presets
-ProviderPreset = ApiProviderPreset | LocalProviderPreset
-ProviderPresetMap = Mapping[str, ProviderPreset]
-ProviderPresetBundle = Mapping[str, ProviderPresetMap]
-
-
-# API Provider Presets
-API_PROVIDER_PRESETS: dict[str, ApiProviderPreset] = {
- "openai": {
- "name": "OpenAI",
- "base_url": "https://api.openai.com/v1",
- "requires_key": True,
- "models": ["gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "gpt-3.5-turbo"],
- },
- "anthropic": {
- "name": "Anthropic",
- "base_url": "https://api.anthropic.com/v1",
- "requires_key": True,
- "binding": "anthropic",
- "models": ["claude-3-5-sonnet-20241022", "claude-3-haiku-20240307"],
- },
- "deepseek": {
- "name": "DeepSeek",
- "base_url": "https://api.deepseek.com",
- "requires_key": True,
- "models": ["deepseek-chat", "deepseek-reasoner"],
- },
- "openrouter": {
- "name": "OpenRouter",
- "base_url": "https://openrouter.ai/api/v1",
- "requires_key": True,
- "models": [],
- },
-}
-
-# Local Provider Presets
-LOCAL_PROVIDER_PRESETS: dict[str, LocalProviderPreset] = {
- "ollama": {
- "name": "Ollama",
- "base_url": "http://localhost:11434/v1",
- "requires_key": False,
- "default_key": "ollama",
- },
- "lm_studio": {
- "name": "LM Studio",
- "base_url": "http://localhost:1234/v1",
- "requires_key": False,
- "default_key": "lm-studio",
- },
- "vllm": {
- "name": "vLLM",
- "base_url": "http://localhost:8000/v1",
- "requires_key": False,
- "default_key": "vllm",
- },
- "llama_cpp": {
- "name": "llama.cpp",
- "base_url": "http://localhost:8080/v1",
- "requires_key": False,
- "default_key": "llama-cpp",
- },
-}
+API_PROVIDER_PRESETS: dict[str, ApiProviderPreset] = _build_api_provider_presets()
+LOCAL_PROVIDER_PRESETS: dict[str, LocalProviderPreset] = _build_local_provider_presets()
def get_provider_presets() -> ProviderPresetBundle:
- """
- Get all provider presets for frontend display.
- """
return {
"api": API_PROVIDER_PRESETS,
"local": LOCAL_PROVIDER_PRESETS,
@@ -606,7 +477,6 @@ __all__ = [
"get_provider_presets",
"API_PROVIDER_PRESETS",
"LOCAL_PROVIDER_PRESETS",
- # Retry configuration defaults
"DEFAULT_MAX_RETRIES",
"DEFAULT_RETRY_DELAY",
"DEFAULT_EXPONENTIAL_BACKOFF",
@@ -615,11 +485,8 @@ __all__ = [
class LLMFactory:
- """Compatibility factory for legacy agent integrations."""
+ """Compatibility factory for legacy integrations."""
@staticmethod
- def get_provider(config: "LLMConfig") -> "BaseLLMProvider":
- """Return a provider instance for the supplied config."""
- from .providers.routing import RoutingProvider
-
- return RoutingProvider(config)
+ def get_provider(config: LLMConfig):
+ return get_runtime_provider(config)
diff --git a/deeptutor/services/llm/multimodal.py b/deeptutor/services/llm/multimodal.py
index 746176d4e..6f69844dd 100644
--- a/deeptutor/services/llm/multimodal.py
+++ b/deeptutor/services/llm/multimodal.py
@@ -72,6 +72,11 @@ def _build_anthropic_image_part(
}
+def _image_placeholder(url: str = "", filename: str = "") -> str:
+ label = filename or url
+ return f"[image: {label}]" if label else "[image omitted]"
+
+
def prepare_multimodal_messages(
messages: list[dict[str, Any]],
attachments: list[Any] | None,
@@ -193,7 +198,45 @@ def _inject_images(
messages[user_idx] = {**msg, "content": content_parts}
+def has_image_parts(messages: list[dict[str, Any]]) -> bool:
+ """Return True when any message content contains image blocks."""
+ for msg in messages:
+ content = msg.get("content")
+ if not isinstance(content, list):
+ continue
+ for item in content:
+ if isinstance(item, dict) and item.get("type") in {"image_url", "image"}:
+ return True
+ return False
+
+
+def strip_image_parts(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Replace image blocks with text placeholders for fallback retries."""
+ stripped: list[dict[str, Any]] = []
+ for msg in messages:
+ content = msg.get("content")
+ if not isinstance(content, list):
+ stripped.append(dict(msg))
+ continue
+ new_content: list[dict[str, Any]] = []
+ for item in content:
+ if isinstance(item, dict) and item.get("type") in {"image_url", "image"}:
+ image_url = item.get("image_url") or {}
+ url = image_url.get("url", "") if isinstance(image_url, dict) else ""
+ meta = item.get("_meta") or {}
+ filename = ""
+ if isinstance(meta, dict):
+ filename = str(meta.get("path") or meta.get("filename") or "")
+ new_content.append({"type": "text", "text": _image_placeholder(url, filename)})
+ else:
+ new_content.append(item)
+ stripped.append({**msg, "content": new_content})
+ return stripped
+
+
__all__ = [
"MultimodalResult",
+ "has_image_parts",
"prepare_multimodal_messages",
+ "strip_image_parts",
]
diff --git a/deeptutor/services/llm/provider_core/__init__.py b/deeptutor/services/llm/provider_core/__init__.py
new file mode 100644
index 000000000..344e99f74
--- /dev/null
+++ b/deeptutor/services/llm/provider_core/__init__.py
@@ -0,0 +1,20 @@
+"""Services-layer provider runtime used by both llm.factory and TutorBot."""
+
+from .anthropic_provider import AnthropicProvider
+from .azure_openai_provider import AzureOpenAIProvider
+from .base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
+from .github_copilot_provider import GitHubCopilotProvider
+from .openai_codex_provider import OpenAICodexProvider
+from .openai_compat_provider import OpenAICompatProvider
+
+__all__ = [
+ "AnthropicProvider",
+ "AzureOpenAIProvider",
+ "GenerationSettings",
+ "GitHubCopilotProvider",
+ "LLMProvider",
+ "LLMResponse",
+ "OpenAICodexProvider",
+ "OpenAICompatProvider",
+ "ToolCallRequest",
+]
diff --git a/deeptutor/services/llm/provider_core/anthropic_provider.py b/deeptutor/services/llm/provider_core/anthropic_provider.py
new file mode 100644
index 000000000..ef80d1c0c
--- /dev/null
+++ b/deeptutor/services/llm/provider_core/anthropic_provider.py
@@ -0,0 +1,520 @@
+"""Anthropic provider — direct SDK integration for Claude models.
+
+Handles message format conversion (OpenAI -> Anthropic Messages API),
+prompt caching, extended thinking, tool calls, and streaming.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import Awaitable, Callable
+import re
+import secrets
+import string
+from typing import Any
+
+import json_repair
+
+from deeptutor.services.llm.provider_core.base import LLMProvider, LLMResponse, ToolCallRequest
+
+_ALNUM = string.ascii_letters + string.digits
+
+
+def _gen_tool_id() -> str:
+ return "toolu_" + "".join(secrets.choice(_ALNUM) for _ in range(22))
+
+
+class AnthropicProvider(LLMProvider):
+ """LLM provider using the native Anthropic SDK for Claude models."""
+
+ def __init__(
+ self,
+ api_key: str | None = None,
+ api_base: str | None = None,
+ default_model: str = "claude-sonnet-4-20250514",
+ extra_headers: dict[str, str] | None = None,
+ supports_prompt_caching: bool = True,
+ ):
+ super().__init__(api_key, api_base)
+ self.default_model = default_model
+ self.extra_headers = extra_headers or {}
+ self._supports_prompt_caching = supports_prompt_caching
+
+ from anthropic import AsyncAnthropic
+ from deeptutor.services.llm.utils import sanitize_url
+
+ client_kw: dict[str, Any] = {"max_retries": 0}
+ if api_key:
+ client_kw["api_key"] = api_key
+ if api_base:
+ client_kw["base_url"] = sanitize_url(api_base)
+ if extra_headers:
+ client_kw["default_headers"] = extra_headers
+ self._client = AsyncAnthropic(**client_kw)
+
+ @classmethod
+ def _handle_error(cls, e: Exception) -> LLMResponse:
+ payload = (
+ getattr(e, "body", None)
+ or getattr(e, "doc", None)
+ or getattr(getattr(e, "response", None), "text", None)
+ )
+ payload_text = (
+ payload if isinstance(payload, str) else str(payload) if payload is not None else ""
+ )
+ msg = (
+ f"Error: {payload_text.strip()[:500]}"
+ if payload_text.strip()
+ else f"Error calling LLM: {e}"
+ )
+ return LLMResponse(content=msg, finish_reason="error")
+
+ @staticmethod
+ def _strip_prefix(model: str) -> str:
+ if model.startswith("anthropic/"):
+ return model[len("anthropic/") :]
+ return model
+
+ # ------------------------------------------------------------------
+ # Message conversion: OpenAI chat format -> Anthropic Messages API
+ # ------------------------------------------------------------------
+
+ def _convert_messages(
+ self,
+ messages: list[dict[str, Any]],
+ ) -> tuple[str | list[dict[str, Any]], list[dict[str, Any]]]:
+ """Return ``(system, anthropic_messages)``."""
+ system: str | list[dict[str, Any]] = ""
+ raw: list[dict[str, Any]] = []
+
+ for msg in messages:
+ role = msg.get("role", "")
+ content = msg.get("content")
+
+ if role == "system":
+ system = content if isinstance(content, (str, list)) else str(content or "")
+ continue
+
+ if role == "tool":
+ block = self._tool_result_block(msg)
+ if raw and raw[-1]["role"] == "user":
+ prev_c = raw[-1]["content"]
+ if isinstance(prev_c, list):
+ prev_c.append(block)
+ else:
+ raw[-1]["content"] = [
+ {"type": "text", "text": prev_c or ""},
+ block,
+ ]
+ else:
+ raw.append({"role": "user", "content": [block]})
+ continue
+
+ if role == "assistant":
+ raw.append({"role": "assistant", "content": self._assistant_blocks(msg)})
+ continue
+
+ if role == "user":
+ raw.append(
+ {
+ "role": "user",
+ "content": self._convert_user_content(content),
+ }
+ )
+ continue
+
+ return system, self._merge_consecutive(raw)
+
+ @staticmethod
+ def _tool_result_block(msg: dict[str, Any]) -> dict[str, Any]:
+ content = msg.get("content")
+ block: dict[str, Any] = {
+ "type": "tool_result",
+ "tool_use_id": msg.get("tool_call_id", ""),
+ }
+ if isinstance(content, (str, list)):
+ block["content"] = content
+ else:
+ block["content"] = str(content) if content else ""
+ return block
+
+ @staticmethod
+ def _assistant_blocks(msg: dict[str, Any]) -> list[dict[str, Any]]:
+ blocks: list[dict[str, Any]] = []
+ content = msg.get("content")
+
+ for tb in msg.get("thinking_blocks") or []:
+ if isinstance(tb, dict) and tb.get("type") == "thinking":
+ blocks.append(
+ {
+ "type": "thinking",
+ "thinking": tb.get("thinking", ""),
+ "signature": tb.get("signature", ""),
+ }
+ )
+
+ if isinstance(content, str) and content:
+ blocks.append({"type": "text", "text": content})
+ elif isinstance(content, list):
+ for item in content:
+ blocks.append(
+ item if isinstance(item, dict) else {"type": "text", "text": str(item)}
+ )
+
+ for tc in msg.get("tool_calls") or []:
+ if not isinstance(tc, dict):
+ continue
+ func = tc.get("function", {})
+ args = func.get("arguments", "{}")
+ if isinstance(args, str):
+ args = json_repair.loads(args)
+ blocks.append(
+ {
+ "type": "tool_use",
+ "id": tc.get("id") or _gen_tool_id(),
+ "name": func.get("name", ""),
+ "input": args,
+ }
+ )
+
+ return blocks or [{"type": "text", "text": ""}]
+
+ def _convert_user_content(self, content: Any) -> Any:
+ if isinstance(content, str) or content is None:
+ return content or "(empty)"
+ if not isinstance(content, list):
+ return str(content)
+
+ result: list[dict[str, Any]] = []
+ for item in content:
+ if not isinstance(item, dict):
+ result.append({"type": "text", "text": str(item)})
+ continue
+ if item.get("type") == "image_url":
+ converted = self._convert_image_block(item)
+ if converted:
+ result.append(converted)
+ continue
+ result.append(item)
+ return result or "(empty)"
+
+ @staticmethod
+ def _convert_image_block(block: dict[str, Any]) -> dict[str, Any] | None:
+ url = (block.get("image_url") or {}).get("url", "")
+ if not url:
+ return None
+ m = re.match(r"data:(image/\w+);base64,(.+)", url, re.DOTALL)
+ if m:
+ return {
+ "type": "image",
+ "source": {"type": "base64", "media_type": m.group(1), "data": m.group(2)},
+ }
+ return {
+ "type": "image",
+ "source": {"type": "url", "url": url},
+ }
+
+ @staticmethod
+ def _merge_consecutive(msgs: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Anthropic requires alternating user/assistant roles."""
+ merged: list[dict[str, Any]] = []
+ for msg in msgs:
+ if merged and merged[-1]["role"] == msg["role"]:
+ prev_c = merged[-1]["content"]
+ cur_c = msg["content"]
+ if isinstance(prev_c, str):
+ prev_c = [{"type": "text", "text": prev_c}]
+ if isinstance(cur_c, str):
+ cur_c = [{"type": "text", "text": cur_c}]
+ if isinstance(cur_c, list):
+ prev_c.extend(cur_c)
+ merged[-1]["content"] = prev_c
+ else:
+ merged.append(msg)
+ return merged
+
+ # ------------------------------------------------------------------
+ # Tool definition conversion
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def _convert_tools(tools: list[dict[str, Any]] | None) -> list[dict[str, Any]] | None:
+ if not tools:
+ return None
+ result = []
+ for tool in tools:
+ func = tool.get("function", tool)
+ entry: dict[str, Any] = {
+ "name": func.get("name", ""),
+ "input_schema": func.get("parameters", {"type": "object", "properties": {}}),
+ }
+ desc = func.get("description")
+ if desc:
+ entry["description"] = desc
+ if "cache_control" in tool:
+ entry["cache_control"] = tool["cache_control"]
+ result.append(entry)
+ return result
+
+ @staticmethod
+ def _convert_tool_choice(
+ tool_choice: str | dict[str, Any] | None,
+ thinking_enabled: bool = False,
+ ) -> dict[str, Any] | None:
+ if thinking_enabled:
+ return {"type": "auto"}
+ if tool_choice is None or tool_choice == "auto":
+ return {"type": "auto"}
+ if tool_choice == "required":
+ return {"type": "any"}
+ if tool_choice == "none":
+ return None
+ if isinstance(tool_choice, dict):
+ name = tool_choice.get("function", {}).get("name")
+ if name:
+ return {"type": "tool", "name": name}
+ return {"type": "auto"}
+
+ # ------------------------------------------------------------------
+ # Prompt caching
+ # ------------------------------------------------------------------
+
+ @classmethod
+ def _apply_cache_control(
+ cls,
+ system: str | list[dict[str, Any]],
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None,
+ ) -> tuple[str | list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]] | None]:
+ marker = {"type": "ephemeral"}
+
+ if isinstance(system, str) and system:
+ system = [{"type": "text", "text": system, "cache_control": marker}]
+ elif isinstance(system, list) and system:
+ system = list(system)
+ system[-1] = {**system[-1], "cache_control": marker}
+
+ new_msgs = list(messages)
+ if len(new_msgs) >= 3:
+ m = new_msgs[-2]
+ c = m.get("content")
+ if isinstance(c, str):
+ new_msgs[-2] = {
+ **m,
+ "content": [{"type": "text", "text": c, "cache_control": marker}],
+ }
+ elif isinstance(c, list) and c:
+ nc = list(c)
+ nc[-1] = {**nc[-1], "cache_control": marker}
+ new_msgs[-2] = {**m, "content": nc}
+
+ new_tools = tools
+ if tools:
+ new_tools = list(tools)
+ for idx in cls._tool_cache_marker_indices(new_tools):
+ new_tools[idx] = {**new_tools[idx], "cache_control": marker}
+
+ return system, new_msgs, new_tools
+
+ # ------------------------------------------------------------------
+ # Build API kwargs
+ # ------------------------------------------------------------------
+
+ def _build_kwargs(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None,
+ model: str | None,
+ max_tokens: int,
+ temperature: float,
+ reasoning_effort: str | None,
+ tool_choice: str | dict[str, Any] | None,
+ ) -> dict[str, Any]:
+ model_name = self._strip_prefix(model or self.default_model)
+ system, anthropic_msgs = self._convert_messages(self._sanitize_empty_content(messages))
+ anthropic_tools = self._convert_tools(tools)
+
+ if self._supports_prompt_caching:
+ system, anthropic_msgs, anthropic_tools = self._apply_cache_control(
+ system,
+ anthropic_msgs,
+ anthropic_tools,
+ )
+
+ max_tokens = max(1, max_tokens)
+ thinking_enabled = bool(reasoning_effort)
+ omit_temperature = "opus-4-7" in model_name
+
+ kwargs: dict[str, Any] = {
+ "model": model_name,
+ "messages": anthropic_msgs,
+ "max_tokens": max_tokens,
+ }
+
+ if system:
+ kwargs["system"] = system
+
+ if reasoning_effort == "adaptive":
+ kwargs["thinking"] = {"type": "adaptive"}
+ if not omit_temperature:
+ kwargs["temperature"] = 1.0
+ elif thinking_enabled:
+ budget_map = {"low": 1024, "medium": 4096, "high": max(8192, max_tokens)}
+ budget = budget_map.get(reasoning_effort.lower(), 4096)
+ kwargs["thinking"] = {"type": "enabled", "budget_tokens": budget}
+ kwargs["max_tokens"] = max(max_tokens, budget + 4096)
+ if not omit_temperature:
+ kwargs["temperature"] = 1.0
+ elif not omit_temperature:
+ kwargs["temperature"] = temperature
+
+ if anthropic_tools:
+ kwargs["tools"] = anthropic_tools
+ tc = self._convert_tool_choice(tool_choice, thinking_enabled)
+ if tc:
+ kwargs["tool_choice"] = tc
+
+ if self.extra_headers:
+ kwargs["extra_headers"] = self.extra_headers
+
+ return kwargs
+
+ # ------------------------------------------------------------------
+ # Response parsing
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def _parse_response(response: Any) -> LLMResponse:
+ content_parts: list[str] = []
+ tool_calls: list[ToolCallRequest] = []
+ thinking_blocks: list[dict[str, Any]] = []
+
+ for block in response.content:
+ if block.type == "text":
+ content_parts.append(block.text)
+ elif block.type == "tool_use":
+ tool_calls.append(
+ ToolCallRequest(
+ id=block.id,
+ name=block.name,
+ arguments=block.input if isinstance(block.input, dict) else {},
+ )
+ )
+ elif block.type == "thinking":
+ thinking_blocks.append(
+ {
+ "type": "thinking",
+ "thinking": block.thinking,
+ "signature": getattr(block, "signature", ""),
+ }
+ )
+
+ stop_map = {"tool_use": "tool_calls", "end_turn": "stop", "max_tokens": "length"}
+ finish_reason = stop_map.get(response.stop_reason or "", response.stop_reason or "stop")
+
+ usage: dict[str, int] = {}
+ if response.usage:
+ input_tokens = response.usage.input_tokens
+ cache_creation = getattr(response.usage, "cache_creation_input_tokens", 0) or 0
+ cache_read = getattr(response.usage, "cache_read_input_tokens", 0) or 0
+ total_prompt = input_tokens + cache_creation + cache_read
+ usage = {
+ "prompt_tokens": total_prompt,
+ "completion_tokens": response.usage.output_tokens,
+ "total_tokens": total_prompt + response.usage.output_tokens,
+ }
+
+ return LLMResponse(
+ content="".join(content_parts) or None,
+ tool_calls=tool_calls,
+ finish_reason=finish_reason,
+ usage=usage,
+ thinking_blocks=thinking_blocks or None,
+ )
+
+ # ------------------------------------------------------------------
+ # Public API
+ # ------------------------------------------------------------------
+
+ async def chat(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ model: str | None = None,
+ max_tokens: int = 4096,
+ temperature: float = 0.7,
+ reasoning_effort: str | None = None,
+ tool_choice: str | dict[str, Any] | None = None,
+ **extra_kwargs: Any,
+ ) -> LLMResponse:
+ kwargs = self._build_kwargs(
+ messages,
+ tools,
+ model,
+ max_tokens,
+ temperature,
+ reasoning_effort,
+ tool_choice,
+ )
+ for key in ("response_format", "seed", "logit_bias", "stream", "stream_options"):
+ extra_kwargs.pop(key, None)
+ kwargs.update({k: v for k, v in extra_kwargs.items() if v is not None})
+ try:
+ response = await self._client.messages.create(**kwargs)
+ return self._parse_response(response)
+ except Exception as e:
+ return self._handle_error(e)
+
+ async def chat_stream(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ model: str | None = None,
+ max_tokens: int = 4096,
+ temperature: float = 0.7,
+ reasoning_effort: str | None = None,
+ tool_choice: str | dict[str, Any] | None = None,
+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,
+ **extra_kwargs: Any,
+ ) -> LLMResponse:
+ kwargs = self._build_kwargs(
+ messages,
+ tools,
+ model,
+ max_tokens,
+ temperature,
+ reasoning_effort,
+ tool_choice,
+ )
+ for key in ("response_format", "seed", "logit_bias", "stream", "stream_options"):
+ extra_kwargs.pop(key, None)
+ kwargs.update({k: v for k, v in extra_kwargs.items() if v is not None})
+ idle_timeout_s = 90
+ try:
+ async with self._client.messages.stream(**kwargs) as stream:
+ if on_content_delta:
+ stream_iter = stream.text_stream.__aiter__()
+ while True:
+ try:
+ text = await asyncio.wait_for(
+ stream_iter.__anext__(),
+ timeout=idle_timeout_s,
+ )
+ except StopAsyncIteration:
+ break
+ await on_content_delta(text)
+ response = await asyncio.wait_for(
+ stream.get_final_message(),
+ timeout=idle_timeout_s,
+ )
+ return self._parse_response(response)
+ except asyncio.TimeoutError:
+ return LLMResponse(
+ content=f"Error calling LLM: stream stalled for more than {idle_timeout_s} seconds",
+ finish_reason="error",
+ )
+ except Exception as e:
+ return self._handle_error(e)
+
+ def get_default_model(self) -> str:
+ return self.default_model
diff --git a/deeptutor/services/llm/provider_core/azure_openai_provider.py b/deeptutor/services/llm/provider_core/azure_openai_provider.py
new file mode 100644
index 000000000..ed190001a
--- /dev/null
+++ b/deeptutor/services/llm/provider_core/azure_openai_provider.py
@@ -0,0 +1,187 @@
+"""Azure OpenAI provider backed by the OpenAI SDK Responses API."""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import Awaitable, Callable
+from typing import Any
+import uuid
+
+from openai import AsyncOpenAI
+
+from deeptutor.services.llm.provider_core.base import LLMProvider, LLMResponse
+from deeptutor.services.llm.provider_core.openai_responses import (
+ consume_sdk_stream,
+ convert_messages,
+ convert_tools,
+ parse_response_output,
+)
+
+
+class AzureOpenAIProvider(LLMProvider):
+ """Azure OpenAI provider using the Responses API."""
+
+ def __init__(
+ self,
+ api_key: str = "",
+ api_base: str = "",
+ default_model: str = "gpt-5.2-chat",
+ extra_headers: dict[str, str] | None = None,
+ ):
+ super().__init__(api_key, api_base)
+ self.default_model = default_model
+ self.extra_headers = extra_headers or {}
+
+ if not api_key:
+ raise ValueError("Azure OpenAI api_key is required")
+ if not api_base:
+ raise ValueError("Azure OpenAI api_base is required")
+
+ base_url = api_base.rstrip("/")
+ if not base_url.endswith("/openai/v1"):
+ base_url = f"{base_url}/openai/v1"
+ base_url = f"{base_url.rstrip('/')}/"
+
+ headers = {"x-session-affinity": uuid.uuid4().hex}
+ if extra_headers:
+ headers.update(extra_headers)
+
+ self._client = AsyncOpenAI(
+ api_key=api_key,
+ base_url=base_url,
+ default_headers=headers,
+ max_retries=0,
+ )
+
+ @staticmethod
+ def _supports_temperature(
+ deployment_name: str,
+ reasoning_effort: str | None = None,
+ ) -> bool:
+ if reasoning_effort and reasoning_effort.lower() != "none":
+ return False
+ name = deployment_name.lower()
+ return not any(token in name for token in ("gpt-5", "o1", "o3", "o4"))
+
+ def _build_body(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None,
+ model: str | None,
+ max_tokens: int,
+ temperature: float,
+ reasoning_effort: str | None,
+ tool_choice: str | dict[str, Any] | None,
+ ) -> dict[str, Any]:
+ deployment = model or self.default_model
+ instructions, input_items = convert_messages(self._sanitize_empty_content(messages))
+
+ body: dict[str, Any] = {
+ "model": deployment,
+ "instructions": instructions or None,
+ "input": input_items,
+ "max_output_tokens": max(1, max_tokens),
+ "store": False,
+ "stream": False,
+ }
+ if self._supports_temperature(deployment, reasoning_effort):
+ body["temperature"] = temperature
+ if reasoning_effort and reasoning_effort.lower() != "none":
+ body["reasoning"] = {"effort": reasoning_effort}
+ body["include"] = ["reasoning.encrypted_content"]
+ if tools:
+ body["tools"] = convert_tools(tools)
+ body["tool_choice"] = tool_choice or "auto"
+ return body
+
+ @staticmethod
+ def _handle_error(exc: Exception) -> LLMResponse:
+ response = getattr(exc, "response", None)
+ body = getattr(exc, "body", None) or getattr(response, "text", None)
+ body_text = str(body).strip() if body is not None else ""
+ message = f"Error: {body_text[:500]}" if body_text else f"Error calling Azure OpenAI: {exc}"
+ return LLMResponse(content=message, finish_reason="error")
+
+ async def chat(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ model: str | None = None,
+ max_tokens: int = 4096,
+ temperature: float = 0.7,
+ reasoning_effort: str | None = None,
+ tool_choice: str | dict[str, Any] | None = None,
+ **extra_kwargs: Any,
+ ) -> LLMResponse:
+ body = self._build_body(
+ messages,
+ tools,
+ model,
+ max_tokens,
+ temperature,
+ reasoning_effort,
+ tool_choice,
+ )
+ body.update({k: v for k, v in extra_kwargs.items() if v is not None})
+ try:
+ return parse_response_output(await self._client.responses.create(**body))
+ except Exception as exc:
+ return self._handle_error(exc)
+
+ async def chat_stream(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ model: str | None = None,
+ max_tokens: int = 4096,
+ temperature: float = 0.7,
+ reasoning_effort: str | None = None,
+ tool_choice: str | dict[str, Any] | None = None,
+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,
+ **extra_kwargs: Any,
+ ) -> LLMResponse:
+ body = self._build_body(
+ messages,
+ tools,
+ model,
+ max_tokens,
+ temperature,
+ reasoning_effort,
+ tool_choice,
+ )
+ body.update({k: v for k, v in extra_kwargs.items() if v is not None})
+ body["stream"] = True
+ idle_timeout_s = 90
+
+ try:
+ stream = await self._client.responses.create(**body)
+
+ async def _timed_stream():
+ stream_iter = stream.__aiter__()
+ while True:
+ try:
+ yield await asyncio.wait_for(stream_iter.__anext__(), timeout=idle_timeout_s)
+ except StopAsyncIteration:
+ break
+
+ content, tool_calls, finish_reason, usage, reasoning_content = await consume_sdk_stream(
+ _timed_stream(),
+ on_content_delta,
+ )
+ return LLMResponse(
+ content=content or None,
+ tool_calls=tool_calls,
+ finish_reason=finish_reason,
+ usage=usage,
+ reasoning_content=reasoning_content,
+ )
+ except asyncio.TimeoutError:
+ return LLMResponse(
+ content=f"Error calling Azure OpenAI: stream stalled for more than {idle_timeout_s} seconds",
+ finish_reason="error",
+ )
+ except Exception as exc:
+ return self._handle_error(exc)
+
+ def get_default_model(self) -> str:
+ return self.default_model
diff --git a/deeptutor/services/llm/provider_core/base.py b/deeptutor/services/llm/provider_core/base.py
new file mode 100644
index 000000000..6a948c524
--- /dev/null
+++ b/deeptutor/services/llm/provider_core/base.py
@@ -0,0 +1,462 @@
+"""Base LLM provider interface."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+import asyncio
+from dataclasses import dataclass, field
+import json
+from typing import Any
+from collections.abc import Awaitable, Callable, Sequence
+
+from loguru import logger
+
+
+@dataclass
+class ToolCallRequest:
+ """A tool call request from the LLM."""
+
+ id: str
+ name: str
+ arguments: dict[str, Any]
+ provider_specific_fields: dict[str, Any] | None = None
+ function_provider_specific_fields: dict[str, Any] | None = None
+
+ def to_openai_tool_call(self) -> dict[str, Any]:
+ """Serialize to an OpenAI-style tool_call payload."""
+ tool_call: dict[str, Any] = {
+ "id": self.id,
+ "type": "function",
+ "function": {
+ "name": self.name,
+ "arguments": json.dumps(self.arguments, ensure_ascii=False),
+ },
+ }
+ if self.provider_specific_fields:
+ tool_call["provider_specific_fields"] = self.provider_specific_fields
+ if self.function_provider_specific_fields:
+ tool_call["function"]["provider_specific_fields"] = (
+ self.function_provider_specific_fields
+ )
+ return tool_call
+
+
+@dataclass
+class LLMResponse:
+ """Response from an LLM provider."""
+
+ content: str | None
+ tool_calls: list[ToolCallRequest] = field(default_factory=list)
+ finish_reason: str = "stop"
+ usage: dict[str, int] = field(default_factory=dict)
+ reasoning_content: str | None = None
+ thinking_blocks: list[dict[str, Any]] | None = None
+
+ @property
+ def has_tool_calls(self) -> bool:
+ """Check if response contains tool calls."""
+ return len(self.tool_calls) > 0
+
+
+@dataclass(frozen=True)
+class GenerationSettings:
+ """Default generation parameters for LLM calls."""
+
+ temperature: float = 0.7
+ max_tokens: int = 4096
+ reasoning_effort: str | None = None
+
+
+class LLMProvider(ABC):
+ """Abstract base class for LLM providers."""
+
+ _CHAT_RETRY_DELAYS = (1, 2, 4)
+ _TRANSIENT_ERROR_MARKERS = (
+ "429",
+ "rate limit",
+ "500",
+ "502",
+ "503",
+ "504",
+ "overloaded",
+ "timeout",
+ "timed out",
+ "connection",
+ "server error",
+ "temporarily unavailable",
+ )
+ _IMAGE_BLOCK_TYPES = frozenset({"image_url", "image"})
+ _SENTINEL = object()
+
+ @staticmethod
+ def _coerce_int(value: object, default: int) -> int:
+ if isinstance(value, bool):
+ return default
+ if isinstance(value, int):
+ return value
+ if isinstance(value, (str, bytes, bytearray)):
+ try:
+ return int(value)
+ except ValueError:
+ return default
+ return default
+
+ @staticmethod
+ def _coerce_float(value: object, default: float) -> float:
+ if isinstance(value, bool):
+ return default
+ if isinstance(value, (int, float)):
+ return float(value)
+ if isinstance(value, (str, bytes, bytearray)):
+ try:
+ return float(value)
+ except ValueError:
+ return default
+ return default
+
+ def __init__(self, api_key: str | None = None, api_base: str | None = None):
+ self.api_key = api_key
+ self.api_base = api_base
+ self.generation: GenerationSettings = GenerationSettings()
+
+ @staticmethod
+ def _sanitize_empty_content(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Replace empty text content that causes provider 400 errors."""
+ result: list[dict[str, Any]] = []
+ for msg in messages:
+ content = msg.get("content")
+
+ if isinstance(content, str) and not content:
+ clean = dict(msg)
+ clean["content"] = (
+ None
+ if (msg.get("role") == "assistant" and msg.get("tool_calls"))
+ else "(empty)"
+ )
+ result.append(clean)
+ continue
+
+ if isinstance(content, list):
+ filtered = [
+ item
+ for item in content
+ if not (
+ isinstance(item, dict)
+ and item.get("type") in ("text", "input_text", "output_text")
+ and not item.get("text")
+ )
+ ]
+ if len(filtered) != len(content):
+ clean = dict(msg)
+ if filtered:
+ clean["content"] = filtered
+ elif msg.get("role") == "assistant" and msg.get("tool_calls"):
+ clean["content"] = None
+ else:
+ clean["content"] = "(empty)"
+ result.append(clean)
+ continue
+
+ if isinstance(content, dict):
+ clean = dict(msg)
+ clean["content"] = [content]
+ result.append(clean)
+ continue
+
+ result.append(msg)
+ return result
+
+ @staticmethod
+ def _tool_cache_marker_indices(tools: list[dict[str, Any]]) -> list[int]:
+ """Return indices of tool definitions that should get cache_control markers."""
+ n = len(tools)
+ if n == 0:
+ return []
+ if n <= 5:
+ return [n - 1]
+ return [i for i in range(n - 1, -1, -5)]
+
+ @staticmethod
+ def _sanitize_request_messages(
+ messages: list[dict[str, Any]],
+ allowed_keys: frozenset[str],
+ ) -> list[dict[str, Any]]:
+ """Keep only provider-safe message keys and normalize assistant content."""
+ sanitized = []
+ for msg in messages:
+ clean = {k: v for k, v in msg.items() if k in allowed_keys}
+ if clean.get("role") == "assistant" and "content" not in clean:
+ clean["content"] = None
+ sanitized.append(clean)
+ return sanitized
+
+ @staticmethod
+ def _image_placeholder(block: dict[str, Any]) -> str:
+ meta = block.get("_meta") or {}
+ label = ""
+ if isinstance(meta, dict):
+ label = str(meta.get("path") or meta.get("filename") or "").strip()
+ if not label and block.get("type") == "image_url":
+ image_url = block.get("image_url") or {}
+ if isinstance(image_url, dict):
+ url = str(image_url.get("url") or "").strip()
+ if url and not url.startswith("data:"):
+ label = url
+ return f"[image: {label}]" if label else "[image omitted]"
+
+ @classmethod
+ def _strip_image_content(cls, messages: list[dict[str, Any]]) -> list[dict[str, Any]] | None:
+ """Replace image blocks with text placeholders."""
+ found = False
+ stripped: list[dict[str, Any]] = []
+ for msg in messages:
+ content = msg.get("content")
+ if not isinstance(content, list):
+ stripped.append(dict(msg))
+ continue
+ new_content: list[dict[str, Any]] = []
+ for block in content:
+ if isinstance(block, dict) and block.get("type") in cls._IMAGE_BLOCK_TYPES:
+ new_content.append({"type": "text", "text": cls._image_placeholder(block)})
+ found = True
+ else:
+ new_content.append(block)
+ stripped.append({**msg, "content": new_content})
+ return stripped if found else None
+
+ @classmethod
+ def _strip_image_content_inplace(cls, messages: list[dict[str, Any]]) -> bool:
+ """Replace image blocks with text placeholders in-place."""
+ found = False
+ for msg in messages:
+ content = msg.get("content")
+ if not isinstance(content, list):
+ continue
+ for idx, block in enumerate(content):
+ if isinstance(block, dict) and block.get("type") in cls._IMAGE_BLOCK_TYPES:
+ content[idx] = {"type": "text", "text": cls._image_placeholder(block)}
+ found = True
+ return found
+
+ @staticmethod
+ def _normalize_retry_delays(retry_delays: Sequence[float] | None) -> tuple[float, ...]:
+ if retry_delays is None:
+ return tuple(float(delay) for delay in LLMProvider._CHAT_RETRY_DELAYS)
+ normalized: list[float] = []
+ for delay in retry_delays:
+ try:
+ value = float(delay)
+ except (TypeError, ValueError):
+ continue
+ if value > 0:
+ normalized.append(value)
+ return tuple(normalized)
+
+ @abstractmethod
+ async def chat(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ model: str | None = None,
+ max_tokens: int = 4096,
+ temperature: float = 0.7,
+ reasoning_effort: str | None = None,
+ tool_choice: str | dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> LLMResponse:
+ """Send a chat completion request."""
+
+ async def chat_stream(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ model: str | None = None,
+ max_tokens: int = 4096,
+ temperature: float = 0.7,
+ reasoning_effort: str | None = None,
+ tool_choice: str | dict[str, Any] | None = None,
+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,
+ **kwargs: Any,
+ ) -> LLMResponse:
+ """Fallback streaming implementation that emits the full response once."""
+ response = await self.chat(
+ messages=messages,
+ tools=tools,
+ model=model,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ reasoning_effort=reasoning_effort,
+ tool_choice=tool_choice,
+ **kwargs,
+ )
+ if on_content_delta and response.content:
+ await on_content_delta(response.content)
+ return response
+
+ @classmethod
+ def _is_transient_error(cls, content: str | None) -> bool:
+ err = (content or "").lower()
+ return any(marker in err for marker in cls._TRANSIENT_ERROR_MARKERS)
+
+ async def _call_with_retry(
+ self,
+ call: Callable[..., Awaitable[LLMResponse]],
+ *,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None,
+ model: str | None,
+ max_tokens: int,
+ temperature: float,
+ reasoning_effort: str | None,
+ tool_choice: str | dict[str, Any] | None,
+ retry_delays: Sequence[float] | None,
+ **kwargs: Any,
+ ) -> LLMResponse:
+ delays = self._normalize_retry_delays(retry_delays)
+ attempt = 0
+
+ while True:
+ attempt += 1
+ try:
+ response = await call(
+ messages=messages,
+ tools=tools,
+ model=model,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ reasoning_effort=reasoning_effort,
+ tool_choice=tool_choice,
+ **kwargs,
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc:
+ response = LLMResponse(
+ content=f"Error calling LLM: {exc}",
+ finish_reason="error",
+ )
+
+ if response.finish_reason != "error":
+ return response
+
+ if not self._is_transient_error(response.content):
+ stripped = self._strip_image_content(messages)
+ if stripped is not None:
+ logger.warning(
+ "Non-transient LLM error with image content, retrying once without images"
+ )
+ retry_response = await call(
+ messages=stripped,
+ tools=tools,
+ model=model,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ reasoning_effort=reasoning_effort,
+ tool_choice=tool_choice,
+ **kwargs,
+ )
+ if retry_response.finish_reason != "error":
+ self._strip_image_content_inplace(messages)
+ return retry_response
+ return response
+
+ if attempt > len(delays):
+ return response
+
+ delay = delays[attempt - 1]
+ logger.warning(
+ "LLM transient error (attempt {}/{}), retrying in {}s: {}",
+ attempt,
+ len(delays) + 1,
+ delay,
+ (response.content or "")[:120].lower(),
+ )
+ await asyncio.sleep(delay)
+
+ async def chat_with_retry(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ model: str | None = None,
+ max_tokens: object = _SENTINEL,
+ temperature: object = _SENTINEL,
+ reasoning_effort: object = _SENTINEL,
+ tool_choice: str | dict[str, Any] | None = None,
+ retry_delays: Sequence[float] | None = None,
+ **kwargs: Any,
+ ) -> LLMResponse:
+ """Call chat() with retry on transient provider failures."""
+ if max_tokens is self._SENTINEL:
+ max_tokens = self.generation.max_tokens
+ if temperature is self._SENTINEL:
+ temperature = self.generation.temperature
+ if reasoning_effort is self._SENTINEL:
+ reasoning_effort = self.generation.reasoning_effort
+
+ resolved_max_tokens = self._coerce_int(max_tokens, self.generation.max_tokens)
+ resolved_temperature = self._coerce_float(temperature, self.generation.temperature)
+ resolved_reasoning_effort = (
+ reasoning_effort
+ if reasoning_effort is None or isinstance(reasoning_effort, str)
+ else None
+ )
+
+ return await self._call_with_retry(
+ self.chat,
+ messages=messages,
+ tools=tools,
+ model=model,
+ max_tokens=resolved_max_tokens,
+ temperature=resolved_temperature,
+ reasoning_effort=resolved_reasoning_effort,
+ tool_choice=tool_choice,
+ retry_delays=retry_delays,
+ **kwargs,
+ )
+
+ async def chat_stream_with_retry(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ model: str | None = None,
+ max_tokens: object = _SENTINEL,
+ temperature: object = _SENTINEL,
+ reasoning_effort: object = _SENTINEL,
+ tool_choice: str | dict[str, Any] | None = None,
+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,
+ retry_delays: Sequence[float] | None = None,
+ **kwargs: Any,
+ ) -> LLMResponse:
+ """Call chat_stream() with the same transient retry policy as chat()."""
+ if max_tokens is self._SENTINEL:
+ max_tokens = self.generation.max_tokens
+ if temperature is self._SENTINEL:
+ temperature = self.generation.temperature
+ if reasoning_effort is self._SENTINEL:
+ reasoning_effort = self.generation.reasoning_effort
+
+ resolved_max_tokens = self._coerce_int(max_tokens, self.generation.max_tokens)
+ resolved_temperature = self._coerce_float(temperature, self.generation.temperature)
+ resolved_reasoning_effort = (
+ reasoning_effort
+ if reasoning_effort is None or isinstance(reasoning_effort, str)
+ else None
+ )
+
+ return await self._call_with_retry(
+ self.chat_stream,
+ messages=messages,
+ tools=tools,
+ model=model,
+ max_tokens=resolved_max_tokens,
+ temperature=resolved_temperature,
+ reasoning_effort=resolved_reasoning_effort,
+ tool_choice=tool_choice,
+ retry_delays=retry_delays,
+ on_content_delta=on_content_delta,
+ **kwargs,
+ )
+
+ @abstractmethod
+ def get_default_model(self) -> str:
+ """Get the default model for this provider."""
diff --git a/deeptutor/services/llm/provider_core/github_copilot_provider.py b/deeptutor/services/llm/provider_core/github_copilot_provider.py
new file mode 100644
index 000000000..7bee1d7fa
--- /dev/null
+++ b/deeptutor/services/llm/provider_core/github_copilot_provider.py
@@ -0,0 +1,214 @@
+"""GitHub Copilot provider with graceful fallback to existing local auth."""
+
+from __future__ import annotations
+
+import time
+from collections.abc import Awaitable, Callable
+from typing import Any
+
+import httpx
+from openai import AuthenticationError
+
+from deeptutor.services.llm.provider_core.openai_compat_provider import OpenAICompatProvider
+from deeptutor.services.provider_registry import find_by_name
+
+DEFAULT_COPILOT_BASE_URL = "https://api.githubcopilot.com"
+DEFAULT_COPILOT_TOKEN_URL = "https://api.github.com/copilot_internal/v2/token"
+USER_AGENT = "DeepTutor/1"
+EDITOR_VERSION = "vscode/1.99.0"
+EDITOR_PLUGIN_VERSION = "copilot-chat/0.26.0"
+_EXPIRY_SKEW_SECONDS = 60
+
+
+class GitHubCopilotProvider(OpenAICompatProvider):
+ """Provider that first tries existing Copilot auth, then oauth-cli-kit tokens."""
+
+ def __init__(self, default_model: str = "github-copilot/gpt-4.1"):
+ self._copilot_access_token: str | None = None
+ self._copilot_expires_at: float = 0.0
+ super().__init__(
+ api_key="copilot",
+ api_base=DEFAULT_COPILOT_BASE_URL,
+ default_model=default_model,
+ extra_headers={
+ "Editor-Version": EDITOR_VERSION,
+ "Editor-Plugin-Version": EDITOR_PLUGIN_VERSION,
+ "User-Agent": USER_AGENT,
+ },
+ spec=find_by_name("github_copilot"),
+ provider_name="github_copilot",
+ )
+
+ async def _try_existing_local_auth(self) -> None:
+ self.api_key = "copilot"
+ self._client.api_key = "copilot"
+
+ async def _load_stored_github_token(self) -> str | None:
+ try:
+ from oauth_cli_kit.storage import FileTokenStorage
+ except ImportError:
+ return None
+ storage = FileTokenStorage(
+ token_filename="github-copilot.json",
+ app_name="nanobot",
+ import_codex_cli=False,
+ )
+ token = storage.load()
+ if not token or not getattr(token, "access", None):
+ return None
+ return str(token.access)
+
+ async def _exchange_token(self) -> str:
+ github_token = await self._load_stored_github_token()
+ if not github_token:
+ raise RuntimeError(
+ "GitHub Copilot auth is unavailable. Validate local Copilot auth or log in first."
+ )
+
+ timeout = httpx.Timeout(20.0, connect=20.0)
+ async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, trust_env=True) as client:
+ response = await client.get(
+ DEFAULT_COPILOT_TOKEN_URL,
+ headers={
+ "Authorization": f"token {github_token}",
+ "Accept": "application/json",
+ "User-Agent": USER_AGENT,
+ "Editor-Version": EDITOR_VERSION,
+ "Editor-Plugin-Version": EDITOR_PLUGIN_VERSION,
+ },
+ )
+ response.raise_for_status()
+ payload = response.json()
+
+ token = payload.get("token")
+ if not token:
+ raise RuntimeError("GitHub Copilot token exchange returned no token.")
+ expires_at = payload.get("expires_at")
+ if isinstance(expires_at, (int, float)):
+ self._copilot_expires_at = float(expires_at)
+ else:
+ refresh_in = payload.get("refresh_in") or 1500
+ self._copilot_expires_at = time.time() + int(refresh_in)
+ self._copilot_access_token = str(token)
+ return self._copilot_access_token
+
+ async def _ensure_api_key(self) -> None:
+ now = time.time()
+ if self._copilot_access_token and now < self._copilot_expires_at - _EXPIRY_SKEW_SECONDS:
+ self.api_key = self._copilot_access_token
+ self._client.api_key = self._copilot_access_token
+ return
+
+ await self._try_existing_local_auth()
+
+ async def _chat_impl(
+ self,
+ stream: bool,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None,
+ model: str | None,
+ max_tokens: int,
+ temperature: float,
+ reasoning_effort: str | None,
+ tool_choice: str | dict[str, Any] | None,
+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,
+ **kwargs: Any,
+ ):
+ await self._ensure_api_key()
+ try:
+ if stream:
+ return await super().chat_stream(
+ messages=messages,
+ tools=tools,
+ model=model,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ reasoning_effort=reasoning_effort,
+ tool_choice=tool_choice,
+ on_content_delta=on_content_delta,
+ **kwargs,
+ )
+ return await super().chat(
+ messages=messages,
+ tools=tools,
+ model=model,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ reasoning_effort=reasoning_effort,
+ tool_choice=tool_choice,
+ **kwargs,
+ )
+ except AuthenticationError:
+ token = await self._exchange_token()
+ self.api_key = token
+ self._client.api_key = token
+ if stream:
+ return await super().chat_stream(
+ messages=messages,
+ tools=tools,
+ model=model,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ reasoning_effort=reasoning_effort,
+ tool_choice=tool_choice,
+ on_content_delta=on_content_delta,
+ **kwargs,
+ )
+ return await super().chat(
+ messages=messages,
+ tools=tools,
+ model=model,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ reasoning_effort=reasoning_effort,
+ tool_choice=tool_choice,
+ **kwargs,
+ )
+
+ async def chat(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ model: str | None = None,
+ max_tokens: int = 4096,
+ temperature: float = 0.7,
+ reasoning_effort: str | None = None,
+ tool_choice: str | dict[str, Any] | None = None,
+ **kwargs: Any,
+ ):
+ return await self._chat_impl(
+ False,
+ messages,
+ tools,
+ model,
+ max_tokens,
+ temperature,
+ reasoning_effort,
+ tool_choice,
+ **kwargs,
+ )
+
+ async def chat_stream(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ model: str | None = None,
+ max_tokens: int = 4096,
+ temperature: float = 0.7,
+ reasoning_effort: str | None = None,
+ tool_choice: str | dict[str, Any] | None = None,
+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,
+ **kwargs: Any,
+ ):
+ return await self._chat_impl(
+ True,
+ messages,
+ tools,
+ model,
+ max_tokens,
+ temperature,
+ reasoning_effort,
+ tool_choice,
+ on_content_delta,
+ **kwargs,
+ )
diff --git a/deeptutor/services/llm/provider_core/openai_codex_provider.py b/deeptutor/services/llm/provider_core/openai_codex_provider.py
new file mode 100644
index 000000000..77fc94a8e
--- /dev/null
+++ b/deeptutor/services/llm/provider_core/openai_codex_provider.py
@@ -0,0 +1,178 @@
+"""OpenAI Codex Responses provider backed by oauth-cli-kit."""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import json
+from collections.abc import Awaitable, Callable
+from typing import Any
+
+import httpx
+from loguru import logger
+
+from deeptutor.services.llm.provider_core.base import LLMProvider, LLMResponse, ToolCallRequest
+from deeptutor.services.llm.provider_core.openai_responses import consume_sse, convert_messages, convert_tools
+
+DEFAULT_CODEX_URL = "https://chatgpt.com/backend-api/codex/responses"
+DEFAULT_ORIGINATOR = "DeepTutor"
+
+
+class OpenAICodexProvider(LLMProvider):
+ """Use OpenAI Codex OAuth tokens to call the Responses API."""
+
+ def __init__(self, default_model: str = "openai-codex/gpt-5.1-codex"):
+ super().__init__(api_key=None, api_base=None)
+ self.default_model = default_model
+
+ async def _load_token(self) -> Any:
+ try:
+ from oauth_cli_kit import get_token as get_codex_token
+ except ImportError as exc: # pragma: no cover - optional dependency
+ raise RuntimeError(
+ "oauth_cli_kit is not installed. Install CLI deps or switch provider."
+ ) from exc
+ return await asyncio.to_thread(get_codex_token)
+
+ async def _call_codex(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None,
+ model: str | None,
+ reasoning_effort: str | None,
+ tool_choice: str | dict[str, Any] | None,
+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,
+ ) -> LLMResponse:
+ model_name = model or self.default_model
+ system_prompt, input_items = convert_messages(messages)
+
+ token = await self._load_token()
+ headers = _build_headers(getattr(token, "account_id", None), getattr(token, "access", None))
+
+ body: dict[str, Any] = {
+ "model": _strip_model_prefix(model_name),
+ "store": False,
+ "stream": True,
+ "instructions": system_prompt,
+ "input": input_items,
+ "text": {"verbosity": "medium"},
+ "include": ["reasoning.encrypted_content"],
+ "prompt_cache_key": _prompt_cache_key(messages),
+ "tool_choice": tool_choice or "auto",
+ "parallel_tool_calls": True,
+ }
+ if reasoning_effort:
+ body["reasoning"] = {"effort": reasoning_effort}
+ if tools:
+ body["tools"] = convert_tools(tools)
+
+ try:
+ try:
+ content, tool_calls, finish_reason = await _request_codex(
+ DEFAULT_CODEX_URL,
+ headers,
+ body,
+ verify=True,
+ on_content_delta=on_content_delta,
+ )
+ except Exception as exc:
+ if "CERTIFICATE_VERIFY_FAILED" not in str(exc):
+ raise
+ logger.warning("SSL verification failed for Codex API; retrying with verify=False")
+ content, tool_calls, finish_reason = await _request_codex(
+ DEFAULT_CODEX_URL,
+ headers,
+ body,
+ verify=False,
+ on_content_delta=on_content_delta,
+ )
+ return LLMResponse(content=content, tool_calls=tool_calls, finish_reason=finish_reason)
+ except Exception as exc:
+ return LLMResponse(content=f"Error calling Codex: {exc}", finish_reason="error")
+
+ async def chat(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ model: str | None = None,
+ max_tokens: int = 4096,
+ temperature: float = 0.7,
+ reasoning_effort: str | None = None,
+ tool_choice: str | dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> LLMResponse:
+ del max_tokens, temperature, kwargs
+ return await self._call_codex(messages, tools, model, reasoning_effort, tool_choice)
+
+ async def chat_stream(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ model: str | None = None,
+ max_tokens: int = 4096,
+ temperature: float = 0.7,
+ reasoning_effort: str | None = None,
+ tool_choice: str | dict[str, Any] | None = None,
+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,
+ **kwargs: Any,
+ ) -> LLMResponse:
+ del max_tokens, temperature, kwargs
+ return await self._call_codex(
+ messages,
+ tools,
+ model,
+ reasoning_effort,
+ tool_choice,
+ on_content_delta,
+ )
+
+ def get_default_model(self) -> str:
+ return self.default_model
+
+
+def _strip_model_prefix(model: str) -> str:
+ if model.startswith("openai-codex/") or model.startswith("openai_codex/"):
+ return model.split("/", 1)[1]
+ return model
+
+
+def _build_headers(account_id: Any, token: Any) -> dict[str, str]:
+ if not token:
+ raise RuntimeError("OpenAI Codex is not logged in. Run `deeptutor provider login openai-codex`.")
+ headers = {
+ "Authorization": f"Bearer {token}",
+ "OpenAI-Beta": "responses=experimental",
+ "originator": DEFAULT_ORIGINATOR,
+ "User-Agent": "DeepTutor (python)",
+ "accept": "text/event-stream",
+ "content-type": "application/json",
+ }
+ if account_id:
+ headers["chatgpt-account-id"] = str(account_id)
+ return headers
+
+
+async def _request_codex(
+ url: str,
+ headers: dict[str, str],
+ body: dict[str, Any],
+ verify: bool,
+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,
+) -> tuple[str, list[ToolCallRequest], str]:
+ async with httpx.AsyncClient(timeout=60.0, verify=verify) as client:
+ async with client.stream("POST", url, headers=headers, json=body) as response:
+ if response.status_code != 200:
+ text = await response.aread()
+ raise RuntimeError(_friendly_error(response.status_code, text.decode("utf-8", "ignore")))
+ return await consume_sse(response, on_content_delta)
+
+
+def _prompt_cache_key(messages: list[dict[str, Any]]) -> str:
+ raw = json.dumps(messages, ensure_ascii=True, sort_keys=True)
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()
+
+
+def _friendly_error(status_code: int, raw: str) -> str:
+ if status_code == 429:
+ return "ChatGPT usage quota exceeded or rate limit triggered. Please try again later."
+ return f"HTTP {status_code}: {raw}"
diff --git a/deeptutor/services/llm/provider_core/openai_compat_provider.py b/deeptutor/services/llm/provider_core/openai_compat_provider.py
new file mode 100644
index 000000000..7d8e3b914
--- /dev/null
+++ b/deeptutor/services/llm/provider_core/openai_compat_provider.py
@@ -0,0 +1,848 @@
+"""OpenAI-compatible provider for all non-Anthropic LLM APIs.
+
+Uses the official ``openai.AsyncOpenAI`` SDK to talk to any OpenAI-compatible
+endpoint (OpenAI, DeepSeek, Gemini, Moonshot, MiniMax, gateways, local, etc.).
+"""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import Awaitable, Callable
+import hashlib
+import time
+import secrets
+import string
+from typing import TYPE_CHECKING, Any
+import uuid
+
+import json_repair
+from openai import AsyncOpenAI
+
+from deeptutor.services.llm.capabilities import disable_response_format_at_runtime
+from deeptutor.services.llm.provider_core.base import LLMProvider, LLMResponse, ToolCallRequest
+from deeptutor.services.llm.provider_core.openai_responses import (
+ consume_sdk_stream,
+ convert_messages,
+ convert_tools,
+ parse_response_output,
+)
+
+if TYPE_CHECKING:
+ from deeptutor.services.provider_registry import ProviderSpec
+
+_ALLOWED_MSG_KEYS = frozenset(
+ {
+ "role",
+ "content",
+ "tool_calls",
+ "tool_call_id",
+ "name",
+ "reasoning_content",
+ "extra_content",
+ }
+)
+_ALNUM = string.ascii_letters + string.digits
+
+_DEFAULT_OPENROUTER_HEADERS = {
+ "HTTP-Referer": "https://github.com/HKUDS/DeepTutor",
+ "X-OpenRouter-Title": "DeepTutor",
+}
+_RESPONSES_FAILURE_THRESHOLD = 2
+_RESPONSES_PROBE_INTERVAL_S = 300.0
+_THINKING_STYLE_MAP = {
+ "thinking_type": lambda enabled: {
+ "thinking": {"type": "enabled" if enabled else "disabled"}
+ },
+ "enable_thinking": lambda enabled: {"enable_thinking": enabled},
+ "reasoning_split": lambda enabled: {"reasoning_split": enabled},
+}
+
+
+def _short_tool_id() -> str:
+ """9-char alphanumeric ID compatible with all providers (incl. Mistral)."""
+ return "".join(secrets.choice(_ALNUM) for _ in range(9))
+
+
+def _get(obj: Any, key: str) -> Any:
+ if isinstance(obj, dict):
+ return obj.get(key)
+ return getattr(obj, key, None)
+
+
+def _coerce_dict(value: Any) -> dict[str, Any] | None:
+ if value is None:
+ return None
+ if isinstance(value, dict):
+ return value if value else None
+ model_dump = getattr(value, "model_dump", None)
+ if callable(model_dump):
+ dumped = model_dump()
+ if isinstance(dumped, dict) and dumped:
+ return dumped
+ return None
+
+
+def _uses_openrouter(spec: "ProviderSpec | None", api_base: str | None) -> bool:
+ if spec and spec.name == "openrouter":
+ return True
+ return bool(api_base and "openrouter" in api_base.lower())
+
+
+def _is_direct_openai_base(api_base: str | None) -> bool:
+ if not api_base:
+ return False
+ base = api_base.lower()
+ return "api.openai.com" in base
+
+
+def _responses_circuit_key(
+ model: str | None,
+ default_model: str,
+ reasoning_effort: str | None,
+) -> str:
+ model_name = (model or default_model or "").strip().lower()
+ effort = (reasoning_effort or "").strip().lower() or "none"
+ return f"{model_name}|{effort}"
+
+
+class OpenAICompatProvider(LLMProvider):
+ """Unified provider for all OpenAI-compatible APIs.
+
+ Receives a resolved ``ProviderSpec`` from the caller — no internal
+ registry lookups needed.
+ """
+
+ def __init__(
+ self,
+ api_key: str | None = None,
+ api_base: str | None = None,
+ default_model: str = "gpt-4o",
+ extra_headers: dict[str, str] | None = None,
+ spec: Any = None,
+ provider_name: str | None = None,
+ ):
+ super().__init__(api_key, api_base)
+ self.default_model = default_model
+ self.extra_headers = extra_headers or {}
+ self._spec = spec
+ self._provider_name = provider_name
+
+ if api_key and spec and spec.env_key:
+ self._setup_env(api_key, api_base)
+
+ effective_base = api_base or (spec.default_api_base if spec else None) or None
+ self._effective_base = effective_base
+ default_headers: dict[str, str] = {"x-session-affinity": uuid.uuid4().hex}
+ if _uses_openrouter(spec, effective_base):
+ default_headers.update(_DEFAULT_OPENROUTER_HEADERS)
+ if extra_headers:
+ default_headers.update(extra_headers)
+
+ self._client = AsyncOpenAI(
+ api_key=api_key or "no-key",
+ base_url=effective_base,
+ default_headers=default_headers,
+ max_retries=0,
+ )
+ self._responses_failures: dict[str, int] = {}
+ self._responses_tripped_at: dict[str, float] = {}
+
+ def _setup_env(self, api_key: str, api_base: str | None) -> None:
+ import os
+
+ spec = self._spec
+ if not spec or not spec.env_key:
+ return
+ if spec.is_gateway:
+ os.environ[spec.env_key] = api_key
+ else:
+ os.environ.setdefault(spec.env_key, api_key)
+ effective_base = api_base or spec.default_api_base
+ for env_name, env_val in spec.env_extras:
+ resolved = env_val.replace("{api_key}", api_key).replace(
+ "{api_base}", effective_base or ""
+ )
+ os.environ.setdefault(env_name, resolved)
+
+ # ------------------------------------------------------------------
+ # Prompt caching
+ # ------------------------------------------------------------------
+
+ @classmethod
+ def _apply_cache_control(
+ cls,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None,
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]] | None]:
+ cache_marker = {"type": "ephemeral"}
+ new_messages = list(messages)
+
+ def _mark(msg: dict[str, Any]) -> dict[str, Any]:
+ content = msg.get("content")
+ if isinstance(content, str):
+ return {
+ **msg,
+ "content": [
+ {"type": "text", "text": content, "cache_control": cache_marker},
+ ],
+ }
+ if isinstance(content, list) and content:
+ nc = list(content)
+ nc[-1] = {**nc[-1], "cache_control": cache_marker}
+ return {**msg, "content": nc}
+ return msg
+
+ if new_messages and new_messages[0].get("role") == "system":
+ new_messages[0] = _mark(new_messages[0])
+ if len(new_messages) >= 3:
+ new_messages[-2] = _mark(new_messages[-2])
+
+ new_tools = tools
+ if tools:
+ new_tools = list(tools)
+ for idx in cls._tool_cache_marker_indices(new_tools):
+ new_tools[idx] = {**new_tools[idx], "cache_control": cache_marker}
+ return new_messages, new_tools
+
+ # ------------------------------------------------------------------
+ # Message sanitization
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def _normalize_tool_call_id(tool_call_id: Any) -> Any:
+ if not isinstance(tool_call_id, str):
+ return tool_call_id
+ if len(tool_call_id) == 9 and tool_call_id.isalnum():
+ return tool_call_id
+ return hashlib.sha256(tool_call_id.encode()).hexdigest()[:9]
+
+ def _sanitize_messages(self, messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ sanitized = LLMProvider._sanitize_request_messages(messages, _ALLOWED_MSG_KEYS)
+ id_map: dict[str, str] = {}
+
+ def map_id(value: Any) -> Any:
+ if not isinstance(value, str):
+ return value
+ return id_map.setdefault(value, self._normalize_tool_call_id(value))
+
+ for clean in sanitized:
+ if isinstance(clean.get("tool_calls"), list):
+ normalized = []
+ for tc in clean["tool_calls"]:
+ if not isinstance(tc, dict):
+ normalized.append(tc)
+ continue
+ tc_clean = dict(tc)
+ tc_clean["id"] = map_id(tc_clean.get("id"))
+ normalized.append(tc_clean)
+ clean["tool_calls"] = normalized
+ if "tool_call_id" in clean and clean["tool_call_id"]:
+ clean["tool_call_id"] = map_id(clean["tool_call_id"])
+ return sanitized
+
+ # ------------------------------------------------------------------
+ # Build kwargs
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def _supports_temperature(
+ model_name: str,
+ reasoning_effort: str | None = None,
+ ) -> bool:
+ if reasoning_effort and reasoning_effort.lower() != "none":
+ return False
+ name = model_name.lower()
+ return not any(token in name for token in ("gpt-5", "o1", "o3", "o4"))
+
+ def _build_kwargs(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None,
+ model: str | None,
+ max_tokens: int,
+ temperature: float,
+ reasoning_effort: str | None,
+ tool_choice: str | dict[str, Any] | None,
+ ) -> dict[str, Any]:
+ model_name = model or self.default_model
+ spec = self._spec
+
+ if spec and spec.supports_prompt_caching:
+ if any(model_name.lower().startswith(k) for k in ("anthropic/", "claude")):
+ messages, tools = self._apply_cache_control(messages, tools)
+
+ if spec and spec.strip_model_prefix:
+ model_name = model_name.split("/")[-1]
+
+ kwargs: dict[str, Any] = {
+ "model": model_name,
+ "messages": self._sanitize_messages(self._sanitize_empty_content(messages)),
+ }
+
+ if self._supports_temperature(model_name, reasoning_effort):
+ kwargs["temperature"] = temperature
+
+ if spec and getattr(spec, "supports_max_completion_tokens", False):
+ kwargs["max_completion_tokens"] = max(1, max_tokens)
+ else:
+ kwargs["max_tokens"] = max(1, max_tokens)
+
+ if spec:
+ model_lower = model_name.lower()
+ for pattern, overrides in spec.model_overrides:
+ if pattern in model_lower:
+ kwargs.update(overrides)
+ break
+
+ semantic_effort: str | None = None
+ if isinstance(reasoning_effort, str):
+ semantic_effort = reasoning_effort.lower()
+ if semantic_effort == "minimum":
+ semantic_effort = "minimal"
+
+ wire_effort = reasoning_effort
+ if spec and spec.name == "dashscope" and semantic_effort == "minimal":
+ wire_effort = "minimum"
+
+ if wire_effort:
+ kwargs["reasoning_effort"] = wire_effort
+
+ if spec and spec.thinking_style and reasoning_effort is not None:
+ thinking_enabled = semantic_effort != "minimal"
+ extra = _THINKING_STYLE_MAP.get(spec.thinking_style, lambda _enabled: None)(
+ thinking_enabled
+ )
+ if extra:
+ kwargs.setdefault("extra_body", {}).update(extra)
+
+ if tools:
+ kwargs["tools"] = tools
+ kwargs["tool_choice"] = tool_choice or "auto"
+
+ return kwargs
+
+ def _should_use_responses_api(
+ self,
+ model: str | None,
+ reasoning_effort: str | None,
+ ) -> bool:
+ spec = self._spec
+ if spec and spec.name not in {"openai", "github_copilot"}:
+ return False
+ if spec is None or spec.name != "github_copilot":
+ if not _is_direct_openai_base(self._effective_base):
+ return False
+
+ model_name = (model or self.default_model).lower()
+ wants_reasoning = bool(reasoning_effort and reasoning_effort.lower() != "none")
+ wants_responses = wants_reasoning or any(
+ token in model_name for token in ("gpt-5", "o1", "o3", "o4")
+ )
+ if not wants_responses:
+ return False
+
+ circuit_key = _responses_circuit_key(model, self.default_model, reasoning_effort)
+ failures = self._responses_failures.get(circuit_key, 0)
+ if failures >= _RESPONSES_FAILURE_THRESHOLD:
+ tripped_at = self._responses_tripped_at.get(circuit_key, 0.0)
+ if (time.monotonic() - tripped_at) < _RESPONSES_PROBE_INTERVAL_S:
+ return False
+ return True
+
+ def _record_responses_failure(self, model: str | None, reasoning_effort: str | None) -> None:
+ circuit_key = _responses_circuit_key(model, self.default_model, reasoning_effort)
+ failures = self._responses_failures.get(circuit_key, 0) + 1
+ self._responses_failures[circuit_key] = failures
+ if failures >= _RESPONSES_FAILURE_THRESHOLD:
+ self._responses_tripped_at[circuit_key] = time.monotonic()
+
+ def _record_responses_success(self, model: str | None, reasoning_effort: str | None) -> None:
+ circuit_key = _responses_circuit_key(model, self.default_model, reasoning_effort)
+ self._responses_failures.pop(circuit_key, None)
+ self._responses_tripped_at.pop(circuit_key, None)
+
+ @staticmethod
+ def _should_fallback_from_responses_error(exc: Exception) -> bool:
+ response = getattr(exc, "response", None)
+ status_code = getattr(exc, "status_code", None)
+ if status_code is None and response is not None:
+ status_code = getattr(response, "status_code", None)
+ if status_code not in {400, 404, 422}:
+ return False
+
+ body = (
+ getattr(exc, "body", None)
+ or getattr(exc, "doc", None)
+ or getattr(response, "text", None)
+ )
+ body_text = str(body).lower() if body is not None else ""
+ return any(
+ marker in body_text
+ for marker in (
+ "responses",
+ "response api",
+ "max_output_tokens",
+ "instructions",
+ "previous_response",
+ "unknown parameter",
+ "unrecognized request argument",
+ "unsupported",
+ "not supported",
+ )
+ )
+
+ @staticmethod
+ def _is_response_format_error(exc: Exception) -> bool:
+ text = str(getattr(exc, "body", None) or getattr(exc, "message", None) or exc).lower()
+ if "response_format" not in text and "response format" not in text:
+ return False
+ return any(
+ marker in text
+ for marker in (
+ "not supported",
+ "unsupported",
+ "json_object",
+ "json_schema",
+ "must be 'json_schema' or 'text'",
+ "specified for 'response_format.type' is not valid",
+ )
+ )
+
+ def _build_responses_body(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None,
+ model: str | None,
+ max_tokens: int,
+ temperature: float,
+ reasoning_effort: str | None,
+ tool_choice: str | dict[str, Any] | None,
+ ) -> dict[str, Any]:
+ model_name = model or self.default_model
+ if self._spec and self._spec.strip_model_prefix:
+ model_name = model_name.split("/")[-1]
+
+ instructions, input_items = convert_messages(
+ self._sanitize_messages(self._sanitize_empty_content(messages))
+ )
+ body: dict[str, Any] = {
+ "model": model_name,
+ "instructions": instructions or None,
+ "input": input_items,
+ "max_output_tokens": max(1, max_tokens),
+ "store": False,
+ "stream": False,
+ }
+
+ if self._supports_temperature(model_name, reasoning_effort):
+ body["temperature"] = temperature
+ if reasoning_effort and reasoning_effort.lower() != "none":
+ body["reasoning"] = {"effort": reasoning_effort}
+ body["include"] = ["reasoning.encrypted_content"]
+ if tools:
+ body["tools"] = convert_tools(tools)
+ body["tool_choice"] = tool_choice or "auto"
+ return body
+
+ # ------------------------------------------------------------------
+ # Response parsing
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def _maybe_mapping(value: Any) -> dict[str, Any] | None:
+ if isinstance(value, dict):
+ return value
+ model_dump = getattr(value, "model_dump", None)
+ if callable(model_dump):
+ dumped = model_dump()
+ if isinstance(dumped, dict):
+ return dumped
+ return None
+
+ @classmethod
+ def _extract_text_content(cls, value: Any) -> str | None:
+ if value is None:
+ return None
+ if isinstance(value, str):
+ return value
+ if isinstance(value, list):
+ parts: list[str] = []
+ for item in value:
+ item_map = cls._maybe_mapping(item)
+ if item_map:
+ text = item_map.get("text")
+ if isinstance(text, str):
+ parts.append(text)
+ continue
+ text = getattr(item, "text", None)
+ if isinstance(text, str):
+ parts.append(text)
+ continue
+ if isinstance(item, str):
+ parts.append(item)
+ return "".join(parts) or None
+ return str(value)
+
+ @classmethod
+ def _extract_usage(cls, response: Any) -> dict[str, int]:
+ usage_obj = None
+ response_map = cls._maybe_mapping(response)
+ if response_map is not None:
+ usage_obj = response_map.get("usage")
+ elif hasattr(response, "usage") and response.usage:
+ usage_obj = response.usage
+
+ usage_map = cls._maybe_mapping(usage_obj)
+ if usage_map is not None:
+ return {
+ "prompt_tokens": int(usage_map.get("prompt_tokens") or 0),
+ "completion_tokens": int(usage_map.get("completion_tokens") or 0),
+ "total_tokens": int(usage_map.get("total_tokens") or 0),
+ }
+ if usage_obj:
+ return {
+ "prompt_tokens": getattr(usage_obj, "prompt_tokens", 0) or 0,
+ "completion_tokens": getattr(usage_obj, "completion_tokens", 0) or 0,
+ "total_tokens": getattr(usage_obj, "total_tokens", 0) or 0,
+ }
+ return {}
+
+ def _parse(self, response: Any) -> LLMResponse:
+ if isinstance(response, str):
+ return LLMResponse(content=response, finish_reason="stop")
+
+ if not response.choices:
+ return LLMResponse(content="Error: API returned empty choices.", finish_reason="error")
+
+ choice = response.choices[0]
+ msg = choice.message
+ content = msg.content
+ finish_reason = choice.finish_reason
+
+ raw_tool_calls: list[Any] = []
+ for ch in response.choices:
+ m = ch.message
+ if hasattr(m, "tool_calls") and m.tool_calls:
+ raw_tool_calls.extend(m.tool_calls)
+ if ch.finish_reason in ("tool_calls", "stop"):
+ finish_reason = ch.finish_reason
+ if not content and m.content:
+ content = m.content
+ if not content and getattr(m, "reasoning", None):
+ content = m.reasoning
+
+ tool_calls = []
+ for tc in raw_tool_calls:
+ args = tc.function.arguments
+ if isinstance(args, str):
+ args = json_repair.loads(args)
+ tool_calls.append(
+ ToolCallRequest(
+ id=_short_tool_id(),
+ name=tc.function.name,
+ arguments=args if isinstance(args, dict) else {},
+ provider_specific_fields=getattr(tc, "provider_specific_fields", None) or None,
+ function_provider_specific_fields=(
+ getattr(tc.function, "provider_specific_fields", None) or None
+ ),
+ )
+ )
+
+ reasoning_content = getattr(msg, "reasoning_content", None) or None
+ if not reasoning_content and getattr(msg, "reasoning", None):
+ reasoning_content = msg.reasoning
+
+ usage = self._extract_usage(response)
+
+ return LLMResponse(
+ content=content,
+ tool_calls=tool_calls,
+ finish_reason=finish_reason or "stop",
+ usage=usage,
+ reasoning_content=reasoning_content,
+ )
+
+ @classmethod
+ def _parse_chunks(cls, chunks: list[Any]) -> LLMResponse:
+ content_parts: list[str] = []
+ reasoning_parts: list[str] = []
+ tc_bufs: dict[int, dict[str, Any]] = {}
+ finish_reason = "stop"
+ usage: dict[str, int] = {}
+
+ def _accum_tc(tc: Any, idx_hint: int) -> None:
+ tc_index: int = _get(tc, "index") if _get(tc, "index") is not None else idx_hint
+ buf = tc_bufs.setdefault(
+ tc_index,
+ {
+ "id": "",
+ "name": "",
+ "arguments": "",
+ },
+ )
+ tc_id = _get(tc, "id")
+ if tc_id:
+ buf["id"] = str(tc_id)
+ fn = _get(tc, "function")
+ if fn is not None:
+ fn_name = _get(fn, "name")
+ if fn_name:
+ buf["name"] = str(fn_name)
+ fn_args = _get(fn, "arguments")
+ if fn_args:
+ buf["arguments"] += str(fn_args)
+
+ for chunk in chunks:
+ if isinstance(chunk, str):
+ content_parts.append(chunk)
+ continue
+
+ if not chunk.choices:
+ usage = cls._extract_usage(chunk) or usage
+ continue
+ choice = chunk.choices[0]
+ if choice.finish_reason:
+ finish_reason = choice.finish_reason
+ delta = choice.delta
+ if delta and delta.content:
+ content_parts.append(delta.content)
+ if delta:
+ reasoning = getattr(delta, "reasoning_content", None)
+ if not reasoning:
+ reasoning = getattr(delta, "reasoning", None)
+ if reasoning:
+ reasoning_parts.append(reasoning)
+ for tc in (delta.tool_calls or []) if delta else []:
+ _accum_tc(tc, getattr(tc, "index", 0))
+
+ return LLMResponse(
+ content="".join(content_parts) or None,
+ tool_calls=[
+ ToolCallRequest(
+ id=b["id"] or _short_tool_id(),
+ name=b["name"],
+ arguments=json_repair.loads(b["arguments"]) if b["arguments"] else {},
+ )
+ for b in tc_bufs.values()
+ ],
+ finish_reason=finish_reason,
+ usage=usage,
+ reasoning_content="".join(reasoning_parts) or None,
+ )
+
+ @staticmethod
+ def _handle_error(e: Exception) -> LLMResponse:
+ body = (
+ getattr(e, "doc", None)
+ or getattr(e, "body", None)
+ or getattr(getattr(e, "response", None), "text", None)
+ )
+ body_text = body if isinstance(body, str) else str(body) if body is not None else ""
+ msg = (
+ f"Error: {body_text.strip()[:500]}" if body_text.strip() else f"Error calling LLM: {e}"
+ )
+ return LLMResponse(content=msg, finish_reason="error")
+
+ # ------------------------------------------------------------------
+ # Public API
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def _is_tool_format_error(e: Exception) -> bool:
+ """Detect errors caused by strict tool-argument JSON validation.
+
+ Some endpoints (e.g. DashScope Coding Plan) reject non-streaming
+ tool calls with 400 when the model produces malformed arguments.
+ Streaming avoids this because the SDK accumulates tokens into a
+ well-formed response.
+ """
+ text = str(getattr(e, "body", None) or getattr(e, "message", None) or e).lower()
+ return any(
+ kw in text
+ for kw in (
+ "function.arguments",
+ "must be in json format",
+ "invalid.*parameter.*function",
+ )
+ )
+
+ async def chat(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ model: str | None = None,
+ max_tokens: int = 4096,
+ temperature: float = 0.7,
+ reasoning_effort: str | None = None,
+ tool_choice: str | dict[str, Any] | None = None,
+ **extra_kwargs: Any,
+ ) -> LLMResponse:
+ try:
+ if self._should_use_responses_api(model, reasoning_effort):
+ try:
+ body = self._build_responses_body(
+ messages,
+ tools,
+ model,
+ max_tokens,
+ temperature,
+ reasoning_effort,
+ tool_choice,
+ )
+ body.update({k: v for k, v in extra_kwargs.items() if v is not None})
+ result = parse_response_output(await self._client.responses.create(**body))
+ self._record_responses_success(model, reasoning_effort)
+ return result
+ except Exception as responses_error:
+ if self._spec and self._spec.name == "github_copilot":
+ raise
+ if not self._should_fallback_from_responses_error(responses_error):
+ raise
+ self._record_responses_failure(model, reasoning_effort)
+
+ request_kwargs = self._build_kwargs(
+ messages,
+ tools,
+ model,
+ max_tokens,
+ temperature,
+ reasoning_effort,
+ tool_choice,
+ )
+ request_kwargs.update({k: v for k, v in extra_kwargs.items() if v is not None})
+ try:
+ return self._parse(await self._client.chat.completions.create(**request_kwargs))
+ except Exception as exc:
+ if request_kwargs.get("response_format") is not None and self._is_response_format_error(
+ exc
+ ):
+ binding = self._provider_name or (self._spec.name if self._spec else "openai")
+ disable_response_format_at_runtime(binding, request_kwargs.get("model"))
+ retry_kwargs = dict(request_kwargs)
+ retry_kwargs.pop("response_format", None)
+ return self._parse(await self._client.chat.completions.create(**retry_kwargs))
+ raise
+ except Exception as e:
+ if tools and self._is_tool_format_error(e):
+ return await self.chat_stream(
+ messages,
+ tools,
+ model,
+ max_tokens,
+ temperature,
+ reasoning_effort,
+ tool_choice,
+ **extra_kwargs,
+ )
+ return self._handle_error(e)
+
+ async def chat_stream(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[dict[str, Any]] | None = None,
+ model: str | None = None,
+ max_tokens: int = 4096,
+ temperature: float = 0.7,
+ reasoning_effort: str | None = None,
+ tool_choice: str | dict[str, Any] | None = None,
+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,
+ **extra_kwargs: Any,
+ ) -> LLMResponse:
+ request_kwargs = self._build_kwargs(
+ messages,
+ tools,
+ model,
+ max_tokens,
+ temperature,
+ reasoning_effort,
+ tool_choice,
+ )
+ request_kwargs.update({k: v for k, v in extra_kwargs.items() if v is not None})
+ idle_timeout_s = 90
+ try:
+ if self._should_use_responses_api(model, reasoning_effort):
+ try:
+ body = self._build_responses_body(
+ messages,
+ tools,
+ model,
+ max_tokens,
+ temperature,
+ reasoning_effort,
+ tool_choice,
+ )
+ body.update({k: v for k, v in extra_kwargs.items() if v is not None})
+ body["stream"] = True
+ stream = await self._client.responses.create(**body)
+
+ async def _timed_stream():
+ stream_iter = stream.__aiter__()
+ while True:
+ try:
+ yield await asyncio.wait_for(
+ stream_iter.__anext__(),
+ timeout=idle_timeout_s,
+ )
+ except StopAsyncIteration:
+ break
+
+ content, tool_calls, finish_reason, usage, reasoning_content = (
+ await consume_sdk_stream(_timed_stream(), on_content_delta)
+ )
+ self._record_responses_success(model, reasoning_effort)
+ return LLMResponse(
+ content=content or None,
+ tool_calls=tool_calls,
+ finish_reason=finish_reason,
+ usage=usage,
+ reasoning_content=reasoning_content,
+ )
+ except Exception as responses_error:
+ if self._spec and self._spec.name == "github_copilot":
+ raise
+ if not self._should_fallback_from_responses_error(responses_error):
+ raise
+ self._record_responses_failure(model, reasoning_effort)
+
+ request_kwargs["stream"] = True
+ request_kwargs["stream_options"] = {"include_usage": True}
+ try:
+ stream = await self._client.chat.completions.create(**request_kwargs)
+ except Exception as exc:
+ if request_kwargs.get("response_format") is not None and self._is_response_format_error(
+ exc
+ ):
+ binding = self._provider_name or (self._spec.name if self._spec else "openai")
+ disable_response_format_at_runtime(binding, request_kwargs.get("model"))
+ retry_kwargs = dict(request_kwargs)
+ retry_kwargs.pop("response_format", None)
+ stream = await self._client.chat.completions.create(**retry_kwargs)
+ else:
+ raise
+
+ chunks: list[Any] = []
+ stream_iter = stream.__aiter__()
+ while True:
+ try:
+ chunk = await asyncio.wait_for(
+ stream_iter.__anext__(),
+ timeout=idle_timeout_s,
+ )
+ except StopAsyncIteration:
+ break
+ chunks.append(chunk)
+ if on_content_delta and chunk.choices:
+ text = getattr(chunk.choices[0].delta, "content", None)
+ if text:
+ await on_content_delta(text)
+ return self._parse_chunks(chunks)
+ except asyncio.TimeoutError:
+ return LLMResponse(
+ content=f"Error calling LLM: stream stalled for more than {idle_timeout_s} seconds",
+ finish_reason="error",
+ )
+ except Exception as e:
+ return self._handle_error(e)
+
+ def get_default_model(self) -> str:
+ return self.default_model
diff --git a/deeptutor/services/llm/provider_core/openai_responses/__init__.py b/deeptutor/services/llm/provider_core/openai_responses/__init__.py
new file mode 100644
index 000000000..b426a0561
--- /dev/null
+++ b/deeptutor/services/llm/provider_core/openai_responses/__init__.py
@@ -0,0 +1,24 @@
+"""Shared helpers for Responses API providers."""
+
+from .converters import convert_messages, convert_tools, convert_user_message, split_tool_call_id
+from .parsing import (
+ FINISH_REASON_MAP,
+ consume_sdk_stream,
+ consume_sse,
+ iter_sse,
+ map_finish_reason,
+ parse_response_output,
+)
+
+__all__ = [
+ "convert_messages",
+ "convert_tools",
+ "convert_user_message",
+ "split_tool_call_id",
+ "iter_sse",
+ "consume_sse",
+ "consume_sdk_stream",
+ "map_finish_reason",
+ "parse_response_output",
+ "FINISH_REASON_MAP",
+]
diff --git a/deeptutor/services/llm/provider_core/openai_responses/converters.py b/deeptutor/services/llm/provider_core/openai_responses/converters.py
new file mode 100644
index 000000000..aad414c32
--- /dev/null
+++ b/deeptutor/services/llm/provider_core/openai_responses/converters.py
@@ -0,0 +1,112 @@
+"""Convert Chat Completions messages/tools to Responses API format."""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+
+def convert_messages(messages: list[dict[str, Any]]) -> tuple[str, list[dict[str, Any]]]:
+ """Convert Chat Completions messages to Responses API input items."""
+ system_prompt = ""
+ input_items: list[dict[str, Any]] = []
+
+ for idx, msg in enumerate(messages):
+ role = msg.get("role")
+ content = msg.get("content")
+
+ if role == "system":
+ system_prompt = content if isinstance(content, str) else ""
+ continue
+
+ if role == "user":
+ input_items.append(convert_user_message(content))
+ continue
+
+ if role == "assistant":
+ if isinstance(content, str) and content:
+ input_items.append(
+ {
+ "type": "message",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": content}],
+ "status": "completed",
+ "id": f"msg_{idx}",
+ }
+ )
+ for tool_call in msg.get("tool_calls", []) or []:
+ fn = tool_call.get("function") or {}
+ call_id, item_id = split_tool_call_id(tool_call.get("id"))
+ input_items.append(
+ {
+ "type": "function_call",
+ "id": item_id or f"fc_{idx}",
+ "call_id": call_id or f"call_{idx}",
+ "name": fn.get("name"),
+ "arguments": fn.get("arguments") or "{}",
+ }
+ )
+ continue
+
+ if role == "tool":
+ call_id, _ = split_tool_call_id(msg.get("tool_call_id"))
+ output_text = (
+ content if isinstance(content, str) else json.dumps(content, ensure_ascii=False)
+ )
+ input_items.append(
+ {"type": "function_call_output", "call_id": call_id, "output": output_text}
+ )
+
+ return system_prompt, input_items
+
+
+def convert_user_message(content: Any) -> dict[str, Any]:
+ """Convert user message content to Responses API blocks."""
+ if isinstance(content, str):
+ return {"role": "user", "content": [{"type": "input_text", "text": content}]}
+ if isinstance(content, list):
+ converted: list[dict[str, Any]] = []
+ for item in content:
+ if not isinstance(item, dict):
+ continue
+ if item.get("type") == "text":
+ converted.append({"type": "input_text", "text": item.get("text", "")})
+ elif item.get("type") == "image_url":
+ url = (item.get("image_url") or {}).get("url")
+ if url:
+ converted.append(
+ {"type": "input_image", "image_url": url, "detail": "auto"}
+ )
+ if converted:
+ return {"role": "user", "content": converted}
+ return {"role": "user", "content": [{"type": "input_text", "text": ""}]}
+
+
+def convert_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Convert OpenAI function calling schemas to Responses API tools."""
+ converted: list[dict[str, Any]] = []
+ for tool in tools:
+ fn = (tool.get("function") or {}) if tool.get("type") == "function" else tool
+ name = fn.get("name")
+ if not name:
+ continue
+ params = fn.get("parameters") or {}
+ converted.append(
+ {
+ "type": "function",
+ "name": name,
+ "description": fn.get("description") or "",
+ "parameters": params if isinstance(params, dict) else {},
+ }
+ )
+ return converted
+
+
+def split_tool_call_id(tool_call_id: Any) -> tuple[str, str | None]:
+ """Split a compound call_id|item_id tool id."""
+ if isinstance(tool_call_id, str) and tool_call_id:
+ if "|" in tool_call_id:
+ call_id, item_id = tool_call_id.split("|", 1)
+ return call_id, item_id or None
+ return tool_call_id, None
+ return "call_0", None
diff --git a/deeptutor/services/llm/provider_core/openai_responses/parsing.py b/deeptutor/services/llm/provider_core/openai_responses/parsing.py
new file mode 100644
index 000000000..497fef940
--- /dev/null
+++ b/deeptutor/services/llm/provider_core/openai_responses/parsing.py
@@ -0,0 +1,282 @@
+"""Parse Responses API SSE streams and SDK response objects."""
+
+from __future__ import annotations
+
+import json
+from collections.abc import Awaitable, Callable
+from typing import Any, AsyncGenerator
+
+import httpx
+import json_repair
+from loguru import logger
+
+from deeptutor.services.llm.provider_core.base import LLMResponse, ToolCallRequest
+
+FINISH_REASON_MAP = {
+ "completed": "stop",
+ "incomplete": "length",
+ "failed": "error",
+ "cancelled": "error",
+}
+
+
+def map_finish_reason(status: str | None) -> str:
+ return FINISH_REASON_MAP.get(status or "completed", "stop")
+
+
+async def iter_sse(response: httpx.Response) -> AsyncGenerator[dict[str, Any], None]:
+ """Yield parsed JSON events from a Responses API SSE stream."""
+ buffer: list[str] = []
+
+ def _flush() -> dict[str, Any] | None:
+ data_lines = [line[5:].strip() for line in buffer if line.startswith("data:")]
+ buffer.clear()
+ if not data_lines:
+ return None
+ data = "\n".join(data_lines).strip()
+ if not data or data == "[DONE]":
+ return None
+ try:
+ return json.loads(data)
+ except Exception:
+ logger.warning("Failed to parse SSE event JSON: {}", data[:200])
+ return None
+
+ async for line in response.aiter_lines():
+ if line == "":
+ if buffer:
+ event = _flush()
+ if event is not None:
+ yield event
+ continue
+ buffer.append(line)
+
+ if buffer:
+ event = _flush()
+ if event is not None:
+ yield event
+
+
+async def consume_sse(
+ response: httpx.Response,
+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,
+) -> tuple[str, list[ToolCallRequest], str]:
+ """Consume a Responses API SSE stream."""
+ content = ""
+ tool_calls: list[ToolCallRequest] = []
+ tool_call_buffers: dict[str, dict[str, Any]] = {}
+ finish_reason = "stop"
+
+ async for event in iter_sse(response):
+ event_type = event.get("type")
+ if event_type == "response.output_item.added":
+ item = event.get("item") or {}
+ if item.get("type") == "function_call":
+ call_id = item.get("call_id")
+ if not call_id:
+ continue
+ tool_call_buffers[call_id] = {
+ "id": item.get("id") or "fc_0",
+ "name": item.get("name"),
+ "arguments": item.get("arguments") or "",
+ }
+ elif event_type == "response.output_text.delta":
+ delta_text = event.get("delta") or ""
+ content += delta_text
+ if on_content_delta and delta_text:
+ await on_content_delta(delta_text)
+ elif event_type == "response.function_call_arguments.delta":
+ call_id = event.get("call_id")
+ if call_id and call_id in tool_call_buffers:
+ tool_call_buffers[call_id]["arguments"] += event.get("delta") or ""
+ elif event_type == "response.function_call_arguments.done":
+ call_id = event.get("call_id")
+ if call_id and call_id in tool_call_buffers:
+ tool_call_buffers[call_id]["arguments"] = event.get("arguments") or ""
+ elif event_type == "response.output_item.done":
+ item = event.get("item") or {}
+ if item.get("type") == "function_call":
+ call_id = item.get("call_id")
+ if not call_id:
+ continue
+ buf = tool_call_buffers.get(call_id) or {}
+ args_raw = buf.get("arguments") or item.get("arguments") or "{}"
+ try:
+ args = json.loads(args_raw)
+ except Exception:
+ logger.warning(
+ "Failed to parse tool call arguments for '{}': {}",
+ buf.get("name") or item.get("name"),
+ args_raw[:200],
+ )
+ args = json_repair.loads(args_raw)
+ if not isinstance(args, dict):
+ args = {"raw": args_raw}
+ tool_calls.append(
+ ToolCallRequest(
+ id=f"{call_id}|{buf.get('id') or item.get('id') or 'fc_0'}",
+ name=buf.get("name") or item.get("name") or "",
+ arguments=args if isinstance(args, dict) else {},
+ )
+ )
+ elif event_type == "response.completed":
+ status = (event.get("response") or {}).get("status")
+ finish_reason = map_finish_reason(status)
+ elif event_type in {"error", "response.failed"}:
+ detail = event.get("error") or event.get("message") or event
+ raise RuntimeError(f"Response failed: {str(detail)[:500]}")
+
+ return content, tool_calls, finish_reason
+
+
+def parse_response_output(response: Any) -> LLMResponse:
+ """Parse an SDK Response object into LLMResponse."""
+ if not isinstance(response, dict):
+ dump = getattr(response, "model_dump", None)
+ response = dump() if callable(dump) else vars(response)
+
+ output = response.get("output") or []
+ content_parts: list[str] = []
+ tool_calls: list[ToolCallRequest] = []
+ reasoning_content: str | None = None
+
+ for item in output:
+ if not isinstance(item, dict):
+ dump = getattr(item, "model_dump", None)
+ item = dump() if callable(dump) else vars(item)
+
+ item_type = item.get("type")
+ if item_type == "message":
+ for block in item.get("content") or []:
+ if not isinstance(block, dict):
+ dump = getattr(block, "model_dump", None)
+ block = dump() if callable(dump) else vars(block)
+ if block.get("type") == "output_text":
+ content_parts.append(block.get("text") or "")
+ elif item_type == "reasoning":
+ for summary in item.get("summary") or []:
+ if not isinstance(summary, dict):
+ dump = getattr(summary, "model_dump", None)
+ summary = dump() if callable(dump) else vars(summary)
+ if summary.get("type") == "summary_text" and summary.get("text"):
+ reasoning_content = (reasoning_content or "") + summary["text"]
+ elif item_type == "function_call":
+ call_id = item.get("call_id") or ""
+ item_id = item.get("id") or "fc_0"
+ args_raw = item.get("arguments") or "{}"
+ try:
+ args = json.loads(args_raw) if isinstance(args_raw, str) else args_raw
+ except Exception:
+ logger.warning(
+ "Failed to parse tool call arguments for '{}': {}",
+ item.get("name"),
+ str(args_raw)[:200],
+ )
+ args = json_repair.loads(args_raw) if isinstance(args_raw, str) else args_raw
+ if not isinstance(args, dict):
+ args = {"raw": args_raw}
+ tool_calls.append(
+ ToolCallRequest(
+ id=f"{call_id}|{item_id}",
+ name=item.get("name") or "",
+ arguments=args if isinstance(args, dict) else {},
+ )
+ )
+
+ usage_raw = response.get("usage") or {}
+ if not isinstance(usage_raw, dict):
+ dump = getattr(usage_raw, "model_dump", None)
+ usage_raw = dump() if callable(dump) else vars(usage_raw)
+ usage = {}
+ if usage_raw:
+ usage = {
+ "prompt_tokens": int(usage_raw.get("input_tokens") or 0),
+ "completion_tokens": int(usage_raw.get("output_tokens") or 0),
+ "total_tokens": int(usage_raw.get("total_tokens") or 0),
+ }
+
+ finish_reason = map_finish_reason(response.get("status"))
+ return LLMResponse(
+ content="".join(content_parts) or None,
+ tool_calls=tool_calls,
+ finish_reason=finish_reason,
+ usage=usage,
+ reasoning_content=reasoning_content if isinstance(reasoning_content, str) else None,
+ )
+
+
+async def consume_sdk_stream(
+ stream: Any,
+ on_content_delta: Callable[[str], Awaitable[None]] | None = None,
+) -> tuple[str, list[ToolCallRequest], str, dict[str, int], str | None]:
+ """Consume an SDK async stream from client.responses.create(stream=True)."""
+ content = ""
+ tool_calls: list[ToolCallRequest] = []
+ tool_call_buffers: dict[str, dict[str, Any]] = {}
+ finish_reason = "stop"
+ usage: dict[str, int] = {}
+ reasoning_content: str | None = None
+
+ async for event in stream:
+ event_type = getattr(event, "type", None)
+ if event_type == "response.output_item.added":
+ item = getattr(event, "item", None)
+ if item and getattr(item, "type", None) == "function_call":
+ call_id = getattr(item, "call_id", None)
+ if not call_id:
+ continue
+ tool_call_buffers[call_id] = {
+ "id": getattr(item, "id", None) or "fc_0",
+ "name": getattr(item, "name", None),
+ "arguments": getattr(item, "arguments", None) or "",
+ }
+ elif event_type == "response.output_text.delta":
+ delta_text = getattr(event, "delta", "") or ""
+ content += delta_text
+ if on_content_delta and delta_text:
+ await on_content_delta(delta_text)
+ elif event_type == "response.function_call_arguments.delta":
+ call_id = getattr(event, "call_id", None)
+ if call_id and call_id in tool_call_buffers:
+ tool_call_buffers[call_id]["arguments"] += getattr(event, "delta", "") or ""
+ elif event_type == "response.function_call_arguments.done":
+ call_id = getattr(event, "call_id", None)
+ if call_id and call_id in tool_call_buffers:
+ tool_call_buffers[call_id]["arguments"] = getattr(event, "arguments", "") or ""
+ elif event_type == "response.output_item.done":
+ item = getattr(event, "item", None)
+ if item and getattr(item, "type", None) == "function_call":
+ call_id = getattr(item, "call_id", None)
+ if not call_id:
+ continue
+ buf = tool_call_buffers.get(call_id) or {}
+ args_raw = buf.get("arguments") or getattr(item, "arguments", None) or "{}"
+ try:
+ args = json.loads(args_raw) if isinstance(args_raw, str) else args_raw
+ except Exception:
+ args = json_repair.loads(args_raw) if isinstance(args_raw, str) else args_raw
+ if not isinstance(args, dict):
+ args = {"raw": args_raw}
+ tool_calls.append(
+ ToolCallRequest(
+ id=f"{call_id}|{buf.get('id') or getattr(item, 'id', None) or 'fc_0'}",
+ name=buf.get("name") or getattr(item, "name", None) or "",
+ arguments=args if isinstance(args, dict) else {},
+ )
+ )
+ elif event_type == "response.reasoning_summary_text.delta":
+ delta_text = getattr(event, "delta", "") or ""
+ reasoning_content = (reasoning_content or "") + delta_text
+ elif event_type == "response.completed":
+ response = getattr(event, "response", None)
+ status = getattr(response, "status", None) if response is not None else None
+ usage_obj = getattr(response, "usage", None) if response is not None else None
+ finish_reason = map_finish_reason(status)
+ if usage_obj is not None:
+ usage = {
+ "prompt_tokens": int(getattr(usage_obj, "input_tokens", 0) or 0),
+ "completion_tokens": int(getattr(usage_obj, "output_tokens", 0) or 0),
+ "total_tokens": int(getattr(usage_obj, "total_tokens", 0) or 0),
+ }
+
+ return content, tool_calls, finish_reason, usage, reasoning_content
diff --git a/deeptutor/services/llm/provider_factory.py b/deeptutor/services/llm/provider_factory.py
new file mode 100644
index 000000000..54de97dff
--- /dev/null
+++ b/deeptutor/services/llm/provider_factory.py
@@ -0,0 +1,59 @@
+"""Factory for services-layer provider runtime objects."""
+
+from __future__ import annotations
+
+from deeptutor.services.llm.config import LLMConfig, get_llm_config
+from deeptutor.services.llm.provider_core import (
+ AnthropicProvider,
+ AzureOpenAIProvider,
+ GenerationSettings,
+ GitHubCopilotProvider,
+ LLMProvider,
+ OpenAICodexProvider,
+ OpenAICompatProvider,
+)
+from deeptutor.services.provider_registry import find_by_name
+
+
+def get_runtime_provider(config: LLMConfig | None = None) -> LLMProvider:
+ """Build the authoritative services-layer provider for the supplied config."""
+ llm_config = config or get_llm_config()
+ provider_name = llm_config.provider_name or llm_config.binding
+ spec = find_by_name(provider_name)
+ backend = spec.backend if spec else "openai_compat"
+
+ if backend == "openai_codex":
+ provider: LLMProvider = OpenAICodexProvider(default_model=llm_config.model)
+ elif backend == "github_copilot":
+ provider = GitHubCopilotProvider(default_model=llm_config.model)
+ elif backend == "azure_openai":
+ provider = AzureOpenAIProvider(
+ api_key=llm_config.api_key or "",
+ api_base=llm_config.effective_url or llm_config.base_url or "",
+ default_model=llm_config.model,
+ extra_headers=llm_config.extra_headers or None,
+ )
+ elif backend == "anthropic":
+ provider = AnthropicProvider(
+ api_key=llm_config.api_key or None,
+ api_base=llm_config.effective_url or llm_config.base_url or None,
+ default_model=llm_config.model,
+ extra_headers=llm_config.extra_headers or None,
+ supports_prompt_caching=bool(spec and spec.supports_prompt_caching),
+ )
+ else:
+ provider = OpenAICompatProvider(
+ api_key=llm_config.api_key or None,
+ api_base=llm_config.effective_url or llm_config.base_url or None,
+ default_model=llm_config.model,
+ extra_headers=llm_config.extra_headers or None,
+ spec=spec,
+ provider_name=provider_name,
+ )
+
+ provider.generation = GenerationSettings(
+ temperature=llm_config.temperature,
+ max_tokens=llm_config.max_tokens,
+ reasoning_effort=llm_config.reasoning_effort,
+ )
+ return provider
diff --git a/deeptutor/services/notebook/service.py b/deeptutor/services/notebook/service.py
index 645f824ef..1e747abb2 100644
--- a/deeptutor/services/notebook/service.py
+++ b/deeptutor/services/notebook/service.py
@@ -25,6 +25,7 @@ class RecordType(str, Enum):
QUESTION = "question"
RESEARCH = "research"
CHAT = "chat"
+ CO_WRITER = "co_writer"
class NotebookRecord(BaseModel):
@@ -378,6 +379,7 @@ class NotebookManager:
"question": 0,
"research": 0,
"chat": 0,
+ "co_writer": 0,
}
for nb_info in notebooks:
diff --git a/deeptutor/services/prompt/__init__.py b/deeptutor/services/prompt/__init__.py
index ce5ea644f..579889d62 100644
--- a/deeptutor/services/prompt/__init__.py
+++ b/deeptutor/services/prompt/__init__.py
@@ -17,9 +17,19 @@ Usage:
system_prompt = pm.get_prompt(prompts, "system", "base")
"""
+from .language import (
+ append_language_directive,
+ language_directive,
+ language_label,
+ normalize_language,
+)
from .manager import PromptManager, get_prompt_manager
__all__ = [
"PromptManager",
+ "append_language_directive",
"get_prompt_manager",
+ "language_directive",
+ "language_label",
+ "normalize_language",
]
diff --git a/deeptutor/services/prompt/language.py b/deeptutor/services/prompt/language.py
new file mode 100644
index 000000000..a4ce01295
--- /dev/null
+++ b/deeptutor/services/prompt/language.py
@@ -0,0 +1,81 @@
+"""Shared language directives for prompt-driven LLM calls.
+
+This helper centralizes the "stay in the requested language" instruction so
+different modules can share the same behavior without depending on book-only
+utilities.
+"""
+
+from __future__ import annotations
+
+_LANGUAGE_LABELS: dict[str, str] = {
+ "zh": "中文(简体)",
+ "zh-cn": "中文(简体)",
+ "zh-tw": "繁體中文",
+ "en": "English",
+ "ja": "日本語",
+ "ko": "한국어",
+ "es": "Español",
+ "fr": "Français",
+ "de": "Deutsch",
+ "ru": "Русский",
+ "pt": "Português",
+ "it": "Italiano",
+}
+
+
+def normalize_language(language: str | None) -> str:
+ return (language or "en").strip().lower() or "en"
+
+
+def language_label(language: str | None) -> str:
+ code = normalize_language(language)
+ if code in _LANGUAGE_LABELS:
+ return _LANGUAGE_LABELS[code]
+ base = code.split("-", 1)[0]
+ return _LANGUAGE_LABELS.get(base, language or "English")
+
+
+def language_directive(language: str | None) -> str:
+ """Return a strict reader-facing language instruction for prompts."""
+ code = normalize_language(language)
+ label = language_label(code)
+ if code.startswith("zh"):
+ return (
+ "\n\n[语言要求 / Language] "
+ f"请严格使用{label}撰写所有面向读者的文本(标题、正文、解释、提示、过渡句、"
+ "题干、选项等),即使参考资料、JSON 字段名或英文术语出现在 prompt 中也"
+ "不得切换语言;保留必要的专有名词原文(如人名、产品名、公式中的变量符号"
+ f"等)即可,其余一律使用{label}。"
+ )
+ if code == "en":
+ return (
+ "\n\n[Language] Write ALL reader-facing text (titles, prose, "
+ "explanations, hints, transitions, quiz stems, options, etc.) in "
+ "English. Do NOT switch languages even if the source material, "
+ "JSON keys, or examples in this prompt are in another language. "
+ "Keep proper nouns (people, products, formula symbols) in their "
+ "original form."
+ )
+ return (
+ f"\n\n[Language] Write ALL reader-facing text strictly in {label}. "
+ "Do NOT switch languages even if the source material, JSON keys, or "
+ "examples in this prompt are in a different language. Keep proper "
+ "nouns (people, products, formula symbols) in their original form."
+ )
+
+
+def append_language_directive(system_prompt: str | None, language: str | None) -> str:
+ """Append the language directive to an existing system prompt."""
+ base = (system_prompt or "").rstrip()
+ directive = language_directive(language).strip()
+ if not base:
+ return directive
+ return f"{base}\n\n{directive}"
+
+
+__all__ = [
+ "append_language_directive",
+ "language_directive",
+ "language_label",
+ "normalize_language",
+]
diff --git a/deeptutor/services/provider_registry.py b/deeptutor/services/provider_registry.py
index 6bf0e8b01..7624379fc 100644
--- a/deeptutor/services/provider_registry.py
+++ b/deeptutor/services/provider_registry.py
@@ -12,6 +12,8 @@ from __future__ import annotations
from dataclasses import dataclass
from typing import Any
+from pydantic.alias_generators import to_snake
+
@dataclass(frozen=True)
class ProviderSpec:
@@ -43,6 +45,7 @@ class ProviderSpec:
model_overrides: tuple[tuple[str, dict[str, Any]], ...] = ()
is_oauth: bool = False
is_direct: bool = False
+ thinking_style: str = ""
@property
def mode(self) -> str:
@@ -58,7 +61,7 @@ class ProviderSpec:
@property
def label(self) -> str:
- return self.display_name or self.name
+ return self.display_name or self.name.title()
PROVIDER_ALIASES = {
@@ -69,12 +72,16 @@ PROVIDER_ALIASES = {
"google_genai": "gemini",
"claude": "anthropic",
"openai_compatible": "custom",
+ "openai-compatible": "custom",
+ "anthropic_compatible": "custom_anthropic",
+ "anthropic-compatible": "custom_anthropic",
"volcenginecodingplan": "volcengine_coding_plan",
"volcengineCodingPlan": "volcengine_coding_plan",
"bytepluscodingplan": "byteplus_coding_plan",
"byteplusCodingPlan": "byteplus_coding_plan",
"github-copilot": "github_copilot",
"openai-codex": "openai_codex",
+ "lm-studio": "lm_studio",
}
@@ -85,7 +92,7 @@ def canonical_provider_name(name: str | None) -> str | None:
key = name.strip()
if not key:
return None
- key = key.replace("-", "_")
+ key = to_snake(key.replace("-", "_"))
return PROVIDER_ALIASES.get(key, key)
@@ -103,6 +110,14 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
backend="openai_compat",
is_direct=True,
),
+ ProviderSpec(
+ name="custom_anthropic",
+ keywords=(),
+ env_key="",
+ display_name="Custom (Anthropic API)",
+ backend="anthropic",
+ is_direct=True,
+ ),
ProviderSpec(
name="azure_openai",
keywords=("azure", "azure_openai"),
@@ -154,6 +169,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
is_gateway=True,
detect_by_base_keyword="volces",
default_api_base="https://ark.cn-beijing.volces.com/api/v3",
+ thinking_style="thinking_type",
),
ProviderSpec(
name="volcengine_coding_plan",
@@ -164,6 +180,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
is_gateway=True,
default_api_base="https://ark.cn-beijing.volces.com/api/coding/v3",
strip_model_prefix=True,
+ thinking_style="thinking_type",
),
ProviderSpec(
name="byteplus",
@@ -175,6 +192,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
detect_by_base_keyword="bytepluses",
default_api_base="https://ark.ap-southeast.bytepluses.com/api/v3",
strip_model_prefix=True,
+ thinking_style="thinking_type",
),
ProviderSpec(
name="byteplus_coding_plan",
@@ -185,6 +203,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
is_gateway=True,
default_api_base="https://ark.ap-southeast.bytepluses.com/api/coding/v3",
strip_model_prefix=True,
+ thinking_style="thinking_type",
),
# === Standard providers (matched by model-name keywords) ===============
ProviderSpec(
@@ -207,10 +226,11 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
),
ProviderSpec(
name="openai_codex",
- keywords=("openai_codex", "codex"),
+ keywords=("openai-codex",),
env_key="",
display_name="OpenAI Codex",
backend="openai_codex",
+ detect_by_base_keyword="codex",
is_oauth=True,
default_api_base="https://chatgpt.com/backend-api",
),
@@ -223,6 +243,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
is_oauth=True,
default_api_base="https://api.githubcopilot.com",
strip_model_prefix=True,
+ supports_max_completion_tokens=True,
),
ProviderSpec(
name="deepseek",
@@ -231,6 +252,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
display_name="DeepSeek",
backend="openai_compat",
default_api_base="https://api.deepseek.com",
+ thinking_style="thinking_type",
),
ProviderSpec(
name="gemini",
@@ -256,6 +278,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
display_name="DashScope",
backend="openai_compat",
default_api_base="https://dashscope.aliyuncs.com/compatible-mode/v1",
+ thinking_style="enable_thinking",
),
ProviderSpec(
name="moonshot",
@@ -263,8 +286,11 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
env_key="MOONSHOT_API_KEY",
display_name="Moonshot",
backend="openai_compat",
- default_api_base="https://api.moonshot.ai/v1",
- model_overrides=(("kimi-k2.5", {"temperature": 1.0}),),
+ default_api_base="https://api.moonshot.cn/v1",
+ model_overrides=(
+ ("kimi-k2.5", {"temperature": 1.0}),
+ ("kimi-k2.6", {"temperature": 1.0}),
+ ),
),
ProviderSpec(
name="minimax",
@@ -272,7 +298,16 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
env_key="MINIMAX_API_KEY",
display_name="MiniMax",
backend="openai_compat",
- default_api_base="https://api.minimax.io/v1",
+ default_api_base="https://api.minimaxi.com/v1",
+ thinking_style="reasoning_split",
+ ),
+ ProviderSpec(
+ name="minimax_anthropic",
+ keywords=("minimax_anthropic",),
+ env_key="MINIMAX_API_KEY",
+ display_name="MiniMax (Anthropic)",
+ backend="anthropic",
+ default_api_base="https://api.minimaxi.com/anthropic",
),
ProviderSpec(
name="mistral",
@@ -303,10 +338,9 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
name="vllm",
keywords=("vllm",),
env_key="HOSTED_VLLM_API_KEY",
- display_name="vLLM",
+ display_name="vLLM/Local",
backend="openai_compat",
is_local=True,
- default_api_base="http://localhost:8000/v1",
),
ProviderSpec(
name="ollama",
@@ -320,8 +354,8 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
),
ProviderSpec(
name="lm_studio",
- keywords=("lmstudio", "lm_studio"),
- env_key="",
+ keywords=("lm-studio", "lmstudio", "lm_studio"),
+ env_key="LM_STUDIO_API_KEY",
display_name="LM Studio",
backend="openai_compat",
is_local=True,
diff --git a/deeptutor/services/session/context_builder.py b/deeptutor/services/session/context_builder.py
index 4a3bb12e3..9d3c4c444 100644
--- a/deeptutor/services/session/context_builder.py
+++ b/deeptutor/services/session/context_builder.py
@@ -11,6 +11,7 @@ from deeptutor.agents.base_agent import BaseAgent
from deeptutor.core.stream import StreamEvent, StreamEventType
from deeptutor.core.trace import build_trace_metadata, merge_trace_metadata, new_call_id
from deeptutor.services.llm.config import LLMConfig
+from deeptutor.services.llm.context_window import resolve_effective_context_window
from .sqlite_store import SQLiteSessionStore
@@ -97,9 +98,16 @@ class ContextBuilder:
self.history_budget_ratio = history_budget_ratio
self.summary_target_ratio = summary_target_ratio
+ def _effective_context_window(self, llm_config: LLMConfig) -> int:
+ return resolve_effective_context_window(
+ context_window=getattr(llm_config, "context_window", None),
+ model=str(getattr(llm_config, "model", "") or ""),
+ max_tokens=getattr(llm_config, "max_tokens", None),
+ )
+
def _history_budget(self, llm_config: LLMConfig) -> int:
- configured = int(getattr(llm_config, "max_tokens", 4096) or 4096)
- return max(256, int(configured * self.history_budget_ratio))
+ effective_context_window = self._effective_context_window(llm_config)
+ return max(256, int(effective_context_window * self.history_budget_ratio))
def _summary_budget(self, budget: int) -> int:
return max(96, int(budget * self.summary_target_ratio))
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index 3e548d1ca..c3b9f1118 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -555,7 +555,22 @@ class TurnRuntimeManager:
"mime_type": item.get("mime_type", ""),
}
attachment_records.append(record)
- attachments.append(Attachment(**record))
+
+ from deeptutor.utils.document_extractor import extract_documents_from_records
+
+ document_texts, attachment_records = extract_documents_from_records(
+ attachment_records
+ )
+ attachments = [
+ Attachment(
+ type=r.get("type", "file"),
+ url=r.get("url", ""),
+ base64=r.get("base64", ""),
+ filename=r.get("filename", ""),
+ mime_type=r.get("mime_type", ""),
+ )
+ for r in attachment_records
+ ]
if followup_question_context:
existing_messages = await self.store.get_messages_for_context(session_id)
@@ -691,6 +706,8 @@ class TurnRuntimeManager:
effective_user_message = raw_user_content
context_parts: list[str] = []
+ if document_texts:
+ context_parts.append("[Attached Documents]\n" + "\n\n".join(document_texts))
if notebook_context:
context_parts.append(f"[Notebook Context]\n{notebook_context}")
if history_context:
diff --git a/deeptutor/tutorbot/config/schema.py b/deeptutor/tutorbot/config/schema.py
index 7f9bc3fa0..b7226c525 100644
--- a/deeptutor/tutorbot/config/schema.py
+++ b/deeptutor/tutorbot/config/schema.py
@@ -71,6 +71,9 @@ class ProvidersConfig(Base):
"""Configuration for LLM providers."""
custom: ProviderConfig = Field(default_factory=ProviderConfig) # Any OpenAI-compatible endpoint
+ custom_anthropic: ProviderConfig = Field(
+ default_factory=ProviderConfig
+ ) # Any Anthropic-compatible endpoint
azure_openai: ProviderConfig = Field(
default_factory=ProviderConfig
) # Azure OpenAI (model = deployment name)
diff --git a/deeptutor/tutorbot/providers/deeptutor_adapter.py b/deeptutor/tutorbot/providers/deeptutor_adapter.py
index 705f9f779..f83be5193 100644
--- a/deeptutor/tutorbot/providers/deeptutor_adapter.py
+++ b/deeptutor/tutorbot/providers/deeptutor_adapter.py
@@ -7,47 +7,11 @@ delegates to the appropriate provider (OpenAICompat or Anthropic).
from __future__ import annotations
-from deeptutor.tutorbot.providers.base import LLMProvider
+from deeptutor.services.llm.provider_core.base import LLMProvider
def create_deeptutor_provider() -> LLMProvider:
"""Build a provider pre-configured from DeepTutor's LLMConfig."""
- from deeptutor.services.llm.config import get_llm_config
- from deeptutor.services.provider_registry import find_by_model, find_by_name
+ from deeptutor.services.llm.provider_factory import get_runtime_provider
- cfg = get_llm_config()
-
- api_key = cfg.api_key or None
- api_base = cfg.effective_url or cfg.base_url or None
- model = cfg.model
- extra_headers = cfg.extra_headers or {}
- provider_name = cfg.provider_name or None
-
- spec = None
- if provider_name:
- spec = find_by_name(provider_name)
- if spec is None and model:
- spec = find_by_model(model)
-
- backend = spec.backend if spec else "openai_compat"
-
- if backend == "anthropic":
- from deeptutor.tutorbot.providers.anthropic_provider import AnthropicProvider
-
- return AnthropicProvider(
- api_key=api_key,
- api_base=api_base,
- default_model=model,
- extra_headers=extra_headers,
- )
-
- from deeptutor.tutorbot.providers.openai_compat_provider import OpenAICompatProvider
-
- return OpenAICompatProvider(
- api_key=api_key,
- api_base=api_base,
- default_model=model,
- extra_headers=extra_headers,
- spec=spec,
- provider_name=provider_name,
- )
+ return get_runtime_provider()
diff --git a/deeptutor/tutorbot/providers/registry.py b/deeptutor/tutorbot/providers/registry.py
index b4b5732ec..3ce100931 100644
--- a/deeptutor/tutorbot/providers/registry.py
+++ b/deeptutor/tutorbot/providers/registry.py
@@ -91,6 +91,14 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
backend="openai_compat",
is_direct=True,
),
+ ProviderSpec(
+ name="custom_anthropic",
+ keywords=(),
+ env_key="",
+ display_name="Custom (Anthropic API)",
+ backend="anthropic",
+ is_direct=True,
+ ),
ProviderSpec(
name="azure_openai",
keywords=("azure", "azure-openai"),
@@ -251,7 +259,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
env_key="MOONSHOT_API_KEY",
display_name="Moonshot",
backend="openai_compat",
- default_api_base="https://api.moonshot.ai/v1",
+ default_api_base="https://api.moonshot.cn/v1",
model_overrides=(("kimi-k2.5", {"temperature": 1.0}),),
),
ProviderSpec(
@@ -260,7 +268,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
env_key="MINIMAX_API_KEY",
display_name="MiniMax",
backend="openai_compat",
- default_api_base="https://api.minimax.io/v1",
+ default_api_base="https://api.minimaxi.com/v1",
),
ProviderSpec(
name="mistral",
diff --git a/deeptutor/utils/document_extractor.py b/deeptutor/utils/document_extractor.py
new file mode 100644
index 000000000..3138e7963
--- /dev/null
+++ b/deeptutor/utils/document_extractor.py
@@ -0,0 +1,375 @@
+"""Document text extraction for chat attachments.
+
+Bytes-in, text-out. Used by the chat turn runtime to inline the text of
+user-dropped Office documents (.pdf / .docx / .xlsx / .pptx) into the
+``effective_user_message`` sent to the LLM.
+
+Design mirrors ``nanobot/nanobot/utils/document.py`` but works on bytes
+instead of file paths so the server never touches disk.
+"""
+
+from __future__ import annotations
+
+import base64
+from collections.abc import Iterable
+import io
+import logging
+from pathlib import PurePosixPath
+
+try:
+ import fitz # pymupdf
+except ImportError: # pragma: no cover
+ fitz = None # type: ignore[assignment]
+
+try:
+ from pypdf import PdfReader
+ from pypdf.errors import FileNotDecryptedError as _PypdfNotDecryptedError
+except ImportError: # pragma: no cover
+ PdfReader = None # type: ignore[assignment]
+ _PypdfNotDecryptedError = Exception # type: ignore[assignment,misc]
+
+try:
+ from docx import Document as DocxDocument
+except ImportError: # pragma: no cover
+ DocxDocument = None # type: ignore[assignment]
+
+try:
+ from openpyxl import load_workbook
+except ImportError: # pragma: no cover
+ load_workbook = None # type: ignore[assignment]
+
+try:
+ from pptx import Presentation as PptxPresentation
+except ImportError: # pragma: no cover
+ PptxPresentation = None # type: ignore[assignment]
+
+
+logger = logging.getLogger(__name__)
+
+
+SUPPORTED_DOC_EXTENSIONS: frozenset[str] = frozenset({".pdf", ".docx", ".xlsx", ".pptx"})
+
+MAX_DOC_BYTES = 10 * 1024 * 1024
+MAX_TOTAL_DOC_BYTES = 25 * 1024 * 1024
+MAX_EXTRACTED_CHARS_PER_DOC = 200_000
+MAX_EXTRACTED_CHARS_TOTAL = 150_000
+
+_PDF_MAGIC = b"%PDF-"
+_OOXML_MAGIC = b"PK\x03\x04"
+
+
+class DocumentExtractionError(Exception):
+ """Base class for extraction failures. ``str(exc)`` is user-friendly."""
+
+ def __init__(self, message: str, filename: str = "") -> None:
+ super().__init__(message)
+ self.filename = filename
+
+
+class UnsupportedDocumentError(DocumentExtractionError):
+ pass
+
+
+class CorruptDocumentError(DocumentExtractionError):
+ pass
+
+
+class EmptyDocumentError(DocumentExtractionError):
+ pass
+
+
+class DocumentTooLargeError(DocumentExtractionError):
+ pass
+
+
+def is_document_extension(filename: str) -> bool:
+ return _ext(filename) in SUPPORTED_DOC_EXTENSIONS
+
+
+def _ext(filename: str) -> str:
+ return PurePosixPath(filename or "").suffix.lower()
+
+
+def _truncate(text: str, max_length: int) -> str:
+ if len(text) <= max_length:
+ return text
+ return text[:max_length] + f"... (truncated, {len(text)} chars total)"
+
+
+def _check_magic(ext: str, data: bytes, filename: str) -> None:
+ """Validate file header to catch extension spoofing."""
+ if ext == ".pdf":
+ if not data.startswith(_PDF_MAGIC):
+ raise CorruptDocumentError(
+ f"{filename} does not look like a PDF (bad header)", filename=filename
+ )
+ elif ext in {".docx", ".xlsx", ".pptx"}:
+ if not data.startswith(_OOXML_MAGIC):
+ raise CorruptDocumentError(
+ f"{filename} does not look like a valid Office file (bad header)",
+ filename=filename,
+ )
+
+
+def extract_text_from_bytes(filename: str, data: bytes) -> str:
+ """Extract text from a single document's raw bytes.
+
+ Raises a ``DocumentExtractionError`` subclass on failure. Successful
+ output is truncated to ``MAX_EXTRACTED_CHARS_PER_DOC`` with a notice.
+ """
+ if not data:
+ raise EmptyDocumentError(f"{filename} is empty", filename=filename)
+ if len(data) > MAX_DOC_BYTES:
+ raise DocumentTooLargeError(
+ f"{filename} exceeds the {MAX_DOC_BYTES // (1024 * 1024)} MB per-file limit",
+ filename=filename,
+ )
+
+ ext = _ext(filename)
+ if ext not in SUPPORTED_DOC_EXTENSIONS:
+ raise UnsupportedDocumentError(
+ f"{filename} has unsupported extension '{ext}'", filename=filename
+ )
+
+ _check_magic(ext, data, filename)
+
+ if ext == ".pdf":
+ text = _extract_pdf(data, filename)
+ elif ext == ".docx":
+ text = _extract_docx(data, filename)
+ elif ext == ".xlsx":
+ text = _extract_xlsx(data, filename)
+ elif ext == ".pptx":
+ text = _extract_pptx(data, filename)
+ else: # pragma: no cover - guarded above
+ raise UnsupportedDocumentError(f"{filename}: unreachable", filename=filename)
+
+ if not text.strip():
+ raise EmptyDocumentError(f"{filename}: no extractable text", filename=filename)
+ return _truncate(text, MAX_EXTRACTED_CHARS_PER_DOC)
+
+
+def _extract_pdf(data: bytes, filename: str) -> str:
+ if fitz is not None:
+ try:
+ with fitz.open(stream=data, filetype="pdf") as doc:
+ if doc.is_encrypted and not doc.authenticate(""):
+ raise CorruptDocumentError(
+ f"{filename} is encrypted and cannot be read", filename=filename
+ )
+ pages = [f"--- Page {i} ---\n{page.get_text() or ''}" for i, page in enumerate(doc, 1)]
+ return "\n\n".join(pages)
+ except CorruptDocumentError:
+ raise
+ except Exception as exc:
+ logger.warning("pymupdf failed on %s: %s — falling back to pypdf", filename, exc)
+
+ if PdfReader is None:
+ raise CorruptDocumentError(
+ f"{filename}: no PDF reader available (install pymupdf or pypdf)",
+ filename=filename,
+ )
+ try:
+ reader = PdfReader(io.BytesIO(data))
+ if getattr(reader, "is_encrypted", False):
+ raise CorruptDocumentError(
+ f"{filename} is encrypted and cannot be read", filename=filename
+ )
+ pages = [f"--- Page {i} ---\n{page.extract_text() or ''}" for i, page in enumerate(reader.pages, 1)]
+ return "\n\n".join(pages)
+ except CorruptDocumentError:
+ raise
+ except _PypdfNotDecryptedError as exc:
+ raise CorruptDocumentError(
+ f"{filename} is encrypted and cannot be read", filename=filename
+ ) from exc
+ except Exception as exc:
+ raise CorruptDocumentError(f"{filename}: failed to read PDF ({exc})", filename=filename) from exc
+
+
+def _extract_docx(data: bytes, filename: str) -> str:
+ if DocxDocument is None:
+ raise CorruptDocumentError(
+ f"{filename}: python-docx not installed", filename=filename
+ )
+ try:
+ doc = DocxDocument(io.BytesIO(data))
+ except Exception as exc:
+ raise CorruptDocumentError(
+ f"{filename}: failed to open DOCX ({exc})", filename=filename
+ ) from exc
+ paragraphs = [p.text for p in doc.paragraphs if p.text and p.text.strip()]
+ return "\n\n".join(paragraphs)
+
+
+def _extract_xlsx(data: bytes, filename: str) -> str:
+ if load_workbook is None:
+ raise CorruptDocumentError(
+ f"{filename}: openpyxl not installed", filename=filename
+ )
+ try:
+ wb = load_workbook(io.BytesIO(data), read_only=True, data_only=True)
+ except Exception as exc:
+ raise CorruptDocumentError(
+ f"{filename}: failed to open XLSX ({exc})", filename=filename
+ ) from exc
+ try:
+ sheets: list[str] = []
+ for sheet_name in wb.sheetnames:
+ ws = wb[sheet_name]
+ rows: list[str] = []
+ for row in ws.iter_rows(values_only=True):
+ row_text = "\t".join(str(cell) if cell is not None else "" for cell in row)
+ if row_text.strip():
+ rows.append(row_text)
+ if rows:
+ sheets.append(f"--- Sheet: {sheet_name} ---\n" + "\n".join(rows))
+ return "\n\n".join(sheets)
+ finally:
+ wb.close()
+
+
+def _extract_pptx(data: bytes, filename: str) -> str:
+ if PptxPresentation is None:
+ raise CorruptDocumentError(
+ f"{filename}: python-pptx not installed", filename=filename
+ )
+ try:
+ prs = PptxPresentation(io.BytesIO(data))
+ except Exception as exc:
+ raise CorruptDocumentError(
+ f"{filename}: failed to open PPTX ({exc})", filename=filename
+ ) from exc
+ slides: list[str] = []
+ for i, slide in enumerate(prs.slides, 1):
+ slide_text: list[str] = []
+ for shape in slide.shapes:
+ _collect_pptx_shape_text(shape, slide_text)
+ if slide_text:
+ slides.append(f"--- Slide {i} ---\n" + "\n".join(slide_text))
+ return "\n\n".join(slides)
+
+
+def _collect_pptx_shape_text(shape, out: list[str]) -> None:
+ """Recurse into groups + tables, same semantics as nanobot's version."""
+ sub_shapes = getattr(shape, "shapes", None)
+ if sub_shapes is not None:
+ for sub in sub_shapes:
+ _collect_pptx_shape_text(sub, out)
+ return
+
+ if getattr(shape, "has_table", False):
+ for row in shape.table.rows:
+ cells = [cell.text.strip() for cell in row.cells]
+ line = "\t".join(cell for cell in cells if cell)
+ if line:
+ out.append(line)
+ return
+
+ text = getattr(shape, "text", "")
+ if text:
+ out.append(text)
+
+
+def extract_documents_from_records(
+ records: Iterable[dict],
+) -> tuple[list[str], list[dict]]:
+ """Process a list of attachment records from the WS payload.
+
+ Parameters
+ ----------
+ records:
+ Raw attachment records as parsed by the turn runtime
+ (``{"type", "url", "base64", "filename", "mime_type"}``).
+
+ Returns
+ -------
+ (doc_texts, updated_records)
+ ``doc_texts`` is a list of strings formatted as
+ ``"[File: <name>]\\n<text>"`` (one per processed or skipped doc).
+ ``updated_records`` is the input list with the ``base64`` field
+ cleared on successfully-extracted docs (to save DB space) and an
+ ``extracted_chars`` field added. Image / non-document records are
+ returned unchanged.
+ """
+ doc_texts: list[str] = []
+ updated: list[dict] = []
+ total_bytes = 0
+ total_chars = 0
+ over_quota = False
+
+ for raw in records:
+ record = dict(raw)
+ filename = str(record.get("filename") or "")
+ if not is_document_extension(filename):
+ updated.append(record)
+ continue
+
+ b64 = record.get("base64") or ""
+ if not b64:
+ updated.append(record)
+ continue
+
+ if over_quota:
+ doc_texts.append(
+ f"[File: {filename} — skipped: total attachment quota exceeded]"
+ )
+ record["base64"] = ""
+ record["extracted_chars"] = 0
+ updated.append(record)
+ continue
+
+ try:
+ data = base64.b64decode(b64, validate=False)
+ except Exception as exc:
+ doc_texts.append(f"[File: {filename} — could not be read: invalid base64 ({exc})]")
+ record["base64"] = ""
+ record["extracted_chars"] = 0
+ updated.append(record)
+ continue
+
+ if total_bytes + len(data) > MAX_TOTAL_DOC_BYTES:
+ over_quota = True
+ doc_texts.append(
+ f"[File: {filename} — skipped: total attachment quota exceeded]"
+ )
+ record["base64"] = ""
+ record["extracted_chars"] = 0
+ updated.append(record)
+ continue
+
+ total_bytes += len(data)
+
+ try:
+ text = extract_text_from_bytes(filename, data)
+ except DocumentExtractionError as exc:
+ logger.info("Document extraction failed for %s: %s", filename, exc)
+ doc_texts.append(f"[File: {filename} — could not be read: {exc}]")
+ record["base64"] = ""
+ record["extracted_chars"] = 0
+ updated.append(record)
+ continue
+
+ remaining_budget = MAX_EXTRACTED_CHARS_TOTAL - total_chars
+ if remaining_budget <= 0:
+ doc_texts.append(
+ f"[File: {filename} — skipped: total extracted-text quota exceeded]"
+ )
+ record["base64"] = ""
+ record["extracted_chars"] = 0
+ updated.append(record)
+ continue
+
+ if len(text) > remaining_budget:
+ text = (
+ text[:remaining_budget]
+ + f"... (truncated, {len(text)} chars total; turn quota hit)"
+ )
+
+ total_chars += len(text)
+ doc_texts.append(f"[File: {filename}]\n{text}")
+ record["base64"] = ""
+ record["extracted_chars"] = len(text)
+ updated.append(record)
+
+ return doc_texts, updated
diff --git a/deeptutor/utils/json_parser.py b/deeptutor/utils/json_parser.py
index 65c175b7d..f4be27321 100644
--- a/deeptutor/utils/json_parser.py
+++ b/deeptutor/utils/json_parser.py
@@ -23,6 +23,9 @@ except ImportError:
else:
_repair_json_fn = _repair_json_import
+# Keep a public alias so tests and callers can patch the repair hook directly.
+repair_json = _repair_json_fn
+
logger = logging.getLogger(__name__)
_UNSET = object()
@@ -82,14 +85,14 @@ def parse_json_response(
log.debug(f"Direct JSON parse failed: {parse_error}")
# Strategy 2: Try json-repair if available
- if _repair_json_fn is None:
+ if repair_json is None:
log.warning("json-repair library not installed, cannot repair malformed JSON")
log.debug(f"Response: {extracted_response[:200]}")
return fallback
try:
log.debug("Attempting JSON repair")
- repaired = _repair_json_fn(extracted_response)
+ repaired = repair_json(extracted_response)
result = json.loads(repaired)
log.info("Successfully repaired malformed JSON")
return result
diff --git a/nanobot b/nanobot
new file mode 160000
index 000000000..3441d5f89
--- /dev/null
+++ b/nanobot
@@ -0,0 +1 @@
+Subproject commit 3441d5f89c972489e881c5c738e6485a77e38697
diff --git a/requirements/cli.txt b/requirements/cli.txt
index dd0b84489..fc9173ed1 100644
--- a/requirements/cli.txt
+++ b/requirements/cli.txt
@@ -39,6 +39,12 @@ PyMuPDF>=1.26.0
numpy>=1.24.0,<2.0.0
arxiv>=2.0.0
+# --- Document text extraction (chat attachments) ---
+python-docx>=1.1.0
+openpyxl>=3.1.0
+python-pptx>=1.0.0
+pypdf>=4.0.0
+
# --- Web search ---
ddgs>=9.9.1
diff --git a/scripts/start_tour.py b/scripts/start_tour.py
index 3cb2b0139..444dbae4e 100644
--- a/scripts/start_tour.py
+++ b/scripts/start_tour.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python
-"""DeepTutor Setup Tour — minimal terminal-first guided installer."""
+"""DeepTutor Setup Tour - simplified CLI configuration wizard."""
from __future__ import annotations
@@ -11,27 +11,22 @@ import platform
import shutil
import subprocess
import sys
-import time
from typing import Any
-from uuid import uuid4
PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
+ENV_PATH = PROJECT_ROOT / ".env"
+ENV_EXAMPLE_PATH = PROJECT_ROOT / ".env.example"
+INTERFACE_SETTINGS_PATH = PROJECT_ROOT / "data" / "user" / "settings" / "interface.json"
+LEGACY_TOUR_CACHE_PATH = PROJECT_ROOT / "data" / "user" / "settings" / ".tour_cache.json"
-def _resolve_python() -> str:
- """Return a validated path to the current Python interpreter.
- ``sys.executable`` can be empty or point to a non-existent path on
- some platforms (notably Windows with Python 3.14+). This helper
- resolves the real path first, then falls back to ``shutil.which``.
- """
+def _resolve_python() -> str:
+ """Return a validated path to the current Python interpreter."""
exe = sys.executable
if exe:
- # Prefer the unresolved path first — resolving symlinks can escape
- # a virtual-env and point at the system Python, which on modern
- # Homebrew / PEP 668 installs will refuse ``pip install``.
if Path(exe).exists():
return exe
resolved = str(Path(exe).resolve())
@@ -46,15 +41,20 @@ def _resolve_python() -> str:
_PYTHON: str = _resolve_python()
-# ---------------------------------------------------------------------------
-# Bootstrap: ensure minimum packages required to import project modules
-# ---------------------------------------------------------------------------
-
_BOOTSTRAP_PACKAGES = [
("yaml", "PyYAML>=6.0"),
]
+def _can_import(name: str) -> bool:
+ try:
+ __import__(name)
+ return True
+ except ImportError:
+ return False
+
+
+
def _bootstrap() -> None:
missing = [pip for imp, pip in _BOOTSTRAP_PACKAGES if not _can_import(imp)]
if not missing:
@@ -67,17 +67,8 @@ def _bootstrap() -> None:
)
-def _can_import(name: str) -> bool:
- try:
- __import__(name)
- return True
- except ImportError:
- return False
-
-
_bootstrap()
-# ---------------------------------------------------------------------------
def _load_runtime_deps():
@@ -97,11 +88,7 @@ def _load_runtime_deps():
text_input,
)
- from deeptutor.services.config import (
- get_config_test_runner,
- get_env_store,
- get_model_catalog_service,
- )
+ from deeptutor.services.config import get_env_store
return (
accent,
@@ -117,9 +104,7 @@ def _load_runtime_deps():
select,
step,
text_input,
- get_config_test_runner,
get_env_store,
- get_model_catalog_service,
)
@@ -137,13 +122,11 @@ def _load_runtime_deps():
select,
step,
text_input,
- get_config_test_runner,
get_env_store,
- get_model_catalog_service,
) = _load_runtime_deps()
# ---------------------------------------------------------------------------
-# Constants
+# Legacy install helpers kept for compatibility and tests
# ---------------------------------------------------------------------------
PROFILE_COMMANDS: dict[str, list[str]] = {
@@ -153,7 +136,6 @@ PROFILE_COMMANDS: dict[str, list[str]] = {
"web-rag": ["requirements/server.txt"],
}
-# Legacy aliases kept for backward compatibility (hidden from UI).
PROFILE_ALIASES: dict[str, str] = {
"cli-rag-lite": "cli-rag",
"cli-rag-full": "cli-rag",
@@ -161,49 +143,166 @@ PROFILE_ALIASES: dict[str, str] = {
"web-rag-full": "web-rag",
}
-CACHE_PATH = PROJECT_ROOT / "data" / "user" / "settings" / ".tour_cache.json"
MATH_ANIMATOR_REQUIREMENTS = "requirements/math-animator.txt"
-# ---------------------------------------------------------------------------
-# Cache helpers
-# ---------------------------------------------------------------------------
-
-
-def _save_cache(data: dict[str, Any]) -> None:
- data["updated_at"] = time.strftime("%Y-%m-%dT%H:%M:%S")
- CACHE_PATH.parent.mkdir(parents=True, exist_ok=True)
- CACHE_PATH.write_text(json.dumps(data, indent=2), encoding="utf-8")
+MESSAGES: dict[str, dict[str, str]] = {
+ "en": {
+ "banner_line_1": "Configure DeepTutor from the terminal.",
+ "banner_line_2": "We will write ports and provider settings directly into .env.",
+ "env_created": "Created `.env` from `.env.example`.",
+ "env_exists": "Using existing `.env` file.",
+ "env_missing_template": "`.env.example` was not found. Creating an empty `.env` instead.",
+ "platform": "Platform",
+ "python": "Python",
+ "node": "Node",
+ "env_path": ".env",
+ "language_step": "Choose language",
+ "language_prompt": "Choose your language",
+ "language_en_desc": "Run the setup wizard in English",
+ "language_zh_desc": "Run the setup wizard in Chinese",
+ "language_saved": "Saved interface language to `{path}`.",
+ "ports_step": "Configure ports",
+ "backend_port": "Backend port",
+ "frontend_port": "Frontend port",
+ "llm_step": "Configure LLM",
+ "embedding_step": "Configure embedding",
+ "search_step": "Configure search",
+ "review_step": "Write configuration",
+ "provider_prompt": "Choose a provider",
+ "search_provider_prompt": "Choose a search provider",
+ "profile_binding": "Provider / binding",
+ "base_url": "Base URL",
+ "api_key": "API key",
+ "api_version": "API version",
+ "model_id": "Model ID",
+ "dimension": "Dimension",
+ "send_dimensions": "Send `dimensions` parameter",
+ "send_dimensions_auto": "auto",
+ "send_dimensions_yes": "yes",
+ "send_dimensions_no": "no",
+ "search_enable": "Configure web search?",
+ "search_base_url": "Search base URL",
+ "search_proxy": "Search proxy",
+ "keep_secret": "Press Enter to keep the existing secret value.",
+ "optional": "Optional",
+ "none": "None",
+ "write_confirm": "Write these settings into `.env` now?",
+ "write_success": "Updated `.env` successfully.",
+ "no_changes": "No files changed.",
+ "next_steps": "Setup complete. You can now start DeepTutor with:",
+ "next_command": "python scripts/start_web.py",
+ "summary_ports": "Ports",
+ "summary_llm": "LLM",
+ "summary_embedding": "Embedding",
+ "summary_search": "Search",
+ "search_disabled": "disabled",
+ "tour_cache_removed": "Removed legacy setup-tour cache.",
+ "interrupt": "Setup interrupted.",
+ "manual_desc": "Enter a custom provider name",
+ "custom_desc": "Any OpenAI-compatible endpoint",
+ "local_desc": "Local model endpoint",
+ "search_none_desc": "Disable web search integration",
+ "search_proxy_placeholder": "http://127.0.0.1:7890",
+ "searxng_default": "http://localhost:8080",
+ },
+ "zh": {
+ "banner_line_1": "在命令行中完成 DeepTutor 配置。",
+ "banner_line_2": "我们会把端口和提供商配置直接写入 .env。",
+ "env_created": "已根据 `.env.example` 创建 `.env`。",
+ "env_exists": "检测到现有 `.env` 文件。",
+ "env_missing_template": "未找到 `.env.example`,将创建一个空的 `.env`。",
+ "platform": "平台",
+ "python": "Python",
+ "node": "Node",
+ "env_path": ".env",
+ "language_step": "选择语言",
+ "language_prompt": "选择界面语言",
+ "language_en_desc": "使用英文完成配置",
+ "language_zh_desc": "使用中文完成配置",
+ "language_saved": "已将界面语言写入 `{path}`。",
+ "ports_step": "配置端口",
+ "backend_port": "后端端口",
+ "frontend_port": "前端端口",
+ "llm_step": "配置 LLM",
+ "embedding_step": "配置 Embedding",
+ "search_step": "配置 Search",
+ "review_step": "写入配置",
+ "provider_prompt": "选择提供商",
+ "search_provider_prompt": "选择搜索提供商",
+ "profile_binding": "提供商 / 绑定",
+ "base_url": "Base URL",
+ "api_key": "API Key",
+ "api_version": "API 版本",
+ "model_id": "模型 ID",
+ "dimension": "维度",
+ "send_dimensions": "是否发送 `dimensions` 参数",
+ "send_dimensions_auto": "自动",
+ "send_dimensions_yes": "是",
+ "send_dimensions_no": "否",
+ "search_enable": "是否配置联网搜索?",
+ "search_base_url": "搜索服务 Base URL",
+ "search_proxy": "搜索代理",
+ "keep_secret": "直接回车即可保留当前密钥。",
+ "optional": "可选",
+ "none": "不配置",
+ "write_confirm": "现在将这些设置写入 `.env` 吗?",
+ "write_success": "已成功更新 `.env`。",
+ "no_changes": "未修改任何文件。",
+ "next_steps": "配置完成。你现在可以用下面的命令启动 DeepTutor:",
+ "next_command": "python scripts/start_web.py",
+ "summary_ports": "端口",
+ "summary_llm": "LLM",
+ "summary_embedding": "Embedding",
+ "summary_search": "Search",
+ "search_disabled": "未启用",
+ "tour_cache_removed": "已移除旧版 setup-tour 缓存。",
+ "interrupt": "配置已中断。",
+ "manual_desc": "手动输入自定义提供商名称",
+ "custom_desc": "任意兼容 OpenAI 的接口",
+ "local_desc": "本地模型服务",
+ "search_none_desc": "关闭联网搜索集成",
+ "search_proxy_placeholder": "http://127.0.0.1:7890",
+ "searxng_default": "http://localhost:8080",
+ },
+}
-def _load_cache() -> dict[str, Any] | None:
- if CACHE_PATH.exists():
- try:
- return json.loads(CACHE_PATH.read_text(encoding="utf-8"))
- except (json.JSONDecodeError, OSError):
- pass
- return None
+_LANG = "en"
+
+LLM_MODEL_SUGGESTIONS = {
+ "openai": "gpt-4o-mini",
+ "deepseek": "deepseek-chat",
+ "dashscope": "qwen-max",
+ "gemini": "gemini-2.5-flash",
+ "groq": "llama-3.3-70b-versatile",
+ "zhipu": "glm-4.5",
+ "ollama": "qwen3:8b",
+ "vllm": "Qwen/Qwen3-8B",
+}
+EMBEDDING_MODEL_SUGGESTIONS = {
+ "openai": "text-embedding-3-large",
+ "cohere": "embed-v4.0",
+ "jina": "jina-embeddings-v3",
+ "ollama": "nomic-embed-text",
+}
-def _cleanup_cache() -> None:
- if CACHE_PATH.exists():
- CACHE_PATH.unlink(missing_ok=True)
+SEARCH_PROVIDERS = (
+ ("none", "None", "Disable web search integration"),
+ ("brave", "Brave", "API key required"),
+ ("tavily", "Tavily", "API key required"),
+ ("jina", "Jina", "API key required"),
+ ("searxng", "SearXNG", "Self-hosted or public instance"),
+ ("duckduckgo", "DuckDuckGo", "No API key required"),
+ ("perplexity", "Perplexity", "API key required"),
+)
# ---------------------------------------------------------------------------
-# Environment detection
+# Compatibility helpers
# ---------------------------------------------------------------------------
-def _python_strategy() -> str:
- if os.environ.get("CONDA_DEFAULT_ENV"):
- return f"conda:{os.environ['CONDA_DEFAULT_ENV']}"
- if os.environ.get("VIRTUAL_ENV"):
- return f"venv:{Path(os.environ['VIRTUAL_ENV']).name}"
- if (PROJECT_ROOT / ".venv").exists():
- return "repo-.venv"
- return "system"
-
-
def _node_strategy() -> str:
if shutil.which("node") and shutil.which("npm"):
return "installed"
@@ -218,178 +317,15 @@ def _node_strategy() -> str:
return "manual"
-def _node_install_cmd() -> list[str] | None:
- mapping: dict[str, list[str]] = {
- "brew": ["brew", "install", "node"],
- "winget": ["winget", "install", "OpenJS.NodeJS.LTS"],
- "apt": ["sudo", "apt", "install", "-y", "nodejs", "npm"],
- "dnf": ["sudo", "dnf", "install", "-y", "nodejs", "npm"],
- "yum": ["sudo", "yum", "install", "-y", "nodejs", "npm"],
- }
- return mapping.get(_node_strategy())
-
-
-def _has_cairo_pkgconfig() -> bool:
- pkg_config = shutil.which("pkg-config")
- if not pkg_config:
- return False
- check = subprocess.run(
- [pkg_config, "--exists", "cairo"],
- cwd=str(PROJECT_ROOT),
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- check=False,
- )
- return check.returncode == 0
-
-
-def _missing_math_animator_system_deps() -> list[str]:
- missing: list[str] = []
- for tool in ("latex", "pkg-config", "cmake", "ffmpeg"):
- if not shutil.which(tool):
- missing.append(tool)
- if not _has_cairo_pkgconfig():
- missing.append("cairo")
- return missing
-
-
-def _math_animator_install_cmd(dep: str) -> list[str] | None:
- system = platform.system().lower()
- _INSTALL_MAPS: dict[str, dict[str, list[str]]] = {
- "brew": {
- "latex": ["brew", "install", "--cask", "basictex"],
- "pkg-config": ["brew", "install", "pkgconf"],
- "cmake": ["brew", "install", "cmake"],
- "ffmpeg": ["brew", "install", "ffmpeg"],
- "cairo": ["brew", "install", "cairo"],
- },
- "apt": {
- "latex": ["sudo", "apt", "install", "-y", "texlive-latex-base"],
- "pkg-config": ["sudo", "apt", "install", "-y", "pkg-config"],
- "cmake": ["sudo", "apt", "install", "-y", "cmake"],
- "ffmpeg": ["sudo", "apt", "install", "-y", "ffmpeg"],
- "cairo": ["sudo", "apt", "install", "-y", "libcairo2-dev"],
- },
- "dnf": {
- "latex": ["sudo", "dnf", "install", "-y", "texlive-scheme-basic"],
- "pkg-config": ["sudo", "dnf", "install", "-y", "pkgconf"],
- "cmake": ["sudo", "dnf", "install", "-y", "cmake"],
- "ffmpeg": ["sudo", "dnf", "install", "-y", "ffmpeg"],
- "cairo": ["sudo", "dnf", "install", "-y", "cairo-devel"],
- },
- "yum": {
- "latex": ["sudo", "yum", "install", "-y", "texlive-latex"],
- "pkg-config": ["sudo", "yum", "install", "-y", "pkgconfig"],
- "cmake": ["sudo", "yum", "install", "-y", "cmake"],
- "ffmpeg": ["sudo", "yum", "install", "-y", "ffmpeg"],
- "cairo": ["sudo", "yum", "install", "-y", "cairo-devel"],
- },
- "winget": {
- "latex": ["winget", "install", "MiKTeX.MiKTeX"],
- "cmake": ["winget", "install", "Kitware.CMake"],
- "ffmpeg": ["winget", "install", "Gyan.FFmpeg"],
- },
- "choco": {
- "latex": ["choco", "install", "miktex", "-y"],
- "pkg-config": ["choco", "install", "pkgconfiglite", "-y"],
- "cmake": ["choco", "install", "cmake", "-y"],
- "ffmpeg": ["choco", "install", "ffmpeg", "-y"],
- "cairo": ["choco", "install", "gtk-runtime", "-y"],
- },
- }
- if system == "darwin" and shutil.which("brew"):
- return _INSTALL_MAPS["brew"].get(dep)
- if system == "linux":
- for pm in ("apt", "dnf", "yum"):
- if shutil.which(pm):
- return _INSTALL_MAPS[pm].get(dep)
- if system == "windows":
- for pm in ("winget", "choco"):
- if shutil.which(pm):
- return _INSTALL_MAPS[pm].get(dep)
- return None
-
-
-def _ensure_math_animator_system_deps() -> None:
- missing = _missing_math_animator_system_deps()
- if not missing:
- return
-
- pretty_names = {
- "latex": "LaTeX executable",
- "pkg-config": "pkg-config",
- "cmake": "CMake",
- "ffmpeg": "FFmpeg",
- "cairo": "Cairo development library",
- }
- details = ", ".join(pretty_names.get(item, item) for item in missing)
- log_warn(f"Math animator system dependencies missing: {details}")
-
- installable = [dep for dep in missing if _math_animator_install_cmd(dep) is not None]
- if installable and confirm("Install missing system dependencies automatically?", default=True):
- for dep in installable:
- cmd = _math_animator_install_cmd(dep)
- if cmd:
- _run_cmd(cmd, PROJECT_ROOT)
-
- still_missing = _missing_math_animator_system_deps()
- if still_missing:
- commands = []
- for dep in still_missing:
- cmd = _math_animator_install_cmd(dep)
- commands.append(" ".join(cmd) if cmd else f"install {dep} manually")
- log_warn("Math animator may fail until these are installed: " + " | ".join(commands))
-
-
-# ---------------------------------------------------------------------------
-# Provider detection (providers are now bundled in cli.txt)
-# ---------------------------------------------------------------------------
-
-_NATIVE_BINDINGS = frozenset(
- {
- "anthropic",
- "azure_openai",
- "dashscope",
- "perplexity",
- "exa",
- "tavily",
- "serper",
- "jina",
- "baidu",
- }
-)
-
-
-def _needs_providers(catalog: dict[str, Any]) -> bool:
- bindings: list[str] = []
- for svc in ("llm", "embedding"):
- p = get_model_catalog_service().get_active_profile(catalog, svc)
- if p:
- bindings.append(str(p.get("binding") or "").lower())
- sp = get_model_catalog_service().get_active_profile(catalog, "search")
- if sp:
- bindings.append(str(sp.get("provider") or "").lower())
- return bool(_NATIVE_BINDINGS & set(bindings))
-
-
-# ---------------------------------------------------------------------------
-# Dependency installation
-# ---------------------------------------------------------------------------
-
def _get_npm_command() -> str:
- """Return the correct npm command for the current platform.
-
- With shell=True on Windows, we can just use "npm" and let the shell resolve it.
- """
if platform.system().lower() == "windows":
return "npm.cmd"
- else:
- # On Unix-like systems, npm should be found directly
- npm = shutil.which("npm")
- if npm:
- return npm
- return "npm"
+ npm = shutil.which("npm")
+ if npm:
+ return npm
+ return "npm"
+
def _install_commands(
@@ -398,6 +334,7 @@ def _install_commands(
*,
include_math_animator: bool = False,
) -> list[tuple[list[str], Path]]:
+ del catalog
profile = PROFILE_ALIASES.get(profile, profile)
if profile not in PROFILE_COMMANDS:
raise ValueError(f"Unknown install profile: {profile}")
@@ -411,554 +348,476 @@ def _install_commands(
)
cmds.append(([_PYTHON, "-m", "pip", "install", "-e", ".", "--no-deps"], PROJECT_ROOT))
if profile.startswith("web"):
- npm_cmd = _get_npm_command()
- cmds.append(([npm_cmd, "install"], PROJECT_ROOT / "web"))
- # Provider SDKs are now bundled in cli.txt, no separate install needed.
+ cmds.append(([_get_npm_command(), "install"], PROJECT_ROOT / "web"))
return cmds
+
def _run_cmd(cmd: list[str], cwd: Path) -> None:
log_info(f"{dim(str(cwd))} {' '.join(cmd)}")
- # On Windows, use shell=True to handle .cmd files properly
use_shell = platform.system().lower() == "windows"
result = subprocess.run(cmd, cwd=str(cwd), check=False, shell=use_shell)
if result.returncode != 0:
- # winget may return non-zero even on success (e.g., pending reboot)
- if "winget" in cmd[0]:
- log_warn(f"winget command may have issues (exit {result.returncode}): {' '.join(cmd)}")
- else:
- raise RuntimeError(f"Command failed (exit {result.returncode}): {' '.join(cmd)}")
-
+ raise RuntimeError(f"Command failed (exit {result.returncode}): {' '.join(cmd)}")
-# ---------------------------------------------------------------------------
-# Model catalog helpers
-# ---------------------------------------------------------------------------
-def _ensure_service(
- catalog: dict[str, Any], svc: str
-) -> tuple[dict[str, Any], dict[str, Any] | None]:
- services = catalog.setdefault("services", {})
- service = services.setdefault(svc, {"active_profile_id": None, "profiles": []})
- profiles = service.setdefault("profiles", [])
-
- if not profiles:
- pid = f"{svc}-profile-{uuid4().hex[:8]}"
- profile: dict[str, Any] = {
- "id": pid,
- "name": f"Default {svc.title()} Profile",
- "base_url": "",
- "api_key": "",
- "api_version": "",
- "models": [],
- }
- if svc == "search":
- profile["provider"] = "perplexity"
- else:
- profile["binding"] = "openai"
- mid = f"{svc}-model-{uuid4().hex[:8]}"
- model: dict[str, Any] = {"id": mid, "name": f"Default {svc.title()} Model", "model": ""}
- if svc == "embedding":
- model["dimension"] = "3072"
- profile["models"] = [model]
- service["active_model_id"] = mid
- profiles.append(profile)
- service["active_profile_id"] = pid
-
- active_profile = get_model_catalog_service().get_active_profile(catalog, svc)
- if active_profile is None:
- active_profile = profiles[0]
- service["active_profile_id"] = active_profile["id"]
-
- if svc == "search":
- return active_profile, None
-
- models = active_profile.setdefault("models", [])
- if not models:
- mid = f"{svc}-model-{uuid4().hex[:8]}"
- m = {"id": mid, "name": f"Default {svc.title()} Model", "model": ""}
- if svc == "embedding":
- m["dimension"] = "3072"
- models.append(m)
- service["active_model_id"] = mid
-
- active_model = get_model_catalog_service().get_active_model(catalog, svc)
- if active_model is None:
- active_model = models[0]
- service["active_model_id"] = active_model["id"]
- return active_profile, active_model
+def _stream_text_kwargs() -> dict[str, object]:
+ """Best-effort text decoding for subprocess output."""
+ encoding = locale.getpreferredencoding(False) or "utf-8"
+ return {
+ "stdout": subprocess.PIPE,
+ "stderr": subprocess.STDOUT,
+ "text": True,
+ "encoding": encoding,
+ "errors": "replace",
+ "bufsize": 1,
+ }
# ---------------------------------------------------------------------------
-# Configure a single service interactively (CLI path only)
+# Localized prompt helpers
# ---------------------------------------------------------------------------
-def _configure_service(catalog: dict[str, Any], svc: str) -> None:
- profile, model = _ensure_service(catalog, svc)
+def _set_language(language: str) -> None:
+ global _LANG
+ _LANG = "zh" if str(language).strip().lower().startswith("zh") else "en"
- print(f" {bold(svc.upper())}")
- print()
- profile["name"] = text_input("Profile name", str(profile.get("name") or ""))
- if svc == "search":
- profile["provider"] = text_input("Provider", str(profile.get("provider") or "perplexity"))
- else:
- profile["binding"] = text_input("Binding", str(profile.get("binding") or "openai"))
- profile["base_url"] = text_input("Base URL", str(profile.get("base_url") or ""))
- profile["api_key"] = text_input("API key", str(profile.get("api_key") or ""), secret=True)
- profile["api_version"] = text_input("API version", str(profile.get("api_version") or ""))
-
- if model is not None:
- model["name"] = text_input("Model label", str(model.get("name") or ""))
- model["model"] = text_input("Model id", str(model.get("model") or ""))
- if svc == "embedding":
- model["dimension"] = text_input("Dimension", str(model.get("dimension") or "3072"))
-
- print()
+def _t(key: str, **kwargs: Any) -> str:
+ template = MESSAGES[_LANG].get(key, MESSAGES["en"].get(key, key))
+ return template.format(**kwargs)
-# ---------------------------------------------------------------------------
-# Live connectivity test (CLI path only)
-# ---------------------------------------------------------------------------
-def _stream_test(svc: str, catalog: dict[str, Any]) -> bool:
- run = get_config_test_runner().start(svc, catalog)
- seen = 0
- print(f" {dim(f'Testing {svc.upper()} endpoint ...')}")
+def _secret_mask(value: str) -> str:
+ if not value:
+ return "-"
+ if len(value) <= 8:
+ return "****"
+ return f"{value[:4]}...{value[-4:]}"
- while True:
- events = run.snapshot(seen)
- if events:
- for ev in events:
- kind = ev["type"]
- msg = ev["message"]
- if kind == "info":
- log_info(dim(msg))
- elif kind == "config":
- p = ev.get("profile", {})
- log_info(
- dim(f"{p.get('name', '')} {p.get('binding', '')} {p.get('base_url', '')}")
- )
- elif kind == "response":
- snippet = ev.get("snippet", "")
- d_actual = ev.get("actual_dimension")
- if snippet:
- log_success(f"Response received {dim(snippet[:120])}")
- elif d_actual is not None:
- log_success(f"Embedding OK dim={d_actual}")
- else:
- log_success("Response received")
- elif kind == "completed":
- log_success(msg)
- elif kind == "failed":
- log_error(msg)
- seen += len(events)
- last = events[-1]["type"]
- if last in ("completed", "failed"):
- return last == "completed"
- time.sleep(0.15)
-# ---------------------------------------------------------------------------
-# Build final .env dict
-# ---------------------------------------------------------------------------
+def _save_ui_language(language: str, path: Path = INTERFACE_SETTINGS_PATH) -> None:
+ payload: dict[str, Any] = {"theme": "light", "language": language}
+ if path.exists():
+ try:
+ payload.update(json.loads(path.read_text(encoding="utf-8")) or {})
+ except Exception:
+ pass
+ payload["language"] = "zh" if language == "zh" else "en"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
-def _build_env(ports: dict[str, int], catalog: dict[str, Any]) -> dict[str, str]:
- rendered = get_env_store().render_from_catalog(catalog)
- rendered["BACKEND_PORT"] = str(ports["backend"])
- rendered["FRONTEND_PORT"] = str(ports["frontend"])
- return rendered
+def _ensure_env_file(env_path: Path = ENV_PATH, template_path: Path = ENV_EXAMPLE_PATH) -> bool:
+ if env_path.exists():
+ return False
+ env_path.parent.mkdir(parents=True, exist_ok=True)
+ if template_path.exists():
+ shutil.copyfile(template_path, env_path)
+ return True
+ env_path.write_text("", encoding="utf-8")
+ return True
-# ---------------------------------------------------------------------------
-# Tour banner
-# ---------------------------------------------------------------------------
-def _tour_banner() -> None:
- banner(
- "DeepTutor Setup Tour",
- [
- "Configure your local DeepTutor environment.",
- "Choose a workflow, set API endpoints, verify connections.",
- ],
- )
+def _cleanup_legacy_tour_cache(path: Path = LEGACY_TOUR_CACHE_PATH) -> bool:
+ if not path.exists():
+ return False
+ path.unlink(missing_ok=True)
+ return True
-# ===================================================================
-# Web path — install deps, start temp server, wait for browser config
-# ===================================================================
+def _prompt_int(prompt: str, default: int) -> int:
+ while True:
+ value = text_input(prompt, str(default)).strip()
+ try:
+ return int(value)
+ except ValueError:
+ log_warn(f"{prompt}: {value!r} is not a valid integer.")
-def _stream_text_kwargs() -> dict[str, object]:
- """Best-effort text decoding for background process output."""
- # Some Windows child processes emit locale-specific bytes even when Python
- # runs in UTF-8 mode. Replace undecodable bytes so the background drain
- # thread keeps consuming output instead of crashing.
- encoding = locale.getpreferredencoding(False) or "utf-8"
- return {
- "stdout": subprocess.PIPE,
- "stderr": subprocess.STDOUT,
- "text": True,
- "encoding": encoding,
- "errors": "replace",
- "bufsize": 1,
- }
-def _spawn_process(
- cmd: list[str],
- *,
- cwd: Path,
- env: dict[str, str],
- name: str,
-) -> subprocess.Popen[str]:
- import threading
-
- kwargs: dict[str, object] = {
- "cwd": str(cwd),
- "env": env,
- **_stream_text_kwargs(),
- }
- if os.name == "nt":
- kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore[attr-defined]
- else:
- kwargs["start_new_session"] = True
+def _prompt_secret(prompt: str, default: str) -> str:
+ if default:
+ log_info(dim(_t("keep_secret")))
+ return text_input(prompt, default, secret=True)
- proc = subprocess.Popen(cmd, **kwargs) # type: ignore[arg-type]
- def _drain() -> None:
- assert proc.stdout is not None
- for line in proc.stdout:
- pass # silently drain; tour terminal stays clean
- threading.Thread(target=_drain, daemon=True).start()
- return proc
+def _enum_options(options: list[tuple[str, str, str]], current: str | None = None) -> list[tuple[str, str, str]]:
+ normalized_current = str(current or "").strip()
+ if not normalized_current:
+ return options
+ seen = {value for value, _, _ in options}
+ if normalized_current in seen:
+ return options
+ current_label = normalized_current
+ current_desc = "current value" if _LANG == "en" else "当前值"
+ return [(normalized_current, current_label, current_desc)] + options
-def _kill_process(proc: subprocess.Popen[str] | None, name: str) -> None:
- import signal as _sig
- if proc is None or proc.poll() is not None:
- return
- try:
- if os.name == "nt":
- proc.send_signal(_sig.CTRL_BREAK_EVENT) # type: ignore[attr-defined]
- else:
- os.killpg(os.getpgid(proc.pid), _sig.SIGTERM)
- proc.wait(timeout=5)
- except Exception:
- proc.kill()
+def _load_provider_metadata():
+ from deeptutor.services.config.provider_runtime import EMBEDDING_PROVIDERS
+ from deeptutor.services.provider_registry import find_by_name
+ return EMBEDDING_PROVIDERS, find_by_name
-def _run_web_tour() -> None:
- total = 4
- # -- Step 1: Profile ---------------------------------------------------
- step(1, total, "Install profile")
- profile = select(
- "Choose a dependency profile",
- [
- ("web-basic", "web-basic", "FastAPI + Next.js"),
- ("web-rag", "web-rag", "+ LlamaIndex RAG"),
- ],
- )
- _save_cache({"step": 1, "mode": "web", "profile": profile, "status": "running"})
- # -- Step 2: Ports -----------------------------------------------------
- step(2, total, "Ports")
- summary = get_env_store().as_summary()
- ports = {
- "backend": summary.backend_port,
- "frontend": summary.frontend_port,
- }
- ports["frontend"] = int(text_input("Frontend port", str(ports["frontend"])))
- ports["backend"] = int(text_input("Backend port", str(ports["backend"])))
- print()
- _save_cache({"step": 2, "mode": "web", "profile": profile, "ports": ports, "status": "running"})
-
- # -- Step 3: Install dependencies --------------------------------------
- catalog = get_model_catalog_service().load()
-
- step(3, total, "Install dependencies")
- if confirm("Install dependencies now?", default=True):
- install_math_animator = confirm("Install Math Animator addon (Manim) now?", default=True)
- if not (shutil.which("node") and shutil.which("npm")):
- cmd = _node_install_cmd()
- if cmd:
- if confirm(f"Node.js not found. Install via {cmd[0]}?", default=True):
- _run_cmd(cmd, PROJECT_ROOT)
- else:
- log_warn("No automatic Node.js installer found for this platform.")
- if install_math_animator:
- _ensure_math_animator_system_deps()
-
- for cmd, cwd in _install_commands(
- profile,
- catalog,
- include_math_animator=install_math_animator,
- ):
- _run_cmd(cmd, cwd)
- log_success("Dependencies installed.")
- else:
- log_warn("Skipped. You can rerun the tour later.")
- print()
+def _llm_provider_options(current: str | None) -> list[tuple[str, str, str]]:
+ _, find_by_name = _load_provider_metadata()
+ common = [
+ "openai",
+ "anthropic",
+ "deepseek",
+ "gemini",
+ "dashscope",
+ "zhipu",
+ "groq",
+ "ollama",
+ "lm_studio",
+ "azure_openai",
+ "custom",
+ ]
+ options: list[tuple[str, str, str]] = []
+ for name in common:
+ spec = find_by_name(name)
+ label = spec.label if spec else name
+ if name == "custom":
+ desc = _t("custom_desc")
+ elif spec and spec.is_local:
+ desc = _t("local_desc")
+ else:
+ desc = spec.default_api_base if spec and spec.default_api_base else ""
+ options.append((name, label, desc))
+ return _enum_options(options, current)
+
+
+
+def _embedding_provider_options(current: str | None) -> list[tuple[str, str, str]]:
+ embedding_providers, _ = _load_provider_metadata()
+ common = ["openai", "jina", "cohere", "ollama", "vllm", "azure_openai", "custom"]
+ options: list[tuple[str, str, str]] = []
+ for name in common:
+ spec = embedding_providers.get(name)
+ label = spec.label if spec else name
+ if name == "custom":
+ desc = _t("custom_desc")
+ elif spec and spec.is_local:
+ desc = _t("local_desc")
+ else:
+ desc = spec.default_api_base if spec and spec.default_api_base else ""
+ options.append((name, label, desc))
+ return _enum_options(options, current)
- # -- Step 4: Start temp server & wait for browser config ---------------
- step(4, total, "Configure in browser")
- # Write ports to .env for the temp server
- get_env_store().write(_build_env(ports, catalog))
- # Mark cache as waiting (the backend reads this)
- _save_cache(
- {
- "step": 4,
- "mode": "web",
- "profile": profile,
- "ports": ports,
- "status": "waiting",
- }
- )
+def _search_provider_options(current: str | None) -> list[tuple[str, str, str]]:
+ options = [
+ (value, label, _t("search_none_desc") if value == "none" else desc)
+ for value, label, desc in SEARCH_PROVIDERS
+ ]
+ return _enum_options(options, current)
- npm = _get_npm_command()
- # Verify npm is actually available and works
- try:
- subprocess.run([npm, "--version"], capture_output=True, check=True)
- except (subprocess.CalledProcessError, FileNotFoundError):
- log_error("npm not found. Cannot start frontend.")
- raise SystemExit(1)
-
- api_base = f"http://localhost:{ports['backend']}"
-
- # Write web/.env.local so the frontend picks up the correct backend port
- env_local_path = PROJECT_ROOT / "web" / ".env.local"
- env_local_path.write_text(
- f"# Auto-generated by start_tour.py — do not edit manually\n"
- f"NEXT_PUBLIC_API_BASE={api_base}\n"
- )
- backend_env = os.environ.copy()
- backend_env["PYTHONUNBUFFERED"] = "1"
- frontend_env = os.environ.copy()
- frontend_env["NEXT_PUBLIC_API_BASE"] = api_base
+def _default_base_url(binding: str, current_binding: str, current_value: str, fallback: str = "") -> str:
+ if current_value and binding == current_binding:
+ return current_value
+ embedding_providers, find_by_name = _load_provider_metadata()
+ if binding in embedding_providers:
+ return embedding_providers[binding].default_api_base or fallback
+ spec = find_by_name(binding)
+ if spec and spec.default_api_base:
+ return spec.default_api_base
+ return fallback
- backend_cmd = [_PYTHON, "-m", "deeptutor.api.run_server"]
- frontend_cmd = [npm, "run", "dev", "--", "--port", str(ports["frontend"])]
- log_info("Starting temporary server ...")
- backend = _spawn_process(backend_cmd, cwd=PROJECT_ROOT, env=backend_env, name="backend")
- time.sleep(2)
- frontend = _spawn_process(
- frontend_cmd, cwd=PROJECT_ROOT / "web", env=frontend_env, name="frontend"
- )
- time.sleep(3)
- settings_url = f"http://localhost:{ports['frontend']}/settings?tour=true"
+def _default_llm_model(binding: str, current_binding: str, current_model: str) -> str:
+ if current_model and binding == current_binding:
+ return current_model
+ return LLM_MODEL_SUGGESTIONS.get(binding, current_model)
- banner(
- "Setup Tour",
- [
- f"Open {settings_url}",
- "Configure your endpoints in the browser, then click 'Complete & Launch'.",
- "Waiting for you to finish ...",
- ],
- )
- # Poll the cache file for the "completed" signal from the backend
- try:
- while True:
- if backend.poll() is not None:
- log_error(f"Backend exited unexpectedly (code {backend.returncode}).")
- _kill_process(frontend, "frontend")
- raise SystemExit(1)
- cache = _load_cache()
- if cache and cache.get("status") == "completed":
- break
- time.sleep(1)
- except KeyboardInterrupt:
- log_warn("Interrupted. Stopping temporary server ...")
- _kill_process(frontend, "frontend")
- _kill_process(backend, "backend")
- raise SystemExit(130)
- log_success("Configuration complete!")
- print()
+def _default_embedding_model(binding: str, current_binding: str, current_model: str) -> str:
+ if current_model and binding == current_binding:
+ return current_model
+ embedding_providers, _ = _load_provider_metadata()
+ spec = embedding_providers.get(binding)
+ if spec and spec.default_model:
+ return spec.default_model
+ return EMBEDDING_MODEL_SUGGESTIONS.get(binding, current_model)
- # Shut down temp server
- log_info("Stopping temporary server ...")
- _kill_process(frontend, "frontend")
- _kill_process(backend, "backend")
- time.sleep(1)
- _cleanup_cache()
- log_info("Restarting DeepTutor with your configuration ...")
- print()
- launch_at = None
- if cache:
- try:
- launch_at = int(cache.get("launch_at")) if cache.get("launch_at") is not None else None
- except (TypeError, ValueError):
- launch_at = None
+def _default_embedding_dimension(binding: str, current_binding: str, current_value: str) -> str:
+ if current_value and binding == current_binding:
+ return current_value
+ embedding_providers, _ = _load_provider_metadata()
+ spec = embedding_providers.get(binding)
+ if spec and spec.default_dim:
+ return str(spec.default_dim)
+ return current_value or "3072"
- remaining = max(1, int((launch_at - time.time()) + 0.999)) if launch_at else 3
- countdown(remaining, "Launching in")
- print()
- os.execvp(_PYTHON, [_PYTHON, str(PROJECT_ROOT / "scripts" / "start_web.py")])
+def _send_dimensions_choice(current_value: str) -> str:
+ normalized = str(current_value or "").strip().lower()
+ if normalized in {"true", "1", "yes", "on"}:
+ default = "true"
+ elif normalized in {"false", "0", "no", "off"}:
+ default = "false"
+ else:
+ default = "auto"
+ return select(
+ _t("send_dimensions"),
+ [
+ ("auto", _t("send_dimensions_auto"), ""),
+ ("true", _t("send_dimensions_yes"), ""),
+ ("false", _t("send_dimensions_no"), ""),
+ ],
+ ) or default
-# ===================================================================
-# CLI path — full interactive configuration in the terminal
-# ===================================================================
+# ---------------------------------------------------------------------------
+# Wizard steps
+# ---------------------------------------------------------------------------
-def _run_cli_tour() -> None:
- total = 6
- # -- Step 1: Profile ---------------------------------------------------
- step(1, total, "Install profile")
- profile = select(
- "Choose a dependency profile",
+def _choose_language() -> str:
+ step(1, 6, "Language")
+ language = select(
+ "Choose language / 选择语言",
[
- ("cli-core", "cli-core", "Minimal CLI (~80 MB)"),
- ("cli-rag", "cli-rag", "+ LlamaIndex RAG"),
+ ("en", "English", "Run the setup wizard in English"),
+ ("zh", "中文", "使用中文完成配置"),
],
)
- _save_cache({"step": 1, "mode": "cli", "profile": profile})
+ _set_language(language)
+ _save_ui_language(language)
+ log_success(_t("language_saved", path=INTERFACE_SETTINGS_PATH.relative_to(PROJECT_ROOT)))
+ print()
+ return language
+
+
- # -- Step 2: Ports -----------------------------------------------------
- step(2, total, "Ports")
+def _configure_ports() -> dict[str, str]:
+ step(2, 6, _t("ports_step"))
summary = get_env_store().as_summary()
- ports = {
- "backend": summary.backend_port,
- "frontend": summary.frontend_port,
- }
- ports["backend"] = int(text_input("Backend port", str(ports["backend"])))
+ backend_port = _prompt_int(_t("backend_port"), summary.backend_port)
+ frontend_port = _prompt_int(_t("frontend_port"), summary.frontend_port)
print()
- _save_cache({"step": 2, "mode": "cli", "profile": profile, "ports": ports})
+ return {
+ "BACKEND_PORT": str(backend_port),
+ "FRONTEND_PORT": str(frontend_port),
+ }
- # -- Step 3: Install dependencies --------------------------------------
- catalog = get_model_catalog_service().load()
- step(3, total, "Install dependencies")
- if confirm("Install dependencies now?", default=True):
- for cmd, cwd in _install_commands(profile, catalog):
- _run_cmd(cmd, cwd)
- log_success("Dependencies installed.")
- else:
- log_warn("Skipped. You can rerun the tour later.")
- print()
- _save_cache({"step": 3, "mode": "cli", "profile": profile, "ports": ports})
- # -- Step 4: Configure providers ---------------------------------------
- step(4, total, "Configure providers")
- _configure_service(catalog, "llm")
- _configure_service(catalog, "embedding")
+def _configure_llm() -> dict[str, str]:
+ step(3, 6, _t("llm_step"))
+ summary = get_env_store().as_summary()
+ current_binding = summary.llm["binding"] or "openai"
+ binding = select(_t("provider_prompt"), _llm_provider_options(current_binding))
+ base_url = text_input(
+ _t("base_url"),
+ _default_base_url(binding, current_binding, summary.llm["host"]),
+ )
+ api_key = _prompt_secret(_t("api_key"), summary.llm["api_key"])
+ model_id = text_input(
+ _t("model_id"),
+ _default_llm_model(binding, current_binding, summary.llm["model"]),
+ )
+ api_version_default = summary.llm["api_version"] if binding == current_binding else ""
+ api_version = text_input(_t("api_version"), api_version_default)
+ print()
+ return {
+ "LLM_BINDING": binding,
+ "LLM_HOST": base_url,
+ "LLM_API_KEY": api_key,
+ "LLM_MODEL": model_id,
+ "LLM_API_VERSION": api_version,
+ }
- search_enabled = False
- if confirm("Configure a search provider?", default=False):
- _configure_service(catalog, "search")
- search_enabled = True
- _save_cache({"step": 4, "mode": "cli", "profile": profile, "ports": ports})
- # -- Step 5: Live diagnostics ------------------------------------------
- step(5, total, "Verify connections")
- llm_ok = _stream_test("llm", catalog)
- print()
- emb_ok = _stream_test("embedding", catalog)
+def _configure_embedding() -> dict[str, str]:
+ step(4, 6, _t("embedding_step"))
+ summary = get_env_store().as_summary()
+ current_binding = summary.embedding["binding"] or "openai"
+ binding = select(_t("provider_prompt"), _embedding_provider_options(current_binding))
+ base_url = text_input(
+ _t("base_url"),
+ _default_base_url(binding, current_binding, summary.embedding["host"]),
+ )
+ api_key = _prompt_secret(_t("api_key"), summary.embedding["api_key"])
+ model_id = text_input(
+ _t("model_id"),
+ _default_embedding_model(binding, current_binding, summary.embedding["model"]),
+ )
+ dimension = text_input(
+ _t("dimension"),
+ _default_embedding_dimension(binding, current_binding, summary.embedding["dimension"]),
+ )
+ send_dimensions = _send_dimensions_choice(summary.embedding["send_dimensions"])
+ api_version_default = summary.embedding["api_version"] if binding == current_binding else ""
+ api_version = text_input(_t("api_version"), api_version_default)
print()
+ return {
+ "EMBEDDING_BINDING": binding,
+ "EMBEDDING_HOST": base_url,
+ "EMBEDDING_API_KEY": api_key,
+ "EMBEDDING_MODEL": model_id,
+ "EMBEDDING_DIMENSION": dimension,
+ "EMBEDDING_SEND_DIMENSIONS": "" if send_dimensions == "auto" else send_dimensions,
+ "EMBEDDING_API_VERSION": api_version,
+ }
+
+
+
+def _configure_search() -> dict[str, str]:
+ step(5, 6, _t("search_step"))
+ summary = get_env_store().as_summary()
+ current_provider = summary.search["provider"] or "none"
+ provider = select(_t("search_provider_prompt"), _search_provider_options(current_provider))
- if search_enabled:
- _stream_test("search", catalog)
+ if provider == "none":
print()
+ return {
+ "SEARCH_PROVIDER": "",
+ "SEARCH_API_KEY": "",
+ "SEARCH_BASE_URL": "",
+ "SEARCH_PROXY": "",
+ }
+
+ base_url_default = summary.search["base_url"] if provider == current_provider else ""
+ if provider == "searxng" and not base_url_default:
+ base_url_default = _t("searxng_default")
+ api_key_default = summary.search["api_key"] if provider == current_provider else ""
+ proxy_default = summary.search["proxy"] if provider == current_provider else ""
+
+ base_url = base_url_default
+ if provider == "searxng" or base_url_default:
+ base_url = text_input(_t("search_base_url"), base_url_default)
+
+ api_key = ""
+ if provider in {"brave", "tavily", "jina", "perplexity"} or api_key_default:
+ api_key = _prompt_secret(_t("api_key"), api_key_default)
- if not llm_ok or not emb_ok:
- log_error("LLM and Embedding must both pass before saving.")
- raise SystemExit(1)
+ proxy = text_input(_t("search_proxy"), proxy_default or _t("search_proxy_placeholder"))
+ if proxy == _t("search_proxy_placeholder") and not proxy_default:
+ proxy = ""
- # -- Step 6: Review & apply --------------------------------------------
- step(6, total, "Review & apply")
+ print()
+ return {
+ "SEARCH_PROVIDER": provider,
+ "SEARCH_API_KEY": api_key,
+ "SEARCH_BASE_URL": base_url,
+ "SEARCH_PROXY": proxy,
+ }
- llm_p = get_model_catalog_service().get_active_profile(catalog, "llm")
- llm_m = get_model_catalog_service().get_active_model(catalog, "llm")
- emb_p = get_model_catalog_service().get_active_profile(catalog, "embedding")
- emb_m = get_model_catalog_service().get_active_model(catalog, "embedding")
- search_p = get_model_catalog_service().get_active_profile(catalog, "search")
- log_info(f"Profile {bold(profile)}")
- log_info(f"Backend {bold(str(ports['backend']))}")
+
+def _print_review(values: dict[str, str]) -> None:
+ step(6, 6, _t("review_step"))
log_info(
- f"LLM {bold((llm_p or {}).get('name', '?'))} {dim((llm_m or {}).get('model', '?'))}"
+ f"{_t('summary_ports')} {bold(values['BACKEND_PORT'])} / {bold(values['FRONTEND_PORT'])}"
)
log_info(
- f"Embedding {bold((emb_p or {}).get('name', '?'))} {dim((emb_m or {}).get('model', '?'))}"
+ "{} {} {} {}".format(
+ _t("summary_llm"),
+ bold(values["LLM_BINDING"] or "-"),
+ dim(values["LLM_MODEL"] or "-"),
+ dim(values["LLM_HOST"] or "-"),
+ )
)
- if search_enabled:
- log_info(f"Search {bold((search_p or {}).get('name', '?'))}")
- else:
- log_info(f"Search {dim('skipped')}")
+ log_info(
+ "{} {} {} {}".format(
+ _t("summary_embedding"),
+ bold(values["EMBEDDING_BINDING"] or "-"),
+ dim(values["EMBEDDING_MODEL"] or "-"),
+ dim(values["EMBEDDING_HOST"] or "-"),
+ )
+ )
+ search_summary = values["SEARCH_PROVIDER"] or _t("search_disabled")
+ log_info(f"{_t('summary_search')} {bold(search_summary)}")
+ log_info(f"LLM key {dim(_secret_mask(values['LLM_API_KEY']))}")
+ log_info(f"Emb key {dim(_secret_mask(values['EMBEDDING_API_KEY']))}")
+ if values["SEARCH_PROVIDER"]:
+ log_info(f"Search key {dim(_secret_mask(values['SEARCH_API_KEY']))}")
print()
- if not confirm("Write configuration?", default=True):
- log_warn("No files changed.")
- _cleanup_cache()
- raise SystemExit(0)
- get_model_catalog_service().save(catalog)
- get_env_store().write(_build_env(ports, catalog))
- log_success("Saved model_catalog.json and .env")
- _cleanup_cache()
+def _write_env(values: dict[str, str]) -> None:
+ get_env_store().write(values)
- print()
- log_success("Tour complete. Next commands:")
- print()
- print(f" {dim('$')} deeptutor chat")
- print(f" {dim('$')} deeptutor kb list")
- print(f" {dim('$')} deeptutor serve --port {ports['backend']}")
- print()
-# ===================================================================
-# Entry
-# ===================================================================
+def _tour_banner() -> None:
+ banner(
+ "DeepTutor Setup Tour / DeepTutor 配置向导",
+ [
+ "CLI-first setup wizard.",
+ "命令行配置向导。",
+ ],
+ )
+
def run_tour() -> None:
_tour_banner()
- log_info(f"Platform {dim(f'{platform.system()} {platform.release()}')}")
- log_info(f"Python {dim(_python_strategy())}")
- log_info(f"Node {dim(_node_strategy())}")
+ created_env = _ensure_env_file()
+ removed_cache = _cleanup_legacy_tour_cache()
+
+ _choose_language()
+
+ if created_env:
+ if ENV_EXAMPLE_PATH.exists():
+ log_success(_t("env_created"))
+ else:
+ log_warn(_t("env_missing_template"))
+ else:
+ log_info(_t("env_exists"))
+ if removed_cache:
+ log_info(_t("tour_cache_removed"))
+
+ log_info(f"{_t('platform')} {dim(f'{platform.system()} {platform.release()}')}")
+ log_info(f"{_t('python')} {dim(_resolve_python())}")
+ log_info(f"{_t('node')} {dim(_node_strategy())}")
+ log_info(f"{_t('env_path')} {dim(str(ENV_PATH.relative_to(PROJECT_ROOT)))}")
print()
- cache = _load_cache()
- if cache:
- log_warn("A previous tour session was interrupted.")
- if not confirm("Resume where you left off?", default=True):
- _cleanup_cache()
- cache = None
+ values: dict[str, str] = {}
+ values.update(_configure_ports())
+ values.update(_configure_llm())
+ values.update(_configure_embedding())
+ values.update(_configure_search())
- step(1, "?", "Choose mode")
- mode = select(
- "How would you like to use DeepTutor?",
- [
- ("web", "web", "Browser UI — configure in Settings page (recommended)"),
- ("cli", "cli", "Terminal only — configure interactively here"),
- ],
- )
+ _print_review(values)
+ if not confirm(_t("write_confirm"), default=True):
+ log_warn(_t("no_changes"))
+ return
+
+ _write_env(values)
+ log_success(_t("write_success"))
+ print()
+ log_success(_t("next_steps"))
+ print()
+ print(f" {dim('$')} {_t('next_command')}")
+ print()
- if mode == "web":
- _run_web_tour()
- else:
- _run_cli_tour()
def main() -> None:
@@ -966,7 +825,7 @@ def main() -> None:
run_tour()
except KeyboardInterrupt:
print()
- log_warn("Tour interrupted.")
+ log_warn(_t("interrupt"))
raise SystemExit(130)
diff --git a/tests/agents/question/test_language_prompts.py b/tests/agents/question/test_language_prompts.py
new file mode 100644
index 000000000..4e99f005a
--- /dev/null
+++ b/tests/agents/question/test_language_prompts.py
@@ -0,0 +1,156 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from deeptutor.agents.question.agents.followup_agent import FollowupAgent
+from deeptutor.agents.question.agents.generator import Generator
+from deeptutor.agents.question.agents.idea_agent import IdeaAgent
+from deeptutor.agents.question.models import QuestionTemplate
+
+
+class CaptureIdeaAgent(IdeaAgent):
+ def __init__(self, language: str = "zh") -> None:
+ self.language = language
+ self.prompts = {
+ "system": "Idea agent system",
+ "generate_ideas": (
+ "Topic: {user_topic}\n"
+ "Preference: {preference}\n"
+ "Knowledge context:\n{knowledge_context}\n"
+ "Existing concentrations:\n{existing_concentrations}\n"
+ 'Return JSON {{"ideas":[{{"idea_id":"idea_1","concentration":"基础概念","question_type":"written","difficulty":"medium","rationale":"覆盖核心知识点"}}]}}'
+ ),
+ }
+ self.logger = SimpleNamespace(warning=lambda *args, **kwargs: None)
+ self.captured_system_prompts: list[str] = []
+
+ async def stream_llm(self, **kwargs): # type: ignore[override]
+ self.captured_system_prompts.append(str(kwargs["system_prompt"]))
+ yield (
+ '{"ideas":[{"idea_id":"idea_1","concentration":"基础概念",'
+ '"question_type":"written","difficulty":"medium",'
+ '"rationale":"覆盖核心知识点"}]}'
+ )
+
+
+class CaptureGenerator(Generator):
+ def __init__(self, language: str = "zh") -> None:
+ self.language = language
+ self.prompts = {
+ "system": "Generator system",
+ "generate": (
+ "QuestionTemplate:\n{template}\n"
+ "User topic:\n{user_topic}\n"
+ "User preference:\n{preference}\n"
+ "Knowledge context:\n{knowledge_context}\n"
+ "Tools:\n{available_tools}\n"
+ "History:\n{history_context}\n"
+ "Previous questions:\n{previous_questions}\n"
+ 'Return JSON {{"question_type":"written","question":"问题","options":null,"correct_answer":"答案","explanation":"解释"}}'
+ ),
+ }
+ self.captured_system_prompts: list[str] = []
+
+ async def stream_llm(self, **kwargs): # type: ignore[override]
+ self.captured_system_prompts.append(str(kwargs["system_prompt"]))
+ yield (
+ '{"question_type":"written","question":"问题",'
+ '"options":null,"correct_answer":"答案","explanation":"解释"}'
+ )
+
+
+class CaptureFollowupAgent(FollowupAgent):
+ def __init__(self, language: str = "zh") -> None:
+ self.language = language
+ self.prompts = {
+ "system": "Followup system",
+ "answer_followup": (
+ "Question context:\n{question_context}\n\n"
+ "Conversation history:\n{history_context}\n\n"
+ "User follow-up:\n{user_message}\n"
+ ),
+ }
+ self.captured_system_prompts: list[str] = []
+
+ async def stream_llm(self, **kwargs): # type: ignore[override]
+ self.captured_system_prompts.append(str(kwargs["system_prompt"]))
+ yield "已回答"
+
+
+async def test_idea_agent_appends_language_directive_to_system_prompt() -> None:
+ agent = CaptureIdeaAgent(language="zh")
+
+ templates = await agent._generate_templates(
+ user_topic="线性代数",
+ preference="请用中文出题",
+ knowledge_context="矩阵和向量空间",
+ num_ideas=1,
+ )
+
+ assert templates
+ assert agent.captured_system_prompts
+ assert "Idea agent system" in agent.captured_system_prompts[0]
+ assert "请严格使用中文(简体)" in agent.captured_system_prompts[0]
+
+
+async def test_generator_appends_language_directive_to_generate_and_repair_prompts() -> None:
+ agent = CaptureGenerator(language="zh")
+ template = QuestionTemplate(
+ question_id="q_1",
+ concentration="矩阵乘法",
+ question_type="written",
+ difficulty="medium",
+ )
+
+ payload = await agent._generate_payload(
+ template=template,
+ user_topic="线性代数",
+ preference="请使用中文",
+ history_context="",
+ knowledge_context="矩阵乘法的定义",
+ available_tools="(no tools available)",
+ )
+
+ repaired = await agent._repair_payload(
+ template=template,
+ payload=payload,
+ issues=["missing_explanation"],
+ user_topic="线性代数",
+ preference="请使用中文",
+ history_context="",
+ knowledge_context="矩阵乘法的定义",
+ available_tools="(no tools available)",
+ )
+
+ assert repaired["question"] == "问题"
+ assert len(agent.captured_system_prompts) == 2
+ assert "Generator system" in agent.captured_system_prompts[0]
+ assert "请严格使用中文(简体)" in agent.captured_system_prompts[0]
+ assert "You fix malformed quiz payloads" in agent.captured_system_prompts[1]
+ assert "请严格使用中文(简体)" in agent.captured_system_prompts[1]
+
+
+async def test_followup_agent_appends_language_directive_to_system_prompt() -> None:
+ agent = CaptureFollowupAgent(language="zh")
+
+ reply = await agent.process(
+ user_message="为什么这题是这个答案?",
+ question_context={
+ "question_id": "q_1",
+ "question_type": "choice",
+ "question": "矩阵乘法什么时候有定义?",
+ "correct_answer": "当内维度一致时。",
+ "explanation": "矩阵 A 的列数必须等于矩阵 B 的行数。",
+ },
+ history_context="",
+ )
+
+ assert reply == "已回答"
+ assert agent.captured_system_prompts
+ assert "Followup system" in agent.captured_system_prompts[0]
+ assert "请严格使用中文(简体)" in agent.captured_system_prompts[0]
diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.py
index ae854b4b8..9d931a397 100644
--- a/tests/api/test_knowledge_router.py
+++ b/tests/api/test_knowledge_router.py
@@ -78,6 +78,10 @@ def _upload_payload() -> list[tuple[str, tuple[str, bytes, str]]]:
return [("files", ("demo.txt", b"hello", "text/plain"))]
+def _invalid_upload_payload() -> list[tuple[str, tuple[str, bytes, str]]]:
+ return [("files", ("archive.zip", b"PK\x03\x04", "application/zip"))]
+
+
def test_rag_providers_returns_llamaindex_only() -> None:
with TestClient(_build_app()) as client:
response = client.get("/api/v1/knowledge/rag-providers")
@@ -95,6 +99,18 @@ def test_rag_providers_returns_llamaindex_only() -> None:
}
+def test_supported_file_types_returns_upload_policy() -> None:
+ with TestClient(_build_app()) as client:
+ response = client.get("/api/v1/knowledge/supported-file-types")
+
+ assert response.status_code == 200
+ payload = response.json()
+ assert ".pdf" in payload["extensions"]
+ assert ".md" in payload["extensions"]
+ assert payload["max_file_size_bytes"] > payload["max_pdf_size_bytes"] > 0
+ assert ".pdf" in payload["accept"]
+
+
def test_create_kb_does_not_require_llm_precheck(monkeypatch, tmp_path: Path) -> None:
manager = _FakeKBManager(tmp_path / "knowledge_bases")
monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)
@@ -149,6 +165,25 @@ def test_create_coerces_legacy_provider_to_llamaindex(monkeypatch, tmp_path: Pat
assert manager.config["knowledge_bases"]["kb-legacy"]["rag_provider"] == "llamaindex"
+def test_create_rejects_invalid_files_before_registering_kb(
+ monkeypatch, tmp_path: Path
+) -> None:
+ manager = _FakeKBManager(tmp_path / "knowledge_bases")
+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)
+ monkeypatch.setattr(knowledge_router_module, "_kb_base_dir", tmp_path / "knowledge_bases")
+
+ with TestClient(_build_app()) as client:
+ response = client.post(
+ "/api/v1/knowledge/create",
+ data={"name": "kb-invalid", "rag_provider": "llamaindex"},
+ files=_invalid_upload_payload(),
+ )
+
+ assert response.status_code == 400
+ assert "unsupported file type" in response.json()["detail"].lower()
+ assert "kb-invalid" not in manager.config["knowledge_bases"]
+
+
def test_upload_returns_409_when_kb_needs_reindex(monkeypatch, tmp_path: Path) -> None:
manager = _FakeKBManager(tmp_path / "knowledge_bases")
manager.config["knowledge_bases"]["legacy-kb"] = {
diff --git a/tests/knowledge/test_manager_delete.py b/tests/knowledge/test_manager_delete.py
new file mode 100644
index 000000000..b1faf822a
--- /dev/null
+++ b/tests/knowledge/test_manager_delete.py
@@ -0,0 +1,79 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from deeptutor.knowledge.manager import KnowledgeBaseManager
+
+
+def _create_kb(manager: KnowledgeBaseManager, name: str) -> Path:
+ kb_dir = manager.base_dir / name
+ (kb_dir / "raw").mkdir(parents=True, exist_ok=True)
+ (kb_dir / "llamaindex_storage").mkdir(parents=True, exist_ok=True)
+ manager.config.setdefault("knowledge_bases", {})[name] = {
+ "path": name,
+ "description": "",
+ }
+ manager._save_config()
+ return kb_dir
+
+
+def _read_config(path: Path) -> dict:
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def test_delete_knowledge_base_removes_config_and_directory(tmp_path: Path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path))
+ kb_dir = _create_kb(manager, "demo")
+
+ assert manager.delete_knowledge_base("demo", confirm=True) is True
+
+ assert not kb_dir.exists()
+ assert "demo" not in _read_config(manager.config_file).get("knowledge_bases", {})
+
+
+def test_delete_knowledge_base_clears_config_when_rmtree_fails(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Regression for issue #370.
+
+ If a KB was left in a broken state (e.g. ``Initialization failed: RAG pipeline
+ returned failure``) and its directory can no longer be fully removed (stale
+ file handles, read-only bits on Windows bind mounts, etc.), deletion must
+ still purge the config entry so the KB disappears from the list. Previously
+ the raised OSError aborted the delete and the entry was stuck forever.
+ """
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path))
+ _create_kb(manager, "broken")
+
+ import shutil as _shutil
+
+ def _rmtree_always_errors(path, onerror=None, **_kwargs):
+ # Simulate a persistent OSError that chmod-retry cannot recover from.
+ if onerror is not None:
+ onerror(_shutil.rmtree, str(path), (OSError, OSError("busy"), None))
+
+ monkeypatch.setattr(_shutil, "rmtree", _rmtree_always_errors)
+ # The manager imports shutil at module level, so patch there too.
+ from deeptutor.knowledge import manager as manager_mod
+
+ monkeypatch.setattr(manager_mod.shutil, "rmtree", _rmtree_always_errors)
+
+ assert manager.delete_knowledge_base("broken", confirm=True) is True
+ assert "broken" not in _read_config(manager.config_file).get("knowledge_bases", {})
+
+
+def test_delete_knowledge_base_removes_orphan_config_when_directory_missing(
+ tmp_path: Path,
+) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path))
+ _create_kb(manager, "orphan")
+ # Simulate the on-disk directory being wiped externally.
+ import shutil as _shutil
+
+ _shutil.rmtree(manager.base_dir / "orphan")
+
+ assert manager.delete_knowledge_base("orphan", confirm=True) is True
+ assert "orphan" not in _read_config(manager.config_file).get("knowledge_bases", {})
diff --git a/tests/knowledge/test_progress_tracker.py b/tests/knowledge/test_progress_tracker.py
new file mode 100644
index 000000000..16f4590b5
--- /dev/null
+++ b/tests/knowledge/test_progress_tracker.py
@@ -0,0 +1,58 @@
+from __future__ import annotations
+
+import json
+
+from deeptutor.knowledge.manager import KnowledgeBaseManager
+from deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker
+
+
+def test_progress_tracker_persists_snapshot_and_config(tmp_path) -> None:
+ tracker = ProgressTracker("demo-kb", tmp_path)
+
+ tracker.update(
+ ProgressStage.PROCESSING_DOCUMENTS,
+ "Embedding batches: 2/8 complete",
+ current=2,
+ total=8,
+ )
+
+ assert tracker.progress_file.exists()
+
+ with open(tracker.progress_file, encoding="utf-8") as f:
+ payload = json.load(f)
+
+ assert payload["stage"] == "processing_documents"
+ assert payload["progress_percent"] == 25
+ assert payload["message"] == "Embedding batches: 2/8 complete"
+
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path))
+ status = manager.get_kb_status("demo-kb")
+
+ assert status is not None
+ assert status["status"] == "processing"
+ assert status["progress"]["message"] == "Embedding batches: 2/8 complete"
+
+
+def test_progress_tracker_get_progress_falls_back_to_config(tmp_path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path))
+ manager.update_kb_status(
+ name="demo-kb",
+ status="processing",
+ progress={
+ "stage": "processing_documents",
+ "message": "Recovered from kb_config",
+ "percent": 60,
+ "current": 3,
+ "total": 5,
+ },
+ )
+
+ tracker = ProgressTracker("demo-kb", tmp_path)
+
+ assert tracker.get_progress() == {
+ "stage": "processing_documents",
+ "message": "Recovered from kb_config",
+ "percent": 60,
+ "current": 3,
+ "total": 5,
+ }
diff --git a/tests/scripts/test_start_tour.py b/tests/scripts/test_start_tour.py
index f0054b793..364cc3744 100644
--- a/tests/scripts/test_start_tour.py
+++ b/tests/scripts/test_start_tour.py
@@ -141,3 +141,27 @@ class TestResolvePython:
assert cmd[0] == python_used, (
f"Expected resolved python {python_used!r}, got {cmd[0]!r}"
)
+
+
+def test_ensure_env_file_copies_template_when_missing(tmp_path: Path) -> None:
+ start_tour = _load_start_tour_module()
+ env_path = tmp_path / ".env"
+ template_path = tmp_path / ".env.example"
+ template_path.write_text("BACKEND_PORT=8001\n", encoding="utf-8")
+
+ created = start_tour._ensure_env_file(env_path=env_path, template_path=template_path)
+
+ assert created is True
+ assert env_path.read_text(encoding="utf-8") == "BACKEND_PORT=8001\n"
+
+
+def test_save_ui_language_preserves_existing_theme(tmp_path: Path) -> None:
+ start_tour = _load_start_tour_module()
+ settings_path = tmp_path / "interface.json"
+ settings_path.write_text('{"theme":"glass","language":"en"}', encoding="utf-8")
+
+ start_tour._save_ui_language("zh", path=settings_path)
+
+ saved = settings_path.read_text(encoding="utf-8")
+ assert '"theme": "glass"' in saved
+ assert '"language": "zh"' in saved
diff --git a/tests/services/config/test_chat_params_config.py b/tests/services/config/test_chat_params_config.py
index 04181f25e..717d1faea 100644
--- a/tests/services/config/test_chat_params_config.py
+++ b/tests/services/config/test_chat_params_config.py
@@ -7,6 +7,7 @@ from typing import Any
import yaml
+from deeptutor.services.config import loader as loader_module
from deeptutor.services.config.loader import (
DEFAULT_CHAT_PARAMS,
get_chat_params,
@@ -25,10 +26,7 @@ class TestGetChatParams:
"""Verify get_chat_params() correctly resolves capabilities.chat."""
def test_returns_defaults_when_file_missing(self, tmp_path: Path, monkeypatch):
- monkeypatch.setattr(
- "deeptutor.services.config.loader.PROJECT_ROOT",
- tmp_path,
- )
+ monkeypatch.setattr(loader_module, "PROJECT_ROOT", tmp_path)
params = get_chat_params()
assert params == DEFAULT_CHAT_PARAMS
@@ -39,10 +37,7 @@ class TestGetChatParams:
"capabilities": {"solve": {"temperature": 0.3}},
},
)
- monkeypatch.setattr(
- "deeptutor.services.config.loader.PROJECT_ROOT",
- project_root,
- )
+ monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)
params = get_chat_params()
assert params["temperature"] == DEFAULT_CHAT_PARAMS["temperature"]
assert params["responding"]["max_tokens"] == 8000
@@ -59,10 +54,7 @@ class TestGetChatParams:
},
},
)
- monkeypatch.setattr(
- "deeptutor.services.config.loader.PROJECT_ROOT",
- project_root,
- )
+ monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)
params = get_chat_params()
assert params["responding"]["max_tokens"] == 12000
assert params["answer_now"]["max_tokens"] == 8000
@@ -76,10 +68,7 @@ class TestGetChatParams:
"capabilities": {"chat": {"temperature": 0.7}},
},
)
- monkeypatch.setattr(
- "deeptutor.services.config.loader.PROJECT_ROOT",
- project_root,
- )
+ monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)
params = get_chat_params()
assert params["temperature"] == 0.7
assert params["responding"]["max_tokens"] == 8000
@@ -101,10 +90,7 @@ class TestGetChatParams:
},
},
)
- monkeypatch.setattr(
- "deeptutor.services.config.loader.PROJECT_ROOT",
- project_root,
- )
+ monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)
params = get_chat_params()
assert params["temperature"] == 0.4
assert params["responding"]["max_tokens"] == 16000
diff --git a/tests/services/config/test_context_window_detection.py b/tests/services/config/test_context_window_detection.py
new file mode 100644
index 000000000..c996fcaff
--- /dev/null
+++ b/tests/services/config/test_context_window_detection.py
@@ -0,0 +1,60 @@
+from __future__ import annotations
+
+import asyncio
+
+from deeptutor.services.config.context_window_detection import (
+ detect_context_window,
+)
+from deeptutor.services.llm.config import LLMConfig
+
+
+def _config(**overrides):
+ defaults = {
+ "model": "gpt-4o-mini",
+ "api_key": "sk-test",
+ "base_url": "https://api.example.com/v1",
+ "effective_url": "https://api.example.com/v1",
+ "binding": "openai",
+ "provider_name": "openai",
+ "provider_mode": "standard",
+ "api_version": None,
+ "extra_headers": {},
+ "reasoning_effort": None,
+ "max_tokens": 4096,
+ }
+ defaults.update(overrides)
+ return LLMConfig(**defaults)
+
+
+async def _metadata_128k(*_args, **_kwargs):
+ return 128000
+
+
+async def _metadata_none(*_args, **_kwargs):
+ return None
+
+
+def test_detect_context_window_prefers_provider_metadata(monkeypatch) -> None:
+ monkeypatch.setattr(
+ "deeptutor.services.config.context_window_detection._detect_from_models_endpoint",
+ _metadata_128k,
+ )
+ result = asyncio.run(detect_context_window(_config(model="kimi-k2.6")))
+
+ assert result.context_window == 128000
+ assert result.source == "metadata"
+
+
+def test_detect_context_window_uses_runtime_default_when_metadata_missing(
+ monkeypatch,
+) -> None:
+ monkeypatch.setattr(
+ "deeptutor.services.config.context_window_detection._detect_from_models_endpoint",
+ _metadata_none,
+ )
+ result = asyncio.run(
+ detect_context_window(_config(model="unknown-model", max_tokens=5000))
+ )
+
+ assert result.context_window == 20000
+ assert result.source == "default"
diff --git a/tests/services/config/test_llm_probe_config.py b/tests/services/config/test_llm_probe_config.py
index b6d72bec7..1bdcf8ea1 100644
--- a/tests/services/config/test_llm_probe_config.py
+++ b/tests/services/config/test_llm_probe_config.py
@@ -116,6 +116,11 @@ class TestLlmProbeUsesAgentsYaml:
"resolve_llm_runtime_config",
lambda catalog: _stub_resolved_llm(),
)
+ monkeypatch.setattr(
+ test_runner_module,
+ "detect_context_window",
+ _stub_context_window_detection,
+ )
monkeypatch.setattr(llm_module, "get_token_limit_kwargs", _real_get_token_limit_kwargs)
monkeypatch.setattr(llm_module, "complete", _fake_llm_complete)
monkeypatch.setattr(llm_module, "clear_llm_config_cache", lambda: None)
@@ -150,6 +155,11 @@ class TestLlmProbeUsesAgentsYaml:
"resolve_llm_runtime_config",
lambda catalog: _stub_resolved_llm(),
)
+ monkeypatch.setattr(
+ test_runner_module,
+ "detect_context_window",
+ _stub_context_window_detection,
+ )
monkeypatch.setattr(llm_module, "get_token_limit_kwargs", _real_get_token_limit_kwargs)
monkeypatch.setattr(llm_module, "complete", _fake_llm_complete)
monkeypatch.setattr(llm_module, "clear_llm_config_cache", lambda: None)
@@ -163,6 +173,86 @@ class TestLlmProbeUsesAgentsYaml:
or captured_kwargs.get("max_completion_tokens") == 4096
)
+ @pytest.mark.asyncio
+ async def test_probe_persists_detected_context_window_when_catalog_present(
+ self, tmp_path, monkeypatch
+ ):
+ from deeptutor.services import llm as llm_module
+ from deeptutor.services.config import test_runner as test_runner_module
+ from deeptutor.services.config.model_catalog import ModelCatalogService
+ from deeptutor.services.config.test_runner import ConfigTestRunner, TestRun
+
+ catalog = {
+ "version": 1,
+ "services": {
+ "llm": {
+ "active_profile_id": "llm-p",
+ "active_model_id": "llm-m",
+ "profiles": [
+ {
+ "id": "llm-p",
+ "name": "LLM",
+ "binding": "openai",
+ "base_url": "https://api.example.com/v1",
+ "api_key": "sk-test",
+ "api_version": "",
+ "extra_headers": {},
+ "models": [
+ {
+ "id": "llm-m",
+ "name": "GPT",
+ "model": "gpt-4o-mini",
+ }
+ ],
+ }
+ ],
+ },
+ "embedding": {
+ "active_profile_id": None,
+ "active_model_id": None,
+ "profiles": [],
+ },
+ "search": {"active_profile_id": None, "profiles": []},
+ },
+ }
+ service = ModelCatalogService(path=tmp_path / "model_catalog.json")
+ service.save(catalog)
+
+ async def _fake_llm_complete(**_kwargs):
+ return "OK I am gpt-4o-mini"
+
+ monkeypatch.setattr(
+ test_runner_module,
+ "get_model_catalog_service",
+ lambda: service,
+ )
+ monkeypatch.setattr(
+ test_runner_module,
+ "resolve_llm_runtime_config",
+ lambda catalog: _stub_resolved_llm(),
+ )
+ monkeypatch.setattr(
+ test_runner_module,
+ "detect_context_window",
+ _stub_metadata_context_window_detection,
+ )
+ monkeypatch.setattr(test_runner_module, "clear_llm_config_cache", lambda: None)
+ monkeypatch.setattr(test_runner_module, "reset_llm_client", lambda: None)
+ monkeypatch.setattr(llm_module, "get_token_limit_kwargs", _real_get_token_limit_kwargs)
+ monkeypatch.setattr(llm_module, "complete", _fake_llm_complete)
+ monkeypatch.setattr(llm_module, "clear_llm_config_cache", lambda: None)
+
+ runner = ConfigTestRunner()
+ run = TestRun(id="test-llm-context-window", service="llm")
+ await runner._test_llm(run, catalog=catalog)
+
+ saved = service.load()
+ saved_model = saved["services"]["llm"]["profiles"][0]["models"][0]
+ assert saved_model["context_window"] == "128000"
+ assert saved_model["context_window_source"] == "metadata"
+ assert saved_model["context_window_detected_at"] == "2026-04-24T08:00:00+00:00"
+ assert any(event["type"] == "catalog" for event in run.events)
+
# ---------------------------------------------------------------------------
# Helpers
@@ -194,3 +284,29 @@ def _real_get_token_limit_kwargs(model: str, max_tokens: int) -> dict[str, int]:
if uses_max_completion_tokens(model):
return {"max_completion_tokens": max_tokens}
return {"max_tokens": max_tokens}
+
+
+async def _stub_context_window_detection(*_args, **_kwargs):
+ from deeptutor.services.config.context_window_detection import (
+ ContextWindowDetectionResult,
+ )
+
+ return ContextWindowDetectionResult(
+ context_window=65536,
+ source="default",
+ detail="stub",
+ detected_at="2026-04-24T00:00:00+00:00",
+ )
+
+
+async def _stub_metadata_context_window_detection(*_args, **_kwargs):
+ from deeptutor.services.config.context_window_detection import (
+ ContextWindowDetectionResult,
+ )
+
+ return ContextWindowDetectionResult(
+ context_window=128000,
+ source="metadata",
+ detail="stub",
+ detected_at="2026-04-24T08:00:00+00:00",
+ )
diff --git a/tests/services/config/test_provider_runtime.py b/tests/services/config/test_provider_runtime.py
index baaaf7738..5d3161cc4 100644
--- a/tests/services/config/test_provider_runtime.py
+++ b/tests/services/config/test_provider_runtime.py
@@ -164,6 +164,109 @@ def test_llm_local_fallback(tmp_path: Path) -> None:
assert resolved.api_key == "sk-no-key-required"
+def test_llm_minimax_binding_uses_minimaxi_endpoint(tmp_path: Path) -> None:
+ catalog = _build_catalog(
+ llm_profile={
+ "id": "llm-p",
+ "name": "LLM",
+ "binding": "minimax",
+ "base_url": "",
+ "api_key": "minimax-key",
+ "api_version": "",
+ "extra_headers": {},
+ "models": [{"id": "llm-m", "name": "m", "model": "MiniMax-M2.7"}],
+ }
+ )
+ resolved = resolve_llm_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ assert resolved.provider_name == "minimax"
+ assert resolved.provider_mode == "standard"
+ assert resolved.effective_url == "https://api.minimaxi.com/v1"
+
+
+def test_llm_minimax_anthropic_binding_uses_anthropic_endpoint(tmp_path: Path) -> None:
+ catalog = _build_catalog(
+ llm_profile={
+ "id": "llm-p",
+ "name": "LLM",
+ "binding": "minimax_anthropic",
+ "base_url": "",
+ "api_key": "minimax-key",
+ "api_version": "",
+ "extra_headers": {},
+ "models": [{"id": "llm-m", "name": "c", "model": "claude-sonnet-4-20250514"}],
+ }
+ )
+ resolved = resolve_llm_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ assert resolved.provider_name == "minimax_anthropic"
+ assert resolved.provider_mode == "standard"
+ assert resolved.effective_url == "https://api.minimaxi.com/anthropic"
+
+
+def test_llm_custom_anthropic_binding_stays_direct(tmp_path: Path) -> None:
+ catalog = _build_catalog(
+ llm_profile={
+ "id": "llm-p",
+ "name": "LLM",
+ "binding": "custom_anthropic",
+ "base_url": "https://claude-proxy.example/v1/messages",
+ "api_key": "anthropic-key",
+ "api_version": "",
+ "extra_headers": {"x-tenant": "lab"},
+ "models": [{"id": "llm-m", "name": "c", "model": "claude-sonnet-4-20250514"}],
+ }
+ )
+ resolved = resolve_llm_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ assert resolved.provider_name == "custom_anthropic"
+ assert resolved.provider_mode == "direct"
+ assert resolved.binding == "custom_anthropic"
+ assert resolved.effective_url == "https://claude-proxy.example/v1/messages"
+ assert resolved.extra_headers == {"x-tenant": "lab"}
+
+
+def test_llm_lm_studio_alias_resolves_to_local_provider(tmp_path: Path) -> None:
+ catalog = _build_catalog(
+ llm_profile={
+ "id": "llm-p",
+ "name": "LLM",
+ "binding": "lm-studio",
+ "base_url": "",
+ "api_key": "",
+ "api_version": "",
+ "extra_headers": {},
+ "models": [{"id": "llm-m", "name": "m", "model": "llama-3.2"}],
+ }
+ )
+ resolved = resolve_llm_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ assert resolved.provider_name == "lm_studio"
+ assert resolved.provider_mode == "local"
+ assert resolved.effective_url == "http://localhost:1234/v1"
+ assert resolved.api_key == "sk-no-key-required"
+
+
+def test_llm_context_window_passes_through_from_catalog(tmp_path: Path) -> None:
+ catalog = _build_catalog(
+ llm_profile={
+ "id": "llm-p",
+ "name": "LLM",
+ "binding": "openai",
+ "base_url": "https://api.openai.com/v1",
+ "api_key": "sk-test",
+ "api_version": "",
+ "extra_headers": {},
+ "models": [
+ {
+ "id": "llm-m",
+ "name": "GPT 4o mini",
+ "model": "gpt-4o-mini",
+ "context_window": 128000,
+ }
+ ],
+ }
+ )
+ resolved = resolve_llm_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ assert resolved.context_window == 128000
+
+
def test_search_fallback_to_duckduckgo_without_key(tmp_path: Path) -> None:
catalog = _build_catalog(
search_profile={
diff --git a/tests/services/llm/test_config_module.py b/tests/services/llm/test_config_module.py
index 3ea03890b..298125c56 100644
--- a/tests/services/llm/test_config_module.py
+++ b/tests/services/llm/test_config_module.py
@@ -43,6 +43,7 @@ def test_get_llm_config_from_resolver(monkeypatch) -> None:
api_version=None,
extra_headers={"X-Test": "1"},
reasoning_effort="medium",
+ context_window=128000,
)
monkeypatch.setattr(config_module, "resolve_llm_runtime_config", _fake_resolver)
@@ -55,6 +56,7 @@ def test_get_llm_config_from_resolver(monkeypatch) -> None:
assert config.base_url == "https://openrouter.ai/api/v1"
assert config.extra_headers == {"X-Test": "1"}
assert config.reasoning_effort == "medium"
+ assert config.context_window == 128000
def test_get_llm_config_falls_back_to_env(monkeypatch, tmp_path: Path) -> None:
@@ -105,6 +107,7 @@ def test_initialize_environment_sets_openai_env(monkeypatch) -> None:
api_version=None,
extra_headers={},
reasoning_effort=None,
+ context_window=None,
),
)
config_module.initialize_environment()
@@ -112,6 +115,33 @@ def test_initialize_environment_sets_openai_env(monkeypatch) -> None:
assert os.environ["OPENAI_BASE_URL"] == "https://example.com/v1"
+def test_initialize_environment_skips_openai_env_for_custom_anthropic(monkeypatch) -> None:
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ monkeypatch.delenv("OPENAI_BASE_URL", raising=False)
+
+ monkeypatch.setattr(
+ config_module,
+ "resolve_llm_runtime_config",
+ lambda: ResolvedLLMConfig(
+ model="claude-sonnet-4-20250514",
+ provider_name="custom_anthropic",
+ provider_mode="direct",
+ binding_hint="custom_anthropic",
+ binding="custom_anthropic",
+ api_key="anthropic-key",
+ base_url="https://claude-proxy.example/v1",
+ effective_url="https://claude-proxy.example/v1",
+ api_version=None,
+ extra_headers={},
+ reasoning_effort=None,
+ context_window=None,
+ ),
+ )
+ config_module.initialize_environment()
+ assert "OPENAI_API_KEY" not in os.environ
+ assert "OPENAI_BASE_URL" not in os.environ
+
+
def test_strip_value_handles_quotes() -> None:
assert config_module._strip_value(" 'value' ") == "value"
@@ -134,6 +164,7 @@ def test_resolver_missing_model_raises(monkeypatch, tmp_path: Path) -> None:
api_version=None,
extra_headers={},
reasoning_effort=None,
+ context_window=None,
),
)
_set_temp_env_store(
diff --git a/tests/services/llm/test_factory_provider_exec.py b/tests/services/llm/test_factory_provider_exec.py
index 24446f064..8f2aa95d8 100644
--- a/tests/services/llm/test_factory_provider_exec.py
+++ b/tests/services/llm/test_factory_provider_exec.py
@@ -2,120 +2,216 @@
from __future__ import annotations
+from typing import Any
+
import pytest
from deeptutor.services.llm.config import LLMConfig
-from deeptutor.services.llm.factory import complete, stream # noqa: F401
-
-# ---------------------------------------------------------------------------
-# extra_headers dedup / merge (regression for #324)
-# ---------------------------------------------------------------------------
-
-
-def _make_cfg(**overrides):
+from deeptutor.services.llm.factory import complete, stream
+from deeptutor.services.llm.provider_core.base import LLMResponse
+
+
+class _FakeProvider:
+ def __init__(
+ self,
+ *,
+ complete_response: LLMResponse | None = None,
+ stream_response: LLMResponse | None = None,
+ stream_chunk: str = "chunk",
+ ) -> None:
+ self.complete_kwargs: dict[str, Any] = {}
+ self.stream_kwargs: dict[str, Any] = {}
+ self.complete_response = complete_response or LLMResponse(content="ok")
+ self.stream_response = stream_response or LLMResponse(content=stream_chunk)
+ self.stream_chunk = stream_chunk
+
+ async def chat_with_retry(self, **kwargs: Any) -> LLMResponse:
+ self.complete_kwargs = kwargs
+ return self.complete_response
+
+ async def chat_stream_with_retry(self, **kwargs: Any) -> LLMResponse:
+ self.stream_kwargs = kwargs
+ on_content_delta = kwargs.get("on_content_delta")
+ if on_content_delta is not None:
+ await on_content_delta(self.stream_chunk)
+ return self.stream_response
+
+
+def _make_cfg(**overrides: Any) -> LLMConfig:
defaults = dict(
model="gpt-4o-mini",
api_key="test-key",
base_url="https://api.example.com/v1",
+ effective_url="https://api.example.com/v1",
binding="openai",
provider_name="openai",
provider_mode="standard",
+ extra_headers={},
)
defaults.update(overrides)
return LLMConfig(**defaults)
@pytest.mark.asyncio
-async def test_complete_extra_headers_from_kwargs_no_duplicate(monkeypatch) -> None:
- """Passing extra_headers via kwargs must not cause 'multiple values' TypeError."""
- cfg = _make_cfg(extra_headers={})
- captured: dict[str, object] = {}
-
- async def _fake_sdk_complete(**kwargs):
- captured.update(kwargs)
- return "ok"
+async def test_complete_merges_config_and_caller_extra_headers(monkeypatch) -> None:
+ cfg = _make_cfg(extra_headers={"X-Config": "from-config"})
+ provider = _FakeProvider()
+ captured_config: dict[str, Any] = {}
monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: cfg)
- monkeypatch.setattr("deeptutor.services.llm.executors.sdk_complete", _fake_sdk_complete)
- monkeypatch.setattr("deeptutor.services.llm.factory.sdk_complete", _fake_sdk_complete)
- result = await complete("hello", extra_headers={"X-Custom": "val"})
+ def _fake_get_runtime_provider(config: LLMConfig):
+ captured_config["config"] = config
+ return provider
+
+ monkeypatch.setattr("deeptutor.services.llm.factory.get_runtime_provider", _fake_get_runtime_provider)
+
+ result = await complete("hello", extra_headers={"X-Caller": "from-caller"})
+
assert result == "ok"
- assert captured["extra_headers"] == {"X-Custom": "val"}
+ merged = captured_config["config"].extra_headers
+ assert merged == {"X-Config": "from-config", "X-Caller": "from-caller"}
@pytest.mark.asyncio
-async def test_complete_merges_config_and_caller_extra_headers(monkeypatch) -> None:
- """Caller extra_headers should be merged with config-level headers."""
- cfg = _make_cfg(extra_headers={"X-Config": "from-config"})
- captured: dict[str, object] = {}
+async def test_stream_merges_config_and_caller_extra_headers(monkeypatch) -> None:
+ cfg = _make_cfg(extra_headers={"X-Config": "cfg"})
+ provider = _FakeProvider(stream_chunk="A")
+ captured_config: dict[str, Any] = {}
- async def _fake_sdk_complete(**kwargs):
- captured.update(kwargs)
- return "ok"
+ monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: cfg)
+
+ def _fake_get_runtime_provider(config: LLMConfig):
+ captured_config["config"] = config
+ return provider
+
+ monkeypatch.setattr("deeptutor.services.llm.factory.get_runtime_provider", _fake_get_runtime_provider)
+
+ chunks = []
+ async for chunk in stream("hello", extra_headers={"X-Caller": "clr"}):
+ chunks.append(chunk)
+
+ assert chunks == ["A"]
+ merged = captured_config["config"].extra_headers
+ assert merged == {"X-Config": "cfg", "X-Caller": "clr"}
+
+
+async def test_complete_injects_openai_image_parts(monkeypatch) -> None:
+ cfg = _make_cfg(model="gpt-4o-mini", binding="openai", provider_name="openai")
+ provider = _FakeProvider()
monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: cfg)
- monkeypatch.setattr("deeptutor.services.llm.executors.sdk_complete", _fake_sdk_complete)
- monkeypatch.setattr("deeptutor.services.llm.factory.sdk_complete", _fake_sdk_complete)
+ monkeypatch.setattr(
+ "deeptutor.services.llm.factory.get_runtime_provider",
+ lambda _config: provider,
+ )
+
+ result = await complete(
+ "ignored",
+ messages=[{"role": "user", "content": "hi"}],
+ image_data="abc123",
+ )
- result = await complete("hello", extra_headers={"X-Caller": "from-caller"})
assert result == "ok"
- headers = captured["extra_headers"]
- assert headers["X-Config"] == "from-config"
- assert headers["X-Caller"] == "from-caller"
+ content = provider.complete_kwargs["messages"][0]["content"]
+ assert isinstance(content, list)
+ assert content[0]["type"] == "text"
+ assert content[1]["type"] == "image_url"
+ assert content[1]["image_url"]["url"].startswith("data:image/png;base64,abc123")
@pytest.mark.asyncio
-async def test_stream_extra_headers_from_kwargs_no_duplicate(monkeypatch) -> None:
- """Passing extra_headers via kwargs to stream must not cause 'multiple values' TypeError."""
- cfg = _make_cfg(extra_headers={})
- captured: dict[str, object] = {}
+async def test_complete_injects_anthropic_image_parts(monkeypatch) -> None:
+ cfg = _make_cfg(
+ model="claude-sonnet-4-20250514",
+ binding="anthropic",
+ provider_name="anthropic",
+ )
+ provider = _FakeProvider()
+
+ monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: cfg)
+ monkeypatch.setattr(
+ "deeptutor.services.llm.factory.get_runtime_provider",
+ lambda _config: provider,
+ )
+
+ result = await complete(
+ "ignored",
+ messages=[{"role": "user", "content": "hi"}],
+ image_data="abc123",
+ )
+
+ assert result == "ok"
+ content = provider.complete_kwargs["messages"][0]["content"]
+ assert isinstance(content, list)
+ assert content[1]["type"] == "image"
+ assert content[1]["source"]["type"] == "base64"
- async def _fake_sdk_stream(**kwargs):
- captured.update(kwargs)
- yield "chunk"
+
+async def test_complete_injects_custom_anthropic_image_parts(monkeypatch) -> None:
+ cfg = _make_cfg(
+ model="claude-sonnet-4-20250514",
+ binding="custom_anthropic",
+ provider_name="custom_anthropic",
+ )
+ provider = _FakeProvider()
monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: cfg)
- monkeypatch.setattr("deeptutor.services.llm.executors.sdk_stream", _fake_sdk_stream)
- monkeypatch.setattr("deeptutor.services.llm.factory.sdk_stream", _fake_sdk_stream)
+ monkeypatch.setattr(
+ "deeptutor.services.llm.factory.get_runtime_provider",
+ lambda _config: provider,
+ )
- chunks = []
- async for c in stream("hello", extra_headers={"X-Custom": "val"}):
- chunks.append(c)
- assert chunks == ["chunk"]
- assert captured["extra_headers"] == {"X-Custom": "val"}
+ result = await complete(
+ "ignored",
+ messages=[{"role": "user", "content": "hi"}],
+ image_data="abc123",
+ )
+
+ assert result == "ok"
+ content = provider.complete_kwargs["messages"][0]["content"]
+ assert isinstance(content, list)
+ assert content[1]["type"] == "image"
+ assert content[1]["source"]["type"] == "base64"
@pytest.mark.asyncio
-async def test_stream_merges_config_and_caller_extra_headers(monkeypatch) -> None:
- """Caller extra_headers should be merged with config-level headers in stream."""
- cfg = _make_cfg(extra_headers={"X-Config": "cfg"})
- captured: dict[str, object] = {}
+async def test_complete_strips_unsupported_response_format(monkeypatch) -> None:
+ cfg = _make_cfg(
+ model="deepseek-reasoner",
+ binding="deepseek",
+ provider_name="deepseek",
+ )
+ provider = _FakeProvider()
+
+ monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: cfg)
+ monkeypatch.setattr(
+ "deeptutor.services.llm.factory.get_runtime_provider",
+ lambda _config: provider,
+ )
+
+ result = await complete(
+ "hello",
+ response_format={"type": "json_object"},
+ )
- async def _fake_sdk_stream(**kwargs):
- captured.update(kwargs)
- yield "chunk"
+ assert result == "ok"
+ assert "response_format" not in provider.complete_kwargs
+
+
+async def test_complete_passes_retry_delays(monkeypatch) -> None:
+ cfg = _make_cfg()
+ provider = _FakeProvider()
monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: cfg)
- monkeypatch.setattr("deeptutor.services.llm.executors.sdk_stream", _fake_sdk_stream)
- monkeypatch.setattr("deeptutor.services.llm.factory.sdk_stream", _fake_sdk_stream)
+ monkeypatch.setattr(
+ "deeptutor.services.llm.factory.get_runtime_provider",
+ lambda _config: provider,
+ )
- chunks = []
- async for c in stream("hello", extra_headers={"X-Caller": "clr"}):
- chunks.append(c)
- assert chunks == ["chunk"]
- headers = captured["extra_headers"]
- assert headers["X-Config"] == "cfg"
- assert headers["X-Caller"] == "clr"
-
-
-# NOTE: The legacy litellm-routing tests (test_factory_complete_uses_litellm,
-# test_factory_complete_uses_direct_azure,
-# test_factory_complete_openai_codex_requires_oauth,
-# test_factory_stream_uses_litellm) were removed. The factory no longer
-# delegates to litellm — see deeptutor/services/llm/executors.py — so the
-# `litellm_available`/`litellm_complete`/`litellm_stream` symbols and their
-# routing branches no longer exist. The factory now always goes through
-# `sdk_complete` / `sdk_stream`, which is exercised by the four
-# extra_headers tests above and by tests/services/llm/test_factory_*.py
-# elsewhere.
+ await complete("hello", max_retries=3, retry_delay=0.5, exponential_backoff=True)
+
+ assert provider.complete_kwargs["retry_delays"] == (0.5, 1.0, 2.0)
diff --git a/tests/services/session/test_context_builder.py b/tests/services/session/test_context_builder.py
index ee0ebd553..81a94fed7 100644
--- a/tests/services/session/test_context_builder.py
+++ b/tests/services/session/test_context_builder.py
@@ -127,19 +127,32 @@ class TestContextBuildResult:
class TestContextBuilderBudgets:
- def _make_llm_config(self, max_tokens: int) -> MagicMock:
+ def _make_llm_config(
+ self,
+ max_tokens: int,
+ *,
+ model: str = "test-model",
+ context_window: int | None = None,
+ ) -> MagicMock:
cfg = MagicMock()
cfg.max_tokens = max_tokens
+ cfg.model = model
+ cfg.context_window = context_window
return cfg
- def test_history_budget_ratio(self) -> None:
+ def test_history_budget_uses_explicit_context_window(self) -> None:
builder = ContextBuilder(store=MagicMock(), history_budget_ratio=0.35)
- budget = builder._history_budget(self._make_llm_config(4096))
- assert budget == int(4096 * 0.35)
+ budget = builder._history_budget(self._make_llm_config(4096, context_window=128000))
+ assert budget == int(65536 * 0.35)
+
+ def test_history_budget_uses_large_context_model_heuristic(self) -> None:
+ builder = ContextBuilder(store=MagicMock(), history_budget_ratio=0.35)
+ budget = builder._history_budget(self._make_llm_config(4096, model="gpt-4o-mini"))
+ assert budget == int(65536 * 0.35)
def test_history_budget_minimum(self) -> None:
builder = ContextBuilder(store=MagicMock(), history_budget_ratio=0.01)
- budget = builder._history_budget(self._make_llm_config(100))
+ budget = builder._history_budget(self._make_llm_config(100, model="unknown-local-model"))
assert budget >= 256
def test_summary_budget(self) -> None:
@@ -282,3 +295,33 @@ class TestContextBuilderBuild:
assert len(result.conversation_history) == 2
assert result.events == []
assert result.token_count > 0
+
+ @pytest.mark.asyncio
+ async def test_large_context_model_avoids_premature_summarize(self) -> None:
+ long_user = "user says " + ("alpha " * 1400)
+ long_assistant = "assistant says " + ("beta " * 1400)
+ store = AsyncMock()
+ store.get_session = AsyncMock(
+ return_value={
+ "id": "s1",
+ "compressed_summary": "",
+ "summary_up_to_msg_id": 0,
+ }
+ )
+ store.get_messages_for_context = AsyncMock(
+ return_value=[
+ {"id": 1, "role": "user", "content": long_user},
+ {"id": 2, "role": "assistant", "content": long_assistant},
+ ]
+ )
+
+ builder = ContextBuilder(store=store)
+ cfg = MagicMock()
+ cfg.max_tokens = 4096
+ cfg.model = "gpt-4o-mini"
+ cfg.context_window = None
+
+ result = await builder.build(session_id="s1", llm_config=cfg)
+ assert len(result.conversation_history) == 2
+ assert result.events == []
+ store.update_summary.assert_not_called()
diff --git a/tests/utils/test_document_extractor.py b/tests/utils/test_document_extractor.py
new file mode 100644
index 000000000..8f4e5d923
--- /dev/null
+++ b/tests/utils/test_document_extractor.py
@@ -0,0 +1,245 @@
+"""Tests for deeptutor.utils.document_extractor."""
+
+from __future__ import annotations
+
+import base64
+import io
+
+from docx import Document as DocxDocument
+from openpyxl import Workbook
+from pptx import Presentation
+from pptx.util import Inches
+import pytest
+
+from deeptutor.utils.document_extractor import (
+ CorruptDocumentError,
+ DocumentTooLargeError,
+ EmptyDocumentError,
+ MAX_DOC_BYTES,
+ MAX_EXTRACTED_CHARS_PER_DOC,
+ UnsupportedDocumentError,
+ extract_documents_from_records,
+ extract_text_from_bytes,
+ is_document_extension,
+)
+
+
+# ---------------------------------------------------------------------------
+# Fixtures — generate office docs on the fly
+# ---------------------------------------------------------------------------
+
+
+def _make_docx(paragraphs: list[str]) -> bytes:
+ doc = DocxDocument()
+ for p in paragraphs:
+ doc.add_paragraph(p)
+ buf = io.BytesIO()
+ doc.save(buf)
+ return buf.getvalue()
+
+
+def _make_xlsx(sheets: dict[str, list[list[object]]]) -> bytes:
+ wb = Workbook()
+ default = wb.active
+ first = True
+ for name, rows in sheets.items():
+ ws = default if first else wb.create_sheet()
+ ws.title = name
+ for row in rows:
+ ws.append(row)
+ first = False
+ buf = io.BytesIO()
+ wb.save(buf)
+ return buf.getvalue()
+
+
+def _make_pptx(slides_text: list[list[str]]) -> bytes:
+ prs = Presentation()
+ for slide_texts in slides_text:
+ slide = prs.slides.add_slide(prs.slide_layouts[5]) # blank-ish layout
+ for i, text in enumerate(slide_texts):
+ tb = slide.shapes.add_textbox(Inches(1), Inches(1 + i * 0.5), Inches(6), Inches(0.5))
+ tb.text_frame.text = text
+ buf = io.BytesIO()
+ prs.save(buf)
+ return buf.getvalue()
+
+
+# ---------------------------------------------------------------------------
+# is_document_extension
+# ---------------------------------------------------------------------------
+
+
+class TestIsDocumentExtension:
+ def test_supported(self) -> None:
+ assert is_document_extension("foo.pdf")
+ assert is_document_extension("foo.DOCX")
+ assert is_document_extension("report.xlsx")
+ assert is_document_extension("deck.pptx")
+
+ def test_unsupported(self) -> None:
+ assert not is_document_extension("foo.png")
+ assert not is_document_extension("foo.txt")
+ assert not is_document_extension("foo")
+ assert not is_document_extension("")
+
+
+# ---------------------------------------------------------------------------
+# extract_text_from_bytes — happy paths
+# ---------------------------------------------------------------------------
+
+
+class TestExtractDocx:
+ def test_basic_paragraphs(self) -> None:
+ data = _make_docx(["Hello world", "Second paragraph", ""])
+ text = extract_text_from_bytes("doc.docx", data)
+ assert "Hello world" in text
+ assert "Second paragraph" in text
+
+
+class TestExtractXlsx:
+ def test_multiple_sheets(self) -> None:
+ data = _make_xlsx(
+ {
+ "Alpha": [["a1", "b1"], ["a2", 42]],
+ "Beta": [["x", "y"]],
+ }
+ )
+ text = extract_text_from_bytes("book.xlsx", data)
+ assert "--- Sheet: Alpha ---" in text
+ assert "--- Sheet: Beta ---" in text
+ assert "a1" in text and "42" in text
+ assert "x" in text
+
+
+class TestExtractPptx:
+ def test_basic_slides(self) -> None:
+ data = _make_pptx([["Slide 1 title", "Slide 1 body"], ["Slide 2 only text"]])
+ text = extract_text_from_bytes("deck.pptx", data)
+ assert "--- Slide 1 ---" in text
+ assert "--- Slide 2 ---" in text
+ assert "Slide 1 title" in text
+ assert "Slide 2 only text" in text
+
+
+class TestExtractPdf:
+ def test_minimal_pdf(self) -> None:
+ # Build a minimal valid PDF via pymupdf (dependency already in project).
+ pytest.importorskip("fitz")
+ import fitz # noqa: WPS433
+
+ doc = fitz.open()
+ page = doc.new_page()
+ page.insert_text((72, 72), "Hello PDF world")
+ buf = io.BytesIO()
+ doc.save(buf)
+ doc.close()
+ data = buf.getvalue()
+
+ text = extract_text_from_bytes("sample.pdf", data)
+ assert "Hello PDF world" in text
+ assert "--- Page 1 ---" in text
+
+
+# ---------------------------------------------------------------------------
+# Failure modes
+# ---------------------------------------------------------------------------
+
+
+class TestFailureModes:
+ def test_unsupported_extension(self) -> None:
+ with pytest.raises(UnsupportedDocumentError):
+ extract_text_from_bytes("foo.zip", b"\x00\x00")
+
+ def test_empty_bytes(self) -> None:
+ with pytest.raises(EmptyDocumentError):
+ extract_text_from_bytes("foo.docx", b"")
+
+ def test_too_large(self) -> None:
+ fake = b"PK\x03\x04" + b"\x00" * (MAX_DOC_BYTES + 1)
+ with pytest.raises(DocumentTooLargeError):
+ extract_text_from_bytes("foo.docx", fake)
+
+ def test_pdf_magic_mismatch(self) -> None:
+ with pytest.raises(CorruptDocumentError):
+ extract_text_from_bytes("foo.pdf", b"this is not a pdf")
+
+ def test_ooxml_magic_mismatch(self) -> None:
+ with pytest.raises(CorruptDocumentError):
+ extract_text_from_bytes("foo.docx", b"not an office file")
+
+ def test_corrupt_docx(self) -> None:
+ # OOXML header but garbage body
+ with pytest.raises(CorruptDocumentError):
+ extract_text_from_bytes("foo.docx", b"PK\x03\x04" + b"\x00" * 512)
+
+ def test_empty_docx_no_text(self) -> None:
+ data = _make_docx([]) # no paragraphs
+ with pytest.raises(EmptyDocumentError):
+ extract_text_from_bytes("foo.docx", data)
+
+
+# ---------------------------------------------------------------------------
+# Truncation
+# ---------------------------------------------------------------------------
+
+
+class TestTruncation:
+ def test_long_docx_is_truncated(self) -> None:
+ # single paragraph of 250k chars → well over the 200k per-doc cap
+ long_text = "a" * 250_000
+ data = _make_docx([long_text])
+ text = extract_text_from_bytes("big.docx", data)
+ assert len(text) <= MAX_EXTRACTED_CHARS_PER_DOC + 200 # allow notice suffix
+ assert "truncated" in text
+
+
+# ---------------------------------------------------------------------------
+# extract_documents_from_records
+# ---------------------------------------------------------------------------
+
+
+class TestExtractDocumentsFromRecords:
+ def test_mixed_image_and_doc(self) -> None:
+ docx_bytes = _make_docx(["hello there"])
+ docx_b64 = base64.b64encode(docx_bytes).decode()
+ image_b64 = base64.b64encode(b"\x89PNG\r\n\x1a\n").decode()
+
+ records = [
+ {"type": "image", "filename": "pic.png", "base64": image_b64, "mime_type": "image/png", "url": ""},
+ {"type": "file", "filename": "note.docx", "base64": docx_b64, "mime_type": "", "url": ""},
+ ]
+
+ doc_texts, updated = extract_documents_from_records(records)
+
+ assert len(doc_texts) == 1
+ assert "[File: note.docx]" in doc_texts[0]
+ assert "hello there" in doc_texts[0]
+
+ # image record untouched
+ assert updated[0]["base64"] == image_b64
+ # doc record base64 cleared, extracted_chars set
+ assert updated[1]["base64"] == ""
+ assert updated[1]["extracted_chars"] > 0
+
+ def test_unsupported_record_is_passthrough(self) -> None:
+ records = [{"type": "file", "filename": "foo.zip", "base64": "AAAA", "mime_type": "", "url": ""}]
+ doc_texts, updated = extract_documents_from_records(records)
+ assert doc_texts == []
+ assert updated[0]["base64"] == "AAAA" # untouched — not a doc extension
+
+ def test_failed_extraction_emits_error_marker(self) -> None:
+ records = [{"type": "file", "filename": "bad.pdf", "base64": base64.b64encode(b"not a pdf").decode(), "mime_type": "", "url": ""}]
+ doc_texts, updated = extract_documents_from_records(records)
+ assert len(doc_texts) == 1
+ assert "bad.pdf" in doc_texts[0]
+ assert "could not be read" in doc_texts[0]
+ assert updated[0]["base64"] == "" # stripped even on failure
+
+ def test_invalid_base64_emits_error_marker(self) -> None:
+ records = [{"type": "file", "filename": "bad.docx", "base64": "!!!not base64!!!", "mime_type": "", "url": ""}]
+ doc_texts, updated = extract_documents_from_records(records)
+ # invalid base64 with validate=False may silently decode or emit error — both
+ # paths end up as an error marker since resulting bytes won't pass magic check
+ assert len(doc_texts) == 1
+ assert "bad.docx" in doc_texts[0]
diff --git a/web/app/(utility)/knowledge/page.tsx b/web/app/(utility)/knowledge/page.tsx
index 86c040542..6ff9b49b2 100644
--- a/web/app/(utility)/knowledge/page.tsx
+++ b/web/app/(utility)/knowledge/page.tsx
@@ -4,6 +4,7 @@ import dynamic from "next/dynamic";
import Link from "next/link";
import {
Suspense,
+ type DragEvent,
useCallback,
useEffect,
useMemo,
@@ -17,19 +18,25 @@ import {
ArrowRight,
Bookmark,
BookOpen,
+ CheckCircle2,
ChevronDown,
ChevronRight,
ClipboardList,
+ Clock3,
Database,
ExternalLink,
FileUp,
+ FileText,
+ Files,
FolderOpen,
+ Layers,
Loader2,
MessageSquare,
NotebookPen,
Pencil,
Plus,
Search,
+ Sparkles,
Star,
Trash2,
Upload,
@@ -38,9 +45,11 @@ import {
} from "lucide-react";
import { apiUrl, wsUrl } from "@/lib/api";
import {
+ getKnowledgeUploadPolicy,
invalidateKnowledgeCaches,
listKnowledgeBases,
listRagProviders,
+ type KnowledgeUploadPolicy,
} from "@/lib/knowledge-api";
import {
listCategories,
@@ -89,12 +98,25 @@ interface ProgressInfo {
interface KnowledgeBase {
name: string;
+ path?: string;
is_default?: boolean;
status?: string;
+ metadata?: {
+ created_at?: string;
+ last_updated?: string;
+ rag_provider?: string;
+ needs_reindex?: boolean;
+ embedding_model?: string;
+ embedding_dim?: number;
+ embedding_mismatch?: boolean;
+ };
progress?: ProgressInfo;
statistics?: {
raw_documents?: number;
+ images?: number;
+ content_lists?: number;
rag_provider?: string;
+ rag_initialized?: boolean;
needs_reindex?: boolean;
status?: string;
progress?: ProgressInfo;
@@ -144,7 +166,30 @@ interface ProcessState {
error: string | null;
}
+interface DropZoneState {
+ active: boolean;
+ invalid: boolean;
+ draggedCount: number;
+}
+
+interface ValidatedSelectionFile {
+ id: string;
+ file: File;
+ extension: string;
+ sizeLabel: string;
+ valid: boolean;
+ error: string | null;
+}
+
+interface ValidatedFileSelection {
+ items: ValidatedSelectionFile[];
+ validFiles: File[];
+ invalidFiles: ValidatedSelectionFile[];
+ totalBytes: number;
+}
+
type ProcessKind = "create" | "upload";
+type DropZoneKind = "create" | "upload";
const EMPTY_PROCESS_STATE: ProcessState = {
taskId: null,
@@ -154,6 +199,54 @@ const EMPTY_PROCESS_STATE: ProcessState = {
error: null,
};
+const EMPTY_DROP_ZONE_STATE: DropZoneState = {
+ active: false,
+ invalid: false,
+ draggedCount: 0,
+};
+
+const DEFAULT_UPLOAD_POLICY: KnowledgeUploadPolicy = {
+ extensions: [],
+ accept: "",
+ max_file_size_bytes: 100 * 1024 * 1024,
+ max_pdf_size_bytes: 50 * 1024 * 1024,
+};
+
+const formatFileSize = (bytes: number): string => {
+ if (bytes >= 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
+ if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+ if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${bytes} B`;
+};
+
+const getFileExtension = (filename: string): string => {
+ const index = filename.lastIndexOf(".");
+ return index >= 0 ? filename.slice(index).toLowerCase() : "";
+};
+
+const mergeSelectedFiles = (existing: File[], incoming: File[]): File[] => {
+ const merged = new Map<string, File>();
+ [...existing, ...incoming].forEach((file) => {
+ merged.set(selectionFileId(file), file);
+ });
+ return Array.from(merged.values());
+};
+
+const parseKnowledgeTimestamp = (value?: string): Date | null => {
+ if (!value) return null;
+ const normalized = value.includes("T") ? value : value.replace(" ", "T");
+ const parsed = new Date(normalized);
+ return Number.isNaN(parsed.getTime()) ? null : parsed;
+};
+
+const formatKnowledgeTimestamp = (value?: string): string | null => {
+ const parsed = parseKnowledgeTimestamp(value);
+ return parsed ? parsed.toLocaleString() : value || null;
+};
+
+const selectionFileId = (file: File): string =>
+ `${file.name}:${file.size}:${file.lastModified}`;
+
const resolveKbStatus = (kb: KnowledgeBase): string =>
kb.status ?? kb.statistics?.status ?? "unknown";
@@ -164,6 +257,27 @@ const kbNeedsReindex = (kb: KnowledgeBase): boolean =>
const kbIsUploadable = (kb: KnowledgeBase): boolean =>
resolveKbStatus(kb) === "ready" && !kbNeedsReindex(kb);
+const kbHasLiveProgress = (kb: KnowledgeBase): boolean => {
+ const status = resolveKbStatus(kb);
+ const stage = kb.progress?.stage;
+ return (
+ status !== "ready" &&
+ status !== "error" &&
+ stage !== "completed" &&
+ stage !== "error"
+ );
+};
+
+const resolveProgressPercent = (progress?: ProgressInfo): number => {
+ const directPercent = progress?.progress_percent ?? progress?.percent;
+ if (typeof directPercent === "number") return directPercent;
+
+ const current = progress?.current ?? 0;
+ const total = progress?.total ?? 0;
+ if (!current || !total) return 0;
+ return Math.round((current / total) * 100);
+};
+
type TabKey = "knowledge" | "notebooks" | "questions" | "skills";
function KnowledgePageContent() {
@@ -175,6 +289,8 @@ function KnowledgePageContent() {
const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);
const [notebooks, setNotebooks] = useState<NotebookInfo[]>([]);
const [providers, setProviders] = useState<RAGProvider[]>([]);
+ const [uploadPolicy, setUploadPolicy] =
+ useState<KnowledgeUploadPolicy>(DEFAULT_UPLOAD_POLICY);
const [loading, setLoading] = useState(true);
const [pageError, setPageError] = useState<string | null>(null);
const [creating, setCreating] = useState(false);
@@ -207,6 +323,200 @@ function KnowledgePageContent() {
});
const createFileRef = useRef<HTMLInputElement>(null);
const uploadFileRef = useRef<HTMLInputElement>(null);
+ const createDropDepthRef = useRef(0);
+ const uploadDropDepthRef = useRef(0);
+ const [createDropZone, setCreateDropZone] =
+ useState<DropZoneState>(EMPTY_DROP_ZONE_STATE);
+ const [uploadDropZone, setUploadDropZone] =
+ useState<DropZoneState>(EMPTY_DROP_ZONE_STATE);
+
+ const validateFileSelection = useCallback(
+ (files: File[]): ValidatedFileSelection => {
+ const allowedExtensions = new Set(
+ uploadPolicy.extensions.map((ext) => ext.toLowerCase()),
+ );
+
+ const items = files.map((file) => {
+ const extension = getFileExtension(file.name);
+ let error: string | null = null;
+
+ if (allowedExtensions.size > 0 && !allowedExtensions.has(extension)) {
+ error = t("Unsupported file type");
+ } else if (
+ extension === ".pdf" &&
+ file.size > uploadPolicy.max_pdf_size_bytes
+ ) {
+ error = t("PDF files must be smaller than {{size}}.", {
+ size: formatFileSize(uploadPolicy.max_pdf_size_bytes),
+ });
+ } else if (file.size > uploadPolicy.max_file_size_bytes) {
+ error = t("This file exceeds the maximum size of {{size}}.", {
+ size: formatFileSize(uploadPolicy.max_file_size_bytes),
+ });
+ }
+
+ return {
+ id: selectionFileId(file),
+ file,
+ extension: extension || t("No extension"),
+ sizeLabel: formatFileSize(file.size),
+ valid: !error,
+ error,
+ };
+ });
+
+ return {
+ items,
+ validFiles: items.filter((item) => item.valid).map((item) => item.file),
+ invalidFiles: items.filter((item) => !item.valid),
+ totalBytes: files.reduce((total, file) => total + file.size, 0),
+ };
+ },
+ [t, uploadPolicy],
+ );
+
+ const newKbSelection = useMemo(
+ () => validateFileSelection(newKbFiles),
+ [newKbFiles, validateFileSelection],
+ );
+ const uploadSelection = useMemo(
+ () => validateFileSelection(uploadFiles),
+ [uploadFiles, validateFileSelection],
+ );
+
+ const visibleSupportedFormats = useMemo(
+ () => uploadPolicy.extensions.slice(0, 8),
+ [uploadPolicy.extensions],
+ );
+ const hiddenSupportedFormatCount = Math.max(
+ 0,
+ uploadPolicy.extensions.length - visibleSupportedFormats.length,
+ );
+
+ const removeNewKbFile = (fileId: string) => {
+ setNewKbFiles((prev) =>
+ prev.filter((file) => selectionFileId(file) !== fileId),
+ );
+ };
+
+ const removeUploadFile = (fileId: string) => {
+ setUploadFiles((prev) =>
+ prev.filter((file) => selectionFileId(file) !== fileId),
+ );
+ };
+
+ const resetDropZone = useCallback((kind: DropZoneKind) => {
+ if (kind === "create") {
+ createDropDepthRef.current = 0;
+ setCreateDropZone(EMPTY_DROP_ZONE_STATE);
+ return;
+ }
+
+ uploadDropDepthRef.current = 0;
+ setUploadDropZone(EMPTY_DROP_ZONE_STATE);
+ }, []);
+
+ const previewDroppedFiles = useCallback(
+ (files: File[]) => {
+ const selection = validateFileSelection(files);
+ return {
+ count: files.length,
+ invalid: selection.invalidFiles.length > 0,
+ };
+ },
+ [validateFileSelection],
+ );
+
+ const handleDropZoneEnter = useCallback(
+ (kind: DropZoneKind, event: DragEvent<HTMLElement>) => {
+ if (!Array.from(event.dataTransfer.types).includes("Files")) return;
+ event.preventDefault();
+ event.stopPropagation();
+
+ const depthRef =
+ kind === "create" ? createDropDepthRef : uploadDropDepthRef;
+ const setDropZone = kind === "create" ? setCreateDropZone : setUploadDropZone;
+
+ depthRef.current += 1;
+ const previewFiles = Array.from(event.dataTransfer.items)
+ .filter((item) => item.kind === "file")
+ .map((item) => item.getAsFile())
+ .filter((file): file is File => Boolean(file));
+ const preview = previewDroppedFiles(previewFiles);
+
+ setDropZone({
+ active: true,
+ invalid: preview.invalid,
+ draggedCount: preview.count,
+ });
+ },
+ [previewDroppedFiles],
+ );
+
+ const handleDropZoneOver = useCallback(
+ (kind: DropZoneKind, event: DragEvent<HTMLElement>) => {
+ if (!Array.from(event.dataTransfer.types).includes("Files")) return;
+ event.preventDefault();
+ event.stopPropagation();
+ event.dataTransfer.dropEffect = "copy";
+
+ const previewFiles = Array.from(event.dataTransfer.items)
+ .filter((item) => item.kind === "file")
+ .map((item) => item.getAsFile())
+ .filter((file): file is File => Boolean(file));
+ const preview = previewDroppedFiles(previewFiles);
+
+ if (kind === "create") {
+ setCreateDropZone({
+ active: true,
+ invalid: preview.invalid,
+ draggedCount: preview.count,
+ });
+ } else {
+ setUploadDropZone({
+ active: true,
+ invalid: preview.invalid,
+ draggedCount: preview.count,
+ });
+ }
+ },
+ [previewDroppedFiles],
+ );
+
+ const handleDropZoneLeave = useCallback(
+ (kind: DropZoneKind, event: DragEvent<HTMLElement>) => {
+ if (!Array.from(event.dataTransfer.types).includes("Files")) return;
+ event.preventDefault();
+ event.stopPropagation();
+
+ const depthRef =
+ kind === "create" ? createDropDepthRef : uploadDropDepthRef;
+ depthRef.current = Math.max(0, depthRef.current - 1);
+ if (depthRef.current === 0) {
+ resetDropZone(kind);
+ }
+ },
+ [resetDropZone],
+ );
+
+ const handleDropZoneDrop = useCallback(
+ (kind: DropZoneKind, event: DragEvent<HTMLElement>) => {
+ if (!Array.from(event.dataTransfer.types).includes("Files")) return;
+ event.preventDefault();
+ event.stopPropagation();
+
+ const droppedFiles = Array.from(event.dataTransfer.files || []);
+ resetDropZone(kind);
+ if (!droppedFiles.length) return;
+
+ if (kind === "create") {
+ setNewKbFiles((prev) => mergeSelectedFiles(prev, droppedFiles));
+ } else {
+ setUploadFiles((prev) => mergeSelectedFiles(prev, droppedFiles));
+ }
+ },
+ [resetDropZone],
+ );
// ── Question Notebook state ──
type QFilterMode = "all" | "bookmarked" | "wrong";
@@ -512,6 +822,7 @@ function KnowledgePageContent() {
kind: ProcessKind,
taskId: string,
label: string,
+ kbName?: string,
) => {
closeTaskLogStream(kind);
const setProcess = getProcessSetter(kind);
@@ -547,9 +858,20 @@ function KnowledgePageContent() {
}
});
+ source.addEventListener("progress", (event) => {
+ if (!kbName) return;
+ try {
+ const payload = JSON.parse((event as MessageEvent).data) as ProgressInfo;
+ setProgressMap((prev) => ({ ...prev, [kbName]: payload }));
+ } catch {
+ // Ignore malformed progress events.
+ }
+ });
+
source.addEventListener("complete", () => {
settled = true;
setProcess((prev) => ({ ...prev, taskId, label, executing: false }));
+ void loadAll({ force: true, showSpinner: false });
closeTaskLogStream(kind);
});
@@ -571,6 +893,7 @@ function KnowledgePageContent() {
executing: false,
error: detail,
}));
+ void loadAll({ force: true, showSpinner: false });
closeTaskLogStream(kind);
});
@@ -590,16 +913,21 @@ function KnowledgePageContent() {
};
};
- const loadAll = async () => {
- setLoading(true);
+ const loadAll = async (options?: { force?: boolean; showSpinner?: boolean }) => {
+ const showSpinner = options?.showSpinner ?? true;
+ if (showSpinner) setLoading(true);
setPageError(null);
try {
- const [kbs, providerData, nbs] = await Promise.all([
- listKnowledgeBases(),
- listRagProviders(),
+ const [kbs, providerData, nbs, nextUploadPolicy] = await Promise.all([
+ listKnowledgeBases({ force: options?.force }),
+ listRagProviders({ force: options?.force }),
listNotebooks(),
+ getKnowledgeUploadPolicy({ force: options?.force }).catch(
+ () => DEFAULT_UPLOAD_POLICY,
+ ),
]);
setKnowledgeBases(kbs);
+ setUploadPolicy(nextUploadPolicy);
setProviders(
providerData.length
? providerData
@@ -652,34 +980,33 @@ function KnowledgePageContent() {
return preferredUploadTarget;
});
+ const nextProgressEntries: Record<string, ProgressInfo> = {};
for (const kb of kbs) {
const status = kb.status ?? kb.statistics?.status;
const progress = kb.progress ?? kb.statistics?.progress;
- const progressStage = (progress as ProgressInfo | undefined)?.stage;
- if (
- status &&
- status !== "ready" &&
- status !== "error" &&
- progressStage !== "completed" &&
- progressStage !== "error"
- ) {
- setProgressMap((prev) => ({
- ...prev,
- [kb.name]: progress || prev[kb.name] || {},
- }));
+ const progressInfo = progress as ProgressInfo | undefined;
+
+ if (status === "error" && progressInfo) {
+ nextProgressEntries[kb.name] = progressInfo;
+ continue;
+ }
+
+ if (kbHasLiveProgress({ ...kb, progress: progressInfo })) {
+ nextProgressEntries[kb.name] = progressInfo || {};
const taskId = (progress as ProgressInfo | undefined)?.task_id;
subscribeProgress(kb.name, taskId || undefined);
}
}
+ setProgressMap(nextProgressEntries);
} catch (error) {
setPageError(error instanceof Error ? error.message : String(error));
} finally {
- setLoading(false);
+ if (showSpinner) setLoading(false);
}
};
useEffect(() => {
- loadAll();
+ void loadAll();
return () => {
closeAllProgressSockets();
closeTaskLogStream("create");
@@ -730,9 +1057,7 @@ function KnowledgePageContent() {
const stage = progress.stage;
if (stage === "completed" || stage === "error") {
closeProgressSocket(kbName);
- if (expectedTaskId) {
- void loadAll();
- }
+ void loadAll({ force: true, showSpinner: false });
}
} catch {
// Ignore malformed progress events.
@@ -749,15 +1074,21 @@ function KnowledgePageContent() {
};
const createKnowledgeBase = async () => {
- if (!newKbName.trim() || !newKbFiles.length) return;
+ if (
+ !newKbName.trim() ||
+ !newKbSelection.validFiles.length ||
+ newKbSelection.invalidFiles.length > 0
+ ) {
+ return;
+ }
const kbName = newKbName.trim();
- const fileCount = newKbFiles.length;
+ const fileCount = newKbSelection.validFiles.length;
setCreating(true);
try {
const form = new FormData();
form.append("name", kbName);
form.append("rag_provider", selectedProvider);
- newKbFiles.forEach((file) => form.append("files", file));
+ newKbSelection.validFiles.forEach((file) => form.append("files", file));
const res = await fetch(apiUrl("/api/v1/knowledge/create"), {
method: "POST",
@@ -771,7 +1102,7 @@ function KnowledgePageContent() {
const data = (await res.json()) as KnowledgeTaskResponse;
invalidateKnowledgeCaches();
if (data.task_id) {
- openTaskLogStream("create", data.task_id, `Create ${kbName}`);
+ openTaskLogStream("create", data.task_id, `Create ${kbName}`, kbName);
subscribeProgress(kbName, data.task_id);
setProgressMap((prev) => ({
...prev,
@@ -791,7 +1122,7 @@ function KnowledgePageContent() {
setNewKbName("");
setNewKbFiles([]);
if (createFileRef.current) createFileRef.current.value = "";
- await loadAll();
+ await loadAll({ force: true, showSpinner: false });
} catch (error) {
setCreateProcess((prev) => ({
...prev,
@@ -805,13 +1136,19 @@ function KnowledgePageContent() {
};
const uploadToKnowledgeBase = async () => {
- if (!uploadTarget || !uploadFiles.length) return;
+ if (
+ !uploadTarget ||
+ !uploadSelection.validFiles.length ||
+ uploadSelection.invalidFiles.length > 0
+ ) {
+ return;
+ }
const targetKb = uploadTarget;
- const fileCount = uploadFiles.length;
+ const fileCount = uploadSelection.validFiles.length;
setUploadingKb(uploadTarget);
try {
const form = new FormData();
- uploadFiles.forEach((file) => form.append("files", file));
+ uploadSelection.validFiles.forEach((file) => form.append("files", file));
if (selectedProvider) form.append("rag_provider", selectedProvider);
const res = await fetch(apiUrl(`/api/v1/knowledge/${targetKb}/upload`), {
@@ -826,7 +1163,7 @@ function KnowledgePageContent() {
const data = (await res.json()) as KnowledgeTaskResponse;
invalidateKnowledgeCaches();
if (data.task_id) {
- openTaskLogStream("upload", data.task_id, `Upload to ${targetKb}`);
+ openTaskLogStream("upload", data.task_id, `Upload to ${targetKb}`, targetKb);
subscribeProgress(targetKb, data.task_id);
setProgressMap((prev) => ({
...prev,
@@ -845,7 +1182,7 @@ function KnowledgePageContent() {
setUploadFiles([]);
if (uploadFileRef.current) uploadFileRef.current.value = "";
- await loadAll();
+ await loadAll({ force: true, showSpinner: false });
} catch (error) {
setUploadProcess((prev) => ({
...prev,
@@ -863,7 +1200,7 @@ function KnowledgePageContent() {
method: "PUT",
});
invalidateKnowledgeCaches();
- await loadAll();
+ await loadAll({ force: true, showSpinner: false });
};
const deleteKnowledgeBase = async (kbName: string) => {
@@ -895,7 +1232,7 @@ function KnowledgePageContent() {
return next;
});
invalidateKnowledgeCaches();
- await loadAll();
+ await loadAll({ force: true, showSpinner: false });
} catch (err) {
setPageError(err instanceof Error ? err.message : String(err));
}
@@ -984,6 +1321,13 @@ function KnowledgePageContent() {
"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300",
icon: Search,
};
+ case "co_writer":
+ return {
+ label: t("Co-Writer"),
+ color:
+ "bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300",
+ icon: Pencil,
+ };
default:
return {
label: type,
@@ -1032,12 +1376,139 @@ function KnowledgePageContent() {
return null;
}, [uploadTargetKb]);
+ const createDisabled =
+ creating ||
+ !newKbName.trim() ||
+ !newKbSelection.validFiles.length ||
+ newKbSelection.invalidFiles.length > 0;
+
const uploadDisabled =
!uploadTarget ||
- !uploadFiles.length ||
+ !uploadSelection.validFiles.length ||
+ uploadSelection.invalidFiles.length > 0 ||
!!uploadingKb ||
Boolean(uploadBlockedReason);
+ const hasActiveKbWork = useMemo(
+ () => combinedKbs.some((kb) => kbHasLiveProgress(kb)),
+ [combinedKbs],
+ );
+
+ useEffect(() => {
+ if (!hasActiveKbWork) return;
+
+ const interval = window.setInterval(() => {
+ void loadAll({ force: true, showSpinner: false });
+ }, 4000);
+
+ return () => window.clearInterval(interval);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [hasActiveKbWork]);
+
+ const renderSelectionSummary = (
+ selection: ValidatedFileSelection,
+ onRemove: (fileId: string) => void,
+ onClear: () => void,
+ ) => {
+ if (!selection.items.length) return null;
+
+ const invalidCount = selection.invalidFiles.length;
+ const readyCount = selection.validFiles.length;
+ const hasIssues = invalidCount > 0;
+
+ return (
+ <div
+ className={`rounded-2xl border p-3 ${
+ hasIssues
+ ? "border-amber-200 bg-amber-50/80 dark:border-amber-900/70 dark:bg-amber-950/20"
+ : "border-emerald-200 bg-emerald-50/70 dark:border-emerald-900/60 dark:bg-emerald-950/15"
+ }`}
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div>
+ <div className="flex items-center gap-2 text-[13px] font-medium text-[var(--foreground)]">
+ {hasIssues ? (
+ <AlertTriangle className="h-4 w-4 text-amber-600 dark:text-amber-400" />
+ ) : (
+ <CheckCircle2 className="h-4 w-4 text-emerald-600 dark:text-emerald-400" />
+ )}
+ {hasIssues
+ ? t("{{count}} invalid files", { count: invalidCount })
+ : t("{{count}} files ready", { count: readyCount })}
+ </div>
+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">
+ {hasIssues
+ ? t("Only supported files can continue.")
+ : t("Ready to upload")}{" "}
+ · {formatFileSize(selection.totalBytes)}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={onClear}
+ className="rounded-md border border-[var(--border)] px-2 py-1 text-[11px] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--background)] hover:text-[var(--foreground)]"
+ >
+ {t("Clear selection")}
+ </button>
+ </div>
+
+ <div className="mt-3 space-y-2">
+ {selection.items.map((item) => (
+ <div
+ key={item.id}
+ className={`flex items-start gap-3 rounded-xl border px-3 py-2.5 ${
+ item.valid
+ ? "border-white/60 bg-white/70 dark:border-white/10 dark:bg-white/5"
+ : "border-amber-200/80 bg-amber-100/60 dark:border-amber-900/60 dark:bg-amber-950/20"
+ }`}
+ >
+ <div
+ className={`mt-0.5 rounded-lg p-2 ${
+ item.valid
+ ? "bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-300"
+ : "bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-300"
+ }`}
+ >
+ <FileText className="h-3.5 w-3.5" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[12px] font-medium text-[var(--foreground)]">
+ {item.file.name}
+ </div>
+ <div className="mt-1 flex flex-wrap items-center gap-2 text-[10px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">
+ <span>{item.extension}</span>
+ <span>{item.sizeLabel}</span>
+ <span
+ className={`rounded-full px-2 py-0.5 normal-case tracking-normal ${
+ item.valid
+ ? "bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-300"
+ : "bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-300"
+ }`}
+ >
+ {item.valid ? t("Supported") : t("Needs attention")}
+ </span>
+ </div>
+ {item.error && (
+ <p className="mt-1.5 text-[11px] leading-relaxed text-amber-700 dark:text-amber-300">
+ {item.error}
+ </p>
+ )}
+ </div>
+ <button
+ type="button"
+ onClick={() => onRemove(item.id)}
+ title={t("Remove")}
+ className="rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--background)] hover:text-[var(--foreground)]"
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+ };
+
return (
<div className="h-full overflow-y-auto bg-[var(--background)] [scrollbar-gutter:stable]">
<div className="mx-auto max-w-5xl px-6 py-8 pb-10">
@@ -1093,7 +1564,8 @@ function KnowledgePageContent() {
<div className="space-y-5">
<div className="grid gap-5 lg:grid-cols-2">
{/* Create KB */}
- <section className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-sm">
+ <section className="relative overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-sm">
+ <div className="absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-[var(--foreground)]/20 to-transparent" />
<div className="mb-4 flex items-center gap-2">
<Plus size={15} className="text-[var(--muted-foreground)]" />
<h2 className="text-[14px] font-semibold text-[var(--foreground)]">
@@ -1101,7 +1573,7 @@ function KnowledgePageContent() {
</h2>
</div>
- <div className="space-y-3">
+ <div className="space-y-4">
<input
value={newKbName}
onChange={(event) => setNewKbName(event.target.value)}
@@ -1123,47 +1595,117 @@ function KnowledgePageContent() {
))}
</select>
- {/* Styled file upload area */}
+ <div className="rounded-2xl border border-[var(--border)] bg-[var(--background)]/70 p-4">
+ <div className="mb-3 flex items-start justify-between gap-3">
+ <div>
+ <div className="flex items-center gap-2 text-[12px] font-medium text-[var(--foreground)]">
+ <Sparkles className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />
+ {t("Supported formats")}
+ </div>
+ <p className="mt-1 text-[11px] leading-relaxed text-[var(--muted-foreground)]">
+ {t("Maximum file size: {{size}}", {
+ size: formatFileSize(uploadPolicy.max_file_size_bytes),
+ })}{" "}
+ ·{" "}
+ {t("PDF limit: {{size}}", {
+ size: formatFileSize(uploadPolicy.max_pdf_size_bytes),
+ })}
+ </p>
+ </div>
+ <div className="rounded-full bg-[var(--muted)] px-2 py-1 text-[10px] text-[var(--muted-foreground)]">
+ {uploadPolicy.extensions.length} {t("types")}
+ </div>
+ </div>
+ <div className="flex flex-wrap gap-1.5">
+ {visibleSupportedFormats.map((extension) => (
+ <span
+ key={`create-ext-${extension}`}
+ className="rounded-full border border-[var(--border)] bg-[var(--card)] px-2 py-1 text-[10px] font-medium uppercase tracking-[0.12em] text-[var(--muted-foreground)]"
+ >
+ {extension.replace(".", "")}
+ </span>
+ ))}
+ {hiddenSupportedFormatCount > 0 && (
+ <span className="rounded-full border border-[var(--border)] bg-[var(--muted)] px-2 py-1 text-[10px] font-medium text-[var(--muted-foreground)]">
+ +{hiddenSupportedFormatCount}
+ </span>
+ )}
+ </div>
+ </div>
+
<button
type="button"
onClick={() => createFileRef.current?.click()}
- className="flex w-full items-center justify-center gap-2 rounded-lg border border-dashed border-[var(--border)] bg-[var(--background)] px-4 py-3 text-[13px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--foreground)]/25 hover:text-[var(--foreground)]"
+ onDragEnter={(event) => handleDropZoneEnter("create", event)}
+ onDragLeave={(event) => handleDropZoneLeave("create", event)}
+ onDragOver={(event) => handleDropZoneOver("create", event)}
+ onDrop={(event) => handleDropZoneDrop("create", event)}
+ className={`group relative flex w-full flex-col items-center justify-center gap-2 overflow-hidden rounded-2xl border border-dashed px-5 py-6 text-center transition-all ${
+ createDropZone.active
+ ? createDropZone.invalid
+ ? "border-amber-400 bg-amber-50/90 shadow-[0_0_0_4px_rgba(245,158,11,0.08)] dark:border-amber-700 dark:bg-amber-950/20"
+ : "border-sky-400 bg-sky-50/90 shadow-[0_0_0_4px_rgba(56,189,248,0.08)] dark:border-sky-700 dark:bg-sky-950/20"
+ : "border-[var(--border)] bg-[linear-gradient(180deg,var(--background),var(--muted)_180%)] hover:border-[var(--foreground)]/25 hover:bg-[var(--muted)]/30"
+ }`}
>
- <FileUp size={15} />
- {newKbFiles.length
- ? newKbFiles.length > 1
- ? t("{n} files selected", { n: newKbFiles.length })
- : t("{n} file selected", { n: newKbFiles.length })
- : t("Choose files...")}
+ <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top,rgba(255,255,255,0.32),transparent_60%)] opacity-60" />
+ <div className="rounded-2xl bg-[var(--muted)] p-3 text-[var(--muted-foreground)] transition-colors group-hover:text-[var(--foreground)]">
+ <Files className="h-5 w-5" />
+ </div>
+ <div className="space-y-1">
+ <div className="text-[13px] font-medium text-[var(--foreground)]">
+ {createDropZone.active
+ ? createDropZone.invalid
+ ? t("Some dragged files are not supported")
+ : t("Drop files to add them")
+ : newKbFiles.length
+ ? newKbSelection.invalidFiles.length > 0
+ ? t("{{count}} invalid files", {
+ count: newKbSelection.invalidFiles.length,
+ })
+ : t("{{count}} files ready", {
+ count: newKbSelection.validFiles.length,
+ })
+ : t("Choose files...")}
+ </div>
+ <p className="text-[11px] text-[var(--muted-foreground)]">
+ {createDropZone.active
+ ? createDropZone.draggedCount > 0
+ ? t("{{count}} files detected", {
+ count: createDropZone.draggedCount,
+ })
+ : t("Release to attach the files")
+ : newKbFiles.length
+ ? formatFileSize(newKbSelection.totalBytes)
+ : t("Click to browse supported documents")}
+ </p>
+ </div>
</button>
<input
ref={createFileRef}
type="file"
multiple
+ accept={uploadPolicy.accept || undefined}
className="hidden"
- onChange={(event) =>
- setNewKbFiles(Array.from(event.target.files || []))
- }
+ onChange={(event) => {
+ setNewKbFiles((prev) =>
+ mergeSelectedFiles(
+ prev,
+ Array.from(event.target.files || []),
+ ),
+ );
+ event.target.value = "";
+ }}
/>
- {!!newKbFiles.length && (
- <div className="flex flex-wrap gap-1.5">
- {newKbFiles.map((file) => (
- <span
- key={file.name}
- className="rounded-md bg-[var(--muted)] px-2 py-0.5 text-[11px] text-[var(--muted-foreground)]"
- >
- {file.name}
- </span>
- ))}
- </div>
- )}
+ {renderSelectionSummary(newKbSelection, removeNewKbFile, () => {
+ setNewKbFiles([]);
+ if (createFileRef.current) createFileRef.current.value = "";
+ })}
<button
onClick={createKnowledgeBase}
- disabled={
- creating || !newKbName.trim() || !newKbFiles.length
- }
+ disabled={createDisabled}
className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 py-1.5 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity disabled:cursor-not-allowed disabled:opacity-40"
>
{creating ? (
@@ -1203,7 +1745,8 @@ function KnowledgePageContent() {
</section>
{/* Upload to existing KB */}
- <section className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-sm">
+ <section className="relative overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-sm">
+ <div className="absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-[var(--foreground)]/20 to-transparent" />
<div className="mb-4 flex items-center gap-2">
<Upload
size={15}
@@ -1214,7 +1757,7 @@ function KnowledgePageContent() {
</h2>
</div>
- <div className="space-y-3">
+ <div className="space-y-4">
<select
value={uploadTarget}
onChange={(event) => setUploadTarget(event.target.value)}
@@ -1258,40 +1801,113 @@ function KnowledgePageContent() {
</div>
)}
+ <div className="rounded-2xl border border-[var(--border)] bg-[var(--background)]/70 p-4">
+ <div className="mb-3 flex items-start justify-between gap-3">
+ <div>
+ <div className="flex items-center gap-2 text-[12px] font-medium text-[var(--foreground)]">
+ <Sparkles className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />
+ {t("Supported formats")}
+ </div>
+ <p className="mt-1 text-[11px] leading-relaxed text-[var(--muted-foreground)]">
+ {t("Maximum file size: {{size}}", {
+ size: formatFileSize(uploadPolicy.max_file_size_bytes),
+ })}{" "}
+ ·{" "}
+ {t("PDF limit: {{size}}", {
+ size: formatFileSize(uploadPolicy.max_pdf_size_bytes),
+ })}
+ </p>
+ </div>
+ <div className="rounded-full bg-[var(--muted)] px-2 py-1 text-[10px] text-[var(--muted-foreground)]">
+ {uploadPolicy.extensions.length} {t("types")}
+ </div>
+ </div>
+ <div className="flex flex-wrap gap-1.5">
+ {visibleSupportedFormats.map((extension) => (
+ <span
+ key={`upload-ext-${extension}`}
+ className="rounded-full border border-[var(--border)] bg-[var(--card)] px-2 py-1 text-[10px] font-medium uppercase tracking-[0.12em] text-[var(--muted-foreground)]"
+ >
+ {extension.replace(".", "")}
+ </span>
+ ))}
+ {hiddenSupportedFormatCount > 0 && (
+ <span className="rounded-full border border-[var(--border)] bg-[var(--muted)] px-2 py-1 text-[10px] font-medium text-[var(--muted-foreground)]">
+ +{hiddenSupportedFormatCount}
+ </span>
+ )}
+ </div>
+ </div>
+
<button
type="button"
onClick={() => uploadFileRef.current?.click()}
- className="flex w-full items-center justify-center gap-2 rounded-lg border border-dashed border-[var(--border)] bg-[var(--background)] px-4 py-3 text-[13px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--foreground)]/25 hover:text-[var(--foreground)]"
+ onDragEnter={(event) => handleDropZoneEnter("upload", event)}
+ onDragLeave={(event) => handleDropZoneLeave("upload", event)}
+ onDragOver={(event) => handleDropZoneOver("upload", event)}
+ onDrop={(event) => handleDropZoneDrop("upload", event)}
+ className={`group relative flex w-full flex-col items-center justify-center gap-2 overflow-hidden rounded-2xl border border-dashed px-5 py-6 text-center transition-all ${
+ uploadDropZone.active
+ ? uploadDropZone.invalid
+ ? "border-amber-400 bg-amber-50/90 shadow-[0_0_0_4px_rgba(245,158,11,0.08)] dark:border-amber-700 dark:bg-amber-950/20"
+ : "border-sky-400 bg-sky-50/90 shadow-[0_0_0_4px_rgba(56,189,248,0.08)] dark:border-sky-700 dark:bg-sky-950/20"
+ : "border-[var(--border)] bg-[linear-gradient(180deg,var(--background),var(--muted)_180%)] hover:border-[var(--foreground)]/25 hover:bg-[var(--muted)]/30"
+ }`}
>
- <FileUp size={15} />
- {uploadFiles.length
- ? uploadFiles.length > 1
- ? t("{n} files selected", { n: uploadFiles.length })
- : t("{n} file selected", { n: uploadFiles.length })
- : t("Choose files...")}
+ <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top,rgba(255,255,255,0.32),transparent_60%)] opacity-60" />
+ <div className="rounded-2xl bg-[var(--muted)] p-3 text-[var(--muted-foreground)] transition-colors group-hover:text-[var(--foreground)]">
+ <Files className="h-5 w-5" />
+ </div>
+ <div className="space-y-1">
+ <div className="text-[13px] font-medium text-[var(--foreground)]">
+ {uploadDropZone.active
+ ? uploadDropZone.invalid
+ ? t("Some dragged files are not supported")
+ : t("Drop files to add them")
+ : uploadFiles.length
+ ? uploadSelection.invalidFiles.length > 0
+ ? t("{{count}} invalid files", {
+ count: uploadSelection.invalidFiles.length,
+ })
+ : t("{{count}} files ready", {
+ count: uploadSelection.validFiles.length,
+ })
+ : t("Choose files...")}
+ </div>
+ <p className="text-[11px] text-[var(--muted-foreground)]">
+ {uploadDropZone.active
+ ? uploadDropZone.draggedCount > 0
+ ? t("{{count}} files detected", {
+ count: uploadDropZone.draggedCount,
+ })
+ : t("Release to attach the files")
+ : uploadFiles.length
+ ? formatFileSize(uploadSelection.totalBytes)
+ : t("Click to browse supported documents")}
+ </p>
+ </div>
</button>
<input
ref={uploadFileRef}
type="file"
multiple
+ accept={uploadPolicy.accept || undefined}
className="hidden"
- onChange={(event) =>
- setUploadFiles(Array.from(event.target.files || []))
- }
+ onChange={(event) => {
+ setUploadFiles((prev) =>
+ mergeSelectedFiles(
+ prev,
+ Array.from(event.target.files || []),
+ ),
+ );
+ event.target.value = "";
+ }}
/>
- {!!uploadFiles.length && (
- <div className="flex flex-wrap gap-1.5">
- {uploadFiles.map((file) => (
- <span
- key={file.name}
- className="rounded-md bg-[var(--muted)] px-2 py-0.5 text-[11px] text-[var(--muted-foreground)]"
- >
- {file.name}
- </span>
- ))}
- </div>
- )}
+ {renderSelectionSummary(uploadSelection, removeUploadFile, () => {
+ setUploadFiles([]);
+ if (uploadFileRef.current) uploadFileRef.current.value = "";
+ })}
<button
onClick={uploadToKnowledgeBase}
@@ -1352,58 +1968,107 @@ function KnowledgePageContent() {
const progress = kb.progress;
const status = resolveKbStatus(kb);
const needsReindex = kbNeedsReindex(kb);
- const displayStatus = needsReindex
- ? t("needs reindex")
- : status !== "ready"
- ? status.replaceAll("_", " ")
- : null;
- const percent =
- progress?.progress_percent ??
- progress?.percent ??
- ((progress?.current ?? 0) && (progress?.total ?? 0)
- ? Math.round(
- ((progress?.current ?? 0) / (progress?.total ?? 1)) *
- 100,
+ const kbMetadata = kb.metadata || {};
+ const isReady = status === "ready" && !needsReindex;
+ const isError = status === "error";
+ const isLive = kbHasLiveProgress(kb);
+ const percent = resolveProgressPercent(progress);
+ const documentsCount = kb.statistics?.raw_documents ?? 0;
+ const imagesCount = kb.statistics?.images ?? 0;
+ const contentListsCount = kb.statistics?.content_lists ?? 0;
+ const assetCount = imagesCount + contentListsCount;
+ const createdLabel =
+ formatKnowledgeTimestamp(kbMetadata.created_at) ||
+ t("Unknown time");
+ const updatedLabel =
+ formatKnowledgeTimestamp(kbMetadata.last_updated) ||
+ t("Unknown time");
+ const embeddingLabel = kbMetadata.embedding_model
+ ? typeof kbMetadata.embedding_dim === "number"
+ ? `${kbMetadata.embedding_model} · ${kbMetadata.embedding_dim}d`
+ : kbMetadata.embedding_model
+ : t("Default embedding");
+ const activityMessage =
+ progress?.message ||
+ (needsReindex
+ ? t(
+ "This knowledge base needs reindex before it can accept new files.",
)
- : 0);
+ : isError
+ ? t("The last processing run failed.")
+ : isLive
+ ? t("Waiting for live progress...")
+ : null);
+ const statusLabel = needsReindex
+ ? t("Needs reindex")
+ : isError
+ ? t("Error")
+ : isLive
+ ? t("Processing live")
+ : isReady
+ ? t("Ready")
+ : status.replaceAll("_", " ");
return (
<div
key={kb.name}
- className="group rounded-lg border border-[var(--border)] bg-[var(--background)] p-4 transition-colors hover:border-[var(--foreground)]/10"
+ className="group rounded-2xl border border-[var(--border)] bg-[linear-gradient(180deg,var(--card),var(--background)_180%)] p-4 transition-colors hover:border-[var(--foreground)]/10"
>
<div className="flex flex-wrap items-start justify-between gap-3">
- <div className="min-w-0">
- <div className="flex items-center gap-2">
- <h3 className="text-[14px] font-medium text-[var(--foreground)]">
- {kb.name}
- </h3>
- {kb.is_default && (
- <span className="inline-flex items-center gap-1 rounded-md bg-[var(--muted)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--muted-foreground)]">
- <Star size={10} /> {t("Default")}
- </span>
- )}
+ <div className="flex min-w-0 flex-1 items-start gap-4">
+ <div className="relative hidden h-14 w-14 shrink-0 overflow-hidden rounded-2xl border border-[var(--border)] bg-[linear-gradient(180deg,var(--card),var(--muted)_160%)] sm:block">
+ <div className="absolute -right-3 -top-3 h-10 w-10 rounded-full bg-[var(--primary)]/12 blur-xl" />
+ <div className="absolute inset-0 bg-[radial-gradient(circle_at_top,rgba(255,255,255,0.26),transparent_58%)]" />
+ <div className="relative flex h-full items-center justify-center text-[var(--foreground)]">
+ <Layers className="h-5 w-5 opacity-80" />
+ </div>
</div>
- <div className="mt-1.5 flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-[var(--muted-foreground)]">
- <span>
- {t("Provider")}:{" "}
- {kb.statistics?.rag_provider || "llamaindex"}
- </span>
- <span>
- {t("Documents")}:{" "}
- {kb.statistics?.raw_documents ?? 0}
- </span>
- {displayStatus && (
+
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <h3 className="text-[15px] font-semibold text-[var(--foreground)]">
+ {kb.name}
+ </h3>
+ {kb.is_default && (
+ <span className="inline-flex items-center gap-1 rounded-full bg-[var(--muted)] px-2 py-0.5 text-[10px] font-medium text-[var(--muted-foreground)]">
+ <Star size={10} /> {t("Default")}
+ </span>
+ )}
<span
- className={
+ className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium ${
needsReindex
- ? "font-medium text-amber-600 dark:text-amber-400"
- : "capitalize"
- }
+ ? "bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-300"
+ : isError
+ ? "bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-300"
+ : isLive
+ ? "bg-sky-100 text-sky-700 dark:bg-sky-950/30 dark:text-sky-300"
+ : "bg-emerald-100 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-300"
+ }`}
>
- {t("Status")}: {displayStatus}
+ {isLive ? (
+ <Clock3 className="h-3 w-3" />
+ ) : isReady ? (
+ <CheckCircle2 className="h-3 w-3" />
+ ) : (
+ <AlertTriangle className="h-3 w-3" />
+ )}
+ {statusLabel}
</span>
- )}
+ </div>
+ <div className="mt-2 flex flex-wrap gap-2 text-[11px] text-[var(--muted-foreground)]">
+ <span className="rounded-full border border-[var(--border)] px-2.5 py-1">
+ {t("Provider")}:{" "}
+ {kb.statistics?.rag_provider || "llamaindex"}
+ </span>
+ <span className="rounded-full border border-[var(--border)] px-2.5 py-1">
+ {t("Embedding")}: {embeddingLabel}
+ </span>
+ {!!progress?.current && !!progress?.total && isLive && (
+ <span className="rounded-full border border-[var(--border)] px-2.5 py-1">
+ {t("Progress")}: {progress.current}/{progress.total}
+ </span>
+ )}
+ </div>
</div>
</div>
@@ -1425,19 +2090,111 @@ function KnowledgePageContent() {
</div>
</div>
- {progress?.message && (
- <div className="mt-3 rounded-lg bg-[var(--muted)] p-3">
- <div className="text-[12px] text-[var(--foreground)]">
- {progress.message}
+ <div className="mt-4 grid gap-2 sm:grid-cols-2 xl:grid-cols-4">
+ <div className="rounded-2xl border border-[var(--border)] bg-[var(--background)]/65 p-3">
+ <div className="text-[10px] font-medium uppercase tracking-[0.14em] text-[var(--muted-foreground)]">
+ {t("Documents")}
</div>
- {percent > 0 && (
- <div className="mt-2 h-1 overflow-hidden rounded-full bg-[var(--border)]">
- <div
- className="h-full rounded-full bg-[var(--primary)] transition-all duration-300"
- style={{ width: `${percent}%` }}
- />
+ <div className="mt-2 text-[20px] font-semibold text-[var(--foreground)]">
+ {documentsCount}
+ </div>
+ <div className="mt-1 text-[11px] text-[var(--muted-foreground)]">
+ {assetCount > 0
+ ? t("{{count}} derived assets", { count: assetCount })
+ : t("No derived assets yet")}
+ </div>
+ </div>
+
+ <div className="rounded-2xl border border-[var(--border)] bg-[var(--background)]/65 p-3">
+ <div className="text-[10px] font-medium uppercase tracking-[0.14em] text-[var(--muted-foreground)]">
+ {t("Updated")}
+ </div>
+ <div className="mt-2 text-[13px] font-medium leading-relaxed text-[var(--foreground)]">
+ {updatedLabel}
+ </div>
+ <div className="mt-1 text-[11px] text-[var(--muted-foreground)]">
+ {t("Created")}: {createdLabel}
+ </div>
+ </div>
+
+ <div className="rounded-2xl border border-[var(--border)] bg-[var(--background)]/65 p-3">
+ <div className="text-[10px] font-medium uppercase tracking-[0.14em] text-[var(--muted-foreground)]">
+ {t("Index")}
+ </div>
+ <div className="mt-2 text-[13px] font-medium text-[var(--foreground)]">
+ {kb.statistics?.rag_initialized
+ ? t("Vector index ready")
+ : t("Index not ready")}
+ </div>
+ <div className="mt-1 break-all text-[11px] text-[var(--muted-foreground)]">
+ {kb.path || t("No storage path")}
+ </div>
+ </div>
+
+ <div className="rounded-2xl border border-[var(--border)] bg-[var(--background)]/65 p-3">
+ <div className="text-[10px] font-medium uppercase tracking-[0.14em] text-[var(--muted-foreground)]">
+ {t("Assets")}
+ </div>
+ <div className="mt-2 text-[13px] font-medium text-[var(--foreground)]">
+ {imagesCount} {t("images")} · {contentListsCount}{" "}
+ {t("lists")}
+ </div>
+ <div className="mt-1 text-[11px] text-[var(--muted-foreground)]">
+ {kbMetadata.embedding_mismatch
+ ? t("Embedding config changed")
+ : t("Embedding config aligned")}
+ </div>
+ </div>
+ </div>
+
+ {(isLive || isError || needsReindex) && activityMessage && (
+ <div
+ className={`mt-4 rounded-2xl border p-4 ${
+ isError
+ ? "border-red-200 bg-red-50/70 dark:border-red-900/60 dark:bg-red-950/20"
+ : needsReindex
+ ? "border-amber-200 bg-amber-50/80 dark:border-amber-900/60 dark:bg-amber-950/20"
+ : "border-sky-200 bg-sky-50/70 dark:border-sky-900/60 dark:bg-sky-950/20"
+ }`}
+ >
+ <div className="flex items-center justify-between gap-3">
+ <div className="text-[11px] font-medium uppercase tracking-[0.14em] text-[var(--muted-foreground)]">
+ {isError
+ ? t("Latest activity")
+ : isLive
+ ? t("Live pipeline")
+ : t("Action required")}
+ </div>
+ {isLive && percent > 0 && (
+ <div className="text-[12px] font-medium text-[var(--foreground)]">
+ {percent}%
+ </div>
+ )}
+ </div>
+ <div className="mt-2 text-[13px] text-[var(--foreground)]">
+ {activityMessage}
+ </div>
+ {isLive && (
+ <div className="mt-3">
+ <div className="h-1.5 overflow-hidden rounded-full bg-[var(--border)]/70">
+ <div
+ className="h-full rounded-full bg-[var(--primary)] transition-all duration-300"
+ style={{ width: `${percent}%` }}
+ />
+ </div>
</div>
)}
+ {isLive &&
+ progress?.current !== undefined &&
+ progress?.total !== undefined &&
+ progress.total > 0 && (
+ <div className="mt-2 text-[11px] text-[var(--muted-foreground)]">
+ {t("Step {{current}} of {{total}}", {
+ current: progress.current,
+ total: progress.total,
+ })}
+ </div>
+ )}
</div>
)}
</div>
@@ -1445,8 +2202,18 @@ function KnowledgePageContent() {
})}
{!combinedKbs.length && (
- <div className="rounded-lg border border-dashed border-[var(--border)] px-6 py-10 text-center text-[13px] text-[var(--muted-foreground)]">
- {t("No knowledge bases yet. Create one to get started.")}
+ <div className="rounded-2xl border border-dashed border-[var(--border)] bg-[var(--background)]/40 px-6 py-12 text-center">
+ <div className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-2xl bg-[var(--muted)] text-[var(--muted-foreground)]">
+ <Database className="h-5 w-5" />
+ </div>
+ <div className="text-[14px] font-medium text-[var(--foreground)]">
+ {t("No knowledge bases yet. Create one to get started.")}
+ </div>
+ <p className="mx-auto mt-2 max-w-md text-[12px] leading-relaxed text-[var(--muted-foreground)]">
+ {t(
+ "Once a knowledge base is ready, it stays clean here as a reusable resource instead of showing stale completion banners.",
+ )}
+ </p>
</div>
)}
</div>
diff --git a/web/app/(utility)/settings/page.tsx b/web/app/(utility)/settings/page.tsx
index 3e6cfe0d4..0eeaea4c4 100644
--- a/web/app/(utility)/settings/page.tsx
+++ b/web/app/(utility)/settings/page.tsx
@@ -2,10 +2,8 @@
"use client";
import { Suspense, useCallback, useEffect, useRef, useState } from "react";
-import { useSearchParams } from "next/navigation";
import {
Brain,
- CheckCircle2,
ChevronDown,
ChevronRight,
Database,
@@ -15,13 +13,11 @@ import {
Loader2,
Plus,
Rocket,
- RotateCcw,
Save,
Search,
Terminal,
Trash2,
Wand2,
- X,
} from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -38,6 +34,9 @@ type CatalogModel = {
model: string;
dimension?: string;
send_dimensions?: boolean;
+ context_window?: string;
+ context_window_source?: string;
+ context_window_detected_at?: string;
};
type CatalogProfile = {
@@ -94,19 +93,6 @@ type SystemStatus = {
search: { status: string; provider?: string; error?: string };
};
-type TourTestResult = "pass" | "fail" | "skip" | "pending";
-type TourTestResults = {
- llm: TourTestResult;
- embedding: TourTestResult;
- search: TourTestResult;
-};
-type TourCompleteResponse = {
- status: string;
- message: string;
- launch_at?: number;
- redirect_at?: number;
-};
-
// ---------------------------------------------------------------------------
function cloneCatalog(catalog: Catalog): Catalog {
@@ -185,6 +171,29 @@ function stringifyExtraHeaders(value: CatalogProfile["extra_headers"]): string {
}
}
+function formatContextWindowSource(
+ source: string | undefined,
+ t: (key: string) => string,
+): string {
+ if (source === "manual") return t("Manual");
+ if (source === "metadata") return t("Auto");
+ if (source === "default") return t("Default");
+ return t("Unset");
+}
+
+function formatContextWindowUpdatedAt(
+ value: string | undefined,
+ language: "en" | "zh",
+): string {
+ if (!value) return "";
+ const parsed = new Date(value);
+ if (Number.isNaN(parsed.getTime())) return value;
+ return parsed.toLocaleString(language === "zh" ? "zh-CN" : "en-US", {
+ dateStyle: "medium",
+ timeStyle: "short",
+ });
+}
+
// ---------------------------------------------------------------------------
// Tour onboarding steps
// ---------------------------------------------------------------------------
@@ -192,23 +201,31 @@ function stringifyExtraHeaders(value: CatalogProfile["extra_headers"]): string {
const TOUR_GUIDE_STEPS = [
{
target: "tour-llm",
- title: "1 / 4 — LLM",
- desc: "Configure your language model endpoint. This powers all chat and reasoning.",
+ service: "llm" as const,
+ titleKey: "settingsTour.llm.title",
+ descKey: "settingsTour.llm.desc",
},
{
target: "tour-embedding",
- title: "2 / 4 — Embedding",
- desc: "Set the embedding model for knowledge retrieval.",
+ service: "embedding" as const,
+ titleKey: "settingsTour.embedding.title",
+ descKey: "settingsTour.embedding.desc",
},
{
target: "tour-search",
- title: "3 / 4 — Search",
- desc: "Optional: add a web search provider for real-time information.",
+ service: "search" as const,
+ titleKey: "settingsTour.search.title",
+ descKey: "settingsTour.search.desc",
},
{
- target: "tour-complete",
- title: "4 / 4 — Complete",
- desc: "When you are ready, click here to test and launch DeepTutor.",
+ target: "tour-save-test",
+ titleKey: "settingsTour.saveTest.title",
+ descKey: "settingsTour.saveTest.desc",
+ },
+ {
+ target: "tour-actions",
+ titleKey: "settingsTour.apply.title",
+ descKey: "settingsTour.apply.desc",
},
];
@@ -284,10 +301,10 @@ function SpotlightOverlay({
style={{ top: tooltipTop, left: tooltipLeft }}
>
<div className="mb-1 text-[13px] font-semibold text-[var(--foreground)]">
- {t(guideStep.title)}
+ {t(guideStep.titleKey)}
</div>
<p className="mb-4 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
- {t(guideStep.desc)}
+ {t(guideStep.descKey)}
</p>
<div className="flex items-center justify-between">
<button
@@ -309,122 +326,12 @@ function SpotlightOverlay({
);
}
-// ---------------------------------------------------------------------------
-// Test results modal
-// ---------------------------------------------------------------------------
-
-function TestResultsModal({
- results,
- testing,
- onConfirm,
- onCancel,
-}: {
- results: TourTestResults;
- testing: boolean;
- onConfirm: () => void;
- onCancel: () => void;
-}) {
- const { t } = useTranslation();
- const hasCriticalFailure =
- results.llm === "fail" || results.embedding === "fail";
- const allDone =
- !testing && results.llm !== "pending" && results.embedding !== "pending";
-
- const dot = (r: TourTestResult) => {
- if (r === "pass") return "bg-emerald-500";
- if (r === "fail") return "bg-red-400";
- if (r === "skip") return "bg-[var(--border)]";
- return "bg-amber-400 animate-pulse";
- };
-
- const label = (r: TourTestResult) => {
- if (r === "pass") return t("Passed");
- if (r === "fail") return t("Failed");
- if (r === "skip") return t("Skipped");
- return t("Testing...");
- };
-
- return (
- <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/40">
- <div className="w-[400px] rounded-2xl border border-[var(--border)] bg-[var(--card)] p-6 shadow-2xl">
- <div className="mb-5 flex items-center justify-between">
- <h2 className="text-[16px] font-semibold text-[var(--foreground)]">
- {testing ? t("Running tests...") : t("Test Results")}
- </h2>
- {!testing && (
- <button
- onClick={onCancel}
- className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- >
- <X className="h-4 w-4" />
- </button>
- )}
- </div>
-
- <div className="mb-6 space-y-3">
- {(["llm", "embedding", "search"] as const).map((svc) => (
- <div
- key={svc}
- className="flex items-center justify-between rounded-lg border border-[var(--border)]/50 px-4 py-3"
- >
- <div className="flex items-center gap-2.5">
- {serviceIcon(svc)}
- <span className="text-[13px] font-medium text-[var(--foreground)]">
- {svc.toUpperCase()}
- </span>
- </div>
- <div className="flex items-center gap-2">
- <span
- className={`inline-block h-2 w-2 rounded-full ${dot(results[svc])}`}
- />
- <span className="text-[12px] text-[var(--muted-foreground)]">
- {label(results[svc])}
- </span>
- </div>
- </div>
- ))}
- </div>
-
- {allDone && (
- <div className="flex items-center gap-3">
- <button
- onClick={onCancel}
- className="flex-1 rounded-lg border border-[var(--border)] px-4 py-2 text-[13px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--foreground)]/20 hover:text-[var(--foreground)]"
- >
- {t("Back to editing")}
- </button>
- <button
- onClick={onConfirm}
- className={`flex-1 rounded-lg px-4 py-2 text-[13px] font-medium transition-opacity hover:opacity-80 ${
- hasCriticalFailure
- ? "bg-red-500 text-white"
- : "bg-[var(--foreground)] text-[var(--background)]"
- }`}
- >
- {hasCriticalFailure ? t("Launch anyway") : t("Confirm & Launch")}
- </button>
- </div>
- )}
-
- {testing && (
- <div className="flex items-center justify-center gap-2 py-2 text-[13px] text-[var(--muted-foreground)]">
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- {t("Please wait...")}
- </div>
- )}
- </div>
- </div>
- );
-}
-
// ═══════════════════════════════════════════════════════════════════════════
// Main component
// ═══════════════════════════════════════════════════════════════════════════
function SettingsPageContent() {
const { t } = useTranslation();
- const searchParams = useSearchParams();
- const isTourMode = searchParams.get("tour") === "true";
const [status, setStatus] = useState<SystemStatus | null>(null);
const [theme, setTheme] = useState<"light" | "dark" | "glass" | "snow">(
@@ -447,18 +354,7 @@ function SettingsPageContent() {
const eventSourceRef = useRef<EventSource | null>(null);
// Tour-specific state
- const [tourGuideStep, setTourGuideStep] = useState(isTourMode ? 0 : -1);
- const [tourTestPhase, setTourTestPhase] = useState<
- "idle" | "testing" | "results"
- >("idle");
- const [tourTestResults, setTourTestResults] = useState<TourTestResults>({
- llm: "pending",
- embedding: "pending",
- search: "pending",
- });
- const [tourCompleted, setTourCompleted] = useState(false);
- const [tourRedirectAt, setTourRedirectAt] = useState<number | null>(null);
- const [redirectCountdown, setRedirectCountdown] = useState(-1);
+ const [tourGuideStep, setTourGuideStep] = useState(-1);
// -- Data loading -------------------------------------------------------
@@ -489,34 +385,13 @@ function SettingsPageContent() {
return () => clearTimeout(timer);
}, [toast]);
- // -- Redirect countdown after tour complete -----------------------------
-
- useEffect(() => {
- if (!tourCompleted || !tourRedirectAt) return;
- const tick = () => {
- const secondsLeft = Math.max(
- 0,
- Math.ceil(tourRedirectAt - Date.now() / 1000),
- );
- setRedirectCountdown(secondsLeft);
- };
- tick();
- const timer = setInterval(tick, 250);
- return () => clearInterval(timer);
- }, [tourCompleted, tourRedirectAt]);
-
- useEffect(() => {
- if (redirectCountdown === 0 && tourCompleted) {
- window.location.href = "/";
- }
- }, [redirectCountdown, tourCompleted]);
-
// -- Tour guide auto-switch active service tab --------------------------
useEffect(() => {
- if (tourGuideStep === 0) setActiveService("llm");
- else if (tourGuideStep === 1) setActiveService("embedding");
- else if (tourGuideStep === 2) setActiveService("search");
+ const currentStep = TOUR_GUIDE_STEPS[tourGuideStep];
+ if (currentStep?.service) {
+ setActiveService(currentStep.service);
+ }
}, [tourGuideStep]);
// -- Derived ------------------------------------------------------------
@@ -692,6 +567,24 @@ function SettingsPageContent() {
});
};
+ const updateContextWindowField = (value: string) => {
+ if (activeService !== "llm") return;
+ const normalized = value.replace(/[^\d]/g, "");
+ mutateCatalog((next) => {
+ const model = getActiveModel(next, activeService);
+ if (!model) return;
+ if (normalized) {
+ model.context_window = normalized;
+ model.context_window_source = "manual";
+ delete model.context_window_detected_at;
+ } else {
+ delete model.context_window;
+ delete model.context_window_source;
+ delete model.context_window_detected_at;
+ }
+ });
+ };
+
const updateModelBoolField = (
field: keyof CatalogModel,
value: boolean,
@@ -777,8 +670,13 @@ function SettingsPageContent() {
const entry = JSON.parse(event.data) as {
type: string;
message: string;
+ catalog?: Catalog;
};
setLogs((current) => `${current}[${entry.type}] ${entry.message}\n`);
+ if (entry.catalog) {
+ setCatalog(entry.catalog);
+ setDraft(cloneCatalog(entry.catalog));
+ }
if (entry.type === "completed" || entry.type === "failed") {
source.close();
eventSourceRef.current = null;
@@ -804,143 +702,11 @@ function SettingsPageContent() {
}
};
- // -- Tour: run a single service test and return pass/fail ---------------
-
- const runSingleTest = useCallback(
- async (
- svc: ServiceName,
- catalogSnapshot: Catalog,
- ): Promise<"pass" | "fail"> => {
- try {
- const response = await fetch(
- apiUrl(`/api/v1/settings/tests/${svc}/start`),
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ catalog: catalogSnapshot }),
- },
- );
- const payload = (await response.json()) as { run_id?: string };
- if (!response.ok || !payload.run_id) return "fail";
-
- return new Promise((resolve) => {
- const source = new EventSource(
- apiUrl(`/api/v1/settings/tests/${svc}/${payload.run_id}/events`),
- );
- const timeout = setTimeout(() => {
- source.close();
- resolve("fail");
- }, 30000);
- source.onmessage = (event) => {
- const entry = JSON.parse(event.data) as { type: string };
- if (entry.type === "completed") {
- clearTimeout(timeout);
- source.close();
- resolve("pass");
- } else if (entry.type === "failed") {
- clearTimeout(timeout);
- source.close();
- resolve("fail");
- }
- };
- source.onerror = () => {
- clearTimeout(timeout);
- source.close();
- resolve("fail");
- };
- });
- } catch {
- return "fail";
- }
- },
- [],
- );
-
- // -- Tour: Complete & Launch flow ---------------------------------------
-
- const startTourComplete = async () => {
- setTourTestPhase("testing");
- const results: TourTestResults = {
- llm: "pending",
- embedding: "pending",
- search: "pending",
- };
- setTourTestResults({ ...results });
-
- // Apply catalog first so backend picks up config
- await fetch(apiUrl("/api/v1/settings/apply"), {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ catalog: draft }),
- });
-
- const catalogSnapshot = cloneCatalog(draft);
-
- // Test LLM
- results.llm = await runSingleTest("llm", catalogSnapshot);
- setTourTestResults({ ...results });
-
- // Test Embedding
- results.embedding = await runSingleTest("embedding", catalogSnapshot);
- setTourTestResults({ ...results });
-
- // Test Search (skip if no provider configured)
- const searchProfile = getActiveProfile(catalogSnapshot, "search");
- const hasSearchProvider =
- searchProfile?.provider && searchProfile.provider.trim() !== "";
- if (hasSearchProvider) {
- results.search = await runSingleTest("search", catalogSnapshot);
- } else {
- results.search = "skip";
- }
- setTourTestResults({ ...results });
-
- setTourTestPhase("results");
- };
-
- const confirmTourComplete = async () => {
- setTourTestPhase("idle");
- try {
- const response = await fetch(apiUrl("/api/v1/settings/tour/complete"), {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ catalog: draft, test_results: tourTestResults }),
- });
- if (response.ok) {
- const payload = (await response.json()) as TourCompleteResponse;
- setTourCompleted(true);
- setTourRedirectAt(
- payload.redirect_at ?? Math.floor(Date.now() / 1000) + 5,
- );
- } else {
- setToast(t("Failed to complete tour"));
- }
- } catch {
- setToast(t("Failed to complete tour"));
- }
- };
-
- const cancelTourTest = () => {
- setTourTestPhase("idle");
- };
+ // -- Tour ---------------------------------------------------------------
- // -- Reopen tour --------------------------------------------------------
-
- const reopenTour = async () => {
- const response = await fetch(apiUrl("/api/v1/settings/tour/reopen"), {
- method: "POST",
- });
- const payload = (await response.json()) as {
- command?: string;
- message?: string;
- };
- setToast(
- payload.command
- ? t("Run {{command}} in your terminal.", { command: payload.command })
- : payload.message ||
- t("Run python scripts/start_tour.py in your terminal."),
- );
- };
+ const runTour = useCallback(() => {
+ setTourGuideStep(0);
+ }, []);
// ═══════════════════════════════════════════════════════════════════════
// Render
@@ -949,53 +715,6 @@ function SettingsPageContent() {
return (
<div className="h-full overflow-y-auto [scrollbar-gutter:stable]">
<div className="mx-auto max-w-[960px] px-6 py-8">
- {/* ── Tour Banner ── */}
- {isTourMode && !tourCompleted && (
- <div className="mb-6 flex items-center justify-between rounded-xl border border-[var(--primary)]/20 bg-[var(--primary)]/5 px-5 py-4">
- <div>
- <div className="flex items-center gap-2 text-[14px] font-semibold text-[var(--foreground)]">
- <Rocket className="h-4 w-4 text-[var(--primary)]" />
- {t("Setup Tour")}
- </div>
- <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">
- {t(
- "Configure your endpoints below, run tests, then launch DeepTutor.",
- )}
- </p>
- </div>
- <button
- data-tour="tour-complete"
- onClick={startTourComplete}
- disabled={tourTestPhase === "testing"}
- className="ml-4 inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-4 py-2 text-[13px] font-medium text-[var(--background)] transition-opacity hover:opacity-80 disabled:opacity-40"
- >
- {tourTestPhase === "testing" ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <CheckCircle2 className="h-3.5 w-3.5" />
- )}
- {t("Complete & Launch")}
- </button>
- </div>
- )}
-
- {/* Tour completed banner with countdown */}
- {isTourMode && tourCompleted && (
- <div className="mb-6 rounded-xl border border-emerald-500/20 bg-emerald-500/5 px-5 py-4 text-center">
- <div className="flex items-center justify-center gap-2 text-[14px] font-semibold text-emerald-600 dark:text-emerald-400">
- <CheckCircle2 className="h-4 w-4" />
- {t("Configuration saved")}
- </div>
- <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">
- {redirectCountdown > 0
- ? t("Redirecting to DeepTutor in {{count}}s...", {
- count: redirectCountdown,
- })
- : t("Redirecting...")}
- </p>
- </div>
- )}
-
{/* ── Header ── */}
<div className="mb-6 flex items-start justify-between">
<div>
@@ -1016,6 +735,14 @@ function SettingsPageContent() {
</div>
<div className="flex items-center gap-2">
<button
+ onClick={runTour}
+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
+ >
+ <Rocket className="h-3 w-3" />
+ {t("Tour")}
+ </button>
+ <button
+ data-tour="tour-save-test"
onClick={saveCatalog}
disabled={saving}
className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"
@@ -1028,14 +755,10 @@ function SettingsPageContent() {
{t("Save Draft")}
</button>
<button
+ data-tour="tour-actions"
onClick={applyCatalog}
- disabled={applying || isTourMode}
- title={isTourMode ? t("Complete the tour first") : undefined}
- className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] font-medium transition-opacity disabled:opacity-40 ${
- isTourMode
- ? "cursor-not-allowed border border-[var(--border)]/30 bg-[var(--muted)] text-[var(--muted-foreground)]"
- : "bg-[var(--foreground)] text-[var(--background)] hover:opacity-80"
- }`}
+ disabled={applying}
+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] transition-opacity hover:opacity-80 disabled:opacity-40"
>
{applying ? (
<Loader2 className="h-3 w-3 animate-spin" />
@@ -1462,6 +1185,66 @@ function SettingsPageContent() {
placeholder="gpt-4o"
/>
</div>
+ {activeService === "llm" && (
+ <>
+ <div>
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ {t("Context Window")}
+ </div>
+ <input
+ className={inputClass}
+ inputMode="numeric"
+ value={activeModel.context_window || ""}
+ onChange={(e) =>
+ updateContextWindowField(e.target.value)
+ }
+ placeholder="65536"
+ />
+ </div>
+ <div className="rounded-xl border border-[var(--border)]/70 bg-[var(--muted)]/30 px-3.5 py-3">
+ <div className="flex items-center justify-between gap-3">
+ <div className="text-[11px] uppercase tracking-[0.16em] text-[var(--muted-foreground)]/70">
+ {t("Source")}
+ </div>
+ <span className="rounded-full border border-[var(--border)]/70 bg-[var(--card)] px-2.5 py-1 text-[11px] font-medium text-[var(--foreground)]">
+ {formatContextWindowSource(
+ activeModel.context_window_source,
+ t,
+ )}
+ </span>
+ </div>
+ <p className="mt-2 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
+ {activeModel.context_window_source ===
+ "metadata"
+ ? t(
+ "Detected from the provider during the latest LLM test and saved into model_catalog.json.",
+ )
+ : activeModel.context_window_source ===
+ "default"
+ ? t(
+ "The provider did not expose a context window, so the runtime fallback was saved during the latest LLM test.",
+ )
+ : activeModel.context_window_source ===
+ "manual"
+ ? t(
+ "Manual override from Settings. Save Draft to persist your edit.",
+ )
+ : t(
+ "Run the LLM test to auto-fill this field, or enter a value manually.",
+ )}
+ </p>
+ {activeModel.context_window_detected_at && (
+ <div className="mt-2 text-[11px] text-[var(--muted-foreground)]/70">
+ {t("Detected at")}:{" "}
+ {formatContextWindowUpdatedAt(
+ activeModel.context_window_detected_at,
+ language,
+ )}
+ </div>
+ )}
+ </div>
+ </>
+ )}
{activeService === "embedding" && (
<div>
<div className="mb-1.5 flex items-center justify-between gap-2">
@@ -1585,28 +1368,16 @@ function SettingsPageContent() {
)}
</div>
- {/* ── Footer ── */}
- <div className="flex items-center justify-between border-t border-[var(--border)]/30 pt-4 pb-2">
- {!isTourMode && (
- <button
- onClick={reopenTour}
- className="inline-flex items-center gap-1.5 text-[12px] text-[var(--muted-foreground)]/40 transition-colors hover:text-[var(--muted-foreground)]"
- >
- <RotateCcw className="h-3 w-3" />
- {t("Run Terminal Tour")}
- </button>
- )}
- <span className="text-[11px] text-[var(--muted-foreground)]/30 ml-auto">
- v{draft.version}
- </span>
- </div>
+ {/* ── Footer note ── */}
+ <p className="mt-2 pb-4 text-[11px] leading-relaxed text-[var(--muted-foreground)]/40">
+ {t("settings.configNote")}
+ </p>
</div>
{/* ── Spotlight overlay (tour onboarding) ── */}
- {isTourMode &&
- tourGuideStep >= 0 &&
+ {tourGuideStep >= 0 &&
tourGuideStep < TOUR_GUIDE_STEPS.length &&
- !tourCompleted && (
+ (
<SpotlightOverlay
stepIndex={tourGuideStep}
onNext={() => {
@@ -1619,16 +1390,6 @@ function SettingsPageContent() {
onSkip={() => setTourGuideStep(-1)}
/>
)}
-
- {/* ── Test results modal (tour) ── */}
- {isTourMode && tourTestPhase !== "idle" && (
- <TestResultsModal
- results={tourTestResults}
- testing={tourTestPhase === "testing"}
- onConfirm={confirmTourComplete}
- onCancel={cancelTourTest}
- />
- )}
</div>
);
}
diff --git a/web/app/(workspace)/agents/page.tsx b/web/app/(workspace)/agents/page.tsx
index dd9cf812b..c188f584a 100644
--- a/web/app/(workspace)/agents/page.tsx
+++ b/web/app/(workspace)/agents/page.tsx
@@ -849,12 +849,22 @@ function BotsTab({
};
const botId = useMemo(() => {
- const slug = formName
- .trim()
+ const trimmed = formName.trim();
+ if (!trimmed) return "";
+ const slug = trimmed
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "");
- return slug || "";
+ if (slug) return slug;
+ // Name has no ASCII alphanumerics (e.g. pure Chinese / Japanese).
+ // Derive a deterministic ASCII fallback so the bot ID stays
+ // filesystem- and URL-safe while the display name keeps its CJK form.
+ let h = 0;
+ for (let i = 0; i < trimmed.length; i++) {
+ h = (h << 5) - h + trimmed.charCodeAt(i);
+ h |= 0;
+ }
+ return `bot-${Math.abs(h).toString(36).padStart(6, "0").slice(0, 8)}`;
}, [formName]);
const selectSoul = (id: string) => {
@@ -885,11 +895,22 @@ function BotsTab({
setShowCreate(false);
resetForm();
await onReload();
+ } else {
+ const err = (await res.json().catch(() => ({}))) as {
+ detail?: string | { message?: string };
+ };
+ const detail =
+ typeof err.detail === "string"
+ ? err.detail
+ : (err.detail?.message ?? t("Failed to create bot"));
+ onToast(detail);
}
+ } catch {
+ onToast(t("Failed to create bot"));
} finally {
setCreating(false);
}
- }, [botId, formName, formDesc, formSoul, formModel, onReload, onToast]);
+ }, [botId, formName, formDesc, formSoul, formModel, onReload, onToast, t]);
const startBot = useCallback(
async (bid: string) => {
diff --git a/web/app/(workspace)/book/components/blocks/QuizBlock.tsx b/web/app/(workspace)/book/components/blocks/QuizBlock.tsx
index 2262e9ff7..5cf403b87 100644
--- a/web/app/(workspace)/book/components/blocks/QuizBlock.tsx
+++ b/web/app/(workspace)/book/components/blocks/QuizBlock.tsx
@@ -1,9 +1,15 @@
"use client";
import { useEffect, useState } from "react";
-import { CheckCircle2, XCircle, Eye, EyeOff } from "lucide-react";
+import { CheckCircle2, Eye, EyeOff, XCircle } from "lucide-react";
+
import MarkdownRenderer from "@/components/common/MarkdownRenderer";
import type { Block } from "@/lib/book-types";
+import {
+ isChoiceQuizQuestion,
+ normalizeQuizQuestionType,
+ resolveChoiceAnswerKey,
+} from "@/lib/quiz-question-type";
export interface QuizAttemptArgs {
questionId?: string;
@@ -69,27 +75,44 @@ function QuizQuestionCard({
const [selected, setSelected] = useState<string | null>(null);
const [revealed, setRevealed] = useState(false);
const [reported, setReported] = useState(false);
- const isMultiple =
- (question.question_type || "").toLowerCase() === "multiple_choice";
- const correct = String(question.correct_answer || "").trim();
+ const normalizedType = normalizeQuizQuestionType(question.question_type);
const options = question.options || {};
+ const isChoice = isChoiceQuizQuestion(normalizedType);
+ const correct = String(question.correct_answer || "").trim();
+ const correctChoiceKey = resolveChoiceAnswerKey(correct, options);
useEffect(() => {
if (revealed && selected && !reported && onAttempt) {
onAttempt({
questionId: question.question_id,
userAnswer: selected,
- isCorrect: selected === correct,
+ isCorrect: selected.toUpperCase() === correctChoiceKey,
});
setReported(true);
}
- }, [revealed, selected, reported, onAttempt, question.question_id, correct]);
+ }, [
+ revealed,
+ selected,
+ reported,
+ onAttempt,
+ question.question_id,
+ correctChoiceKey,
+ ]);
return (
<div className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-3">
- <div className="flex items-baseline justify-between gap-2">
- <div className="text-sm font-medium text-[var(--foreground)]">
- {index + 1}. {question.question || "(missing)"}
+ <div className="flex items-start justify-between gap-2">
+ <div className="flex min-w-0 flex-1 items-start gap-2">
+ <span className="pt-0.5 text-sm font-medium text-[var(--foreground)]">
+ {index + 1}.
+ </span>
+ <div className="min-w-0 flex-1">
+ <MarkdownRenderer
+ content={String(question.question || "(missing)")}
+ variant="compact"
+ className="font-sans text-sm font-medium text-[var(--foreground)] [&_ol]:my-2 [&_p:first-child]:mt-0 [&_p:last-child]:mb-0 [&_p]:my-1.5 [&_pre]:my-2 [&_ul]:my-2"
+ />
+ </div>
</div>
{question.difficulty && (
<span className="rounded-full bg-[var(--muted)] px-2 py-0.5 text-[10px] uppercase tracking-wider text-[var(--muted-foreground)]">
@@ -98,16 +121,18 @@ function QuizQuestionCard({
)}
</div>
- {isMultiple && Object.keys(options).length > 0 ? (
+ {isChoice && Object.keys(options).length > 0 ? (
<div className="mt-3 space-y-1.5">
{Object.entries(options).map(([key, label]) => {
- const isSelected = selected === key;
- const isCorrect = revealed && key === correct;
- const isWrongPick = revealed && isSelected && key !== correct;
+ const upperKey = key.toUpperCase();
+ const isSelected = selected === upperKey;
+ const isCorrect = revealed && upperKey === correctChoiceKey;
+ const isWrongPick =
+ revealed && isSelected && upperKey !== correctChoiceKey;
return (
<button
key={key}
- onClick={() => setSelected(key)}
+ onClick={() => setSelected(upperKey)}
className={`flex w-full items-start gap-2 rounded-lg border px-3 py-2 text-left text-sm transition-colors ${
isCorrect
? "border-emerald-300 bg-emerald-50 text-emerald-900 dark:border-emerald-500/40 dark:bg-emerald-500/10 dark:text-emerald-100"
@@ -119,9 +144,11 @@ function QuizQuestionCard({
}`}
>
<span className="font-mono text-xs uppercase text-[var(--muted-foreground)]">
- {key}.
+ {upperKey}.
+ </span>
+ <span className="flex-1 whitespace-pre-wrap break-words">
+ {label}
</span>
- <span className="flex-1">{label}</span>
{isCorrect && <CheckCircle2 className="mt-0.5 h-4 w-4" />}
{isWrongPick && <XCircle className="mt-0.5 h-4 w-4" />}
</button>
@@ -130,7 +157,7 @@ function QuizQuestionCard({
</div>
) : (
<div className="mt-2 text-xs text-[var(--muted-foreground)]">
- {question.question_type === "fill_in_blank"
+ {normalizedType === "written"
? "Think about your answer, then reveal the solution."
: "Open response — click reveal to see the model answer."}
</div>
@@ -148,16 +175,29 @@ function QuizQuestionCard({
)}
{revealed ? "Hide answer" : "Reveal answer"}
</button>
- {revealed && correct && (
+ {revealed && correct && isChoice && (
<span className="text-xs text-[var(--muted-foreground)]">
Answer:{" "}
<span className="font-mono text-[var(--foreground)]">
- {correct}
+ {correctChoiceKey || correct}
</span>
</span>
)}
</div>
+ {revealed && correct && !isChoice && (
+ <div className="mt-2 rounded-lg border border-[var(--border)] bg-[var(--card)]/70 p-2">
+ <div className="mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--muted-foreground)]">
+ Answer
+ </div>
+ <MarkdownRenderer
+ content={correct}
+ variant="compact"
+ className="font-sans text-sm text-[var(--foreground)] [&_p:first-child]:mt-0 [&_p:last-child]:mb-0 [&_p]:my-1.5 [&_pre]:my-2"
+ />
+ </div>
+ )}
+
{revealed && question.explanation && (
<div className="mt-2 rounded-lg border border-[var(--border)] bg-[var(--muted)]/40 p-2">
<MarkdownRenderer
diff --git a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
index 01ece6059..e51d6b664 100644
--- a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
@@ -34,6 +34,11 @@ import {
extractBase64FromDataUrl,
readFileAsDataUrl,
} from "@/lib/file-attachments";
+import {
+ classifyFile,
+ MAX_ATTACHMENT_BYTES,
+ MAX_TOTAL_ATTACHMENT_BYTES,
+} from "@/lib/doc-attachments";
import { useChatAutoScroll } from "@/hooks/useChatAutoScroll";
import { useMeasuredHeight } from "@/hooks/useMeasuredHeight";
import {
@@ -208,6 +213,8 @@ interface PendingAttachment {
filename: string;
base64?: string;
previewUrl?: string;
+ size?: number;
+ mimeType?: string;
}
/* ------------------------------------------------------------------ */
@@ -245,6 +252,8 @@ export default function ChatPage() {
useState<CapabilityPlaygroundConfigMap>({});
const [attachments, setAttachments] = useState<PendingAttachment[]>([]);
const [dragging, setDragging] = useState(false);
+ const [attachmentError, setAttachmentError] = useState<string | null>(null);
+ const attachmentErrorTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const [capMenuOpen, setCapMenuOpen] = useState(false);
const [quizConfig, setQuizConfig] = useState<DeepQuestionFormConfig>({
...DEFAULT_QUIZ_CONFIG,
@@ -282,7 +291,7 @@ export default function ChatPage() {
>([]);
const [availableSkills, setAvailableSkills] = useState<SkillInfo[]>([]);
const [selectedSkills, setSelectedSkills] = useState<string[]>([]);
- const [skillsAutoMode, setSkillsAutoMode] = useState(true);
+ const [skillsAutoMode, setSkillsAutoMode] = useState(false);
const dragCounter = useRef(0);
const capMenuRef = useRef<HTMLDivElement>(null);
const capBtnRef = useRef<HTMLButtonElement>(null);
@@ -652,6 +661,8 @@ export default function ChatPage() {
filename: f.name,
base64: b64,
previewUrl: isImage ? raw : undefined,
+ size: f.size,
+ mimeType: f.type || undefined,
});
})
.catch(reject);
@@ -659,19 +670,73 @@ export default function ChatPage() {
[],
);
+ const showAttachmentError = useCallback((message: string) => {
+ setAttachmentError(message);
+ if (attachmentErrorTimer.current) {
+ clearTimeout(attachmentErrorTimer.current);
+ }
+ attachmentErrorTimer.current = setTimeout(() => {
+ setAttachmentError(null);
+ attachmentErrorTimer.current = null;
+ }, 4000);
+ }, []);
+
+ const filterAndReportFiles = useCallback(
+ (files: File[]): File[] => {
+ let runningTotal = attachments.reduce((s, a) => s + (a.size ?? 0), 0);
+ const accepted: File[] = [];
+ const rejected: {
+ name: string;
+ reason: "unsupported" | "too_large" | "quota";
+ }[] = [];
+ for (const f of files) {
+ const kind = classifyFile(f);
+ if (!kind) {
+ rejected.push({ name: f.name, reason: "unsupported" });
+ continue;
+ }
+ if (f.size > MAX_ATTACHMENT_BYTES) {
+ rejected.push({ name: f.name, reason: "too_large" });
+ continue;
+ }
+ if (runningTotal + f.size > MAX_TOTAL_ATTACHMENT_BYTES) {
+ rejected.push({ name: f.name, reason: "quota" });
+ break;
+ }
+ runningTotal += f.size;
+ accepted.push(f);
+ }
+ if (rejected.length) {
+ const first = rejected[0];
+ let msg: string;
+ if (first.reason === "too_large") {
+ msg = t("File too large: {{name}}", { name: first.name });
+ } else if (first.reason === "quota") {
+ msg = t("Too many files, skipped some");
+ } else {
+ msg = t("Unsupported file type: {{name}}", { name: first.name });
+ }
+ showAttachmentError(msg);
+ }
+ return accepted;
+ },
+ [attachments, showAttachmentError, t],
+ );
+
const handlePaste = useCallback(
async (event: React.ClipboardEvent) => {
const items = Array.from(event.clipboardData.items);
- const imageFiles = items
- .filter((item) => item.type.startsWith("image/"))
+ const files = items
+ .filter((item) => item.kind === "file")
.map((item) => item.getAsFile())
.filter((f): f is File => f !== null);
- if (!imageFiles.length) return;
+ const accepted = filterAndReportFiles(files);
+ if (!accepted.length) return;
event.preventDefault();
- const next = await Promise.all(imageFiles.map(fileToAttachment));
+ const next = await Promise.all(accepted.map(fileToAttachment));
setAttachments((prev) => [...prev, ...next]);
},
- [fileToAttachment],
+ [fileToAttachment, filterAndReportFiles],
);
const removeAttachment = useCallback((index: number) => {
@@ -703,14 +768,22 @@ export default function ChatPage() {
e.stopPropagation();
setDragging(false);
dragCounter.current = 0;
- const files = Array.from(e.dataTransfer.files).filter((f) =>
- f.type.startsWith("image/"),
- );
- if (!files.length) return;
- const next = await Promise.all(files.map(fileToAttachment));
+ const accepted = filterAndReportFiles(Array.from(e.dataTransfer.files));
+ if (!accepted.length) return;
+ const next = await Promise.all(accepted.map(fileToAttachment));
setAttachments((prev) => [...prev, ...next]);
},
- [fileToAttachment],
+ [fileToAttachment, filterAndReportFiles],
+ );
+
+ const handleAddFiles = useCallback(
+ async (files: File[]) => {
+ const accepted = filterAndReportFiles(files);
+ if (!accepted.length) return;
+ const next = await Promise.all(accepted.map(fileToAttachment));
+ setAttachments((prev) => [...prev, ...next]);
+ },
+ [fileToAttachment, filterAndReportFiles],
);
const handleSend = useCallback(
@@ -729,6 +802,7 @@ export default function ChatPage() {
type: a.type,
filename: a.filename,
base64: a.base64,
+ mime_type: a.mimeType,
}));
let config: Record<string, unknown> | undefined;
@@ -740,7 +814,12 @@ export default function ChatPage() {
);
extraAttachments = [
...extraAttachments,
- { type: "pdf", filename: quizPdf.name, base64: b64 },
+ {
+ type: "pdf",
+ filename: quizPdf.name,
+ base64: b64,
+ mime_type: "application/pdf",
+ },
];
}
}
@@ -1005,6 +1084,7 @@ export default function ChatPage() {
skillMenuOpen={skillMenuOpen}
hasMessages={hasMessages}
attachments={attachments}
+ attachmentError={attachmentError}
activeCap={activeCap}
visibleTools={visibleTools}
selectedTools={selectedTools}
@@ -1054,6 +1134,7 @@ export default function ChatPage() {
onDragOver={handleDragOver}
onDrop={handleDrop}
onPaste={handlePaste}
+ onAddFiles={handleAddFiles}
onSelectCapability={handleSelectCapability}
onCancelStreaming={cancelStreamingTurn}
onChangeQuizConfig={setQuizConfig}
diff --git a/web/app/(workspace)/co-writer/[docId]/page.tsx b/web/app/(workspace)/co-writer/[docId]/page.tsx
index 7732013d5..f7f0f7cee 100644
--- a/web/app/(workspace)/co-writer/[docId]/page.tsx
+++ b/web/app/(workspace)/co-writer/[docId]/page.tsx
@@ -31,6 +31,7 @@ import {
ListTodo,
Loader2,
Minus,
+ NotebookPen,
Quote,
Redo2,
Strikethrough,
@@ -47,6 +48,9 @@ import {
updateCoWriterDocument,
} from "@/lib/co-writer-api";
import { notifyCoWriterChanged } from "@/lib/co-writer-events";
+import SaveToNotebookModal, {
+ type NotebookSavePayload,
+} from "@/components/notebook/SaveToNotebookModal";
import { CO_WRITER_SAMPLE_TEMPLATE } from "../sampleTemplate";
const MarkdownRenderer = dynamic(
@@ -199,6 +203,8 @@ export default function CoWriterPage() {
const [error, setError] = useState("");
const [status, setStatus] = useState("");
const [isEditModalOpen, setIsEditModalOpen] = useState(false);
+ const [notebookSavePayload, setNotebookSavePayload] =
+ useState<NotebookSavePayload | null>(null);
const [selectedRange, setSelectedRange] = useState<SelectedRange | null>(
null,
);
@@ -674,6 +680,26 @@ export default function CoWriterPage() {
URL.revokeObjectURL(url);
};
+ const handleOpenSaveToNotebook = useCallback(() => {
+ if (!markdown.trim()) {
+ setError(t("Add some content before saving to a notebook."));
+ return;
+ }
+ const fallbackTitle = t("Untitled Co-Writer Document");
+ const titleForRecord = (docTitle || fallbackTitle).trim() || fallbackTitle;
+ setNotebookSavePayload({
+ recordType: "co_writer",
+ title: titleForRecord,
+ userQuery: titleForRecord,
+ output: markdown,
+ metadata: {
+ source: "co_writer",
+ doc_id: docId,
+ },
+ kbName: kbName || null,
+ });
+ }, [docId, docTitle, kbName, markdown, t]);
+
const replaceSelectedText = useCallback(
(range: SelectedRange, replacement: string) => {
pushUndo(range.snapshot);
@@ -1607,6 +1633,12 @@ export default function CoWriterPage() {
<ToolbarIconBtn title={t("Export Markdown")} onClick={handleDownload}>
<Download size={17} strokeWidth={1.7} />
</ToolbarIconBtn>
+ <ToolbarIconBtn
+ title={t("Save to Notebook")}
+ onClick={handleOpenSaveToNotebook}
+ >
+ <NotebookPen size={17} strokeWidth={1.7} />
+ </ToolbarIconBtn>
<ToolbarIconBtn
title={t("Load Example Template")}
onClick={loadExampleTemplate}
@@ -2185,6 +2217,16 @@ export default function CoWriterPage() {
</div>
</div>
)}
+
+ <SaveToNotebookModal
+ open={notebookSavePayload !== null}
+ payload={notebookSavePayload}
+ onClose={() => setNotebookSavePayload(null)}
+ onSaved={() => {
+ setStatus(t("Saved to notebook."));
+ setError("");
+ }}
+ />
</div>
);
}
diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsx
index 5bd5dd4a1..e2ec66830 100644
--- a/web/components/chat/home/ChatComposer.tsx
+++ b/web/components/chat/home/ChatComposer.tsx
@@ -17,7 +17,6 @@ import {
BookOpen,
ChevronDown,
ClipboardList,
- FilePlus2,
Layers,
MessageSquare,
Paperclip,
@@ -27,6 +26,11 @@ import {
X,
type LucideIcon,
} from "lucide-react";
+import {
+ ATTACHMENT_ACCEPT,
+ docIconFor,
+ formatBytes,
+} from "@/lib/doc-attachments";
import { useTranslation } from "react-i18next";
import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";
import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";
@@ -65,6 +69,8 @@ interface PendingAttachment {
filename: string;
base64?: string;
previewUrl?: string;
+ size?: number;
+ mimeType?: string;
}
interface KnowledgeBase {
@@ -109,6 +115,7 @@ export default memo(function ChatComposer({
skillMenuOpen,
hasMessages,
attachments,
+ attachmentError,
activeCap,
visibleTools,
selectedTools,
@@ -158,6 +165,7 @@ export default memo(function ChatComposer({
onDragOver,
onDrop,
onPaste,
+ onAddFiles,
onSelectCapability,
onCancelStreaming,
onChangeQuizConfig,
@@ -184,6 +192,7 @@ export default memo(function ChatComposer({
skillMenuOpen: boolean;
hasMessages: boolean;
attachments: PendingAttachment[];
+ attachmentError: string | null;
activeCap: CapabilityDef;
visibleTools: ToolDef[];
selectedTools: Set<string>;
@@ -237,6 +246,7 @@ export default memo(function ChatComposer({
onDragOver: (event: React.DragEvent) => void;
onDrop: (event: React.DragEvent) => void;
onPaste: (event: React.ClipboardEvent) => void;
+ onAddFiles: (files: File[]) => void;
onSelectCapability: (value: string) => void;
onCancelStreaming: () => void;
onChangeQuizConfig: (next: DeepQuestionFormConfig) => void;
@@ -252,6 +262,21 @@ export default memo(function ChatComposer({
const [hasContent, setHasContent] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const inputHandleRef = useRef<ComposerInputHandle>(null);
+ const fileInputRef = useRef<HTMLInputElement>(null);
+
+ const handlePickFiles = useCallback(() => {
+ fileInputRef.current?.click();
+ }, []);
+
+ const handleFileInputChange = useCallback(
+ (event: React.ChangeEvent<HTMLInputElement>) => {
+ const picked = Array.from(event.target.files ?? []);
+ if (picked.length) onAddFiles(picked);
+ // Reset so picking the same file twice still triggers `change`.
+ event.target.value = "";
+ },
+ [onAddFiles],
+ );
const activeCapabilityKey = activeCap.value || "chat";
@@ -361,15 +386,29 @@ export default memo(function ChatComposer({
>
{dragging && (
<div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-2xl border-2 border-dashed border-[var(--primary)]/50 bg-[var(--primary)]/[0.04]">
- <div className="flex flex-col items-center gap-1.5 text-[var(--primary)]">
+ <div className="flex flex-col items-center gap-1 text-[var(--primary)]">
<Paperclip size={22} strokeWidth={1.6} />
<span className="text-[13px] font-medium">
- {t("Drop images here")}
+ {t("Drop files here")}
+ </span>
+ <span className="text-[11px] text-[var(--primary)]/70">
+ {t("Images, PDF, DOCX, XLSX, PPTX")}
</span>
</div>
</div>
)}
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ accept={ATTACHMENT_ACCEPT}
+ onChange={handleFileInputChange}
+ className="hidden"
+ aria-hidden="true"
+ tabIndex={-1}
+ />
+
{hasReferences && (
<div className="px-4 pt-3.5 [&>div]:mb-0">
<ReferenceChips
@@ -399,37 +438,72 @@ export default memo(function ChatComposer({
{!!attachments.length && (
<div className="flex flex-wrap gap-2 px-4 pb-2">
- {attachments.map((a, i) => (
- <div key={`${a.filename}-${i}`} className="group relative">
- {a.type === "image" && a.previewUrl ? (
- <div className="relative h-16 w-16 overflow-hidden rounded-lg border border-[var(--border)]">
- <Image
- src={a.previewUrl}
- alt={a.filename || t("Attachment preview")}
- fill
- unoptimized
- className="object-cover"
- />
- <button
- onClick={() => onRemoveAttachment(i)}
- className="absolute -right-1.5 -top-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-[var(--foreground)] text-[var(--background)] opacity-0 shadow-sm transition-opacity group-hover:opacity-100"
- >
- <X size={10} />
- </button>
+ {attachments.map((a, i) => {
+ if (a.type === "image" && a.previewUrl) {
+ return (
+ <div
+ key={`${a.filename}-${i}`}
+ className="group relative"
+ >
+ <div className="relative h-16 w-16 overflow-hidden rounded-lg border border-[var(--border)]">
+ <Image
+ src={a.previewUrl}
+ alt={a.filename || t("Attachment preview")}
+ fill
+ unoptimized
+ className="object-cover"
+ />
+ <button
+ onClick={() => onRemoveAttachment(i)}
+ className="absolute -right-1.5 -top-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-[var(--foreground)] text-[var(--background)] opacity-0 shadow-sm transition-opacity group-hover:opacity-100"
+ >
+ <X size={10} />
+ </button>
+ </div>
</div>
- ) : (
- <span className="inline-flex items-center gap-1 rounded-md bg-[var(--muted)] px-2 py-0.5 text-[11px] text-[var(--muted-foreground)]">
- <FilePlus2 size={10} /> {a.filename}
- <button
- onClick={() => onRemoveAttachment(i)}
- className="ml-0.5 opacity-60 hover:opacity-100"
- >
- <X size={10} />
- </button>
- </span>
- )}
- </div>
- ))}
+ );
+ }
+ const spec = docIconFor(a.filename);
+ const Icon = spec.Icon;
+ const sizeLabel = a.size ? formatBytes(a.size) : "";
+ return (
+ <div
+ key={`${a.filename}-${i}`}
+ className="group relative"
+ title={a.filename}
+ >
+ <div className="flex h-16 w-[160px] items-center gap-2.5 rounded-lg border border-[var(--border)] bg-[var(--card)] px-2.5">
+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-[var(--muted)]/60">
+ <Icon
+ size={22}
+ strokeWidth={1.5}
+ className={spec.tint}
+ />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[12px] font-medium text-[var(--foreground)]">
+ {a.filename}
+ </div>
+ <div className="truncate text-[10px] uppercase tracking-wide text-[var(--muted-foreground)]">
+ {sizeLabel ? `${spec.label} · ${sizeLabel}` : spec.label}
+ </div>
+ </div>
+ </div>
+ <button
+ onClick={() => onRemoveAttachment(i)}
+ className="absolute -right-1.5 -top-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-[var(--foreground)] text-[var(--background)] opacity-0 shadow-sm transition-opacity group-hover:opacity-100"
+ >
+ <X size={10} />
+ </button>
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {attachmentError && (
+ <div className="px-4 pb-2 text-[11px] text-red-600">
+ {attachmentError}
</div>
)}
@@ -591,6 +665,17 @@ export default memo(function ChatComposer({
</div>
) : null}
+ <button
+ type="button"
+ onClick={handlePickFiles}
+ title={t("Attach files")}
+ aria-label={t("Attach files")}
+ className="inline-flex shrink-0 items-center gap-1 py-1 px-1.5 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
+ >
+ <Paperclip size={12} strokeWidth={1.7} />
+ {t("Attach")}
+ </button>
+
<div className="relative flex items-center gap-0.5">
<button
ref={refBtnRef}
diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsx
index 0b662cf0e..c94ba87a5 100644
--- a/web/components/chat/home/ChatMessages.tsx
+++ b/web/components/chat/home/ChatMessages.tsx
@@ -19,6 +19,7 @@ import type { SelectedHistorySession } from "@/components/chat/HistorySessionPic
import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";
import AssistantResponse from "@/components/common/AssistantResponse";
import type { MessageRequestSnapshot } from "@/context/UnifiedChatContext";
+import { docIconFor } from "@/lib/doc-attachments";
import { extractMathAnimatorResult } from "@/lib/math-animator-types";
import { extractQuizQuestions } from "@/lib/quiz-types";
import { extractVisualizeResult } from "@/lib/visualize-types";
@@ -51,6 +52,7 @@ interface ChatMessageItem {
type: string;
filename?: string;
base64?: string;
+ mime_type?: string;
}>;
requestSnapshot?: MessageRequestSnapshot;
}
@@ -320,6 +322,61 @@ const UserMessage = memo(function UserMessage({
))}
</div>
)}
+ {msg.attachments?.some((a) => a.type !== "image") && (
+ <div className="flex flex-wrap justify-end gap-2">
+ {msg.attachments
+ .filter((a) => a.type !== "image")
+ .map((a, ai) => {
+ const filename = a.filename || t("Attachment");
+ const spec = docIconFor(filename);
+ const Icon = spec.Icon;
+ const href =
+ a.base64 && a.mime_type
+ ? `data:${a.mime_type};base64,${a.base64}`
+ : null;
+ const cardClass =
+ "flex h-14 w-[220px] items-center gap-2.5 rounded-xl border border-[var(--border)] bg-[var(--card)] px-2.5 shadow-sm transition-colors hover:border-[var(--border)]/80";
+ const inner = (
+ <>
+ <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-[var(--muted)]/60">
+ <Icon
+ size={20}
+ strokeWidth={1.5}
+ className={spec.tint}
+ />
+ </div>
+ <div className="min-w-0 flex-1 text-left">
+ <div className="truncate text-[12px] font-medium text-[var(--foreground)]">
+ {filename}
+ </div>
+ <div className="truncate text-[10px] uppercase tracking-wide text-[var(--muted-foreground)]">
+ {spec.label}
+ </div>
+ </div>
+ </>
+ );
+ return href ? (
+ <a
+ key={`doc-${ai}`}
+ href={href}
+ download={filename}
+ title={filename}
+ className={cardClass}
+ >
+ {inner}
+ </a>
+ ) : (
+ <div
+ key={`doc-${ai}`}
+ title={filename}
+ className={cardClass}
+ >
+ {inner}
+ </div>
+ );
+ })}
+ </div>
+ )}
<div className="rounded-2xl bg-[var(--secondary)] px-4 py-2.5 text-[14px] leading-relaxed text-[var(--foreground)] shadow-sm">
{(() => {
const snap = msg.requestSnapshot;
diff --git a/web/components/common/AssistantResponse.tsx b/web/components/common/AssistantResponse.tsx
index 887d57115..5d39b2c31 100644
--- a/web/components/common/AssistantResponse.tsx
+++ b/web/components/common/AssistantResponse.tsx
@@ -1,7 +1,11 @@
"use client";
+import { Fragment, useMemo } from "react";
+
import MarkdownRenderer from "@/components/common/MarkdownRenderer";
+import ModelThinkingCard from "@/components/common/ModelThinkingCard";
import { hasVisibleMarkdownContent } from "@/lib/markdown-display";
+import { parseModelThinkingSegments } from "@/lib/think-segments";
interface AssistantResponseProps {
content: string;
@@ -12,15 +16,50 @@ export default function AssistantResponse({
content,
className = "text-[14px] leading-[1.75]",
}: AssistantResponseProps) {
- if (!hasVisibleMarkdownContent(content)) return null;
+ const segments = useMemo(
+ () => parseModelThinkingSegments(content),
+ [content],
+ );
+
+ // Decide whether the message has anything worth rendering. We consider both
+ // ordinary markdown segments and model-thinking blocks: a turn that only
+ // ever produced a <think> scratchpad should still render the collapsed card
+ // instead of dropping the assistant bubble entirely.
+ const hasRenderableSegment = useMemo(() => {
+ return segments.some((segment) => {
+ if (segment.kind === "think") return segment.content.trim().length > 0;
+ return hasVisibleMarkdownContent(segment.content);
+ });
+ }, [segments]);
+
+ if (!hasRenderableSegment) return null;
return (
<div className={className}>
- <MarkdownRenderer
- content={content}
- variant="prose"
- className="text-[var(--foreground)]"
- />
+ {segments.map((segment, index) => {
+ if (segment.kind === "think") {
+ return (
+ <ModelThinkingCard
+ key={`think-${index}`}
+ content={segment.content}
+ closed={segment.closed}
+ />
+ );
+ }
+
+ if (!hasVisibleMarkdownContent(segment.content)) {
+ return <Fragment key={`text-${index}`} />;
+ }
+
+ return (
+ <MarkdownRenderer
+ key={`text-${index}`}
+ content={segment.content}
+ variant="prose"
+ className="text-[var(--foreground)]"
+ />
+ );
+ })}
</div>
);
}
diff --git a/web/components/common/ModelThinkingCard.tsx b/web/components/common/ModelThinkingCard.tsx
new file mode 100644
index 000000000..684d69f6c
--- /dev/null
+++ b/web/components/common/ModelThinkingCard.tsx
@@ -0,0 +1,102 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { BrainCircuit, ChevronDown, Loader2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import MarkdownRenderer from "./MarkdownRenderer";
+
+interface ModelThinkingCardProps {
+ /** Inner text of a single <think>...</think> block (already trimmed). */
+ content: string;
+ /**
+ * False while the model is still streaming inside the open <think> tag, so
+ * the card stays expanded and shows a spinner. Once the closing tag arrives
+ * the card auto-collapses (default-folded) unless the user has pinned it
+ * open or closed manually.
+ */
+ closed: boolean;
+}
+
+/**
+ * Collapsible card that surfaces a reasoning model's raw <think> scratchpad
+ * in a way that visually echoes the system trace panels (subtle border,
+ * muted typography) without being mistaken for one.
+ *
+ * Behaviour:
+ * - Default-open while the model is still writing the scratchpad so the
+ * user can watch reasoning happen live.
+ * - Auto-collapses the moment the closing tag arrives.
+ * - Once the user toggles the card themselves, their preference wins for
+ * the rest of the message lifetime.
+ */
+export default function ModelThinkingCard({
+ content,
+ closed,
+}: ModelThinkingCardProps) {
+ const { t } = useTranslation();
+ const [userToggled, setUserToggled] = useState<boolean | null>(null);
+ const detailsRef = useRef<HTMLDetailsElement>(null);
+
+ const open = userToggled !== null ? userToggled : !closed;
+
+ // Keep the underlying <details> element in sync with our derived `open`
+ // state. We do not bind `open` as a controlled prop because React strips
+ // the boolean attribute on `false`, which races with the browser's
+ // built-in toggle handling and produces a flicker the first time `closed`
+ // flips during streaming.
+ useEffect(() => {
+ const el = detailsRef.current;
+ if (el && el.open !== open) {
+ el.open = open;
+ }
+ }, [open]);
+
+ const handleToggle = (event: React.SyntheticEvent<HTMLDetailsElement>) => {
+ const next = event.currentTarget.open;
+ if (next !== open) {
+ setUserToggled(next);
+ }
+ };
+
+ const hasBody = content.trim().length > 0;
+ const placeholder = `${t("Thinking...")}`;
+
+ return (
+ <details
+ ref={detailsRef}
+ onToggle={handleToggle}
+ className="group/think my-3 overflow-hidden rounded-xl border border-[var(--border)]/60 bg-[var(--card)]/40 transition-colors hover:border-[var(--border)]"
+ >
+ <summary className="flex cursor-pointer list-none items-center gap-2 px-3 py-2 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)] [&::-webkit-details-marker]:hidden">
+ <ChevronDown
+ size={12}
+ strokeWidth={1.8}
+ className="shrink-0 opacity-70 transition-transform group-open/think:rotate-180"
+ />
+ <BrainCircuit
+ size={12}
+ strokeWidth={1.6}
+ className="shrink-0 opacity-80"
+ />
+ <span className="tracking-wide">{t("Model thinking")}</span>
+ {!closed && (
+ <Loader2
+ size={11}
+ strokeWidth={1.8}
+ className="ml-1 animate-spin text-[var(--muted-foreground)]/70"
+ />
+ )}
+ </summary>
+ <div className="border-t border-[var(--border)]/40 bg-[var(--background)]/40 px-3 py-2">
+ {hasBody ? (
+ <MarkdownRenderer content={content} variant="trace" />
+ ) : (
+ <div className="text-[11px] italic text-[var(--muted-foreground)]/70">
+ {placeholder}
+ </div>
+ )}
+ </div>
+ </details>
+ );
+}
diff --git a/web/components/notebook/SaveToNotebookModal.tsx b/web/components/notebook/SaveToNotebookModal.tsx
index 97b32960b..9beb37ec4 100644
--- a/web/components/notebook/SaveToNotebookModal.tsx
+++ b/web/components/notebook/SaveToNotebookModal.tsx
@@ -17,7 +17,7 @@ import {
type NotebookSummary as RealNotebookSummary,
} from "@/lib/notebook-api";
-type RecordType = "solve" | "question" | "research" | "chat";
+type RecordType = "solve" | "question" | "research" | "chat" | "co_writer";
export interface NotebookSavePayload {
recordType: RecordType;
diff --git a/web/components/quiz/QuizViewer.tsx b/web/components/quiz/QuizViewer.tsx
index cd69a22fb..542f8e283 100644
--- a/web/components/quiz/QuizViewer.tsx
+++ b/web/components/quiz/QuizViewer.tsx
@@ -18,6 +18,10 @@ import MarkdownRenderer from "@/components/common/MarkdownRenderer";
import QuestionFollowupPanel, {
type FollowupThreadState,
} from "@/components/quiz/QuestionFollowupPanel";
+import {
+ isChoiceQuizQuestion,
+ resolveChoiceAnswerKey,
+} from "@/lib/quiz-question-type";
import { buildQuizFollowupConfig, type QuizQuestion } from "@/lib/quiz-types";
import {
addEntryToCategory,
@@ -73,7 +77,7 @@ function getQuestionKey(question: QuizQuestion, index: number): string {
function getUserAnswer(question: QuizQuestion, answer: AnswerState): string {
if (
- question.question_type === "choice" &&
+ isChoiceQuizQuestion(question.question_type) &&
question.options &&
Object.keys(question.options).length > 0
) {
@@ -87,11 +91,13 @@ function isAnswerCorrect(question: QuizQuestion, answer: AnswerState): boolean {
if (!userAnswer) return false;
const correct = question.correct_answer.trim();
const isChoice =
- question.question_type === "choice" &&
+ isChoiceQuizQuestion(question.question_type) &&
question.options &&
Object.keys(question.options).length > 0;
if (isChoice) {
+ const correctChoiceKey = resolveChoiceAnswerKey(correct, question.options);
return (
+ userAnswer.toUpperCase() === correctChoiceKey ||
userAnswer.toUpperCase() === correct.toUpperCase() ||
userAnswer.toUpperCase() === correct.charAt(0).toUpperCase()
);
@@ -427,7 +433,7 @@ export default function QuizViewer({
);
const isChoice =
- q?.question_type === "choice" &&
+ isChoiceQuizQuestion(q?.question_type) &&
q.options &&
Object.keys(q.options).length > 0;
const currentUserAnswer = q ? getUserAnswer(q, ans) : "";
diff --git a/web/i18n/I18nProvider.tsx b/web/i18n/I18nProvider.tsx
index 88783fc3f..13bafb022 100644
--- a/web/i18n/I18nProvider.tsx
+++ b/web/i18n/I18nProvider.tsx
@@ -5,6 +5,15 @@ import i18n from "i18next";
import { initI18n, normalizeLanguage, type AppLanguage } from "./init";
+// Initialize i18next at module load (before any React render) so that the
+// `init()` call — which fires `initialized` / `languageChanged` events that
+// trigger setState on subscribed components — never happens during another
+// component's render phase. Calling `initI18n` from the render body would
+// produce the React warning:
+// "Cannot update a component (`X`) while rendering a different component
+// (`I18nProvider`)."
+initI18n();
+
export function I18nProvider({
language,
children,
@@ -12,9 +21,6 @@ export function I18nProvider({
language: AppLanguage | string;
children: React.ReactNode;
}) {
- // Ensure initialized on client once
- initI18n(language);
-
useEffect(() => {
const nextLang = normalizeLanguage(language);
if (i18n.language !== nextLang) {
diff --git a/web/lib/doc-attachments.ts b/web/lib/doc-attachments.ts
new file mode 100644
index 000000000..c4e5c3126
--- /dev/null
+++ b/web/lib/doc-attachments.ts
@@ -0,0 +1,97 @@
+/**
+ * Helpers for drag-and-drop document attachments in the chat composer.
+ *
+ * Must stay in sync with backend `deeptutor/utils/document_extractor.py`.
+ */
+
+import type { LucideIcon } from "lucide-react";
+import {
+ FilePlus2,
+ FileSpreadsheet,
+ FileText,
+ FileType2,
+ Presentation,
+} from "lucide-react";
+
+export const SUPPORTED_DOC_EXTS = [".pdf", ".docx", ".xlsx", ".pptx"] as const;
+
+export const SUPPORTED_DOC_MIMES = new Set<string>([
+ "application/pdf",
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+]);
+
+export const MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024;
+export const MAX_TOTAL_ATTACHMENT_BYTES = 25 * 1024 * 1024;
+
+/**
+ * `accept` attribute for the chat composer's file picker. Mirrors the formats
+ * the drag-and-drop / paste paths accept (see `classifyFile`). Listing both
+ * MIME types and extensions improves cross-OS reliability — Windows in
+ * particular often reports an empty `File.type` for OOXML files.
+ */
+export const ATTACHMENT_ACCEPT = [
+ "image/*",
+ ...SUPPORTED_DOC_EXTS,
+ ...Array.from(SUPPORTED_DOC_MIMES),
+].join(",");
+
+export type FileKind = "image" | "doc";
+
+function extOf(filename: string): string {
+ const idx = filename.lastIndexOf(".");
+ return idx >= 0 ? filename.slice(idx).toLowerCase() : "";
+}
+
+/**
+ * Classify a dropped/pasted file. Returns null for unsupported types.
+ *
+ * Checks MIME first, falls back to extension because some OSes report an empty
+ * `File.type` for .pptx / .xlsx.
+ */
+export function classifyFile(file: File): FileKind | null {
+ if (file.type && file.type.startsWith("image/")) return "image";
+ if (file.type && SUPPORTED_DOC_MIMES.has(file.type)) return "doc";
+ const ext = extOf(file.name);
+ if (ext && (SUPPORTED_DOC_EXTS as readonly string[]).includes(ext)) return "doc";
+ // Some browsers report application/zip for unknown OOXML — fall back to extension above.
+ if (!file.type && ext === "") return null;
+ return null;
+}
+
+/**
+ * Human-readable byte size: `1.2 MB`, `34.0 KB`.
+ */
+export function formatBytes(n: number): string {
+ if (!Number.isFinite(n) || n < 0) return "";
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
+ return `${(n / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+export interface DocIconSpec {
+ Icon: LucideIcon;
+ tint: string; // tailwind class, e.g. "text-red-500/80"
+ label: string; // e.g. "PDF"
+}
+
+export function docIconFor(filename: string): DocIconSpec {
+ const ext = extOf(filename);
+ switch (ext) {
+ case ".pdf":
+ return { Icon: FileType2, tint: "text-red-500/80", label: "PDF" };
+ case ".docx":
+ return { Icon: FileText, tint: "text-blue-500/80", label: "DOCX" };
+ case ".xlsx":
+ return { Icon: FileSpreadsheet, tint: "text-emerald-500/80", label: "XLSX" };
+ case ".pptx":
+ return { Icon: Presentation, tint: "text-orange-500/80", label: "PPTX" };
+ default:
+ return {
+ Icon: FilePlus2,
+ tint: "text-[var(--muted-foreground)]",
+ label: ext ? ext.slice(1).toUpperCase() : "FILE",
+ };
+ }
+}
diff --git a/web/lib/knowledge-api.ts b/web/lib/knowledge-api.ts
index 5a5cbb7bc..caae598e7 100644
--- a/web/lib/knowledge-api.ts
+++ b/web/lib/knowledge-api.ts
@@ -7,6 +7,8 @@ export interface KnowledgeBaseSummary {
name: string;
is_default?: boolean;
status?: string;
+ path?: string;
+ metadata?: Record<string, unknown>;
progress?: Record<string, unknown>;
statistics?: Record<string, unknown>;
}
@@ -17,6 +19,13 @@ export interface RagProviderSummary {
description: string;
}
+export interface KnowledgeUploadPolicy {
+ extensions: string[];
+ accept: string;
+ max_file_size_bytes: number;
+ max_pdf_size_bytes: number;
+}
+
export async function listKnowledgeBases(options?: { force?: boolean }) {
return withClientCache<KnowledgeBaseSummary[]>(
`${KNOWLEDGE_CACHE_PREFIX}list`,
@@ -53,6 +62,36 @@ export async function listRagProviders(options?: { force?: boolean }) {
);
}
+export async function getKnowledgeUploadPolicy(options?: { force?: boolean }) {
+ return withClientCache<KnowledgeUploadPolicy>(
+ `${KNOWLEDGE_CACHE_PREFIX}upload-policy`,
+ async () => {
+ const response = await fetch(
+ apiUrl("/api/v1/knowledge/supported-file-types"),
+ {
+ cache: "no-store",
+ },
+ );
+ const data = await response.json();
+ return {
+ extensions: Array.isArray(data?.extensions) ? data.extensions : [],
+ accept: typeof data?.accept === "string" ? data.accept : "",
+ max_file_size_bytes:
+ typeof data?.max_file_size_bytes === "number"
+ ? data.max_file_size_bytes
+ : 100 * 1024 * 1024,
+ max_pdf_size_bytes:
+ typeof data?.max_pdf_size_bytes === "number"
+ ? data.max_pdf_size_bytes
+ : 50 * 1024 * 1024,
+ };
+ },
+ {
+ force: options?.force,
+ },
+ );
+}
+
export function invalidateKnowledgeCaches() {
invalidateClientCache(KNOWLEDGE_CACHE_PREFIX);
}
diff --git a/web/lib/notebook-api.ts b/web/lib/notebook-api.ts
index 712fcf635..a8b2f4150 100644
--- a/web/lib/notebook-api.ts
+++ b/web/lib/notebook-api.ts
@@ -7,7 +7,12 @@ import { apiUrl } from "@/lib/api";
// (NotebookRecordPicker) live in this system. They are distinct from the
// "Question Notebook" categories below which only track quiz entries.
-export type NotebookRecordType = "solve" | "question" | "research" | "chat";
+export type NotebookRecordType =
+ | "solve"
+ | "question"
+ | "research"
+ | "chat"
+ | "co_writer";
export interface NotebookSummary {
id: string;
diff --git a/web/lib/notebook-selection-types.ts b/web/lib/notebook-selection-types.ts
index 012cde27f..73f753008 100644
--- a/web/lib/notebook-selection-types.ts
+++ b/web/lib/notebook-selection-types.ts
@@ -32,6 +32,8 @@ export function getTypeColor(type: string): string {
return "bg-emerald-100 text-emerald-700 border-emerald-200";
case "chat":
return "bg-cyan-100 text-cyan-700 border-cyan-200";
+ case "co_writer":
+ return "bg-amber-100 text-amber-700 border-amber-200";
default:
return "bg-slate-100 text-slate-700 border-slate-200";
}
diff --git a/web/lib/quiz-question-type.ts b/web/lib/quiz-question-type.ts
new file mode 100644
index 000000000..d2b04f4c1
--- /dev/null
+++ b/web/lib/quiz-question-type.ts
@@ -0,0 +1,57 @@
+export type NormalizedQuizQuestionType = "choice" | "written" | "coding";
+
+const QUESTION_TYPE_ALIASES: Record<string, NormalizedQuizQuestionType> = {
+ choice: "choice",
+ multiple_choice: "choice",
+ "multiple-choice": "choice",
+ mcq: "choice",
+ written: "written",
+ open_ended: "written",
+ "open-ended": "written",
+ open_response: "written",
+ "open-response": "written",
+ short_answer: "written",
+ "short-answer": "written",
+ essay: "written",
+ fill_in_blank: "written",
+ "fill-in-the-blank": "written",
+ coding: "coding",
+ code: "coding",
+ programming: "coding",
+};
+
+export function normalizeQuizQuestionType(
+ value: unknown,
+): NormalizedQuizQuestionType {
+ const normalized = String(value || "")
+ .trim()
+ .toLowerCase()
+ .replace(/\s+/g, "_");
+ return QUESTION_TYPE_ALIASES[normalized] || "written";
+}
+
+export function isChoiceQuizQuestion(value: unknown): boolean {
+ return normalizeQuizQuestionType(value) === "choice";
+}
+
+export function resolveChoiceAnswerKey(
+ correctAnswer: unknown,
+ options: Record<string, string> | null | undefined,
+): string {
+ const correct = String(correctAnswer || "").trim();
+ if (!correct || !options) return "";
+
+ const directKey = correct.toUpperCase();
+ if (directKey in options) {
+ return directKey;
+ }
+
+ const normalizedAnswer = correct.toLowerCase();
+ for (const [key, label] of Object.entries(options)) {
+ if (normalizedAnswer === String(label || "").trim().toLowerCase()) {
+ return key.toUpperCase();
+ }
+ }
+
+ return directKey;
+}
diff --git a/web/lib/quiz-types.ts b/web/lib/quiz-types.ts
index 180555a22..11a2c8b05 100644
--- a/web/lib/quiz-types.ts
+++ b/web/lib/quiz-types.ts
@@ -2,6 +2,8 @@
* Shared types for Quiz Generation (deep_question capability).
*/
+import { normalizeQuizQuestionType } from "./quiz-question-type";
+
export type DeepQuestionMode = "custom" | "mimic";
export interface DeepQuestionFormConfig {
@@ -72,8 +74,7 @@ export function extractQuizQuestions(
const question: QuizQuestion = {
question_id: String(qa.question_id ?? ""),
question: String(qa.question ?? ""),
- question_type:
- (qa.question_type as QuizQuestion["question_type"]) ?? "written",
+ question_type: normalizeQuizQuestionType(qa.question_type),
options: qa.options as Record<string, string> | undefined,
correct_answer: String(qa.correct_answer ?? ""),
explanation: String(qa.explanation ?? ""),
diff --git a/web/lib/think-segments.ts b/web/lib/think-segments.ts
new file mode 100644
index 000000000..201526549
--- /dev/null
+++ b/web/lib/think-segments.ts
@@ -0,0 +1,133 @@
+/**
+ * Splits a raw assistant response into ordinary markdown segments and
+ * "model thinking" segments produced by reasoning models that emit their
+ * scratchpad as <think> ... </think> (or <thinking> ... </thinking>) blocks
+ * directly inside the response stream.
+ *
+ * This only deals with thinking that lives **outside** the system trace
+ * (i.e. content the orchestrator forwards as the assistant's user-facing
+ * answer). Trace panels render their own <think>-shaped chunks separately
+ * and are not touched here.
+ *
+ * The parser is robust to two on-the-wire shapes:
+ *
+ * 1. Raw form, as the model streams it:
+ * "<think>foo</think>bar"
+ *
+ * 2. Post-normalized form produced by `normalizeMarkdownForDisplay`,
+ * which wraps unknown lowercase tags in inline-code backticks so
+ * React stops complaining about unknown elements:
+ * "`<think>`foo`</think>`bar"
+ *
+ * It also tolerates open-without-close (still streaming the scratchpad)
+ * and skips any tags that live inside fenced code blocks.
+ */
+
+export interface TextSegment {
+ kind: "text";
+ content: string;
+}
+
+export interface ThinkSegment {
+ kind: "think";
+ content: string;
+ /** False while the model is still streaming inside the open tag. */
+ closed: boolean;
+}
+
+export type ContentSegment = TextSegment | ThinkSegment;
+
+const FENCED_CODE_REGEX = /```[\s\S]*?```/g;
+const FENCED_PLACEHOLDER_REGEX = /\u0000FENCED_(\d+)\u0000/g;
+
+// `?<\s*think(?:ing)?\b[^>]*>`?
+// leading/trailing backtick is optional so we match both the raw streaming
+// form and the post-`escapeUnknownHtmlTags` form. The `[^>]*` swallows any
+// stray attributes some providers emit (e.g. `<thinking duration="3s">`).
+const OPEN_TAG_REGEX = /`?<\s*(think(?:ing)?)\b[^>]*>`?/i;
+
+function closeTagRegex(tag: string): RegExp {
+ return new RegExp(`\`?<\\s*/\\s*${tag}\\s*>\`?`, "i");
+}
+
+function maskFencedCode(input: string): { masked: string; blocks: string[] } {
+ const blocks: string[] = [];
+ const masked = input.replace(FENCED_CODE_REGEX, (match) => {
+ blocks.push(match);
+ return `\u0000FENCED_${blocks.length - 1}\u0000`;
+ });
+ return { masked, blocks };
+}
+
+function restoreFencedCode(input: string, blocks: string[]): string {
+ if (blocks.length === 0) return input;
+ return input.replace(FENCED_PLACEHOLDER_REGEX, (_, idx: string) => {
+ const i = Number(idx);
+ return Number.isFinite(i) ? (blocks[i] ?? "") : "";
+ });
+}
+
+/**
+ * Strip the leading newlines that typically follow `<think>` and the
+ * trailing newlines that precede `</think>`, so the collapsible card
+ * does not render a top/bottom gap.
+ */
+function trimThinkContent(content: string): string {
+ return content.replace(/^\s+/, "").replace(/\s+$/, "");
+}
+
+export function parseModelThinkingSegments(input: string): ContentSegment[] {
+ if (!input) return [];
+ if (!/<\s*think(?:ing)?\b/i.test(input)) {
+ return [{ kind: "text", content: input }];
+ }
+
+ const { masked, blocks } = maskFencedCode(input);
+ const segments: ContentSegment[] = [];
+ let cursor = 0;
+
+ while (cursor < masked.length) {
+ const tail = masked.slice(cursor);
+ const open = OPEN_TAG_REGEX.exec(tail);
+ if (!open) {
+ const text = restoreFencedCode(tail, blocks);
+ if (text.length > 0) segments.push({ kind: "text", content: text });
+ break;
+ }
+
+ if (open.index > 0) {
+ const prefix = restoreFencedCode(tail.slice(0, open.index), blocks);
+ if (prefix.length > 0) segments.push({ kind: "text", content: prefix });
+ }
+
+ const tag = open[1].toLowerCase();
+ const afterOpen = tail.slice(open.index + open[0].length);
+ const close = closeTagRegex(tag).exec(afterOpen);
+
+ if (!close) {
+ const body = restoreFencedCode(afterOpen, blocks);
+ segments.push({
+ kind: "think",
+ content: trimThinkContent(body),
+ closed: false,
+ });
+ break;
+ }
+
+ const body = restoreFencedCode(afterOpen.slice(0, close.index), blocks);
+ segments.push({
+ kind: "think",
+ content: trimThinkContent(body),
+ closed: true,
+ });
+ cursor += open.index + open[0].length + close.index + close[0].length;
+ }
+
+ return segments;
+}
+
+/** True when `input` contains at least one model-thinking block. */
+export function hasModelThinking(input: string): boolean {
+ if (!input) return false;
+ return /<\s*think(?:ing)?\b/i.test(input);
+}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 15a58d764..a6cd13c21 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -49,7 +49,15 @@
"Tools": "Tools",
"Send": "Send",
"Drop images here": "Drop images here",
+ "Drop files here": "Drop files here",
+ "Images, PDF, DOCX, XLSX, PPTX": "Images, PDF, DOCX, XLSX, PPTX",
+ "Unsupported file type: {{name}}": "Unsupported file type: {{name}}",
+ "File too large: {{name}}": "File too large: {{name}}",
+ "Too many files, skipped some": "Too many files, skipped some",
"Attachment preview": "Attachment preview",
+ "Attachment": "Attachment",
+ "Attach": "Attach",
+ "Attach files": "Attach files",
"Describe the math animation or storyboard you want...": "Describe the math animation or storyboard you want...",
"Smart Solver": "Smart Solver",
"Vision Solver": "Vision Solver",
@@ -283,6 +291,9 @@
"New Chat": "New Chat",
"New chat": "New chat",
"Save to Notebook": "Save to Notebook",
+ "Saved to notebook.": "Saved to notebook.",
+ "Add some content before saving to a notebook.": "Add some content before saving to a notebook.",
+ "Untitled Co-Writer Document": "Untitled Co-Writer Document",
"Click to edit": "Click to edit",
"Expand sidebar": "Expand sidebar",
"Collapse sidebar": "Collapse sidebar",
@@ -660,6 +671,13 @@
"Models": "Models",
"Label": "Label",
"Model ID": "Model ID",
+ "Context Window": "Context Window",
+ "Detected at": "Detected at",
+ "Unset": "Unset",
+ "Detected from the provider during the latest LLM test and saved into model_catalog.json.": "Detected from the provider during the latest LLM test and saved into model_catalog.json.",
+ "The provider did not expose a context window, so the runtime fallback was saved during the latest LLM test.": "The provider did not expose a context window, so the runtime fallback was saved during the latest LLM test.",
+ "Manual override from Settings. Save Draft to persist your edit.": "Manual override from Settings. Save Draft to persist your edit.",
+ "Run the LLM test to auto-fill this field, or enter a value manually.": "Run the LLM test to auto-fill this field, or enter a value manually.",
"Dimension": "Dimension",
"Send dimensions": "Send dimensions",
"Some embedding models (e.g. Qwen text-embedding-v4) reject the `dimensions` request param. Turn this off if your provider returns HTTP 400.": "Some embedding models (e.g. Qwen text-embedding-v4) reject the `dimensions` request param. Turn this off if your provider returns HTTP 400.",
@@ -696,6 +714,7 @@
"Trace": "Trace",
"Thought": "Thought",
"Thinking...": "Thinking...",
+ "Model thinking": "Model thinking",
"Tool": "Tool",
"Response": "Response",
"Running tools and preparing the final edit...": "Running tools and preparing the final edit...",
@@ -1021,5 +1040,62 @@
"Latest release": "Latest release",
"Up to date": "Up to date",
"Update available": "Update available",
- "Development build": "Development build"
+ "Development build": "Development build",
+ "Run Tour": "Run Tour",
+ "Tour": "Tour",
+ "settingsTour.llm.title": "1 / 5 — LLM",
+ "settingsTour.llm.desc": "Pick the active LLM profile, endpoint, and model used for chat and reasoning.",
+ "settingsTour.embedding.title": "2 / 5 — Embedding",
+ "settingsTour.embedding.desc": "Configure the embedding provider and model used for knowledge retrieval.",
+ "settingsTour.search.title": "3 / 5 — Search",
+ "settingsTour.search.desc": "Set an optional web-search provider and any related network settings.",
+ "settingsTour.saveTest.title": "4 / 5 — Save & Test",
+ "settingsTour.saveTest.desc": "After editing, click Save Draft to persist your changes to the catalog. Then open Diagnostics below and Run Test to verify the connection works.",
+ "settingsTour.apply.title": "5 / 5 — Apply",
+ "settingsTour.apply.desc": "Once the test passes, click Apply to write the active configuration into .env so DeepTutor starts using it immediately.",
+ "settings.configNote": "Save Draft persists all profiles to model_catalog.json, which DeepTutor reads at runtime. Apply syncs the active profile into .env for CLI and non-UI compatibility. You can keep multiple profiles in the catalog and switch between them anytime.",
+ "Unsupported file type": "Unsupported file type",
+ "No extension": "No extension",
+ "{{count}} invalid files": "{{count}} invalid files",
+ "{{count}} files ready": "{{count}} files ready",
+ "Only supported files can continue.": "Only supported files can continue.",
+ "Ready to upload": "Ready to upload",
+ "Clear selection": "Clear selection",
+ "Supported": "Supported",
+ "Needs attention": "Needs attention",
+ "Supported formats": "Supported formats",
+ "Maximum file size: {{size}}": "Maximum file size: {{size}}",
+ "PDF limit: {{size}}": "PDF limit: {{size}}",
+ "types": "types",
+ "Click to browse supported documents": "Click to browse supported documents",
+ "This knowledge base needs reindex before it can accept new files.": "This knowledge base needs reindex before it can accept new files.",
+ "The last processing run failed.": "The last processing run failed.",
+ "Needs reindex": "Needs reindex",
+ "Processing live": "Processing live",
+ "Latest activity": "Latest activity",
+ "Live pipeline": "Live pipeline",
+ "Action required": "Action required",
+ "Step {{current}} of {{total}}": "Step {{current}} of {{total}}",
+ "Waiting for live progress...": "Waiting for live progress...",
+ "Once a knowledge base is ready, it stays clean here as a reusable resource instead of showing stale completion banners.": "Once a knowledge base is ready, it stays clean here as a reusable resource instead of showing stale completion banners.",
+ "This file exceeds the maximum size of {{size}}.": "This file exceeds the maximum size of {{size}}.",
+ "PDF files must be smaller than {{size}}.": "PDF files must be smaller than {{size}}.",
+ "Some dragged files are not supported": "Some dragged files are not supported",
+ "Drop files to add them": "Drop files to add them",
+ "Release to attach the files": "Release to attach the files",
+ "{{count}} files detected": "{{count}} files detected",
+ "Updated": "Updated",
+ "Created": "Created",
+ "Index": "Index",
+ "Vector index ready": "Vector index ready",
+ "Index not ready": "Index not ready",
+ "No storage path": "No storage path",
+ "Assets": "Assets",
+ "{{count}} derived assets": "{{count}} derived assets",
+ "No derived assets yet": "No derived assets yet",
+ "images": "images",
+ "lists": "lists",
+ "Embedding config changed": "Embedding config changed",
+ "Embedding config aligned": "Embedding config aligned",
+ "Default embedding": "Default embedding"
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 7f22f1e6c..51f7ee480 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -49,7 +49,15 @@
"Tools": "工具",
"Send": "发送",
"Drop images here": "将图片拖放到此处",
+ "Drop files here": "拖拽文件到此处",
+ "Images, PDF, DOCX, XLSX, PPTX": "图片、PDF、DOCX、XLSX、PPTX",
+ "Unsupported file type: {{name}}": "不支持的文件类型:{{name}}",
+ "File too large: {{name}}": "文件过大:{{name}}",
+ "Too many files, skipped some": "附件总量超出限制,已跳过部分文件",
"Attachment preview": "附件预览",
+ "Attachment": "附件",
+ "Attach": "附件",
+ "Attach files": "上传附件",
"Describe the math animation or storyboard you want...": "描述你想要的数学动画或分镜…",
"Smart Solver": "智能解题",
"Vision Solver": "视觉解题",
@@ -127,7 +135,7 @@
"Create": "创建",
"Overview": "概览",
"LLM": "LLM",
- "Embedding": "Embedding",
+ "Embedding": "嵌入模型",
"TTS": "TTS",
"Search": "搜索",
"Snow": "雪白",
@@ -283,6 +291,9 @@
"New Chat": "新对话",
"New chat": "新对话",
"Save to Notebook": "保存到笔记本",
+ "Saved to notebook.": "已保存到笔记本。",
+ "Add some content before saving to a notebook.": "请先写一些内容再保存到笔记本。",
+ "Untitled Co-Writer Document": "未命名的 Co-Writer 文档",
"Click to edit": "点击编辑",
"Expand sidebar": "展开侧边栏",
"Collapse sidebar": "收起侧边栏",
@@ -660,6 +671,13 @@
"Models": "模型列表",
"Label": "标签",
"Model ID": "模型 ID",
+ "Context Window": "上下文窗口",
+ "Detected at": "识别时间",
+ "Unset": "未设置",
+ "Detected from the provider during the latest LLM test and saved into model_catalog.json.": "已在最近一次 LLM 测试中从提供商识别出上下文窗口,并写入 model_catalog.json。",
+ "The provider did not expose a context window, so the runtime fallback was saved during the latest LLM test.": "提供商没有暴露上下文窗口信息,因此在最近一次 LLM 测试中写入了运行时默认窗口。",
+ "Manual override from Settings. Save Draft to persist your edit.": "这是你在设置页中的手动覆盖值。点击“保存草稿”后会持久化。",
+ "Run the LLM test to auto-fill this field, or enter a value manually.": "运行一次 LLM 测试来自动填充这个字段,或者手动输入。",
"Dimension": "维度",
"Send dimensions": "发送 dimensions 参数",
"Some embedding models (e.g. Qwen text-embedding-v4) reject the `dimensions` request param. Turn this off if your provider returns HTTP 400.": "部分 embedding 模型(如 Qwen text-embedding-v4)不支持 `dimensions` 请求参数。若你的服务返回 HTTP 400,请关闭此开关。",
@@ -716,6 +734,7 @@
"Thinking ({{count}} steps)": "思考中({{count}} 步)",
"Working...": "处理中…",
"Thinking...": "思考中…",
+ "Model thinking": "模型思考",
"words": "词",
"chars": "字符",
"Export Markdown": "导出 Markdown",
@@ -1021,5 +1040,62 @@
"Latest release": "最新版本",
"Up to date": "已是最新",
"Update available": "有新版本",
- "Development build": "开发构建"
+ "Development build": "开发构建",
+ "Run Tour": "运行引导",
+ "Tour": "引导",
+ "settingsTour.llm.title": "1 / 5 — LLM",
+ "settingsTour.llm.desc": "在这里选择当前生效的 LLM 配置、接口地址和模型。",
+ "settingsTour.embedding.title": "2 / 5 — Embedding",
+ "settingsTour.embedding.desc": "在这里配置用于知识检索的 Embedding 提供商和模型。",
+ "settingsTour.search.title": "3 / 5 — Search",
+ "settingsTour.search.desc": "在这里设置可选的联网搜索提供商以及相关网络参数。",
+ "settingsTour.saveTest.title": "4 / 5 — 保存与测试",
+ "settingsTour.saveTest.desc": "编辑完成后,点击 Save Draft 将更改保存到配置目录。然后展开下方的 Diagnostics 面板,点击 Run Test 验证连接是否正常。",
+ "settingsTour.apply.title": "5 / 5 — 应用",
+ "settingsTour.apply.desc": "测试通过后,点击 Apply 将当前选中的配置写入 .env,DeepTutor 会立即使用新的配置。",
+ "settings.configNote": "Save Draft 会将所有配置保存到 model_catalog.json,DeepTutor 运行时优先从该文件读取配置。Apply 会将当前选中的配置同步写入 .env,以兼容 CLI 等非 UI 场景。你可以保存多套配置,随时切换。",
+ "Unsupported file type": "不支持的文件类型",
+ "No extension": "无扩展名",
+ "{{count}} invalid files": "{{count}} 个文件不受支持",
+ "{{count}} files ready": "{{count}} 个文件已就绪",
+ "Only supported files can continue.": "只有受支持的文件才能继续。",
+ "Ready to upload": "可开始上传",
+ "Clear selection": "清空选择",
+ "Supported": "已支持",
+ "Needs attention": "需要处理",
+ "Supported formats": "支持的格式",
+ "Maximum file size: {{size}}": "单个文件最大:{{size}}",
+ "PDF limit: {{size}}": "PDF 限制:{{size}}",
+ "types": "种类型",
+ "Click to browse supported documents": "点击选择受支持的文档",
+ "This knowledge base needs reindex before it can accept new files.": "这个知识库需要先重新索引,之后才能接收新文件。",
+ "The last processing run failed.": "上一次处理失败了。",
+ "Needs reindex": "需要重新索引",
+ "Processing live": "实时处理中",
+ "Latest activity": "最新动态",
+ "Live pipeline": "实时流水线",
+ "Action required": "需要处理",
+ "Step {{current}} of {{total}}": "第 {{current}} / {{total}} 步",
+ "Waiting for live progress...": "正在等待实时进度…",
+ "Once a knowledge base is ready, it stays clean here as a reusable resource instead of showing stale completion banners.": "知识库初始化完成后,这里会把它当作可复用资源展示,而不是一直保留陈旧的完成提示。",
+ "This file exceeds the maximum size of {{size}}.": "该文件超过了 {{size}} 的大小限制。",
+ "PDF files must be smaller than {{size}}.": "PDF 文件必须小于 {{size}}。",
+ "Some dragged files are not supported": "拖拽的文件里有不受支持的类型",
+ "Drop files to add them": "松开即可添加这些文件",
+ "Release to attach the files": "松开以上传这些文件",
+ "{{count}} files detected": "检测到 {{count}} 个文件",
+ "Updated": "最近更新",
+ "Created": "创建时间",
+ "Index": "索引状态",
+ "Vector index ready": "向量索引已就绪",
+ "Index not ready": "索引尚未就绪",
+ "No storage path": "暂无存储路径",
+ "Assets": "派生资源",
+ "{{count}} derived assets": "{{count}} 个派生资源",
+ "No derived assets yet": "还没有派生资源",
+ "images": "图片",
+ "lists": "列表",
+ "Embedding config changed": "嵌入配置已变化",
+ "Embedding config aligned": "嵌入配置已对齐",
+ "Default embedding": "默认嵌入配置"
}
diff --git a/web/next-env.d.ts b/web/next-env.d.ts
index c4b7818fb..9edff1c7c 100644
--- a/web/next-env.d.ts
+++ b/web/next-env.d.ts
@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
-import "./.next/dev/types/routes.d.ts";
+import "./.next/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
diff --git a/web/package.json b/web/package.json
index d1f926766..0b9c66b8d 100644
--- a/web/package.json
+++ b/web/package.json
@@ -8,6 +8,7 @@
"build": "next build",
"start": "next start",
"lint": "eslint .",
+ "test:node": "node ./scripts/run-node-tests.mjs",
"perf:check": "node ./scripts/route_budgets.mjs",
"build:perf": "npm run build && npm run perf:check",
"i18n:parity": "node ./scripts/i18n_parity.mjs",
diff --git a/web/scripts/run-node-tests.mjs b/web/scripts/run-node-tests.mjs
new file mode 100644
index 000000000..d553fd36f
--- /dev/null
+++ b/web/scripts/run-node-tests.mjs
@@ -0,0 +1,54 @@
+import { readdirSync, rmSync, statSync } from "node:fs";
+import { spawnSync } from "node:child_process";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+const webRoot = path.resolve(__dirname, "..");
+const distRoot = path.join(webRoot, "dist", "node-tests");
+const testRoot = path.join(distRoot, "tests");
+
+function run(cmd, args) {
+ const result = spawnSync(cmd, args, {
+ cwd: webRoot,
+ stdio: "inherit",
+ env: process.env,
+ });
+ if (result.status !== 0) {
+ process.exit(result.status ?? 1);
+ }
+}
+
+function collectTests(dir) {
+ const entries = readdirSync(dir)
+ .map((name) => path.join(dir, name))
+ .sort((a, b) => a.localeCompare(b));
+ const files = [];
+ for (const entry of entries) {
+ const stats = statSync(entry);
+ if (stats.isDirectory()) {
+ files.push(...collectTests(entry));
+ continue;
+ }
+ if (entry.endsWith(".test.js")) {
+ files.push(entry);
+ }
+ }
+ return files;
+}
+
+rmSync(distRoot, { recursive: true, force: true });
+
+run(path.join(webRoot, "node_modules", ".bin", "tsc"), [
+ "-p",
+ "tsconfig.node-tests.json",
+]);
+
+const testFiles = collectTests(testRoot);
+if (testFiles.length === 0) {
+ console.error("No compiled node tests found.");
+ process.exit(1);
+}
+
+run(process.execPath, ["--test", ...testFiles]);
diff --git a/web/tests/api-resolve-base.test.ts b/web/tests/api-resolve-base.test.ts
index 6a16f639c..d427456df 100644
--- a/web/tests/api-resolve-base.test.ts
+++ b/web/tests/api-resolve-base.test.ts
@@ -5,7 +5,12 @@ import assert from "node:assert/strict";
// read at module-load time and the module throws if it's missing.
process.env.NEXT_PUBLIC_API_BASE = "http://localhost:8001/api";
-const { resolveBase, apiUrl, wsUrl } = await import("../lib/api.ts");
+let apiModulePromise: Promise<typeof import("../lib/api")> | null = null;
+
+async function loadApiModule(): Promise<typeof import("../lib/api")> {
+ apiModulePromise ??= import("../lib/api");
+ return apiModulePromise;
+}
function setWindow(hostname: string | undefined): void {
if (hostname === undefined) {
@@ -17,27 +22,32 @@ function setWindow(hostname: string | undefined): void {
} as unknown;
}
-test("resolveBase returns the build-time base in SSR (no window)", () => {
+test("resolveBase returns the build-time base in SSR (no window)", async () => {
+ const { resolveBase } = await loadApiModule();
setWindow(undefined);
assert.equal(resolveBase(), "http://localhost:8001/api");
});
-test("resolveBase returns base unchanged when client is also on localhost", () => {
+test("resolveBase returns base unchanged when client is also on localhost", async () => {
+ const { resolveBase } = await loadApiModule();
setWindow("localhost");
assert.equal(resolveBase(), "http://localhost:8001/api");
});
-test("resolveBase rewrites loopback hostname to remote LAN host and preserves path", () => {
+test("resolveBase rewrites loopback hostname to remote LAN host and preserves path", async () => {
+ const { resolveBase } = await loadApiModule();
setWindow("192.168.1.10");
assert.equal(resolveBase(), "http://192.168.1.10:8001/api");
});
-test("resolveBase treats IPv6 loopback as loopback (no swap when client is also ::1)", () => {
+test("resolveBase treats IPv6 loopback as loopback (no swap when client is also ::1)", async () => {
+ const { resolveBase } = await loadApiModule();
setWindow("::1");
assert.equal(resolveBase(), "http://localhost:8001/api");
});
-test("apiUrl composes correctly after rewrite, without losing the base path", () => {
+test("apiUrl composes correctly after rewrite, without losing the base path", async () => {
+ const { apiUrl } = await loadApiModule();
setWindow("10.0.0.5");
assert.equal(
apiUrl("/api/v1/knowledge/list"),
@@ -45,12 +55,14 @@ test("apiUrl composes correctly after rewrite, without losing the base path", ()
);
});
-test("wsUrl converts http to ws and respects rewritten host", () => {
+test("wsUrl converts http to ws and respects rewritten host", async () => {
+ const { wsUrl } = await loadApiModule();
setWindow("10.0.0.5");
assert.equal(wsUrl("/api/v1/ws"), "ws://10.0.0.5:8001/api/api/v1/ws");
});
-test("wsUrl keeps original loopback when client is also loopback", () => {
+test("wsUrl keeps original loopback when client is also loopback", async () => {
+ const { wsUrl } = await loadApiModule();
setWindow("127.0.0.1");
assert.equal(wsUrl("/api/v1/ws"), "ws://localhost:8001/api/api/v1/ws");
});
diff --git a/web/tests/doc-attachments.test.ts b/web/tests/doc-attachments.test.ts
new file mode 100644
index 000000000..570b6db0b
--- /dev/null
+++ b/web/tests/doc-attachments.test.ts
@@ -0,0 +1,75 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ classifyFile,
+ docIconFor,
+ formatBytes,
+ MAX_ATTACHMENT_BYTES,
+} from "../lib/doc-attachments";
+
+function makeFile(name: string, type = "", size = 0): File {
+ // File constructor available in modern Node runtimes.
+ return new File([new Uint8Array(size)], name, { type });
+}
+
+// classifyFile ---------------------------------------------------------------
+
+test("classifyFile: image via MIME", () => {
+ assert.equal(classifyFile(makeFile("x.png", "image/png")), "image");
+ assert.equal(classifyFile(makeFile("x.jpg", "image/jpeg")), "image");
+});
+
+test("classifyFile: doc via MIME", () => {
+ assert.equal(
+ classifyFile(makeFile("a.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")),
+ "doc",
+ );
+ assert.equal(classifyFile(makeFile("b.pdf", "application/pdf")), "doc");
+});
+
+test("classifyFile: doc via extension fallback when MIME empty", () => {
+ assert.equal(classifyFile(makeFile("report.pptx")), "doc");
+ assert.equal(classifyFile(makeFile("REPORT.XLSX")), "doc");
+});
+
+test("classifyFile: rejects unsupported", () => {
+ assert.equal(classifyFile(makeFile("a.zip", "application/zip")), null);
+ assert.equal(classifyFile(makeFile("a.txt", "text/plain")), null);
+ assert.equal(classifyFile(makeFile("noext")), null);
+});
+
+// formatBytes ----------------------------------------------------------------
+
+test("formatBytes: B / KB / MB", () => {
+ assert.equal(formatBytes(0), "0 B");
+ assert.equal(formatBytes(512), "512 B");
+ assert.equal(formatBytes(1024), "1.0 KB");
+ assert.equal(formatBytes(1024 * 1024), "1.0 MB");
+ assert.equal(formatBytes(5 * 1024 * 1024), "5.0 MB");
+});
+
+test("formatBytes: negative / NaN returns empty string", () => {
+ assert.equal(formatBytes(-1), "");
+ assert.equal(formatBytes(Number.NaN), "");
+});
+
+// docIconFor -----------------------------------------------------------------
+
+test("docIconFor: labels by extension", () => {
+ assert.equal(docIconFor("report.pdf").label, "PDF");
+ assert.equal(docIconFor("report.docx").label, "DOCX");
+ assert.equal(docIconFor("report.xlsx").label, "XLSX");
+ assert.equal(docIconFor("report.pptx").label, "PPTX");
+});
+
+test("docIconFor: fallback for unknown extension", () => {
+ assert.equal(docIconFor("mystery.bin").label, "BIN");
+ assert.equal(docIconFor("noext").label, "FILE");
+});
+
+// Limits sanity check -------------------------------------------------------
+
+test("MAX_ATTACHMENT_BYTES is 10 MB", () => {
+ assert.equal(MAX_ATTACHMENT_BYTES, 10 * 1024 * 1024);
+});
diff --git a/web/tests/quiz-question-type.test.ts b/web/tests/quiz-question-type.test.ts
new file mode 100644
index 000000000..2c3fd0a35
--- /dev/null
+++ b/web/tests/quiz-question-type.test.ts
@@ -0,0 +1,58 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ isChoiceQuizQuestion,
+ normalizeQuizQuestionType,
+ resolveChoiceAnswerKey,
+} from "../lib/quiz-question-type";
+import { extractQuizQuestions } from "../lib/quiz-types";
+
+test("normalizeQuizQuestionType maps legacy choice aliases to choice", () => {
+ assert.equal(normalizeQuizQuestionType("choice"), "choice");
+ assert.equal(normalizeQuizQuestionType("multiple_choice"), "choice");
+ assert.equal(normalizeQuizQuestionType("multiple choice"), "choice");
+ assert.equal(normalizeQuizQuestionType("mcq"), "choice");
+ assert.equal(isChoiceQuizQuestion("multiple_choice"), true);
+});
+
+test("normalizeQuizQuestionType keeps written and coding families stable", () => {
+ assert.equal(normalizeQuizQuestionType("written"), "written");
+ assert.equal(normalizeQuizQuestionType("fill_in_blank"), "written");
+ assert.equal(normalizeQuizQuestionType("coding"), "coding");
+ assert.equal(normalizeQuizQuestionType("programming"), "coding");
+});
+
+test("resolveChoiceAnswerKey accepts either the option key or label text", () => {
+ const options = {
+ A: "Alpha",
+ B: "Beta",
+ C: "Gamma",
+ D: "Delta",
+ };
+
+ assert.equal(resolveChoiceAnswerKey("C", options), "C");
+ assert.equal(resolveChoiceAnswerKey("gamma", options), "C");
+});
+
+test("extractQuizQuestions normalizes legacy question types from payloads", () => {
+ const questions = extractQuizQuestions({
+ summary: {
+ results: [
+ {
+ qa_pair: {
+ question_id: "q_1",
+ question: "Pick the best answer.",
+ question_type: "multiple_choice",
+ options: { A: "One", B: "Two", C: "Three", D: "Four" },
+ correct_answer: "B",
+ explanation: "Because two is correct.",
+ },
+ },
+ ],
+ },
+ });
+
+ assert.ok(questions);
+ assert.equal(questions?.[0]?.question_type, "choice");
+});
diff --git a/web/tests/route-params.test.ts b/web/tests/route-params.test.ts
index 85ccf8348..aebb5d4a1 100644
--- a/web/tests/route-params.test.ts
+++ b/web/tests/route-params.test.ts
@@ -1,7 +1,7 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { firstParam } from "../lib/route-params.ts";
+import { firstParam } from "../lib/route-params";
test("firstParam returns undefined for missing param", () => {
assert.equal(firstParam(undefined), undefined);
diff --git a/web/tests/think-segments.test.ts b/web/tests/think-segments.test.ts
new file mode 100644
index 000000000..062483842
--- /dev/null
+++ b/web/tests/think-segments.test.ts
@@ -0,0 +1,122 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ hasModelThinking,
+ parseModelThinkingSegments,
+} from "../lib/think-segments";
+
+test("returns a single text segment when there is no <think> tag", () => {
+ const segments = parseModelThinkingSegments("Hello there");
+ assert.deepEqual(segments, [{ kind: "text", content: "Hello there" }]);
+});
+
+test("splits raw streaming form into think + trailing text", () => {
+ const segments = parseModelThinkingSegments(
+ "<think>let me reason</think>Hello!",
+ );
+ assert.equal(segments.length, 2);
+ assert.deepEqual(segments[0], {
+ kind: "think",
+ content: "let me reason",
+ closed: true,
+ });
+ assert.deepEqual(segments[1], { kind: "text", content: "Hello!" });
+});
+
+test("captures leading text before the <think> block", () => {
+ const segments = parseModelThinkingSegments("intro\n<think>foo</think>tail");
+ assert.equal(segments.length, 3);
+ assert.equal(segments[0].kind, "text");
+ assert.equal(segments[0].content, "intro\n");
+ assert.equal(segments[1].kind, "think");
+ if (segments[1].kind === "think") {
+ assert.equal(segments[1].content, "foo");
+ assert.equal(segments[1].closed, true);
+ }
+ assert.equal(segments[2].kind, "text");
+ assert.equal(segments[2].content, "tail");
+});
+
+test("recognises post-normalized backtick-wrapped tags", () => {
+ const segments = parseModelThinkingSegments(
+ "`<think>`reasoning body`</think>`Hello!",
+ );
+ assert.equal(segments.length, 2);
+ assert.deepEqual(segments[0], {
+ kind: "think",
+ content: "reasoning body",
+ closed: true,
+ });
+ assert.deepEqual(segments[1], { kind: "text", content: "Hello!" });
+});
+
+test("treats unclosed <think> as still-streaming", () => {
+ const segments = parseModelThinkingSegments(
+ "<think>partial reasoning still going",
+ );
+ assert.equal(segments.length, 1);
+ assert.deepEqual(segments[0], {
+ kind: "think",
+ content: "partial reasoning still going",
+ closed: false,
+ });
+});
+
+test("supports the <thinking> alias", () => {
+ const segments = parseModelThinkingSegments("<thinking>foo</thinking>bar");
+ assert.equal(segments.length, 2);
+ assert.equal(segments[0].kind, "think");
+ if (segments[0].kind === "think") {
+ assert.equal(segments[0].closed, true);
+ assert.equal(segments[0].content, "foo");
+ }
+ assert.equal(segments[1].kind, "text");
+});
+
+test("ignores <think> that lives inside a fenced code block", () => {
+ const input = "before\n```\n<think>not real</think>\n```\nafter";
+ const segments = parseModelThinkingSegments(input);
+ assert.equal(segments.length, 1);
+ assert.equal(segments[0].kind, "text");
+ assert.equal(segments[0].content, input);
+});
+
+test("handles consecutive <think> blocks", () => {
+ const segments = parseModelThinkingSegments(
+ "<think>first</think>middle<think>second</think>end",
+ );
+ assert.equal(segments.length, 4);
+ assert.equal(segments[0].kind, "think");
+ if (segments[0].kind === "think") {
+ assert.equal(segments[0].closed, true);
+ assert.equal(segments[0].content, "first");
+ }
+ assert.equal(segments[1].kind, "text");
+ assert.equal(segments[1].content, "middle");
+ assert.equal(segments[2].kind, "think");
+ if (segments[2].kind === "think") {
+ assert.equal(segments[2].closed, true);
+ assert.equal(segments[2].content, "second");
+ }
+ assert.equal(segments[3].kind, "text");
+ assert.equal(segments[3].content, "end");
+});
+
+test("trims surrounding whitespace inside the think block", () => {
+ const segments = parseModelThinkingSegments(
+ "<think>\n\nlots of newlines\n\n</think>",
+ );
+ assert.equal(segments.length, 1);
+ if (segments[0].kind !== "think") {
+ assert.fail("Expected first segment to be a think block");
+ }
+ assert.equal(segments[0].content, "lots of newlines");
+});
+
+test("hasModelThinking detects raw and post-normalized tags", () => {
+ assert.equal(hasModelThinking("hello"), false);
+ assert.equal(hasModelThinking("<think>x</think>"), true);
+ assert.equal(hasModelThinking("`<think>`x`</think>`"), true);
+ assert.equal(hasModelThinking("<thinking>x</thinking>"), true);
+});
diff --git a/web/tsconfig.node-tests.json b/web/tsconfig.node-tests.json
new file mode 100644
index 000000000..aeb01cddd
--- /dev/null
+++ b/web/tsconfig.node-tests.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "outDir": "./dist/node-tests",
+ "rootDir": ".",
+ "module": "commonjs",
+ "moduleResolution": "node",
+ "incremental": false,
+ "paths": {}
+ },
+ "include": ["tests/**/*.ts"]
+}